Transaction Hash:
Block:
22007145 at Mar-09-2025 05:12:23 AM +UTC
Transaction Fee:
0.000039112030506984 ETH
$0.07
Gas Used:
65,558 Gas / 0.596601948 Gwei
Emitted Events:
200 |
TransparentUpgradeableProxy.0xf36866d965ee70c8632ff558f5cf8d41ee9ca1d0d0bc7700786e57be60747390( 0xf36866d965ee70c8632ff558f5cf8d41ee9ca1d0d0bc7700786e57be60747390, 00000000000000000000000000000000000000000000000000000000002f4cfc, 4345535200000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000067cd2337 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x6809b956...6a8c5B584 |
1.623567381930459155 Eth
Nonce: 33634
|
1.623528269899952171 Eth
Nonce: 33635
| 0.000039112030506984 | ||
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 5.573833353800308166 Eth | 5.573834909396064602 Eth | 0.000001555595756436 | |
0xd72a6BA4...d0911fC6C |
Execution Trace
TransparentUpgradeableProxy.b7a16251( )
EthereumMultiFeedAdapterWithoutRoundsV2.updateDataFeedsValuesPartial( )
-
Null: 0x000...001.8bcc7af9( )
-
Null: 0x000...001.4ab35cf4( )
-
Null: 0x000...001.4ab35cf4( )
-
updateDataFeedsValuesPartial[MultiFeedAdapterWithoutRounds (ln:831)]
getOracleNumericValuesAndTimestampFromTxMsg[MultiFeedAdapterWithoutRounds (ln:832)]
validateTimestamp[MultiFeedAdapterWithoutRounds (ln:834)]
type[MultiFeedAdapterWithoutRounds (ln:836)]
DataTimestampTooLarge[MultiFeedAdapterWithoutRounds (ln:837)]
type[MultiFeedAdapterWithoutRounds (ln:839)]
BlockTimestampTooLarge[MultiFeedAdapterWithoutRounds (ln:840)]
_tryToUpdateDataFeed[MultiFeedAdapterWithoutRounds (ln:846)]
getLastUpdateDetailsUnsafe[MultiFeedAdapterWithoutRounds (ln:851)]
_getDataFeedsStorage[MultiFeedAdapterWithoutRounds (ln:888)]
_validateBlockTimestamp[MultiFeedAdapterWithoutRounds (ln:852)]
UpdateSkipDueToBlockTimestamp[MultiFeedAdapterWithoutRounds (ln:853)]
_validateDataTimestamp[MultiFeedAdapterWithoutRounds (ln:856)]
UpdateSkipDueToDataTimestamp[MultiFeedAdapterWithoutRounds (ln:857)]
_validateValueBeforeSave[MultiFeedAdapterWithoutRounds (ln:860)]
UpdateSkipDueToInvalidValue[MultiFeedAdapterWithoutRounds (ln:861)]
_saveNewUpdateDetails[MultiFeedAdapterWithoutRounds (ln:864)]
_getDataFeedsStorage[MultiFeedAdapterWithoutRounds (ln:868)]
type[MultiFeedAdapterWithoutRounds (ln:869)]
DataFeedDetails[MultiFeedAdapterWithoutRounds (ln:871)]
_emitEventAfterValueUpdate[MultiFeedAdapterWithoutRounds (ln:865)]
ValueUpdate[MultiFeedAdapterWithoutRounds (ln:926)]
File 1 of 2: TransparentUpgradeableProxy
File 2 of 2: EthereumMultiFeedAdapterWithoutRoundsV2
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../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. * * By default, the owner account will be the one that deploys the contract. 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; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @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 { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); _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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.3) (interfaces/IERC1967.sol) pragma solidity ^0.8.0; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. * * _Available since v4.9._ */ interface IERC1967 { /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @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}. */ constructor(address beacon, bytes memory data) payable { _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @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. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../../access/Ownable.sol"; import "../../utils/Address.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 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 deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override 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); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.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, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializing the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.3) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/IERC1967.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade is IERC1967 { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @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 { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. */ 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 { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {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 bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ 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 { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @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 { _beforeFallback(); _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(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overridden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/ProxyAdmin.sol) pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(ITransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(ITransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(ITransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall( ITransparentUpgradeableProxy proxy, address implementation, bytes memory data ) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy} * does not implement this interface directly, and some of its functions are implemented by an internal dispatch * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not * include them in the ABI so this interface must be used to interact with it. */ interface ITransparentUpgradeableProxy is IERC1967 { function admin() external view returns (address); function implementation() external view returns (address); function changeAdmin(address) external; function upgradeTo(address) external; function upgradeToAndCall(address, bytes memory) external payable; } /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. * * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the * implementation. * * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. * * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the * implementation provides a function with the same selector. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior */ function _fallback() internal virtual override { if (msg.sender == _getAdmin()) { bytes memory ret; bytes4 selector = msg.sig; if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) { ret = _dispatchUpgradeTo(); } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) { ret = _dispatchUpgradeToAndCall(); } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) { ret = _dispatchChangeAdmin(); } else if (selector == ITransparentUpgradeableProxy.admin.selector) { ret = _dispatchAdmin(); } else if (selector == ITransparentUpgradeableProxy.implementation.selector) { ret = _dispatchImplementation(); } else { revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target"); } assembly { return(add(ret, 0x20), mload(ret)) } } else { super._fallback(); } } /** * @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 _dispatchAdmin() private returns (bytes memory) { _requireZeroValue(); address admin = _getAdmin(); return abi.encode(admin); } /** * @dev Returns the current implementation. * * 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 _dispatchImplementation() private returns (bytes memory) { _requireZeroValue(); address implementation = _implementation(); return abi.encode(implementation); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _dispatchChangeAdmin() private returns (bytes memory) { _requireZeroValue(); address newAdmin = abi.decode(msg.data[4:], (address)); _changeAdmin(newAdmin); return ""; } /** * @dev Upgrade the implementation of the proxy. */ function _dispatchUpgradeTo() private returns (bytes memory) { _requireZeroValue(); address newImplementation = abi.decode(msg.data[4:], (address)); _upgradeToAndCall(newImplementation, bytes(""), false); return ""; } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. */ function _dispatchUpgradeToAndCall() private returns (bytes memory) { (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes)); _upgradeToAndCall(newImplementation, data, true); return ""; } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to * emulate some proxy functions being non-payable while still allowing value to pass through. */ function _requireZeroValue() private { require(msg.value == 0); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @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, it is bubbled up by this * function (like regular Solidity function calls). * * 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. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @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`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @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: * ``` * 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(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 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 } } }
File 2 of 2: EthereumMultiFeedAdapterWithoutRoundsV2
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import "./RedstoneConstants.sol"; /** * @title The base contract with the main logic of data extraction from calldata * @author The Redstone Oracles team * @dev This contract was created to reuse the same logic in the RedstoneConsumerBase * and the ProxyConnector contracts */ contract CalldataExtractor is RedstoneConstants { error DataPackageTimestampMustNotBeZero(); error DataPackageTimestampsMustBeEqual(); error RedstonePayloadMustHaveAtLeastOneDataPackage(); error TooLargeValueByteSize(uint256 valueByteSize); function extractTimestampsAndAssertAllAreEqual() public pure returns (uint256 extractedTimestamp) { uint256 calldataNegativeOffset = _extractByteSizeOfUnsignedMetadata(); uint256 dataPackagesCount; (dataPackagesCount, calldataNegativeOffset) = _extractDataPackagesCountFromCalldata(calldataNegativeOffset); if (dataPackagesCount == 0) { revert RedstonePayloadMustHaveAtLeastOneDataPackage(); } for (uint256 dataPackageIndex = 0; dataPackageIndex < dataPackagesCount; dataPackageIndex++) { uint256 dataPackageByteSize = _getDataPackageByteSize(calldataNegativeOffset); // Extracting timestamp for the current data package uint48 dataPackageTimestamp; // uint48, because timestamp uses 6 bytes uint256 timestampNegativeOffset = (calldataNegativeOffset + TIMESTAMP_NEGATIVE_OFFSET_IN_DATA_PACKAGE_WITH_STANDARD_SLOT_BS); uint256 timestampOffset = msg.data.length - timestampNegativeOffset; assembly { dataPackageTimestamp := calldataload(timestampOffset) } if (dataPackageTimestamp == 0) { revert DataPackageTimestampMustNotBeZero(); } if (extractedTimestamp == 0) { extractedTimestamp = dataPackageTimestamp; } else if (dataPackageTimestamp != extractedTimestamp) { revert DataPackageTimestampsMustBeEqual(); } calldataNegativeOffset += dataPackageByteSize; } } function _getDataPackageByteSize(uint256 calldataNegativeOffset) internal pure returns (uint256) { ( uint256 dataPointsCount, uint256 eachDataPointValueByteSize ) = _extractDataPointsDetailsForDataPackage(calldataNegativeOffset); return dataPointsCount * (DATA_POINT_SYMBOL_BS + eachDataPointValueByteSize) + DATA_PACKAGE_WITHOUT_DATA_POINTS_BS; } function _extractByteSizeOfUnsignedMetadata() internal pure returns (uint256) { // Checking if the calldata ends with the RedStone marker bool hasValidRedstoneMarker; assembly { let calldataLast32Bytes := calldataload(sub(calldatasize(), STANDARD_SLOT_BS)) hasValidRedstoneMarker := eq( REDSTONE_MARKER_MASK, and(calldataLast32Bytes, REDSTONE_MARKER_MASK) ) } if (!hasValidRedstoneMarker) { revert CalldataMustHaveValidPayload(); } // Using uint24, because unsigned metadata byte size number has 3 bytes uint24 unsignedMetadataByteSize; if (REDSTONE_MARKER_BS_PLUS_STANDARD_SLOT_BS > msg.data.length) { revert CalldataOverOrUnderFlow(); } assembly { unsignedMetadataByteSize := calldataload( sub(calldatasize(), REDSTONE_MARKER_BS_PLUS_STANDARD_SLOT_BS) ) } uint256 calldataNegativeOffset = unsignedMetadataByteSize + UNSIGNED_METADATA_BYTE_SIZE_BS + REDSTONE_MARKER_BS; if (calldataNegativeOffset + DATA_PACKAGES_COUNT_BS > msg.data.length) { revert IncorrectUnsignedMetadataSize(); } return calldataNegativeOffset; } // We return uint16, because unsigned metadata byte size number has 2 bytes function _extractDataPackagesCountFromCalldata(uint256 calldataNegativeOffset) internal pure returns (uint16 dataPackagesCount, uint256 nextCalldataNegativeOffset) { uint256 calldataNegativeOffsetWithStandardSlot = calldataNegativeOffset + STANDARD_SLOT_BS; if (calldataNegativeOffsetWithStandardSlot > msg.data.length) { revert CalldataOverOrUnderFlow(); } assembly { dataPackagesCount := calldataload( sub(calldatasize(), calldataNegativeOffsetWithStandardSlot) ) } return (dataPackagesCount, calldataNegativeOffset + DATA_PACKAGES_COUNT_BS); } function _extractDataPointValueAndDataFeedId( uint256 dataPointNegativeOffset, uint256 dataPointValueByteSize ) internal pure virtual returns (bytes32 dataPointDataFeedId, uint256 dataPointValue) { uint256 dataPointCalldataOffset = msg.data.length - dataPointNegativeOffset; assembly { dataPointDataFeedId := calldataload(dataPointCalldataOffset) dataPointValue := calldataload(add(dataPointCalldataOffset, DATA_POINT_SYMBOL_BS)) } if (dataPointValueByteSize >= 33) { revert TooLargeValueByteSize(dataPointValueByteSize); } unchecked { dataPointValue = dataPointValue >> (32 - dataPointValueByteSize) * 8; } } function _extractDataPointsDetailsForDataPackage(uint256 calldataNegativeOffsetForDataPackage) internal pure returns (uint256 dataPointsCount, uint256 eachDataPointValueByteSize) { // Using uint24, because data points count byte size number has 3 bytes uint24 dataPointsCount_; // Using uint32, because data point value byte size has 4 bytes uint32 eachDataPointValueByteSize_; // Extract data points count uint256 calldataOffset = msg.data.length - (calldataNegativeOffsetForDataPackage + SIG_BS + STANDARD_SLOT_BS); assembly { dataPointsCount_ := calldataload(calldataOffset) } // Extract each data point value size calldataOffset = calldataOffset - DATA_POINTS_COUNT_BS; assembly { eachDataPointValueByteSize_ := calldataload(calldataOffset) } // Prepare returned values dataPointsCount = dataPointsCount_; eachDataPointValueByteSize = eachDataPointValueByteSize_; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; /** * @title The base contract with helpful constants * @author The Redstone Oracles team * @dev It mainly contains redstone-related values, which improve readability * of other contracts (e.g. CalldataExtractor and RedstoneConsumerBase) */ contract RedstoneConstants { // === Abbreviations === // BS - Bytes size // PTR - Pointer (memory location) // SIG - Signature // Solidity and YUL constants uint256 internal constant STANDARD_SLOT_BS = 32; uint256 internal constant FREE_MEMORY_PTR = 0x40; uint256 internal constant BYTES_ARR_LEN_VAR_BS = 32; uint256 internal constant REVERT_MSG_OFFSET = 68; // Revert message structure described here: https://ethereum.stackexchange.com/a/66173/106364 uint256 internal constant STRING_ERR_MESSAGE_MASK = 0x08c379a000000000000000000000000000000000000000000000000000000000; // RedStone protocol consts uint256 internal constant SIG_BS = 65; uint256 internal constant TIMESTAMP_BS = 6; uint256 internal constant DATA_PACKAGES_COUNT_BS = 2; uint256 internal constant DATA_POINTS_COUNT_BS = 3; uint256 internal constant DATA_POINT_VALUE_BYTE_SIZE_BS = 4; uint256 internal constant DATA_POINT_SYMBOL_BS = 32; uint256 internal constant DEFAULT_DATA_POINT_VALUE_BS = 32; uint256 internal constant UNSIGNED_METADATA_BYTE_SIZE_BS = 3; uint256 internal constant REDSTONE_MARKER_BS = 9; // byte size of 0x000002ed57011e0000 uint256 internal constant REDSTONE_MARKER_MASK = 0x0000000000000000000000000000000000000000000000000002ed57011e0000; // Derived values (based on consts) uint256 internal constant TIMESTAMP_NEGATIVE_OFFSET_IN_DATA_PACKAGE_WITH_STANDARD_SLOT_BS = 104; // SIG_BS + DATA_POINTS_COUNT_BS + DATA_POINT_VALUE_BYTE_SIZE_BS + STANDARD_SLOT_BS uint256 internal constant DATA_PACKAGE_WITHOUT_DATA_POINTS_BS = 78; // DATA_POINT_VALUE_BYTE_SIZE_BS + TIMESTAMP_BS + DATA_POINTS_COUNT_BS + SIG_BS uint256 internal constant DATA_PACKAGE_WITHOUT_DATA_POINTS_AND_SIG_BS = 13; // DATA_POINT_VALUE_BYTE_SIZE_BS + TIMESTAMP_BS + DATA_POINTS_COUNT_BS uint256 internal constant REDSTONE_MARKER_BS_PLUS_STANDARD_SLOT_BS = 41; // REDSTONE_MARKER_BS + STANDARD_SLOT_BS // Error messages error CalldataOverOrUnderFlow(); error IncorrectUnsignedMetadataSize(); error InsufficientNumberOfUniqueSigners(uint256 receivedSignersCount, uint256 requiredSignersCount); error EachSignerMustProvideTheSameValue(); error EmptyCalldataPointersArr(); error InvalidCalldataPointer(); error CalldataMustHaveValidPayload(); error SignerNotAuthorised(address receivedSigner); error DataTimestampCannotBeZero(); error TimestampsMustBeEqual(); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import "./RedstoneConstants.sol"; import "./RedstoneDefaultsLib.sol"; import "./CalldataExtractor.sol"; import "../libs/BitmapLib.sol"; import "../libs/SignatureLib.sol"; /** * @title The base contract with the main Redstone logic * @author The Redstone Oracles team * @dev Do not use this contract directly in consumer contracts, take a * look at `RedstoneConsumerNumericBase` and `RedstoneConsumerBytesBase` instead */ abstract contract RedstoneConsumerBase is CalldataExtractor { error GetDataServiceIdNotImplemented(); /* ========== VIRTUAL FUNCTIONS (MAY BE OVERRIDDEN IN CHILD CONTRACTS) ========== */ /** * @dev This function must be implemented by the child consumer contract. * It should return dataServiceId which DataServiceWrapper will use if not provided explicitly . * If not overridden, value will always have to be provided explicitly in DataServiceWrapper. * @return dataServiceId being consumed by contract */ function getDataServiceId() public view virtual returns (string memory) { revert GetDataServiceIdNotImplemented(); } /** * @dev This function must be implemented by the child consumer contract. * It should return a unique index for a given signer address if the signer * is authorised, otherwise it should revert * @param receivedSigner The address of a signer, recovered from ECDSA signature * @return Unique index for a signer in the range [0..255] */ function getAuthorisedSignerIndex(address receivedSigner) public view virtual returns (uint8); /** * @dev This function may be overridden by the child consumer contract. * It should validate the timestamp against the current time (block.timestamp) * It should revert with a helpful message if the timestamp is not valid * @param receivedTimestampMilliseconds Timestamp extracted from calldata */ function validateTimestamp(uint256 receivedTimestampMilliseconds) public view virtual { RedstoneDefaultsLib.validateTimestamp(receivedTimestampMilliseconds); } /** * @dev This function must be implemented by the child consumer contract. * @return The minimum required value of unique authorised signers */ function getUniqueSignersThreshold() public view virtual returns (uint8); /** * @dev This function may be overridden by the child consumer contract. * It should aggregate values from different signers to a single uint value. * By default, it calculates the median value * @param values An array of uint256 values from different signers * @return Result of the aggregation in the form of a single number */ function aggregateValues(uint256[] memory values) public view virtual returns (uint256) { return RedstoneDefaultsLib.aggregateValues(values); } /* ========== FUNCTIONS WITH IMPLEMENTATION (CAN NOT BE OVERRIDDEN) ========== */ /** * @dev This is an internal helpful function for secure extraction oracle values * from the tx calldata. Security is achieved by signatures verification, timestamp * validation, and aggregating values from different authorised signers into a * single numeric value. If any of the required conditions (e.g. packages with different * timestamps or insufficient number of authorised signers) do not match, the function * will revert. * * Note! You should not call this function in a consumer contract. You can use * `getOracleNumericValuesFromTxMsg` or `getOracleNumericValueFromTxMsg` instead. * * @param dataFeedIds An array of unique data feed identifiers * @return An array of the extracted and verified oracle values in the same order * as they are requested in dataFeedIds array * @return dataPackagesTimestamp timestamp equal for all data packages */ function _securelyExtractOracleValuesAndTimestampFromTxMsg(bytes32[] memory dataFeedIds) internal view returns (uint256[] memory, uint256 dataPackagesTimestamp) { // Initializing helpful variables and allocating memory uint256[] memory uniqueSignerCountForDataFeedIds = new uint256[](dataFeedIds.length); uint256[] memory signersBitmapForDataFeedIds = new uint256[](dataFeedIds.length); uint256[][] memory valuesForDataFeeds = new uint256[][](dataFeedIds.length); for (uint256 i = 0; i < dataFeedIds.length;) { // The line below is commented because newly allocated arrays are filled with zeros // But we left it for better readability // signersBitmapForDataFeedIds[i] = 0; // <- setting to an empty bitmap valuesForDataFeeds[i] = new uint256[](getUniqueSignersThreshold()); unchecked { i++; } } // Extracting the number of data packages from calldata uint256 calldataNegativeOffset = _extractByteSizeOfUnsignedMetadata(); uint256 dataPackagesCount; (dataPackagesCount, calldataNegativeOffset) = _extractDataPackagesCountFromCalldata(calldataNegativeOffset); // Saving current free memory pointer uint256 freeMemPtr; assembly { freeMemPtr := mload(FREE_MEMORY_PTR) } // Data packages extraction in a loop for (uint256 dataPackageIndex = 0; dataPackageIndex < dataPackagesCount;) { // Extract data package details and update calldata offset uint256 dataPackageTimestamp; (calldataNegativeOffset, dataPackageTimestamp) = _extractDataPackage( dataFeedIds, uniqueSignerCountForDataFeedIds, signersBitmapForDataFeedIds, valuesForDataFeeds, calldataNegativeOffset ); if (dataPackageTimestamp == 0) { revert DataTimestampCannotBeZero(); } if (dataPackageTimestamp != dataPackagesTimestamp) { if (dataPackagesTimestamp == 0) { // Setting dataPackagesTimestamp first time dataPackagesTimestamp = dataPackageTimestamp; } else { revert TimestampsMustBeEqual(); } } // Resetting the memory pointer to the initial "safe" value // We add STANDARD_SLOT_BS (32 bytes) to account for potential allocation // of the dataPackageIndex variable, which may or may not be stored in memory assembly { mstore(FREE_MEMORY_PTR, add(freeMemPtr, STANDARD_SLOT_BS)) } unchecked { dataPackageIndex++; } } // Validating numbers of unique signers and calculating aggregated values for each dataFeedId return (_getAggregatedValues(valuesForDataFeeds, uniqueSignerCountForDataFeedIds), dataPackagesTimestamp); } /** * @dev This is a private helpful function, which extracts data for a data package based * on the given negative calldata offset, verifies them, and in the case of successful * verification updates the corresponding data package values in memory * * @param dataFeedIds an array of unique data feed identifiers * @param uniqueSignerCountForDataFeedIds an array with the numbers of unique signers * for each data feed * @param signersBitmapForDataFeedIds an array of signer bitmaps for data feeds * @param valuesForDataFeeds 2-dimensional array, valuesForDataFeeds[i][j] contains * j-th value for the i-th data feed * @param calldataNegativeOffset negative calldata offset for the given data package * * @return nextCalldataNegativeOffset negative calldata offset for the next data package * @return dataPackageTimestamp data package timestamp */ function _extractDataPackage( bytes32[] memory dataFeedIds, uint256[] memory uniqueSignerCountForDataFeedIds, uint256[] memory signersBitmapForDataFeedIds, uint256[][] memory valuesForDataFeeds, uint256 calldataNegativeOffset ) private view returns (uint256 nextCalldataNegativeOffset, uint256 dataPackageTimestamp) { uint256 signerIndex; ( uint256 dataPointsCount, uint256 eachDataPointValueByteSize ) = _extractDataPointsDetailsForDataPackage(calldataNegativeOffset); // We use scopes to resolve problem with too deep stack { address signerAddress; bytes32 signedHash; bytes memory signedMessage; uint256 signedMessageBytesCount; uint48 extractedTimestamp; signedMessageBytesCount = dataPointsCount * (eachDataPointValueByteSize + DATA_POINT_SYMBOL_BS) + DATA_PACKAGE_WITHOUT_DATA_POINTS_AND_SIG_BS; //DATA_POINT_VALUE_BYTE_SIZE_BS + TIMESTAMP_BS + DATA_POINTS_COUNT_BS uint256 timestampCalldataOffset = msg.data.length - (calldataNegativeOffset + TIMESTAMP_NEGATIVE_OFFSET_IN_DATA_PACKAGE_WITH_STANDARD_SLOT_BS); uint256 signedMessageCalldataOffset = msg.data.length - (calldataNegativeOffset + SIG_BS + signedMessageBytesCount); assembly { // Extracting the signed message signedMessage := extractBytesFromCalldata( signedMessageCalldataOffset, signedMessageBytesCount ) // Hashing the signed message signedHash := keccak256(add(signedMessage, BYTES_ARR_LEN_VAR_BS), signedMessageBytesCount) // Extracting timestamp extractedTimestamp := calldataload(timestampCalldataOffset) function initByteArray(bytesCount) -> ptr { ptr := mload(FREE_MEMORY_PTR) mstore(ptr, bytesCount) ptr := add(ptr, BYTES_ARR_LEN_VAR_BS) mstore(FREE_MEMORY_PTR, add(ptr, bytesCount)) } function extractBytesFromCalldata(offset, bytesCount) -> extractedBytes { let extractedBytesStartPtr := initByteArray(bytesCount) calldatacopy( extractedBytesStartPtr, offset, bytesCount ) extractedBytes := sub(extractedBytesStartPtr, BYTES_ARR_LEN_VAR_BS) } } dataPackageTimestamp = extractedTimestamp; // Verifying the off-chain signature against on-chain hashed data signerAddress = SignatureLib.recoverSignerAddress( signedHash, calldataNegativeOffset + SIG_BS ); signerIndex = getAuthorisedSignerIndex(signerAddress); } // Updating helpful arrays { calldataNegativeOffset = calldataNegativeOffset + DATA_PACKAGE_WITHOUT_DATA_POINTS_BS; bytes32 dataPointDataFeedId; uint256 dataPointValue; for (uint256 dataPointIndex = 0; dataPointIndex < dataPointsCount;) { calldataNegativeOffset = calldataNegativeOffset + eachDataPointValueByteSize + DATA_POINT_SYMBOL_BS; // Extracting data feed id and value for the current data point (dataPointDataFeedId, dataPointValue) = _extractDataPointValueAndDataFeedId( calldataNegativeOffset, eachDataPointValueByteSize ); for ( uint256 dataFeedIdIndex = 0; dataFeedIdIndex < dataFeedIds.length; ) { if (dataPointDataFeedId == dataFeedIds[dataFeedIdIndex]) { uint256 bitmapSignersForDataFeedId = signersBitmapForDataFeedIds[dataFeedIdIndex]; if ( !BitmapLib.getBitFromBitmap(bitmapSignersForDataFeedId, signerIndex) && /* current signer was not counted for current dataFeedId */ uniqueSignerCountForDataFeedIds[dataFeedIdIndex] < getUniqueSignersThreshold() ) { // Add new value valuesForDataFeeds[dataFeedIdIndex][uniqueSignerCountForDataFeedIds[dataFeedIdIndex]] = dataPointValue; // Increase unique signer counter uniqueSignerCountForDataFeedIds[dataFeedIdIndex]++; // Update signers bitmap signersBitmapForDataFeedIds[dataFeedIdIndex] = BitmapLib.setBitInBitmap( bitmapSignersForDataFeedId, signerIndex ); } // Breaking, as there couldn't be several indexes for the same feed ID break; } unchecked { dataFeedIdIndex++; } } unchecked { dataPointIndex++; } } } return (calldataNegativeOffset, dataPackageTimestamp); } /** * @dev This is a private helpful function, which aggregates values from different * authorised signers for the given arrays of values for each data feed * * @param valuesForDataFeeds 2-dimensional array, valuesForDataFeeds[i][j] contains * j-th value for the i-th data feed * @param uniqueSignerCountForDataFeedIds an array with the numbers of unique signers * for each data feed * * @return An array of the aggregated values */ function _getAggregatedValues( uint256[][] memory valuesForDataFeeds, uint256[] memory uniqueSignerCountForDataFeedIds ) private view returns (uint256[] memory) { uint256[] memory aggregatedValues = new uint256[](valuesForDataFeeds.length); uint256 uniqueSignersThreshold = getUniqueSignersThreshold(); for (uint256 dataFeedIndex = 0; dataFeedIndex < valuesForDataFeeds.length; dataFeedIndex++) { if (uniqueSignerCountForDataFeedIds[dataFeedIndex] < uniqueSignersThreshold) { revert InsufficientNumberOfUniqueSigners( uniqueSignerCountForDataFeedIds[dataFeedIndex], uniqueSignersThreshold); } uint256 aggregatedValueForDataFeedId = aggregateValues(valuesForDataFeeds[dataFeedIndex]); aggregatedValues[dataFeedIndex] = aggregatedValueForDataFeedId; } return aggregatedValues; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import "./RedstoneConsumerBase.sol"; /** * @title The base contract for Redstone consumers' contracts that allows to * securely calculate numeric redstone oracle values * @author The Redstone Oracles team * @dev This contract can extend other contracts to allow them * securely fetch Redstone oracle data from transactions calldata */ abstract contract RedstoneConsumerNumericBase is RedstoneConsumerBase { /** * @dev This function can be used in a consumer contract to securely extract an * oracle value for a given data feed id. Security is achieved by * signatures verification, timestamp validation, and aggregating values * from different authorised signers into a single numeric value. If any of the * required conditions do not match, the function will revert. * Note! This function expects that tx calldata contains redstone payload in the end * Learn more about redstone payload here: https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/evm-connector#readme * @param dataFeedId bytes32 value that uniquely identifies the data feed * @return Extracted and verified numeric oracle value for the given data feed id */ function getOracleNumericValueFromTxMsg(bytes32 dataFeedId) internal view virtual returns (uint256) { bytes32[] memory dataFeedIds = new bytes32[](1); dataFeedIds[0] = dataFeedId; return getOracleNumericValuesFromTxMsg(dataFeedIds)[0]; } /** * @dev This function can be used in a consumer contract to securely extract several * numeric oracle values for a given array of data feed ids. Security is achieved by * signatures verification, timestamp validation, and aggregating values * from different authorised signers into a single numeric value. If any of the * required conditions do not match, the function will revert. * Note! This function expects that tx calldata contains redstone payload in the end * Learn more about redstone payload here: https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/evm-connector#readme * @param dataFeedIds An array of unique data feed identifiers * @return An array of the extracted and verified oracle values in the same order * as they are requested in the dataFeedIds array */ function getOracleNumericValuesFromTxMsg(bytes32[] memory dataFeedIds) internal view virtual returns (uint256[] memory) { (uint256[] memory values, uint256 timestamp) = _securelyExtractOracleValuesAndTimestampFromTxMsg(dataFeedIds); validateTimestamp(timestamp); return values; } /** * @dev This function can be used in a consumer contract to securely extract several * numeric oracle values for a given array of data feed ids. Security is achieved by * signatures verification and aggregating values from different authorised signers * into a single numeric value. If any of the required conditions do not match, * the function will revert. * Note! This function returns the timestamp of the packages (it requires it to be * the same for all), but does not validate this timestamp. * Note! This function expects that tx calldata contains redstone payload in the end * Learn more about redstone payload here: https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/evm-connector#readme * @param dataFeedIds An array of unique data feed identifiers * @return An array of the extracted and verified oracle values in the same order * as they are requested in the dataFeedIds array and data packages timestamp */ function getOracleNumericValuesAndTimestampFromTxMsg(bytes32[] memory dataFeedIds) internal view virtual returns (uint256[] memory, uint256) { return _securelyExtractOracleValuesAndTimestampFromTxMsg(dataFeedIds); } /** * @dev This function works similarly to the `getOracleNumericValuesFromTxMsg` with the * only difference that it allows to request oracle data for an array of data feeds * that may contain duplicates * * @param dataFeedIdsWithDuplicates An array of data feed identifiers (duplicates are allowed) * @return An array of the extracted and verified oracle values in the same order * as they are requested in the dataFeedIdsWithDuplicates array */ function getOracleNumericValuesWithDuplicatesFromTxMsg(bytes32[] memory dataFeedIdsWithDuplicates) internal view returns (uint256[] memory) { // Building an array without duplicates bytes32[] memory dataFeedIdsWithoutDuplicates = new bytes32[](dataFeedIdsWithDuplicates.length); bool alreadyIncluded; uint256 uniqueDataFeedIdsCount = 0; for (uint256 indexWithDup = 0; indexWithDup < dataFeedIdsWithDuplicates.length; indexWithDup++) { // Checking if current element is already included in `dataFeedIdsWithoutDuplicates` alreadyIncluded = false; for (uint256 indexWithoutDup = 0; indexWithoutDup < uniqueDataFeedIdsCount; indexWithoutDup++) { if (dataFeedIdsWithoutDuplicates[indexWithoutDup] == dataFeedIdsWithDuplicates[indexWithDup]) { alreadyIncluded = true; break; } } // Adding if not included if (!alreadyIncluded) { dataFeedIdsWithoutDuplicates[uniqueDataFeedIdsCount] = dataFeedIdsWithDuplicates[indexWithDup]; uniqueDataFeedIdsCount++; } } // Overriding dataFeedIdsWithoutDuplicates.length // Equivalent to: dataFeedIdsWithoutDuplicates.length = uniqueDataFeedIdsCount; assembly { mstore(dataFeedIdsWithoutDuplicates, uniqueDataFeedIdsCount) } // Requesting oracle values (without duplicates) (uint256[] memory valuesWithoutDuplicates, uint256 timestamp) = _securelyExtractOracleValuesAndTimestampFromTxMsg(dataFeedIdsWithoutDuplicates); validateTimestamp(timestamp); // Preparing result values array uint256[] memory valuesWithDuplicates = new uint256[](dataFeedIdsWithDuplicates.length); for (uint256 indexWithDup = 0; indexWithDup < dataFeedIdsWithDuplicates.length; indexWithDup++) { for (uint256 indexWithoutDup = 0; indexWithoutDup < dataFeedIdsWithoutDuplicates.length; indexWithoutDup++) { if (dataFeedIdsWithDuplicates[indexWithDup] == dataFeedIdsWithoutDuplicates[indexWithoutDup]) { valuesWithDuplicates[indexWithDup] = valuesWithoutDuplicates[indexWithoutDup]; break; } } } return valuesWithDuplicates; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import "../libs/NumericArrayLib.sol"; /** * @title Default implementations of virtual redstone consumer base functions * @author The Redstone Oracles team */ library RedstoneDefaultsLib { uint256 constant DEFAULT_MAX_DATA_TIMESTAMP_DELAY_SECONDS = 3 minutes; uint256 constant DEFAULT_MAX_DATA_TIMESTAMP_AHEAD_SECONDS = 1 minutes; error TimestampFromTooLongFuture(uint256 receivedTimestampSeconds, uint256 blockTimestamp); error TimestampIsTooOld(uint256 receivedTimestampSeconds, uint256 blockTimestamp); function validateTimestamp(uint256 receivedTimestampMilliseconds) internal view { // Getting data timestamp from future seems quite unlikely // But we've already spent too much time with different cases // Where block.timestamp was less than dataPackage.timestamp. // Some blockchains may case this problem as well. // That's why we add MAX_BLOCK_TIMESTAMP_DELAY // and allow data "from future" but with a small delay uint256 receivedTimestampSeconds = receivedTimestampMilliseconds / 1000; if (block.timestamp < receivedTimestampSeconds) { if ((receivedTimestampSeconds - block.timestamp) > DEFAULT_MAX_DATA_TIMESTAMP_AHEAD_SECONDS) { revert TimestampFromTooLongFuture(receivedTimestampSeconds, block.timestamp); } } else if ((block.timestamp - receivedTimestampSeconds) > DEFAULT_MAX_DATA_TIMESTAMP_DELAY_SECONDS) { revert TimestampIsTooOld(receivedTimestampSeconds, block.timestamp); } } function aggregateValues(uint256[] memory values) internal pure returns (uint256) { return NumericArrayLib.pickMedian(values); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; library BitmapLib { function setBitInBitmap(uint256 bitmap, uint256 bitIndex) internal pure returns (uint256) { return bitmap | (1 << bitIndex); } function getBitFromBitmap(uint256 bitmap, uint256 bitIndex) internal pure returns (bool) { uint256 bitAtIndex = bitmap & (1 << bitIndex); return bitAtIndex > 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; library NumericArrayLib { // This function sort array in memory using bubble sort algorithm, // which performs even better than quick sort for small arrays uint256 constant BYTES_ARR_LEN_VAR_BS = 32; uint256 constant UINT256_VALUE_BS = 32; error CanNotPickMedianOfEmptyArray(); // This function modifies the array function pickMedian(uint256[] memory arr) internal pure returns (uint256) { if (arr.length == 2) { return (arr[0] + arr[1]) / 2; } if (arr.length == 0) { revert CanNotPickMedianOfEmptyArray(); } sort(arr); uint256 middleIndex = arr.length / 2; if (arr.length % 2 == 0) { uint256 sum = arr[middleIndex - 1] + arr[middleIndex]; return sum / 2; } else { return arr[middleIndex]; } } function sort(uint256[] memory arr) internal pure { assembly { let arrLength := mload(arr) let valuesPtr := add(arr, BYTES_ARR_LEN_VAR_BS) let endPtr := add(valuesPtr, mul(arrLength, UINT256_VALUE_BS)) for { let arrIPtr := valuesPtr } lt(arrIPtr, endPtr) { arrIPtr := add(arrIPtr, UINT256_VALUE_BS) // arrIPtr += 32 } { for { let arrJPtr := valuesPtr } lt(arrJPtr, arrIPtr) { arrJPtr := add(arrJPtr, UINT256_VALUE_BS) // arrJPtr += 32 } { let arrI := mload(arrIPtr) let arrJ := mload(arrJPtr) if lt(arrI, arrJ) { mstore(arrIPtr, arrJ) mstore(arrJPtr, arrI) } } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; library SignatureLib { uint256 constant ECDSA_SIG_R_BS = 32; uint256 constant ECDSA_SIG_S_BS = 32; error InvalidSignature(bytes32 signedHash); function recoverSignerAddress(bytes32 signedHash, uint256 signatureCalldataNegativeOffset) internal pure returns (address signerAddress) { bytes32 r; bytes32 s; uint8 v; assembly { let signatureCalldataStartPos := sub(calldatasize(), signatureCalldataNegativeOffset) r := calldataload(signatureCalldataStartPos) signatureCalldataStartPos := add(signatureCalldataStartPos, ECDSA_SIG_R_BS) s := calldataload(signatureCalldataStartPos) signatureCalldataStartPos := add(signatureCalldataStartPos, ECDSA_SIG_S_BS) v := byte(0, calldataload(signatureCalldataStartPos)) // last byte of the signature memory array } signerAddress = ecrecover(signedHash, v, r, s); if (signerAddress == address(0)) { revert InvalidSignature(signedHash); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; interface ILToken { function underlying() external view returns (address); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.17; interface IPriceCalculator { struct ReferenceData { uint256 lastData; uint256 lastUpdated; } function priceOf(address asset) external view returns (uint256); function pricesOf( address[] memory assets ) external view returns (uint256[] memory); function priceOfETH() external view returns (uint256); function getUnderlyingPrice(address gToken) external view returns (uint256); function getUnderlyingPrices( address[] memory gTokens ) external view returns (uint256[] memory); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import {MultiFeedAdapterWithoutRounds} from "../without-rounds/MultiFeedAdapterWithoutRounds.sol"; abstract contract MultiFeedAdapterWithoutRoundsPrimaryProd is MultiFeedAdapterWithoutRounds { function getUniqueSignersThreshold() public view virtual override returns (uint8) { return 3; } function getAuthorisedSignerIndex( address signerAddress ) public view virtual override returns (uint8) { if (signerAddress == 0x8BB8F32Df04c8b654987DAaeD53D6B6091e3B774) { return 0; } else if (signerAddress == 0xdEB22f54738d54976C4c0fe5ce6d408E40d88499) { return 1; } else if (signerAddress == 0x51Ce04Be4b3E32572C4Ec9135221d0691Ba7d202) { return 2; } else if (signerAddress == 0xDD682daEC5A90dD295d14DA4b0bec9281017b5bE) { return 3; } else if (signerAddress == 0x9c5AE89C4Af6aA32cE58588DBaF90d18a855B6de) { return 4; } else { revert SignerNotAuthorised(signerAddress); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; interface IMultiFeedAdapter { function updateDataFeedsValuesPartial(bytes32[] memory dataFeedsIds) external; function getLastUpdateDetails(bytes32 dataFeedId) external view returns (uint256 lastDataTimestamp, uint256 lastBlockTimestamp, uint256 lastValue); function getLastUpdateDetailsUnsafe(bytes32 dataFeedId) external view returns (uint256 lastDataTimestamp, uint256 lastBlockTimestamp, uint256 lastValue); function getValuesForDataFeeds(bytes32[] memory requestedDataFeedIds) external view returns (uint256[] memory values); function getValueForDataFeed(bytes32 dataFeedId) external view returns (uint256 dataFeedValue); function getDataTimestampFromLatestUpdate(bytes32 dataFeedId) external view returns (uint256 lastDataTimestamp); function getBlockTimestampFromLatestUpdate(bytes32 dataFeedId) external view returns (uint256 blockTimestamp); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import {RedstoneConsumerNumericBase, RedstoneDefaultsLib} from "@redstone-finance/evm-connector/contracts/core/RedstoneConsumerNumericBase.sol"; import {IMultiFeedAdapter} from "../interfaces/IMultiFeedAdapter.sol"; import {IPriceCalculator} from "../../custom-integrations/layerbank/IPriceCalculator.sol"; import {ILToken} from "../../custom-integrations/layerbank/ILToken.sol"; /** * @title MultiFeedAdapterWithoutRounds * @author The Redstone Oracles team * @dev This abstract contract serves as an adapter for multiple data feeds, facilitating * the updating and retrieval of oracle data values independently. * * Key details about the contract: * - Values for data feeds can be updated using the `updateDataFeedsValuesPartial` function * - Unlike the previous version (RedstoneAdapterBase), this adapter allows updating any set of data feeds, * with each update being made independently. * - Updates are highly independent. Each data feed update is attempted separately, ensuring maximum possible * updates without reverting the entire transaction if some of them fail. Both successful value updates and * update skips due to failed validation are represented in corresponding events. * - Efficient storage usage: Related timestamps and values are packed into a single 32-byte slot when possible. * If a value exceeds the slot capacity, it is stored in the next slot, with one bool prop (isValueBigger) indicating the storage method used. * - All data packages in the Redstone payload must have the same timestamp. Invalid timestamps (too old or too new) will cause transaction reversion. * - The contract includes a built-in IPriceCalculator interface used by LayerBank and other projects */ abstract contract MultiFeedAdapterWithoutRounds is RedstoneConsumerNumericBase, IMultiFeedAdapter, IPriceCalculator { bytes32 internal constant DATA_FEEDS_STORAGE_LOCATION = 0x5e9fb4cb0eb3c2583734d3394f30bb14b241acb9b3a034f7e7ba1a62db4370f1; // keccak256("RedStone.MultiFeedAdapterWithoutRounds.dataFeeds"); bytes32 internal constant ETH_DATA_FEED_ID = bytes32("ETH"); uint256 internal constant MAX_DATA_STALENESS = 30 hours; uint256 internal constant DEFAULT_DECIMAL_SCALER_LAYERBANK = 1e10; error DataTimestampTooLarge(uint256 dataTimestamp); error BlockTimestampTooLarge(uint256 blockTimestamp); error InvalidLastUpdateDetails(bytes32 dataFeedId, uint256 lastDataTimestamp, uint256 lastBlockTimestamp, uint256 lastValue); event ValueUpdate(uint256 value, bytes32 dataFeedId, uint256 updatedAt); event UpdateSkipDueToBlockTimestamp(bytes32 dataFeedId); event UpdateSkipDueToDataTimestamp(bytes32 dataFeedId); event UpdateSkipDueToInvalidValue(bytes32 dataFeedId); // This struct uses exactly one storage slot (32 bytes) struct DataFeedDetails { uint48 dataTimestamp; uint48 blockTimestamp; uint152 value; bool isValueBigger; } struct DataFeedDetailsWithOptionalBigValue { DataFeedDetails details; uint256 biggerValue; } // This struct is used only for returning values struct LastUpdateDetails { uint256 dataTimestamp; uint256 blockTimestamp; uint256 value; } struct DataFeedsStorage { mapping(bytes32 => DataFeedDetailsWithOptionalBigValue) _dataFeeds; } /// This function allows to update any set of data feeds function updateDataFeedsValuesPartial(bytes32[] memory dataFeedsIds) public { (uint256[] memory oracleValues, uint256 extractedDataTimestamp) = getOracleNumericValuesAndTimestampFromTxMsg(dataFeedsIds); // Revert if data timestamp doesn't fit within the allowed block timestamp window validateTimestamp(extractedDataTimestamp); // Revert if data or block timestamp do not fit into 48 bits reserved in storage for timestamps if (extractedDataTimestamp > type(uint48).max) { revert DataTimestampTooLarge(extractedDataTimestamp); } if (block.timestamp > type(uint48).max) { revert BlockTimestampTooLarge(block.timestamp); } // The logic below can fail only in the case when gas limit reached for (uint256 i = 0; i < dataFeedsIds.length;) { // Note, each update is independent. It means that we are trying to update everything we can. // And skip the rest (emitting corresponding events) _tryToUpdateDataFeed(dataFeedsIds[i], oracleValues[i], extractedDataTimestamp); unchecked { i++; } // reduces gas costs } } function _tryToUpdateDataFeed(bytes32 dataFeedId, uint256 value, uint256 dataTimestamp) internal virtual { (uint256 lastDataTimestamp, uint256 lastBlockTimestamp, uint256 lastValue) = getLastUpdateDetailsUnsafe(dataFeedId); if (!_validateBlockTimestamp(lastBlockTimestamp)) { emit UpdateSkipDueToBlockTimestamp(dataFeedId); return; } if (!_validateDataTimestamp(dataTimestamp, lastDataTimestamp)) { emit UpdateSkipDueToDataTimestamp(dataFeedId); return; } if (!_validateValueBeforeSave(dataFeedId, value, lastValue)) { emit UpdateSkipDueToInvalidValue(dataFeedId); return; } _saveNewUpdateDetails(dataFeedId, value, dataTimestamp); _emitEventAfterValueUpdate(dataFeedId, value); } function _saveNewUpdateDetails(bytes32 dataFeedId, uint256 newValue, uint256 dataTimestamp) internal { DataFeedDetailsWithOptionalBigValue storage dataFeed = _getDataFeedsStorage()._dataFeeds[dataFeedId]; bool isValueBigger = newValue > type(uint152).max; // We can safely cast timestamps here, because we checked timestamp values in the `updateDataFeedsValuesPartial` function dataFeed.details = DataFeedDetails({ dataTimestamp: uint48(dataTimestamp), blockTimestamp: uint48(block.timestamp), value: uint152(newValue), // we can store anything here is isValueBigger == true, but it's slightly cheaper to always store the same value isValueBigger: isValueBigger }); if (isValueBigger) { dataFeed.biggerValue = newValue; } } function getLastUpdateDetails(bytes32 dataFeedId) public view virtual returns (uint256 lastDataTimestamp, uint256 lastBlockTimestamp, uint256 lastValue) { (lastDataTimestamp, lastBlockTimestamp, lastValue) = getLastUpdateDetailsUnsafe(dataFeedId); if (!_validateLastUpdateDetailsOnRead(dataFeedId, lastDataTimestamp, lastBlockTimestamp, lastValue)) { revert InvalidLastUpdateDetails(dataFeedId, lastDataTimestamp, lastBlockTimestamp, lastValue); } } function getLastUpdateDetailsUnsafe(bytes32 dataFeedId) public view virtual returns (uint256 lastDataTimestamp, uint256 lastBlockTimestamp, uint256 lastValue) { DataFeedDetailsWithOptionalBigValue storage dataFeed = _getDataFeedsStorage()._dataFeeds[dataFeedId]; lastDataTimestamp = dataFeed.details.dataTimestamp; lastBlockTimestamp = dataFeed.details.blockTimestamp; if (dataFeed.details.isValueBigger) { lastValue = dataFeed.biggerValue; } else { lastValue = dataFeed.details.value; } } function _getDataFeedsStorage() private pure returns (DataFeedsStorage storage $) { assembly { $.slot := DATA_FEEDS_STORAGE_LOCATION } } /// This function can be used to implement time-based whitelisting (e.g. whitelisting for only X seconds after the latest update) /// Important! This function should not revert, it should only return bool result of the validation function _validateBlockTimestamp(uint256 lastBlockTimestamp) internal view virtual returns (bool) { // In the default implementation we just check if the block number is higher // To ensure max 1 update for a given data feed in a block return block.timestamp > lastBlockTimestamp; } /// Important! This function should not revert, it should only return bool result of the validation function _validateDataTimestamp(uint256 proposedDataTimestamp, uint256 lastDataTimestamp) internal view virtual returns (bool) { return proposedDataTimestamp > lastDataTimestamp; } /// Important! This function should not revert, it should only return bool result of the validation /// It can be overridden to handle more specific logic in future function _validateValueBeforeSave(bytes32 /* dataFeedId */, uint256 proposedValue, uint256 /* lastValue */) internal view virtual returns (bool) { return proposedValue > 0; } /// This function can be overridden (e.g. value validation and staleness check) /// We've added dataFeedId for being able to implement custom validation per feed function _validateLastUpdateDetailsOnRead(bytes32 /* dataFeedId */, uint256 /* lastDataTimestamp */, uint256 lastBlockTimestamp, uint256 lastValue) internal view virtual returns (bool) { return lastValue > 0 && lastBlockTimestamp + MAX_DATA_STALENESS > block.timestamp; } /// Important! This function should not revert, it should only emit an event /// It is a separate function, so that we can specify custom events for specific data feeds function _emitEventAfterValueUpdate(bytes32 dataFeedId, uint256 newValue) internal virtual { emit ValueUpdate(newValue, dataFeedId, block.timestamp); } //////////////////////////////////////////////////// /////////// Functions for relayers below /////////// //////////////////////////////////////////////////// function getLastUpdateDetailsUnsafeForMany(bytes32[] memory dataFeedIds) external view returns (LastUpdateDetails[] memory detailsForFeeds) { detailsForFeeds = new LastUpdateDetails[](dataFeedIds.length); for (uint256 i = 0; i < dataFeedIds.length;) { (detailsForFeeds[i].dataTimestamp, detailsForFeeds[i].blockTimestamp, detailsForFeeds[i].value) = getLastUpdateDetailsUnsafe(dataFeedIds[i]); unchecked { i++; } // reduces gas costs } } function getValuesForDataFeeds(bytes32[] memory requestedDataFeedIds) external view returns (uint256[] memory values) { values = new uint256[](requestedDataFeedIds.length); for (uint256 i = 0; i < requestedDataFeedIds.length;) { values[i] = getValueForDataFeed(requestedDataFeedIds[i]); unchecked { i++; } // reduces gas costs } } function getValueForDataFeed(bytes32 dataFeedId) public view virtual returns (uint256 dataFeedValue) { (,, dataFeedValue) = getLastUpdateDetails(dataFeedId); } function getDataTimestampFromLatestUpdate(bytes32 dataFeedId) external view virtual returns (uint256 lastDataTimestamp) { (lastDataTimestamp, ,) = getLastUpdateDetails(dataFeedId); } function getBlockTimestampFromLatestUpdate(bytes32 dataFeedId) external view virtual returns (uint256 blockTimestamp) { (, blockTimestamp, ) = getLastUpdateDetails(dataFeedId); } /////////////////////////////////////////////////////// //////////// LayerBank interface functions //////////// /////////////////////////////////////////////////////// /// We can connect manager contract here or implement it directly here /// By default, users will be able to use data feed identifiers (casted to addresses) in layerbank functions function getDataFeedIdForAsset(address asset) public view virtual returns(bytes32) { return bytes32(uint256(uint160(asset))); } function convertDecimals(bytes32 /* dataFeedId */, uint256 valueFromRedstonePayload) public view virtual returns (uint256) { return valueFromRedstonePayload * DEFAULT_DECIMAL_SCALER_LAYERBANK; } function getUnderlyingAsset(address gToken) public view virtual returns(address) { return ILToken(gToken).underlying(); } function priceOf(address asset) public view virtual returns (uint256) { bytes32 dataFeedId = getDataFeedIdForAsset(asset); uint256 latestValue = getValueForDataFeed(dataFeedId); return convertDecimals(dataFeedId, latestValue); } function priceOfETH() public view virtual returns (uint256) { return convertDecimals(ETH_DATA_FEED_ID, getValueForDataFeed(ETH_DATA_FEED_ID)); } function pricesOf( address[] memory assets ) external view returns (uint256[] memory values) { values = new uint256[](assets.length); for (uint256 i = 0; i < assets.length;) { values[i] = priceOf(assets[i]); unchecked { i++; } // reduces gas costs } } function getUnderlyingPrice(address gToken) public view returns (uint256) { return priceOf(getUnderlyingAsset(gToken)); } function getUnderlyingPrices( address[] memory gTokens ) public view returns (uint256[] memory values) { values = new uint256[](gTokens.length); for (uint256 i = 0; i < gTokens.length;) { values[i] = getUnderlyingPrice(gTokens[i]); unchecked { i++; } // reduces gas costs } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.4; library OldGelatoAddress { address constant public ADDR = 0xc4D1AE5E796E6d7561cdc8335F85e6B57a36e097; } library GelatoAddress { address constant public ADDR = 0xCD6BfDA4D95d5C0f3f2882dC221D792392c99714; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.17; import {OldGelatoAddress, GelatoAddress} from "../__addresses/Addresses.sol"; import {MultiFeedAdapterWithoutRoundsPrimaryProd} from "@redstone-finance/on-chain-relayer/contracts/price-feeds/data-services/MultiFeedAdapterWithoutRoundsPrimaryProd.sol"; contract EthereumMultiFeedAdapterWithoutRoundsV2 is MultiFeedAdapterWithoutRoundsPrimaryProd { address internal constant MAIN_UPDATER_ADDRESS = 0x6809b95622B2dcC53d2F3Fb2301B36F6a8c5B584; address internal constant FALLBACK_UPDATER_ADDRESS = 0x12c88f64e5E35393D38255aB42858010Cbd72eBd; address internal constant MANUAL_UPDATER_ADDRESS = 0x9E7CaAb1924A7e5Bb4305dFd843194B5E19480D3; function _validateBlockTimestamp( uint256 lastBlockTimestamp ) internal view virtual override returns (bool) { if ( msg.sender == MAIN_UPDATER_ADDRESS || msg.sender == FALLBACK_UPDATER_ADDRESS || msg.sender == MANUAL_UPDATER_ADDRESS || msg.sender == GelatoAddress.ADDR || msg.sender == OldGelatoAddress.ADDR ) { // For whitelisted addresses we only require a newer block return block.timestamp > lastBlockTimestamp; } else { // For non-whitelisted addresses we require some time to pass after the latest update return block.timestamp > lastBlockTimestamp + 40 seconds; } } }