Transaction Hash:
Block:
18051538 at Sep-02-2023 09:35:35 PM +UTC
Transaction Fee:
0.001066031790183984 ETH
$2.00
Gas Used:
93,264 Gas / 11.430260231 Gwei
Emitted Events:
180 |
BaseRegistrarImplementation.NameRenewed( id=53277922743354683211652130885209810119066621109545752768215263771235607744142, expires=1722648795 )
|
181 |
ETHRegistrarController.NameRenewed( name=apeperare, label=75CA3C535AE192851E1F0C7DDBBBCF2C11CAE016E3D298AEEC693C5A1D598E8E, cost=3121060426181226, expires=1722648795 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x0645B87d...86C184CB0 |
0.012379397256693234 Eth
Nonce: 32
|
0.008253502303586479 Eth
Nonce: 33
| 0.004125894953106755 | ||
0x1f9090aa...8e676c326
Miner
| 2.864345303749192744 Eth | 2.864354630149192744 Eth | 0.0000093264 | ||
0x25355336...0C782303b | (ENS: ETH Registrar Controller) | 20.403861200220349409 Eth | 20.40692106338327218 Eth | 0.003059863162922771 | |
0x57f1887a...Af147eA85 |
Execution Trace
ETH 0.003121060426181226
ETHRegistrarController.renew( name=apeperare, duration=31536000 )
-
BaseRegistrarImplementation.nameExpires( id=53277922743354683211652130885209810119066621109545752768215263771235607744142 ) => ( 1691112795 )
ExponentialPremiumPriceOracle.price( name=apeperare, expires=1691112795, duration=31536000 ) => ( [{name:base, type:uint256, order:1, indexed:false, value:3059863162922771, valueString:3059863162922771}, {name:premium, type:uint256, order:2, indexed:false, value:0, valueString:0}] )
EACAggregatorProxy.STATICCALL( )
-
AccessControlledOffchainAggregator.STATICCALL( )
-
EACAggregatorProxy.STATICCALL( )
-
AccessControlledOffchainAggregator.STATICCALL( )
-
NameWrapper.renew( tokenId=53277922743354683211652130885209810119066621109545752768215263771235607744142, duration=31536000 ) => ( expires=1722648795 )
BaseRegistrarImplementation.renew( id=53277922743354683211652130885209810119066621109545752768215263771235607744142, duration=31536000 ) => ( 1722648795 )
-
ENSRegistryWithFallback.owner( node=93CDEB708B7545DC668EB9280176169D1C33CFD8ED6F04690A0BCC88A93FC4AE ) => ( 0x57f1887a8BF19b14fC0dF6Fd9B2acc9Af147eA85 )
-
-
BaseRegistrarImplementation.ownerOf( tokenId=53277922743354683211652130885209810119066621109545752768215263771235607744142 ) => ( 0x0645B87d9DA24a42Fa73234555Df93486C184CB0 )
- ETH 0.000061197263258455
0x0645b87d9da24a42fa73234555df93486c184cb0.CALL( )
renew[ETHRegistrarController (ln:1912)]
InsufficientValue[ETHRegistrarController (ln:1920)]
renew[ETHRegistrarController (ln:1922)]
transfer[ETHRegistrarController (ln:1924)]
payable[ETHRegistrarController (ln:1924)]
NameRenewed[ETHRegistrarController (ln:1926)]
File 1 of 7: ETHRegistrarController
File 2 of 7: BaseRegistrarImplementation
File 3 of 7: ExponentialPremiumPriceOracle
File 4 of 7: EACAggregatorProxy
File 5 of 7: AccessControlledOffchainAggregator
File 6 of 7: NameWrapper
File 7 of 7: ENSRegistryWithFallback
// 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.7.0) (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @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 amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` 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 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.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}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => 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 override returns (uint256) { require(owner != address(0), "ERC721: address zero is not a valid owner"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _ownerOf(tokenId); require(owner != address(0), "ERC721: invalid token ID"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _requireMinted(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(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 override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not token owner or approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { _requireMinted(tokenId); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _safeTransfer(from, to, tokenId, data); } /** * @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. * * `data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - 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, bytes memory data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist */ function _ownerOf(uint256 tokenId) internal view virtual returns (address) { return _owners[tokenId]; } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _ownerOf(tokenId) != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * 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 virtual { _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); require( _checkOnERC721Received(address(0), to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @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 virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId, 1); // Check that tokenId was not minted by `_beforeTokenTransfer` hook require(!_exists(tokenId), "ERC721: token already minted"); unchecked { // Will not overflow unless all 2**256 token ids are minted to the same owner. // Given that tokens are minted one by one, it is impossible in practice that // this ever happens. Might change if we allow batch minting. // The ERC fails to describe this case. _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId, 1); } /** * @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 virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook owner = ERC721.ownerOf(tokenId); // Clear approvals delete _tokenApprovals[tokenId]; unchecked { // Cannot overflow, as that would require more tokens to be burned/transferred // out than the owner initially received through minting and transferring in. _balances[owner] -= 1; } delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId, 1); } /** * @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 virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId, 1); // Check that tokenId was not transferred by `_beforeTokenTransfer` hook require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); // Clear approvals from the previous owner delete _tokenApprovals[tokenId]; unchecked { // `_balances[from]` cannot overflow for the same reason as described in `_burn`: // `from`'s balance is the number of token held, which is at least one before the current // transfer. // `_balances[to]` could overflow in the conditions described in `_mint`. That would require // all 2**256 token ids to be minted, which in practice is impossible. _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits an {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Reverts if the `tokenId` has not been minted yet. */ function _requireMinted(uint256 tokenId) internal view virtual { require(_exists(tokenId), "ERC721: invalid token ID"); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * 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 * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { /// @solidity memory-safe-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`. * - When `from` is zero, the tokens will be minted for `to`. * - When `to` is zero, ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * - `batchSize` is non-zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256, /* firstTokenId */ uint256 batchSize ) internal virtual { if (batchSize > 1) { if (from != address(0)) { _balances[from] -= batchSize; } if (to != address(0)) { _balances[to] += batchSize; } } } /** * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`. * - When `from` is zero, the tokens were minted for `to`. * - When `to` is zero, ``from``'s tokens were burned. * - `from` and `to` are never both zero. * - `batchSize` is non-zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../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 caller. * * 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../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); } // 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.8.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @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), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @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) { 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] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./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); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @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 up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (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; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 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. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); 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 (rounding == Rounding.Up && 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 down. * * 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * 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 + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * 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 10, 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 + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } } pragma solidity >=0.8.4; import "../registry/ENS.sol"; import "./IBaseRegistrar.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract BaseRegistrarImplementation is ERC721, IBaseRegistrar, Ownable { // A map of expiry times mapping(uint256 => uint256) expiries; // The ENS registry ENS public ens; // The namehash of the TLD this registrar owns (eg, .eth) bytes32 public baseNode; // A map of addresses that are authorised to register and renew names. mapping(address => bool) public controllers; uint256 public constant GRACE_PERIOD = 90 days; bytes4 private constant INTERFACE_META_ID = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 private constant ERC721_ID = bytes4( keccak256("balanceOf(address)") ^ keccak256("ownerOf(uint256)") ^ keccak256("approve(address,uint256)") ^ keccak256("getApproved(uint256)") ^ keccak256("setApprovalForAll(address,bool)") ^ keccak256("isApprovedForAll(address,address)") ^ keccak256("transferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256,bytes)") ); bytes4 private constant RECLAIM_ID = bytes4(keccak256("reclaim(uint256,address)")); /** * v2.1.3 version of _isApprovedOrOwner which calls ownerOf(tokenId) and takes grace period into consideration instead of ERC721.ownerOf(tokenId); * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.1.3/contracts/token/ERC721/ERC721.sol#L187 * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view override returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } constructor(ENS _ens, bytes32 _baseNode) ERC721("", "") { ens = _ens; baseNode = _baseNode; } modifier live() { require(ens.owner(baseNode) == address(this)); _; } modifier onlyController() { require(controllers[msg.sender]); _; } /** * @dev Gets the owner of the specified token ID. Names become unowned * when their registration expires. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf( uint256 tokenId ) public view override(IERC721, ERC721) returns (address) { require(expiries[tokenId] > block.timestamp); return super.ownerOf(tokenId); } // Authorises a controller, who can register and renew domains. function addController(address controller) external override onlyOwner { controllers[controller] = true; emit ControllerAdded(controller); } // Revoke controller permission for an address. function removeController(address controller) external override onlyOwner { controllers[controller] = false; emit ControllerRemoved(controller); } // Set the resolver for the TLD this registrar manages. function setResolver(address resolver) external override onlyOwner { ens.setResolver(baseNode, resolver); } // Returns the expiration timestamp of the specified id. function nameExpires(uint256 id) external view override returns (uint256) { return expiries[id]; } // Returns true iff the specified name is available for registration. function available(uint256 id) public view override returns (bool) { // Not available if it's registered here or in its grace period. return expiries[id] + GRACE_PERIOD < block.timestamp; } /** * @dev Register a name. * @param id The token ID (keccak256 of the label). * @param owner The address that should own the registration. * @param duration Duration in seconds for the registration. */ function register( uint256 id, address owner, uint256 duration ) external override returns (uint256) { return _register(id, owner, duration, true); } /** * @dev Register a name, without modifying the registry. * @param id The token ID (keccak256 of the label). * @param owner The address that should own the registration. * @param duration Duration in seconds for the registration. */ function registerOnly( uint256 id, address owner, uint256 duration ) external returns (uint256) { return _register(id, owner, duration, false); } function _register( uint256 id, address owner, uint256 duration, bool updateRegistry ) internal live onlyController returns (uint256) { require(available(id)); require( block.timestamp + duration + GRACE_PERIOD > block.timestamp + GRACE_PERIOD ); // Prevent future overflow expiries[id] = block.timestamp + duration; if (_exists(id)) { // Name was previously owned, and expired _burn(id); } _mint(owner, id); if (updateRegistry) { ens.setSubnodeOwner(baseNode, bytes32(id), owner); } emit NameRegistered(id, owner, block.timestamp + duration); return block.timestamp + duration; } function renew( uint256 id, uint256 duration ) external override live onlyController returns (uint256) { require(expiries[id] + GRACE_PERIOD >= block.timestamp); // Name must be registered here or in grace period require( expiries[id] + duration + GRACE_PERIOD > duration + GRACE_PERIOD ); // Prevent future overflow expiries[id] += duration; emit NameRenewed(id, expiries[id]); return expiries[id]; } /** * @dev Reclaim ownership of a name in ENS, if you own it in the registrar. */ function reclaim(uint256 id, address owner) external override live { require(_isApprovedOrOwner(msg.sender, id)); ens.setSubnodeOwner(baseNode, bytes32(id), owner); } function supportsInterface( bytes4 interfaceID ) public view override(ERC721, IERC165) returns (bool) { return interfaceID == INTERFACE_META_ID || interfaceID == ERC721_ID || interfaceID == RECLAIM_ID; } } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import {BaseRegistrarImplementation} from "./BaseRegistrarImplementation.sol"; import {StringUtils} from "./StringUtils.sol"; import {Resolver} from "../resolvers/Resolver.sol"; import {ENS} from "../registry/ENS.sol"; import {ReverseRegistrar} from "../reverseRegistrar/ReverseRegistrar.sol"; import {ReverseClaimer} from "../reverseRegistrar/ReverseClaimer.sol"; import {IETHRegistrarController, IPriceOracle} from "./IETHRegistrarController.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {INameWrapper} from "../wrapper/INameWrapper.sol"; import {ERC20Recoverable} from "../utils/ERC20Recoverable.sol"; error CommitmentTooNew(bytes32 commitment); error CommitmentTooOld(bytes32 commitment); error NameNotAvailable(string name); error DurationTooShort(uint256 duration); error ResolverRequiredWhenDataSupplied(); error UnexpiredCommitmentExists(bytes32 commitment); error InsufficientValue(); error Unauthorised(bytes32 node); error MaxCommitmentAgeTooLow(); error MaxCommitmentAgeTooHigh(); /** * @dev A registrar controller for registering and renewing names at fixed cost. */ contract ETHRegistrarController is Ownable, IETHRegistrarController, IERC165, ERC20Recoverable, ReverseClaimer { using StringUtils for *; using Address for address; uint256 public constant MIN_REGISTRATION_DURATION = 28 days; bytes32 private constant ETH_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; uint64 private constant MAX_EXPIRY = type(uint64).max; BaseRegistrarImplementation immutable base; IPriceOracle public immutable prices; uint256 public immutable minCommitmentAge; uint256 public immutable maxCommitmentAge; ReverseRegistrar public immutable reverseRegistrar; INameWrapper public immutable nameWrapper; mapping(bytes32 => uint256) public commitments; event NameRegistered( string name, bytes32 indexed label, address indexed owner, uint256 baseCost, uint256 premium, uint256 expires ); event NameRenewed( string name, bytes32 indexed label, uint256 cost, uint256 expires ); constructor( BaseRegistrarImplementation _base, IPriceOracle _prices, uint256 _minCommitmentAge, uint256 _maxCommitmentAge, ReverseRegistrar _reverseRegistrar, INameWrapper _nameWrapper, ENS _ens ) ReverseClaimer(_ens, msg.sender) { if (_maxCommitmentAge <= _minCommitmentAge) { revert MaxCommitmentAgeTooLow(); } if (_maxCommitmentAge > block.timestamp) { revert MaxCommitmentAgeTooHigh(); } base = _base; prices = _prices; minCommitmentAge = _minCommitmentAge; maxCommitmentAge = _maxCommitmentAge; reverseRegistrar = _reverseRegistrar; nameWrapper = _nameWrapper; } function rentPrice( string memory name, uint256 duration ) public view override returns (IPriceOracle.Price memory price) { bytes32 label = keccak256(bytes(name)); price = prices.price(name, base.nameExpires(uint256(label)), duration); } function valid(string memory name) public pure returns (bool) { return name.strlen() >= 3; } function available(string memory name) public view override returns (bool) { bytes32 label = keccak256(bytes(name)); return valid(name) && base.available(uint256(label)); } function makeCommitment( string memory name, address owner, uint256 duration, bytes32 secret, address resolver, bytes[] calldata data, bool reverseRecord, uint16 ownerControlledFuses ) public pure override returns (bytes32) { bytes32 label = keccak256(bytes(name)); if (data.length > 0 && resolver == address(0)) { revert ResolverRequiredWhenDataSupplied(); } return keccak256( abi.encode( label, owner, duration, secret, resolver, data, reverseRecord, ownerControlledFuses ) ); } function commit(bytes32 commitment) public override { if (commitments[commitment] + maxCommitmentAge >= block.timestamp) { revert UnexpiredCommitmentExists(commitment); } commitments[commitment] = block.timestamp; } function register( string calldata name, address owner, uint256 duration, bytes32 secret, address resolver, bytes[] calldata data, bool reverseRecord, uint16 ownerControlledFuses ) public payable override { IPriceOracle.Price memory price = rentPrice(name, duration); if (msg.value < price.base + price.premium) { revert InsufficientValue(); } _consumeCommitment( name, duration, makeCommitment( name, owner, duration, secret, resolver, data, reverseRecord, ownerControlledFuses ) ); uint256 expires = nameWrapper.registerAndWrapETH2LD( name, owner, duration, resolver, ownerControlledFuses ); if (data.length > 0) { _setRecords(resolver, keccak256(bytes(name)), data); } if (reverseRecord) { _setReverseRecord(name, resolver, msg.sender); } emit NameRegistered( name, keccak256(bytes(name)), owner, price.base, price.premium, expires ); if (msg.value > (price.base + price.premium)) { payable(msg.sender).transfer( msg.value - (price.base + price.premium) ); } } function renew( string calldata name, uint256 duration ) external payable override { bytes32 labelhash = keccak256(bytes(name)); uint256 tokenId = uint256(labelhash); IPriceOracle.Price memory price = rentPrice(name, duration); if (msg.value < price.base) { revert InsufficientValue(); } uint256 expires = nameWrapper.renew(tokenId, duration); if (msg.value > price.base) { payable(msg.sender).transfer(msg.value - price.base); } emit NameRenewed(name, labelhash, msg.value, expires); } function withdraw() public { payable(owner()).transfer(address(this).balance); } function supportsInterface( bytes4 interfaceID ) external pure returns (bool) { return interfaceID == type(IERC165).interfaceId || interfaceID == type(IETHRegistrarController).interfaceId; } /* Internal functions */ function _consumeCommitment( string memory name, uint256 duration, bytes32 commitment ) internal { // Require an old enough commitment. if (commitments[commitment] + minCommitmentAge > block.timestamp) { revert CommitmentTooNew(commitment); } // If the commitment is too old, or the name is registered, stop if (commitments[commitment] + maxCommitmentAge <= block.timestamp) { revert CommitmentTooOld(commitment); } if (!available(name)) { revert NameNotAvailable(name); } delete (commitments[commitment]); if (duration < MIN_REGISTRATION_DURATION) { revert DurationTooShort(duration); } } function _setRecords( address resolverAddress, bytes32 label, bytes[] calldata data ) internal { // use hardcoded .eth namehash bytes32 nodehash = keccak256(abi.encodePacked(ETH_NODE, label)); Resolver resolver = Resolver(resolverAddress); resolver.multicallWithNodeCheck(nodehash, data); } function _setReverseRecord( string memory name, address resolver, address owner ) internal { reverseRegistrar.setNameForAddr( msg.sender, owner, resolver, string.concat(name, ".eth") ); } } import "../registry/ENS.sol"; import "./IBaseRegistrar.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IBaseRegistrar is IERC721 { event ControllerAdded(address indexed controller); event ControllerRemoved(address indexed controller); event NameMigrated( uint256 indexed id, address indexed owner, uint256 expires ); event NameRegistered( uint256 indexed id, address indexed owner, uint256 expires ); event NameRenewed(uint256 indexed id, uint256 expires); // Authorises a controller, who can register and renew domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Set the resolver for the TLD this registrar manages. function setResolver(address resolver) external; // Returns the expiration timestamp of the specified label hash. function nameExpires(uint256 id) external view returns (uint256); // Returns true iff the specified name is available for registration. function available(uint256 id) external view returns (bool); /** * @dev Register a name. */ function register( uint256 id, address owner, uint256 duration ) external returns (uint256); function renew(uint256 id, uint256 duration) external returns (uint256); /** * @dev Reclaim ownership of a name in ENS, if you own it in the registrar. */ function reclaim(uint256 id, address owner) external; } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "./IPriceOracle.sol"; interface IETHRegistrarController { function rentPrice( string memory, uint256 ) external view returns (IPriceOracle.Price memory); function available(string memory) external returns (bool); function makeCommitment( string memory, address, uint256, bytes32, address, bytes[] calldata, bool, uint16 ) external pure returns (bytes32); function commit(bytes32) external; function register( string calldata, address, uint256, bytes32, address, bytes[] calldata, bool, uint16 ) external payable; function renew(string calldata, uint256) external payable; } //SPDX-License-Identifier: MIT pragma solidity >=0.8.17 <0.9.0; interface IPriceOracle { struct Price { uint256 base; uint256 premium; } /** * @dev Returns the price to register or renew a name. * @param name The name being registered or renewed. * @param expires When the name presently expires (0 if this is a new registration). * @param duration How long the name is being registered or extended for, in seconds. * @return base premium tuple of base price + premium price */ function price( string calldata name, uint256 expires, uint256 duration ) external view returns (Price calldata); } pragma solidity >=0.8.4; library StringUtils { /** * @dev Returns the length of a given string * * @param s The string to measure the length of * @return The length of the input string */ function strlen(string memory s) internal pure returns (uint256) { uint256 len; uint256 i = 0; uint256 bytelength = bytes(s).length; for (len = 0; i < bytelength; len++) { bytes1 b = bytes(s)[i]; if (b < 0x80) { i += 1; } else if (b < 0xE0) { i += 2; } else if (b < 0xF0) { i += 3; } else if (b < 0xF8) { i += 4; } else if (b < 0xFC) { i += 5; } else { i += 6; } } return len; } } pragma solidity >=0.8.4; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setSubnodeRecord( bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl ) external; function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external returns (bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll( address owner, address operator ) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "./profiles/IABIResolver.sol"; import "./profiles/IAddressResolver.sol"; import "./profiles/IAddrResolver.sol"; import "./profiles/IContentHashResolver.sol"; import "./profiles/IDNSRecordResolver.sol"; import "./profiles/IDNSZoneResolver.sol"; import "./profiles/IInterfaceResolver.sol"; import "./profiles/INameResolver.sol"; import "./profiles/IPubkeyResolver.sol"; import "./profiles/ITextResolver.sol"; import "./profiles/IExtendedResolver.sol"; /** * A generic resolver interface which includes all the functions including the ones deprecated */ interface Resolver is IERC165, IABIResolver, IAddressResolver, IAddrResolver, IContentHashResolver, IDNSRecordResolver, IDNSZoneResolver, IInterfaceResolver, INameResolver, IPubkeyResolver, ITextResolver, IExtendedResolver { /* Deprecated events */ event ContentChanged(bytes32 indexed node, bytes32 hash); function setApprovalForAll(address, bool) external; function approve(bytes32 node, address delegate, bool approved) external; function isApprovedForAll(address account, address operator) external; function isApprovedFor( address owner, bytes32 node, address delegate ) external; function setABI( bytes32 node, uint256 contentType, bytes calldata data ) external; function setAddr(bytes32 node, address addr) external; function setAddr(bytes32 node, uint256 coinType, bytes calldata a) external; function setContenthash(bytes32 node, bytes calldata hash) external; function setDnsrr(bytes32 node, bytes calldata data) external; function setName(bytes32 node, string calldata _name) external; function setPubkey(bytes32 node, bytes32 x, bytes32 y) external; function setText( bytes32 node, string calldata key, string calldata value ) external; function setInterface( bytes32 node, bytes4 interfaceID, address implementer ) external; function multicall( bytes[] calldata data ) external returns (bytes[] memory results); function multicallWithNodeCheck( bytes32 nodehash, bytes[] calldata data ) external returns (bytes[] memory results); /* Deprecated functions */ function content(bytes32 node) external view returns (bytes32); function multihash(bytes32 node) external view returns (bytes memory); function setContent(bytes32 node, bytes32 hash) external; function setMultihash(bytes32 node, bytes calldata hash) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IABIResolver { event ABIChanged(bytes32 indexed node, uint256 indexed contentType); /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI( bytes32 node, uint256 contentTypes ) external view returns (uint256, bytes memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /** * Interface for the legacy (ETH-only) addr function. */ interface IAddrResolver { event AddrChanged(bytes32 indexed node, address a); /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) external view returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /** * Interface for the new (multicoin) addr function. */ interface IAddressResolver { event AddressChanged( bytes32 indexed node, uint256 coinType, bytes newAddress ); function addr( bytes32 node, uint256 coinType ) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IContentHashResolver { event ContenthashChanged(bytes32 indexed node, bytes hash); /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IDNSRecordResolver { // DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated. event DNSRecordChanged( bytes32 indexed node, bytes name, uint16 resource, bytes record ); // DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted. event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource); /** * Obtain a DNS record. * @param node the namehash of the node for which to fetch the record * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types * @return the DNS record in wire format if present, otherwise empty */ function dnsRecord( bytes32 node, bytes32 name, uint16 resource ) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IDNSZoneResolver { // DNSZonehashChanged is emitted whenever a given node's zone hash is updated. event DNSZonehashChanged( bytes32 indexed node, bytes lastzonehash, bytes zonehash ); /** * zonehash obtains the hash for the zone. * @param node The ENS node to query. * @return The associated contenthash. */ function zonehash(bytes32 node) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IExtendedResolver { function resolve( bytes memory name, bytes memory data ) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IInterfaceResolver { event InterfaceChanged( bytes32 indexed node, bytes4 indexed interfaceID, address implementer ); /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 165 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer( bytes32 node, bytes4 interfaceID ) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface INameResolver { event NameChanged(bytes32 indexed node, string name); /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface IPubkeyResolver { event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x The X coordinate of the curve point for the public key. * @return y The Y coordinate of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; interface ITextResolver { event TextChanged( bytes32 indexed node, string indexed indexedKey, string key, string value ); /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text( bytes32 node, string calldata key ) external view returns (string memory); } pragma solidity >=0.8.4; interface IReverseRegistrar { function setDefaultResolver(address resolver) external; function claim(address owner) external returns (bytes32); function claimForAddr( address addr, address owner, address resolver ) external returns (bytes32); function claimWithResolver( address owner, address resolver ) external returns (bytes32); function setName(string memory name) external returns (bytes32); function setNameForAddr( address addr, address owner, address resolver, string memory name ) external returns (bytes32); function node(address addr) external pure returns (bytes32); } //SPDX-License-Identifier: MIT pragma solidity >=0.8.17 <0.9.0; import {ENS} from "../registry/ENS.sol"; import {IReverseRegistrar} from "../reverseRegistrar/IReverseRegistrar.sol"; contract ReverseClaimer { bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; constructor(ENS ens, address claimant) { IReverseRegistrar reverseRegistrar = IReverseRegistrar( ens.owner(ADDR_REVERSE_NODE) ); reverseRegistrar.claim(claimant); } } pragma solidity >=0.8.4; import "../registry/ENS.sol"; import "./IReverseRegistrar.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../root/Controllable.sol"; abstract contract NameResolver { function setName(bytes32 node, string memory name) public virtual; } bytes32 constant lookup = 0x3031323334353637383961626364656600000000000000000000000000000000; bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; // namehash('addr.reverse') contract ReverseRegistrar is Ownable, Controllable, IReverseRegistrar { ENS public immutable ens; NameResolver public defaultResolver; event ReverseClaimed(address indexed addr, bytes32 indexed node); event DefaultResolverChanged(NameResolver indexed resolver); /** * @dev Constructor * @param ensAddr The address of the ENS registry. */ constructor(ENS ensAddr) { ens = ensAddr; // Assign ownership of the reverse record to our deployer ReverseRegistrar oldRegistrar = ReverseRegistrar( ensAddr.owner(ADDR_REVERSE_NODE) ); if (address(oldRegistrar) != address(0x0)) { oldRegistrar.claim(msg.sender); } } modifier authorised(address addr) { require( addr == msg.sender || controllers[msg.sender] || ens.isApprovedForAll(addr, msg.sender) || ownsContract(addr), "ReverseRegistrar: Caller is not a controller or authorised by address or the address itself" ); _; } function setDefaultResolver(address resolver) public override onlyOwner { require( address(resolver) != address(0), "ReverseRegistrar: Resolver address must not be 0" ); defaultResolver = NameResolver(resolver); emit DefaultResolverChanged(NameResolver(resolver)); } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param owner The address to set as the owner of the reverse record in ENS. * @return The ENS node hash of the reverse record. */ function claim(address owner) public override returns (bytes32) { return claimForAddr(msg.sender, owner, address(defaultResolver)); } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param addr The reverse record to set * @param owner The address to set as the owner of the reverse record in ENS. * @param resolver The resolver of the reverse node * @return The ENS node hash of the reverse record. */ function claimForAddr( address addr, address owner, address resolver ) public override authorised(addr) returns (bytes32) { bytes32 labelHash = sha3HexAddress(addr); bytes32 reverseNode = keccak256( abi.encodePacked(ADDR_REVERSE_NODE, labelHash) ); emit ReverseClaimed(addr, reverseNode); ens.setSubnodeRecord(ADDR_REVERSE_NODE, labelHash, owner, resolver, 0); return reverseNode; } /** * @dev Transfers ownership of the reverse ENS record associated with the * calling account. * @param owner The address to set as the owner of the reverse record in ENS. * @param resolver The address of the resolver to set; 0 to leave unchanged. * @return The ENS node hash of the reverse record. */ function claimWithResolver( address owner, address resolver ) public override returns (bytes32) { return claimForAddr(msg.sender, owner, resolver); } /** * @dev Sets the `name()` record for the reverse ENS record associated with * the calling account. First updates the resolver to the default reverse * resolver if necessary. * @param name The name to set for this address. * @return The ENS node hash of the reverse record. */ function setName(string memory name) public override returns (bytes32) { return setNameForAddr( msg.sender, msg.sender, address(defaultResolver), name ); } /** * @dev Sets the `name()` record for the reverse ENS record associated with * the account provided. Updates the resolver to a designated resolver * Only callable by controllers and authorised users * @param addr The reverse record to set * @param owner The owner of the reverse node * @param resolver The resolver of the reverse node * @param name The name to set for this address. * @return The ENS node hash of the reverse record. */ function setNameForAddr( address addr, address owner, address resolver, string memory name ) public override returns (bytes32) { bytes32 node = claimForAddr(addr, owner, resolver); NameResolver(resolver).setName(node, name); return node; } /** * @dev Returns the node hash for a given account's reverse records. * @param addr The address to hash * @return The ENS node hash. */ function node(address addr) public pure override returns (bytes32) { return keccak256( abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr)) ); } /** * @dev An optimised function to compute the sha3 of the lower-case * hexadecimal representation of an Ethereum address. * @param addr The address to hash * @return ret The SHA3 hash of the lower-case hexadecimal encoding of the * input address. */ function sha3HexAddress(address addr) private pure returns (bytes32 ret) { assembly { for { let i := 40 } gt(i, 0) { } { i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) } ret := keccak256(0, 40) } } function ownsContract(address addr) internal view returns (bool) { try Ownable(addr).owner() returns (address owner) { return owner == msg.sender; } catch { return false; } } } pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; contract Controllable is Ownable { mapping(address => bool) public controllers; event ControllerChanged(address indexed controller, bool enabled); modifier onlyController() { require( controllers[msg.sender], "Controllable: Caller is not a controller" ); _; } function setController(address controller, bool enabled) public onlyOwner { controllers[controller] = enabled; emit ControllerChanged(controller, enabled); } } //SPDX-License-Identifier: MIT pragma solidity >=0.8.17 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @notice Contract is used to recover ERC20 tokens sent to the contract by mistake. */ contract ERC20Recoverable is Ownable { /** @notice Recover ERC20 tokens sent to the contract by mistake. @dev The contract is Ownable and only the owner can call the recover function. @param _to The address to send the tokens to. @param _token The address of the ERC20 token to recover @param _amount The amount of tokens to recover. */ function recoverFunds( address _token, address _to, uint256 _amount ) external onlyOwner { IERC20(_token).transfer(_to, _amount); } } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; interface IMetadataService { function uri(uint256) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "../registry/ENS.sol"; import "../ethregistrar/IBaseRegistrar.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "./IMetadataService.sol"; import "./INameWrapperUpgrade.sol"; uint32 constant CANNOT_UNWRAP = 1; uint32 constant CANNOT_BURN_FUSES = 2; uint32 constant CANNOT_TRANSFER = 4; uint32 constant CANNOT_SET_RESOLVER = 8; uint32 constant CANNOT_SET_TTL = 16; uint32 constant CANNOT_CREATE_SUBDOMAIN = 32; uint32 constant CANNOT_APPROVE = 64; //uint16 reserved for parent controlled fuses from bit 17 to bit 32 uint32 constant PARENT_CANNOT_CONTROL = 1 << 16; uint32 constant IS_DOT_ETH = 1 << 17; uint32 constant CAN_EXTEND_EXPIRY = 1 << 18; uint32 constant CAN_DO_EVERYTHING = 0; uint32 constant PARENT_CONTROLLED_FUSES = 0xFFFF0000; // all fuses apart from IS_DOT_ETH uint32 constant USER_SETTABLE_FUSES = 0xFFFDFFFF; interface INameWrapper is IERC1155 { event NameWrapped( bytes32 indexed node, bytes name, address owner, uint32 fuses, uint64 expiry ); event NameUnwrapped(bytes32 indexed node, address owner); event FusesSet(bytes32 indexed node, uint32 fuses); event ExpiryExtended(bytes32 indexed node, uint64 expiry); function ens() external view returns (ENS); function registrar() external view returns (IBaseRegistrar); function metadataService() external view returns (IMetadataService); function names(bytes32) external view returns (bytes memory); function name() external view returns (string memory); function upgradeContract() external view returns (INameWrapperUpgrade); function supportsInterface(bytes4 interfaceID) external view returns (bool); function wrap( bytes calldata name, address wrappedOwner, address resolver ) external; function wrapETH2LD( string calldata label, address wrappedOwner, uint16 ownerControlledFuses, address resolver ) external returns (uint64 expires); function registerAndWrapETH2LD( string calldata label, address wrappedOwner, uint256 duration, address resolver, uint16 ownerControlledFuses ) external returns (uint256 registrarExpiry); function renew( uint256 labelHash, uint256 duration ) external returns (uint256 expires); function unwrap(bytes32 node, bytes32 label, address owner) external; function unwrapETH2LD( bytes32 label, address newRegistrant, address newController ) external; function upgrade(bytes calldata name, bytes calldata extraData) external; function setFuses( bytes32 node, uint16 ownerControlledFuses ) external returns (uint32 newFuses); function setChildFuses( bytes32 parentNode, bytes32 labelhash, uint32 fuses, uint64 expiry ) external; function setSubnodeRecord( bytes32 node, string calldata label, address owner, address resolver, uint64 ttl, uint32 fuses, uint64 expiry ) external returns (bytes32); function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setSubnodeOwner( bytes32 node, string calldata label, address newOwner, uint32 fuses, uint64 expiry ) external returns (bytes32); function extendExpiry( bytes32 node, bytes32 labelhash, uint64 expiry ) external returns (uint64); function canModifyName( bytes32 node, address addr ) external view returns (bool); function setResolver(bytes32 node, address resolver) external; function setTTL(bytes32 node, uint64 ttl) external; function ownerOf(uint256 id) external view returns (address owner); function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address); function getData( uint256 id ) external view returns (address, uint32, uint64); function setMetadataService(IMetadataService _metadataService) external; function uri(uint256 tokenId) external view returns (string memory); function setUpgradeContract(INameWrapperUpgrade _upgradeAddress) external; function allFusesBurned( bytes32 node, uint32 fuseMask ) external view returns (bool); function isWrapped(bytes32) external view returns (bool); function isWrapped(bytes32, bytes32) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; interface INameWrapperUpgrade { function wrapFromUpgrade( bytes calldata name, address wrappedOwner, uint32 fuses, uint64 expiry, address approved, bytes calldata extraData ) external; }
File 2 of 7: BaseRegistrarImplementation
// File: @ensdomains/ens/contracts/ENS.sol pragma solidity >=0.4.24; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); _clearApproval(tokenId); _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address * 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 * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @ensdomains/ethregistrar/contracts/BaseRegistrar.sol pragma solidity >=0.4.24; contract BaseRegistrar is IERC721, Ownable { uint constant public GRACE_PERIOD = 90 days; event ControllerAdded(address indexed controller); event ControllerRemoved(address indexed controller); event NameMigrated(uint256 indexed id, address indexed owner, uint expires); event NameRegistered(uint256 indexed id, address indexed owner, uint expires); event NameRenewed(uint256 indexed id, uint expires); // The ENS registry ENS public ens; // The namehash of the TLD this registrar owns (eg, .eth) bytes32 public baseNode; // A map of addresses that are authorised to register and renew names. mapping(address=>bool) public controllers; // Authorises a controller, who can register and renew domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Set the resolver for the TLD this registrar manages. function setResolver(address resolver) external; // Returns the expiration timestamp of the specified label hash. function nameExpires(uint256 id) external view returns(uint); // Returns true iff the specified name is available for registration. function available(uint256 id) public view returns(bool); /** * @dev Register a name. */ function register(uint256 id, address owner, uint duration) external returns(uint); function renew(uint256 id, uint duration) external returns(uint); /** * @dev Reclaim ownership of a name in ENS, if you own it in the registrar. */ function reclaim(uint256 id, address owner) external; } // File: @ensdomains/ethregistrar/contracts/BaseRegistrarImplementation.sol pragma solidity ^0.5.0; contract BaseRegistrarImplementation is BaseRegistrar, ERC721 { // A map of expiry times mapping(uint256=>uint) expiries; bytes4 constant private INTERFACE_META_ID = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant private ERC721_ID = bytes4( keccak256("balanceOf(address)") ^ keccak256("ownerOf(uint256)") ^ keccak256("approve(address,uint256)") ^ keccak256("getApproved(uint256)") ^ keccak256("setApprovalForAll(address,bool)") ^ keccak256("isApprovedForAll(address,address)") ^ keccak256("transferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256,bytes)") ); bytes4 constant private RECLAIM_ID = bytes4(keccak256("reclaim(uint256,address)")); constructor(ENS _ens, bytes32 _baseNode) public { ens = _ens; baseNode = _baseNode; } modifier live { require(ens.owner(baseNode) == address(this)); _; } modifier onlyController { require(controllers[msg.sender]); _; } /** * @dev Gets the owner of the specified token ID. Names become unowned * when their registration expires. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { require(expiries[tokenId] > now); return super.ownerOf(tokenId); } // Authorises a controller, who can register and renew domains. function addController(address controller) external onlyOwner { controllers[controller] = true; emit ControllerAdded(controller); } // Revoke controller permission for an address. function removeController(address controller) external onlyOwner { controllers[controller] = false; emit ControllerRemoved(controller); } // Set the resolver for the TLD this registrar manages. function setResolver(address resolver) external onlyOwner { ens.setResolver(baseNode, resolver); } // Returns the expiration timestamp of the specified id. function nameExpires(uint256 id) external view returns(uint) { return expiries[id]; } // Returns true iff the specified name is available for registration. function available(uint256 id) public view returns(bool) { // Not available if it's registered here or in its grace period. return expiries[id] + GRACE_PERIOD < now; } /** * @dev Register a name. * @param id The token ID (keccak256 of the label). * @param owner The address that should own the registration. * @param duration Duration in seconds for the registration. */ function register(uint256 id, address owner, uint duration) external returns(uint) { return _register(id, owner, duration, true); } /** * @dev Register a name, without modifying the registry. * @param id The token ID (keccak256 of the label). * @param owner The address that should own the registration. * @param duration Duration in seconds for the registration. */ function registerOnly(uint256 id, address owner, uint duration) external returns(uint) { return _register(id, owner, duration, false); } function _register(uint256 id, address owner, uint duration, bool updateRegistry) internal live onlyController returns(uint) { require(available(id)); require(now + duration + GRACE_PERIOD > now + GRACE_PERIOD); // Prevent future overflow expiries[id] = now + duration; if(_exists(id)) { // Name was previously owned, and expired _burn(id); } _mint(owner, id); if(updateRegistry) { ens.setSubnodeOwner(baseNode, bytes32(id), owner); } emit NameRegistered(id, owner, now + duration); return now + duration; } function renew(uint256 id, uint duration) external live onlyController returns(uint) { require(expiries[id] + GRACE_PERIOD >= now); // Name must be registered here or in grace period require(expiries[id] + duration + GRACE_PERIOD > duration + GRACE_PERIOD); // Prevent future overflow expiries[id] += duration; emit NameRenewed(id, expiries[id]); return expiries[id]; } /** * @dev Reclaim ownership of a name in ENS, if you own it in the registrar. */ function reclaim(uint256 id, address owner) external live { require(_isApprovedOrOwner(msg.sender, id)); ens.setSubnodeOwner(baseNode, bytes32(id), owner); } function supportsInterface(bytes4 interfaceID) external view returns (bool) { return interfaceID == INTERFACE_META_ID || interfaceID == ERC721_ID || interfaceID == RECLAIM_ID; } }
File 3 of 7: ExponentialPremiumPriceOracle
// 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 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 v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @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); } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "./StablePriceOracle.sol"; contract ExponentialPremiumPriceOracle is StablePriceOracle { uint256 constant GRACE_PERIOD = 90 days; uint256 immutable startPremium; uint256 immutable endValue; constructor( AggregatorInterface _usdOracle, uint256[] memory _rentPrices, uint256 _startPremium, uint256 totalDays ) StablePriceOracle(_usdOracle, _rentPrices) { startPremium = _startPremium; endValue = _startPremium >> totalDays; } uint256 constant PRECISION = 1e18; uint256 constant bit1 = 999989423469314432; // 0.5 ^ 1/65536 * (10 ** 18) uint256 constant bit2 = 999978847050491904; // 0.5 ^ 2/65536 * (10 ** 18) uint256 constant bit3 = 999957694548431104; uint256 constant bit4 = 999915390886613504; uint256 constant bit5 = 999830788931929088; uint256 constant bit6 = 999661606496243712; uint256 constant bit7 = 999323327502650752; uint256 constant bit8 = 998647112890970240; uint256 constant bit9 = 997296056085470080; uint256 constant bit10 = 994599423483633152; uint256 constant bit11 = 989228013193975424; uint256 constant bit12 = 978572062087700096; uint256 constant bit13 = 957603280698573696; uint256 constant bit14 = 917004043204671232; uint256 constant bit15 = 840896415253714560; uint256 constant bit16 = 707106781186547584; /** * @dev Returns the pricing premium in internal base units. */ function _premium( string memory, uint256 expires, uint256 ) internal view override returns (uint256) { expires = expires + GRACE_PERIOD; if (expires > block.timestamp) { return 0; } uint256 elapsed = block.timestamp - expires; uint256 premium = decayedPremium(startPremium, elapsed); if (premium >= endValue) { return premium - endValue; } return 0; } /** * @dev Returns the premium price at current time elapsed * @param startPremium starting price * @param elapsed time past since expiry */ function decayedPremium( uint256 startPremium, uint256 elapsed ) public pure returns (uint256) { uint256 daysPast = (elapsed * PRECISION) / 1 days; uint256 intDays = daysPast / PRECISION; uint256 premium = startPremium >> intDays; uint256 partDay = (daysPast - intDays * PRECISION); uint256 fraction = (partDay * (2 ** 16)) / PRECISION; uint256 totalPremium = addFractionalPremium(fraction, premium); return totalPremium; } function addFractionalPremium( uint256 fraction, uint256 premium ) internal pure returns (uint256) { if (fraction & (1 << 0) != 0) { premium = (premium * bit1) / PRECISION; } if (fraction & (1 << 1) != 0) { premium = (premium * bit2) / PRECISION; } if (fraction & (1 << 2) != 0) { premium = (premium * bit3) / PRECISION; } if (fraction & (1 << 3) != 0) { premium = (premium * bit4) / PRECISION; } if (fraction & (1 << 4) != 0) { premium = (premium * bit5) / PRECISION; } if (fraction & (1 << 5) != 0) { premium = (premium * bit6) / PRECISION; } if (fraction & (1 << 6) != 0) { premium = (premium * bit7) / PRECISION; } if (fraction & (1 << 7) != 0) { premium = (premium * bit8) / PRECISION; } if (fraction & (1 << 8) != 0) { premium = (premium * bit9) / PRECISION; } if (fraction & (1 << 9) != 0) { premium = (premium * bit10) / PRECISION; } if (fraction & (1 << 10) != 0) { premium = (premium * bit11) / PRECISION; } if (fraction & (1 << 11) != 0) { premium = (premium * bit12) / PRECISION; } if (fraction & (1 << 12) != 0) { premium = (premium * bit13) / PRECISION; } if (fraction & (1 << 13) != 0) { premium = (premium * bit14) / PRECISION; } if (fraction & (1 << 14) != 0) { premium = (premium * bit15) / PRECISION; } if (fraction & (1 << 15) != 0) { premium = (premium * bit16) / PRECISION; } return premium; } function supportsInterface( bytes4 interfaceID ) public view virtual override returns (bool) { return super.supportsInterface(interfaceID); } } //SPDX-License-Identifier: MIT pragma solidity >=0.8.17 <0.9.0; interface IPriceOracle { struct Price { uint256 base; uint256 premium; } /** * @dev Returns the price to register or renew a name. * @param name The name being registered or renewed. * @param expires When the name presently expires (0 if this is a new registration). * @param duration How long the name is being registered or extended for, in seconds. * @return base premium tuple of base price + premium price */ function price( string calldata name, uint256 expires, uint256 duration ) external view returns (Price calldata); } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "./IPriceOracle.sol"; import "./StringUtils.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface AggregatorInterface { function latestAnswer() external view returns (int256); } // StablePriceOracle sets a price in USD, based on an oracle. contract StablePriceOracle is IPriceOracle { using StringUtils for *; // Rent in base price units by length uint256 public immutable price1Letter; uint256 public immutable price2Letter; uint256 public immutable price3Letter; uint256 public immutable price4Letter; uint256 public immutable price5Letter; // Oracle address AggregatorInterface public immutable usdOracle; event RentPriceChanged(uint256[] prices); constructor(AggregatorInterface _usdOracle, uint256[] memory _rentPrices) { usdOracle = _usdOracle; price1Letter = _rentPrices[0]; price2Letter = _rentPrices[1]; price3Letter = _rentPrices[2]; price4Letter = _rentPrices[3]; price5Letter = _rentPrices[4]; } function price( string calldata name, uint256 expires, uint256 duration ) external view override returns (IPriceOracle.Price memory) { uint256 len = name.strlen(); uint256 basePrice; if (len >= 5) { basePrice = price5Letter * duration; } else if (len == 4) { basePrice = price4Letter * duration; } else if (len == 3) { basePrice = price3Letter * duration; } else if (len == 2) { basePrice = price2Letter * duration; } else { basePrice = price1Letter * duration; } return IPriceOracle.Price({ base: attoUSDToWei(basePrice), premium: attoUSDToWei(_premium(name, expires, duration)) }); } /** * @dev Returns the pricing premium in wei. */ function premium( string calldata name, uint256 expires, uint256 duration ) external view returns (uint256) { return attoUSDToWei(_premium(name, expires, duration)); } /** * @dev Returns the pricing premium in internal base units. */ function _premium( string memory name, uint256 expires, uint256 duration ) internal view virtual returns (uint256) { return 0; } function attoUSDToWei(uint256 amount) internal view returns (uint256) { uint256 ethPrice = uint256(usdOracle.latestAnswer()); return (amount * 1e8) / ethPrice; } function weiToAttoUSD(uint256 amount) internal view returns (uint256) { uint256 ethPrice = uint256(usdOracle.latestAnswer()); return (amount * ethPrice) / 1e8; } function supportsInterface( bytes4 interfaceID ) public view virtual returns (bool) { return interfaceID == type(IERC165).interfaceId || interfaceID == type(IPriceOracle).interfaceId; } } pragma solidity >=0.8.4; library StringUtils { /** * @dev Returns the length of a given string * * @param s The string to measure the length of * @return The length of the input string */ function strlen(string memory s) internal pure returns (uint256) { uint256 len; uint256 i = 0; uint256 bytelength = bytes(s).length; for (len = 0; i < bytelength; len++) { bytes1 b = bytes(s)[i]; if (b < 0x80) { i += 1; } else if (b < 0xE0) { i += 2; } else if (b < 0xF0) { i += 3; } else if (b < 0xF8) { i += 4; } else if (b < 0xFC) { i += 5; } else { i += 6; } } return len; } }
File 4 of 7: EACAggregatorProxy
pragma solidity 0.6.6; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } /** * @title A trusted proxy for updating where current answers are read from * @notice This contract provides a consistent address for the * CurrentAnwerInterface but delegates where it reads from to the owner, who is * trusted to update it. */ contract AggregatorProxy is AggregatorV2V3Interface, Owned { struct Phase { uint16 id; AggregatorV2V3Interface aggregator; } Phase private currentPhase; AggregatorV2V3Interface public proposedAggregator; mapping(uint16 => AggregatorV2V3Interface) public phaseAggregators; uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; constructor(address _aggregator) public Owned() { setAggregator(_aggregator); } /** * @notice Reads the current answer from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns (int256 answer) { return currentPhase.aggregator.latestAnswer(); } /** * @notice Reads the last updated height from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns (uint256 updatedAt) { return currentPhase.aggregator.latestTimestamp(); } /** * @notice get past rounds answers * @param _roundId the answer number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view virtual override returns (int256 answer) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256 updatedAt) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns (uint256 roundId) { Phase memory phase = currentPhase; // cache storage reads return addPhase(phase.id, uint64(phase.aggregator.latestRound())); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = phaseAggregators[phaseId].getRoundData(aggregatorRoundId); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, phaseId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Phase memory current = currentPhase; // cache storage reads ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = current.aggregator.latestRoundData(); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, current.id); } /** * @notice Used if an aggregator contract has been proposed. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData(uint80 _roundId) public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.getRoundData(_roundId); } /** * @notice Used if an aggregator contract has been proposed. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData() public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.latestRoundData(); } /** * @notice returns the current phase's aggregator address. */ function aggregator() external view returns (address) { return address(currentPhase.aggregator); } /** * @notice returns the current phase's ID. */ function phaseId() external view returns (uint16) { return currentPhase.id; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals() external view override returns (uint8) { return currentPhase.aggregator.decimals(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version() external view override returns (uint256) { return currentPhase.aggregator.version(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description() external view override returns (string memory) { return currentPhase.aggregator.description(); } /** * @notice Allows the owner to propose a new address for the aggregator * @param _aggregator The new address for the aggregator contract */ function proposeAggregator(address _aggregator) external onlyOwner() { proposedAggregator = AggregatorV2V3Interface(_aggregator); } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param _aggregator The new address for the aggregator contract */ function confirmAggregator(address _aggregator) external onlyOwner() { require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator"); delete proposedAggregator; setAggregator(_aggregator); } /* * Internal */ function setAggregator(address _aggregator) internal { uint16 id = currentPhase.id + 1; currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator)); phaseAggregators[id] = AggregatorV2V3Interface(_aggregator); } function addPhase( uint16 _phase, uint64 _originalId ) internal view returns (uint80) { return uint80(uint256(_phase) << PHASE_OFFSET | _originalId); } function parseIds( uint256 _roundId ) internal view returns (uint16, uint64) { uint16 phaseId = uint16(_roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(_roundId); return (phaseId, aggregatorRoundId); } function addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal view returns (uint80, int256, uint256, uint256, uint80) { return ( addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, addPhase(phaseId, uint64(answeredInRound)) ); } /* * Modifiers */ modifier hasProposal() { require(address(proposedAggregator) != address(0), "No proposed aggregator present"); _; } } interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } /** * @title External Access Controlled Aggregator Proxy * @notice A trusted proxy for updating where current answers are read from * @notice This contract provides a consistent address for the * Aggregator and AggregatorV3Interface but delegates where it reads from to the owner, who is * trusted to update it. * @notice Only access enabled addresses are allowed to access getters for * aggregated answers and round information. */ contract EACAggregatorProxy is AggregatorProxy { AccessControllerInterface public accessController; constructor( address _aggregator, address _accessController ) public AggregatorProxy(_aggregator) { setController(_accessController); } /** * @notice Allows the owner to update the accessController contract address. * @param _accessController The new address for the accessController contract */ function setController(address _accessController) public onlyOwner() { accessController = AccessControllerInterface(_accessController); } /** * @notice Reads the current answer from aggregator delegated to. * @dev overridden function to add the checkAccess() modifier * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view override checkAccess() returns (int256) { return super.latestAnswer(); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view override checkAccess() returns (uint256) { return super.latestTimestamp(); } /** * @notice get past rounds answers * @param _roundId the answer number to retrieve the answer for * @dev overridden function to add the checkAccess() modifier * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view override checkAccess() returns (int256) { return super.getAnswer(_roundId); } /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer number to retrieve the updated timestamp for * @dev overridden function to add the checkAccess() modifier * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view override checkAccess() returns (uint256) { return super.getTimestamp(_roundId); } /** * @notice get the latest completed round where the answer was updated * @dev overridden function to add the checkAccess() modifier * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view override checkAccess() returns (uint256) { return super.latestRound(); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with a phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view checkAccess() override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.getRoundData(_roundId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with a phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view checkAccess() override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.latestRoundData(); } /** * @notice Used if an aggregator contract has been proposed. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData(uint80 _roundId) public view checkAccess() hasProposal() override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.proposedGetRoundData(_roundId); } /** * @notice Used if an aggregator contract has been proposed. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData() public view checkAccess() hasProposal() override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.proposedLatestRoundData(); } /** * @dev reverts if the caller does not have access by the accessController * contract or is the contract itself. */ modifier checkAccess() { AccessControllerInterface ac = accessController; require(address(ac) == address(0) || ac.hasAccess(msg.sender, msg.data), "No access"); _; } }
File 5 of 7: AccessControlledOffchainAggregator
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./OffchainAggregator.sol"; import "./SimpleReadAccessController.sol"; /** * @notice Wrapper of OffchainAggregator which checks read access on Aggregator-interface methods */ contract AccessControlledOffchainAggregator is OffchainAggregator, SimpleReadAccessController { constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, LinkTokenInterface _link, int192 _minAnswer, int192 _maxAnswer, AccessControllerInterface _billingAccessController, AccessControllerInterface _requesterAccessController, uint8 _decimals, string memory description ) OffchainAggregator( _maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission, _link, _minAnswer, _maxAnswer, _billingAccessController, _requesterAccessController, _decimals, description ) { } /* * Versioning */ function typeAndVersion() external override pure virtual returns (string memory) { return "AccessControlledOffchainAggregator 4.0.0"; } /* * v2 Aggregator interface */ /// @inheritdoc OffchainAggregator function latestAnswer() public override view checkAccess() returns (int256) { return super.latestAnswer(); } /// @inheritdoc OffchainAggregator function latestTimestamp() public override view checkAccess() returns (uint256) { return super.latestTimestamp(); } /// @inheritdoc OffchainAggregator function latestRound() public override view checkAccess() returns (uint256) { return super.latestRound(); } /// @inheritdoc OffchainAggregator function getAnswer(uint256 _roundId) public override view checkAccess() returns (int256) { return super.getAnswer(_roundId); } /// @inheritdoc OffchainAggregator function getTimestamp(uint256 _roundId) public override view checkAccess() returns (uint256) { return super.getTimestamp(_roundId); } /* * v3 Aggregator interface */ /// @inheritdoc OffchainAggregator function description() public override view checkAccess() returns (string memory) { return super.description(); } /// @inheritdoc OffchainAggregator function getRoundData(uint80 _roundId) public override view checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.getRoundData(_roundId); } /// @inheritdoc OffchainAggregator function latestRoundData() public override view checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.latestRoundData(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { }// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); }// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./AccessControllerInterface.sol"; import "./AggregatorV2V3Interface.sol"; import "./AggregatorValidatorInterface.sol"; import "./LinkTokenInterface.sol"; import "./Owned.sol"; import "./OffchainAggregatorBilling.sol"; import "./TypeAndVersionInterface.sol"; /** * @notice Onchain verification of reports from the offchain reporting protocol * @dev For details on its operation, see the offchain reporting protocol design * @dev doc, which refers to this contract as simply the "contract". */ contract OffchainAggregator is Owned, OffchainAggregatorBilling, AggregatorV2V3Interface, TypeAndVersionInterface { uint256 constant private maxUint32 = (1 << 32) - 1; // Storing these fields used on the hot path in a HotVars variable reduces the // retrieval of all of them to a single SLOAD. If any further fields are // added, make sure that storage of the struct still takes at most 32 bytes. struct HotVars { // Provides 128 bits of security against 2nd pre-image attacks, but only // 64 bits against collisions. This is acceptable, since a malicious owner has // easier way of messing up the protocol than to find hash collisions. bytes16 latestConfigDigest; uint40 latestEpochAndRound; // 32 most sig bits for epoch, 8 least sig bits for round // Current bound assumed on number of faulty/dishonest oracles participating // in the protocol, this value is referred to as f in the design uint8 threshold; // Chainlink Aggregators expose a roundId to consumers. The offchain reporting // protocol does not use this id anywhere. We increment it whenever a new // transmission is made to provide callers with contiguous ids for successive // reports. uint32 latestAggregatorRoundId; } HotVars internal s_hotVars; // Transmission records the median answer from the transmit transaction at // time timestamp struct Transmission { int192 answer; // 192 bits ought to be enough for anyone uint64 timestamp; } mapping(uint32 /* aggregator round ID */ => Transmission) internal s_transmissions; // incremented each time a new config is posted. This count is incorporated // into the config digest, to prevent replay attacks. uint32 internal s_configCount; uint32 internal s_latestConfigBlockNumber; // makes it easier for offchain systems // to extract config from logs. // Lowest answer the system is allowed to report in response to transmissions int192 immutable public minAnswer; // Highest answer the system is allowed to report in response to transmissions int192 immutable public maxAnswer; /* * @param _maximumGasPrice highest gas price for which transmitter will be compensated * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units * @param _link address of the LINK contract * @param _minAnswer lowest answer the median of a report is allowed to be * @param _maxAnswer highest answer the median of a report is allowed to be * @param _billingAccessController access controller for billing admin functions * @param _requesterAccessController access controller for requesting new rounds * @param _decimals answers are stored in fixed-point format, with this many digits of precision * @param _description short human-readable description of observable this contract's answers pertain to */ constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, LinkTokenInterface _link, int192 _minAnswer, int192 _maxAnswer, AccessControllerInterface _billingAccessController, AccessControllerInterface _requesterAccessController, uint8 _decimals, string memory _description ) OffchainAggregatorBilling(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission, _link, _billingAccessController ) { decimals = _decimals; s_description = _description; setRequesterAccessController(_requesterAccessController); setValidatorConfig(AggregatorValidatorInterface(0x0), 0); minAnswer = _minAnswer; maxAnswer = _maxAnswer; } /* * Versioning */ function typeAndVersion() external override pure virtual returns (string memory) { return "OffchainAggregator 4.0.0"; } /* * Config logic */ /** * @notice triggers a new run of the offchain reporting protocol * @param previousConfigBlockNumber block in which the previous config was set, to simplify historic analysis * @param configCount ordinal number of this config setting among all config settings over the life of this contract * @param signers ith element is address ith oracle uses to sign a report * @param transmitters ith element is address ith oracle uses to transmit a report via the transmit method * @param threshold maximum number of faulty/dishonest oracles the protocol can tolerate while still working correctly * @param encodedConfigVersion version of the serialization format used for "encoded" parameter * @param encoded serialized data used by oracles to configure their offchain operation */ event ConfigSet( uint32 previousConfigBlockNumber, uint64 configCount, address[] signers, address[] transmitters, uint8 threshold, uint64 encodedConfigVersion, bytes encoded ); // Reverts transaction if config args are invalid modifier checkConfigValid ( uint256 _numSigners, uint256 _numTransmitters, uint256 _threshold ) { require(_numSigners <= maxNumOracles, "too many signers"); require(_threshold > 0, "threshold must be positive"); require( _numSigners == _numTransmitters, "oracle addresses out of registration" ); require(_numSigners > 3*_threshold, "faulty-oracle threshold too high"); _; } /** * @notice sets offchain reporting protocol configuration incl. participating oracles * @param _signers addresses with which oracles sign the reports * @param _transmitters addresses oracles use to transmit the reports * @param _threshold number of faulty oracles the system can tolerate * @param _encodedConfigVersion version number for offchainEncoding schema * @param _encoded encoded off-chain oracle configuration */ function setConfig( address[] calldata _signers, address[] calldata _transmitters, uint8 _threshold, uint64 _encodedConfigVersion, bytes calldata _encoded ) external checkConfigValid(_signers.length, _transmitters.length, _threshold) onlyOwner() { while (s_signers.length != 0) { // remove any old signer/transmitter addresses uint lastIdx = s_signers.length - 1; address signer = s_signers[lastIdx]; address transmitter = s_transmitters[lastIdx]; payOracle(transmitter); delete s_oracles[signer]; delete s_oracles[transmitter]; s_signers.pop(); s_transmitters.pop(); } for (uint i = 0; i < _signers.length; i++) { // add new signer/transmitter addresses require( s_oracles[_signers[i]].role == Role.Unset, "repeated signer address" ); s_oracles[_signers[i]] = Oracle(uint8(i), Role.Signer); require(s_payees[_transmitters[i]] != address(0), "payee must be set"); require( s_oracles[_transmitters[i]].role == Role.Unset, "repeated transmitter address" ); s_oracles[_transmitters[i]] = Oracle(uint8(i), Role.Transmitter); s_signers.push(_signers[i]); s_transmitters.push(_transmitters[i]); } s_hotVars.threshold = _threshold; uint32 previousConfigBlockNumber = s_latestConfigBlockNumber; s_latestConfigBlockNumber = uint32(block.number); s_configCount += 1; uint64 configCount = s_configCount; { s_hotVars.latestConfigDigest = configDigestFromConfigData( address(this), configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encoded ); s_hotVars.latestEpochAndRound = 0; } emit ConfigSet( previousConfigBlockNumber, configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encoded ); } function configDigestFromConfigData( address _contractAddress, uint64 _configCount, address[] calldata _signers, address[] calldata _transmitters, uint8 _threshold, uint64 _encodedConfigVersion, bytes calldata _encodedConfig ) internal pure returns (bytes16) { return bytes16(keccak256(abi.encode(_contractAddress, _configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encodedConfig ))); } /** * @notice information about current offchain reporting protocol configuration * @return configCount ordinal number of current config, out of all configs applied to this contract so far * @return blockNumber block at which this config was set * @return configDigest domain-separation tag for current config (see configDigestFromConfigData) */ function latestConfigDetails() external view returns ( uint32 configCount, uint32 blockNumber, bytes16 configDigest ) { return (s_configCount, s_latestConfigBlockNumber, s_hotVars.latestConfigDigest); } /** * @return list of addresses permitted to transmit reports to this contract * @dev The list will match the order used to specify the transmitter during setConfig */ function transmitters() external view returns(address[] memory) { return s_transmitters; } /* * On-chain validation logc */ // Configuration for validator struct ValidatorConfig { AggregatorValidatorInterface validator; uint32 gasLimit; } ValidatorConfig private s_validatorConfig; /** * @notice indicates that the validator configuration has been set * @param previousValidator previous validator contract * @param previousGasLimit previous gas limit for validate calls * @param currentValidator current validator contract * @param currentGasLimit current gas limit for validate calls */ event ValidatorConfigSet( AggregatorValidatorInterface indexed previousValidator, uint32 previousGasLimit, AggregatorValidatorInterface indexed currentValidator, uint32 currentGasLimit ); /** * @notice validator configuration * @return validator validator contract * @return gasLimit gas limit for validate calls */ function validatorConfig() external view returns (AggregatorValidatorInterface validator, uint32 gasLimit) { ValidatorConfig memory vc = s_validatorConfig; return (vc.validator, vc.gasLimit); } /** * @notice sets validator configuration * @dev set _newValidator to 0x0 to disable validate calls * @param _newValidator address of the new validator contract * @param _newGasLimit new gas limit for validate calls */ function setValidatorConfig(AggregatorValidatorInterface _newValidator, uint32 _newGasLimit) public onlyOwner() { ValidatorConfig memory previous = s_validatorConfig; if (previous.validator != _newValidator || previous.gasLimit != _newGasLimit) { s_validatorConfig = ValidatorConfig({ validator: _newValidator, gasLimit: _newGasLimit }); emit ValidatorConfigSet(previous.validator, previous.gasLimit, _newValidator, _newGasLimit); } } function validateAnswer( uint32 _aggregatorRoundId, int256 _answer ) private { ValidatorConfig memory vc = s_validatorConfig; if (address(vc.validator) == address(0)) { return; } uint32 prevAggregatorRoundId = _aggregatorRoundId - 1; int256 prevAggregatorRoundAnswer = s_transmissions[prevAggregatorRoundId].answer; require( callWithExactGasEvenIfTargetIsNoContract( vc.gasLimit, address(vc.validator), abi.encodeWithSignature( "validate(uint256,int256,uint256,int256)", uint256(prevAggregatorRoundId), prevAggregatorRoundAnswer, uint256(_aggregatorRoundId), _answer ) ), "insufficient gas" ); } uint256 private constant CALL_WITH_EXACT_GAS_CUSHION = 5_000; /** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available. */ function callWithExactGasEvenIfTargetIsNoContract( uint256 _gasAmount, address _target, bytes memory _data ) private returns (bool sufficientGas) { // solhint-disable-next-line no-inline-assembly assembly { let g := gas() // Compute g -= CALL_WITH_EXACT_GAS_CUSHION and check for underflow. We // need the cushion since the logic following the above call to gas also // costs gas which we cannot account for exactly. So cushion is a // conservative upper bound for the cost of this logic. if iszero(lt(g, CALL_WITH_EXACT_GAS_CUSHION)) { g := sub(g, CALL_WITH_EXACT_GAS_CUSHION) // If g - g//64 <= _gasAmount, we don't have enough gas. (We subtract g//64 // because of EIP-150.) if gt(sub(g, div(g, 64)), _gasAmount) { // Call and ignore success/return data. Note that we did not check // whether a contract actually exists at the _target address. pop(call(_gasAmount, _target, 0, add(_data, 0x20), mload(_data), 0, 0)) sufficientGas := true } } } } /* * requestNewRound logic */ AccessControllerInterface internal s_requesterAccessController; /** * @notice emitted when a new requester access controller contract is set * @param old the address prior to the current setting * @param current the address of the new access controller contract */ event RequesterAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current); /** * @notice emitted to immediately request a new round * @param requester the address of the requester * @param configDigest the latest transmission's configDigest * @param epoch the latest transmission's epoch * @param round the latest transmission's round */ event RoundRequested(address indexed requester, bytes16 configDigest, uint32 epoch, uint8 round); /** * @notice address of the requester access controller contract * @return requester access controller address */ function requesterAccessController() external view returns (AccessControllerInterface) { return s_requesterAccessController; } /** * @notice sets the requester access controller * @param _requesterAccessController designates the address of the new requester access controller */ function setRequesterAccessController(AccessControllerInterface _requesterAccessController) public onlyOwner() { AccessControllerInterface oldController = s_requesterAccessController; if (_requesterAccessController != oldController) { s_requesterAccessController = AccessControllerInterface(_requesterAccessController); emit RequesterAccessControllerSet(oldController, _requesterAccessController); } } /** * @notice immediately requests a new round * @return the aggregatorRoundId of the next round. Note: The report for this round may have been * transmitted (but not yet mined) *before* requestNewRound() was even called. There is *no* * guarantee of causality between the request and the report at aggregatorRoundId. */ function requestNewRound() external returns (uint80) { require(msg.sender == owner || s_requesterAccessController.hasAccess(msg.sender, msg.data), "Only owner&requester can call"); HotVars memory hotVars = s_hotVars; emit RoundRequested( msg.sender, hotVars.latestConfigDigest, uint32(s_hotVars.latestEpochAndRound >> 8), uint8(s_hotVars.latestEpochAndRound) ); return hotVars.latestAggregatorRoundId + 1; } /* * Transmission logic */ /** * @notice indicates that a new report was transmitted * @param aggregatorRoundId the round to which this report was assigned * @param answer median of the observations attached this report * @param transmitter address from which the report was transmitted * @param observations observations transmitted with this report * @param rawReportContext signature-replay-prevention domain-separation tag */ event NewTransmission( uint32 indexed aggregatorRoundId, int192 answer, address transmitter, int192[] observations, bytes observers, bytes32 rawReportContext ); // decodeReport is used to check that the solidity and go code are using the // same format. See TestOffchainAggregator.testDecodeReport and TestReportParsing function decodeReport(bytes memory _report) internal pure returns ( bytes32 rawReportContext, bytes32 rawObservers, int192[] memory observations ) { (rawReportContext, rawObservers, observations) = abi.decode(_report, (bytes32, bytes32, int192[])); } // Used to relieve stack pressure in transmit struct ReportData { HotVars hotVars; // Only read from storage once bytes observers; // ith element is the index of the ith observer int192[] observations; // ith element is the ith observation bytes vs; // jth element is the v component of the jth signature bytes32 rawReportContext; } /* * @notice details about the most recent report * @return configDigest domain separation tag for the latest report * @return epoch epoch in which the latest report was generated * @return round OCR round in which the latest report was generated * @return latestAnswer median value from latest report * @return latestTimestamp when the latest report was transmitted */ function latestTransmissionDetails() external view returns ( bytes16 configDigest, uint32 epoch, uint8 round, int192 latestAnswer, uint64 latestTimestamp ) { require(msg.sender == tx.origin, "Only callable by EOA"); return ( s_hotVars.latestConfigDigest, uint32(s_hotVars.latestEpochAndRound >> 8), uint8(s_hotVars.latestEpochAndRound), s_transmissions[s_hotVars.latestAggregatorRoundId].answer, s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp ); } // The constant-length components of the msg.data sent to transmit. // See the "If we wanted to call sam" example on for example reasoning // https://solidity.readthedocs.io/en/v0.7.2/abi-spec.html uint16 private constant TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT = 4 + // function selector 32 + // word containing start location of abiencoded _report value 32 + // word containing location start of abiencoded _rs value 32 + // word containing start location of abiencoded _ss value 32 + // _rawVs value 32 + // word containing length of _report 32 + // word containing length _rs 32 + // word containing length of _ss 0; // placeholder function expectedMsgDataLength( bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss ) private pure returns (uint256 length) { // calldata will never be big enough to make this overflow return uint256(TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT) + _report.length + // one byte pure entry in _report _rs.length * 32 + // 32 bytes per entry in _rs _ss.length * 32 + // 32 bytes per entry in _ss 0; // placeholder } /** * @notice transmit is called to post a new report to the contract * @param _report serialized report, which the signatures are signing. See parsing code below for format. The ith element of the observers component must be the index in s_signers of the address for the ith signature * @param _rs ith element is the R components of the ith signature on report. Must have at most maxNumOracles entries * @param _ss ith element is the S components of the ith signature on report. Must have at most maxNumOracles entries * @param _rawVs ith element is the the V component of the ith signature */ function transmit( // NOTE: If these parameters are changed, expectedMsgDataLength and/or // TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT need to be changed accordingly bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss, bytes32 _rawVs // signatures ) external { uint256 initialGas = gasleft(); // This line must come first // Make sure the transmit message-length matches the inputs. Otherwise, the // transmitter could append an arbitrarily long (up to gas-block limit) // string of 0 bytes, which we would reimburse at a rate of 16 gas/byte, but // which would only cost the transmitter 4 gas/byte. (Appendix G of the // yellow paper, p. 25, for G_txdatazero and EIP 2028 for G_txdatanonzero.) // This could amount to reimbursement profit of 36 million gas, given a 3MB // zero tail. require(msg.data.length == expectedMsgDataLength(_report, _rs, _ss), "transmit message too long"); ReportData memory r; // Relieves stack pressure { r.hotVars = s_hotVars; // cache read from storage bytes32 rawObservers; (r.rawReportContext, rawObservers, r.observations) = abi.decode( _report, (bytes32, bytes32, int192[]) ); // rawReportContext consists of: // 11-byte zero padding // 16-byte configDigest // 4-byte epoch // 1-byte round bytes16 configDigest = bytes16(r.rawReportContext << 88); require( r.hotVars.latestConfigDigest == configDigest, "configDigest mismatch" ); uint40 epochAndRound = uint40(uint256(r.rawReportContext)); // direct numerical comparison works here, because // // ((e,r) <= (e',r')) implies (epochAndRound <= epochAndRound') // // because alphabetic ordering implies e <= e', and if e = e', then r<=r', // so e*256+r <= e'*256+r', because r, r' < 256 require(r.hotVars.latestEpochAndRound < epochAndRound, "stale report"); require(_rs.length > r.hotVars.threshold, "not enough signatures"); require(_rs.length <= maxNumOracles, "too many signatures"); require(_ss.length == _rs.length, "signatures out of registration"); require(r.observations.length <= maxNumOracles, "num observations out of bounds"); require(r.observations.length > 2 * r.hotVars.threshold, "too few values to trust median"); // Copy signature parities in bytes32 _rawVs to bytes r.v r.vs = new bytes(_rs.length); for (uint8 i = 0; i < _rs.length; i++) { r.vs[i] = _rawVs[i]; } // Copy observer identities in bytes32 rawObservers to bytes r.observers r.observers = new bytes(r.observations.length); bool[maxNumOracles] memory seen; for (uint8 i = 0; i < r.observations.length; i++) { uint8 observerIdx = uint8(rawObservers[i]); require(!seen[observerIdx], "observer index repeated"); seen[observerIdx] = true; r.observers[i] = rawObservers[i]; } Oracle memory transmitter = s_oracles[msg.sender]; require( // Check that sender is authorized to report transmitter.role == Role.Transmitter && msg.sender == s_transmitters[transmitter.index], "unauthorized transmitter" ); // record epochAndRound here, so that we don't have to carry the local // variable in transmit. The change is reverted if something fails later. r.hotVars.latestEpochAndRound = epochAndRound; } { // Verify signatures attached to report bytes32 h = keccak256(_report); bool[maxNumOracles] memory signed; Oracle memory o; for (uint i = 0; i < _rs.length; i++) { address signer = ecrecover(h, uint8(r.vs[i])+27, _rs[i], _ss[i]); o = s_oracles[signer]; require(o.role == Role.Signer, "address not authorized to sign"); require(!signed[o.index], "non-unique signature"); signed[o.index] = true; } } { // Check the report contents, and record the result for (uint i = 0; i < r.observations.length - 1; i++) { bool inOrder = r.observations[i] <= r.observations[i+1]; require(inOrder, "observations not sorted"); } int192 median = r.observations[r.observations.length/2]; require(minAnswer <= median && median <= maxAnswer, "median is out of min-max range"); r.hotVars.latestAggregatorRoundId++; s_transmissions[r.hotVars.latestAggregatorRoundId] = Transmission(median, uint64(block.timestamp)); emit NewTransmission( r.hotVars.latestAggregatorRoundId, median, msg.sender, r.observations, r.observers, r.rawReportContext ); // Emit these for backwards compatability with offchain consumers // that only support legacy events emit NewRound( r.hotVars.latestAggregatorRoundId, address(0x0), // use zero address since we don't have anybody "starting" the round here block.timestamp ); emit AnswerUpdated( median, r.hotVars.latestAggregatorRoundId, block.timestamp ); validateAnswer(r.hotVars.latestAggregatorRoundId, median); } s_hotVars = r.hotVars; assert(initialGas < maxUint32); reimburseAndRewardOracles(uint32(initialGas), r.observers); } /* * v2 Aggregator interface */ /** * @notice median from the most recent report */ function latestAnswer() public override view virtual returns (int256) { return s_transmissions[s_hotVars.latestAggregatorRoundId].answer; } /** * @notice timestamp of block in which last report was transmitted */ function latestTimestamp() public override view virtual returns (uint256) { return s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp; } /** * @notice Aggregator round (NOT OCR round) in which last report was transmitted */ function latestRound() public override view virtual returns (uint256) { return s_hotVars.latestAggregatorRoundId; } /** * @notice median of report from given aggregator round (NOT OCR round) * @param _roundId the aggregator round of the target report */ function getAnswer(uint256 _roundId) public override view virtual returns (int256) { if (_roundId > 0xFFFFFFFF) { return 0; } return s_transmissions[uint32(_roundId)].answer; } /** * @notice timestamp of block in which report from given aggregator round was transmitted * @param _roundId aggregator round (NOT OCR round) of target report */ function getTimestamp(uint256 _roundId) public override view virtual returns (uint256) { if (_roundId > 0xFFFFFFFF) { return 0; } return s_transmissions[uint32(_roundId)].timestamp; } /* * v3 Aggregator interface */ string constant private V3_NO_DATA_ERROR = "No data present"; /** * @return answers are stored in fixed-point format, with this many digits of precision */ uint8 immutable public override decimals; /** * @notice aggregator contract version */ uint256 constant public override version = 4; string internal s_description; /** * @notice human-readable description of observable this contract is reporting on */ function description() public override view virtual returns (string memory) { return s_description; } /** * @notice details for the given aggregator round * @param _roundId target aggregator round (NOT OCR round). Must fit in uint32 * @return roundId _roundId * @return answer median of report from given _roundId * @return startedAt timestamp of block in which report from given _roundId was transmitted * @return updatedAt timestamp of block in which report from given _roundId was transmitted * @return answeredInRound _roundId */ function getRoundData(uint80 _roundId) public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR); Transmission memory transmission = s_transmissions[uint32(_roundId)]; return ( _roundId, transmission.answer, transmission.timestamp, transmission.timestamp, _roundId ); } /** * @notice aggregator details for the most recently transmitted report * @return roundId aggregator round of latest report (NOT OCR round) * @return answer median of latest report * @return startedAt timestamp of block containing latest report * @return updatedAt timestamp of block containing latest report * @return answeredInRound aggregator round of latest report */ function latestRoundData() public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = s_hotVars.latestAggregatorRoundId; // Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts. // require(roundId != 0, V3_NO_DATA_ERROR); Transmission memory transmission = s_transmissions[uint32(roundId)]; return ( roundId, transmission.answer, transmission.timestamp, transmission.timestamp, roundId ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./AccessControllerInterface.sol"; import "./LinkTokenInterface.sol"; import "./Owned.sol"; /** * @notice tracks administration of oracle-reward and gas-reimbursement parameters. * @dev * If you read or change this, be sure to read or adjust the comments. They * track the units of the values under consideration, and are crucial to * the readability of the operations it specifies. * @notice * Trust Model: * Nothing in this contract prevents a billing admin from setting insane * values for the billing parameters in setBilling. Oracles * participating in this contract should regularly check that the * parameters make sense. Similarly, the outstanding obligations of this * contract to the oracles can exceed the funds held by the contract. * Oracles participating in this contract should regularly check that it * holds sufficient funds and stop interacting with it if funding runs * out. * This still leaves oracles with some risk due to TOCTOU issues. * However, since the sums involved are pretty small (Ethereum * transactions aren't that expensive in the end) and an oracle would * likely stop participating in a contract it repeatedly lost money on, * this risk is deemed acceptable. Oracles should also regularly * withdraw any funds in the contract to prevent issues where the * contract becomes underfunded at a later time, and different oracles * are competing for the left-over funds. * Finally, note that any change to the set of oracles or to the billing * parameters will trigger payout of all oracles first (using the old * parameters), a billing admin cannot take away funds that are already * marked for payment. */ contract OffchainAggregatorBilling is Owned { // Maximum number of oracles the offchain reporting protocol is designed for uint256 constant internal maxNumOracles = 31; // Parameters for oracle payments struct Billing { // Highest compensated gas price, in ETH-gwei uints uint32 maximumGasPrice; // If gas price is less (in ETH-gwei units), transmitter gets half the savings uint32 reasonableGasPrice; // Pay transmitter back this much LINK per unit eth spent on gas // (1e-6LINK/ETH units) uint32 microLinkPerEth; // Fixed LINK reward for each observer, in LINK-gwei units uint32 linkGweiPerObservation; // Fixed reward for transmitter, in linkGweiPerObservation units uint32 linkGweiPerTransmission; } Billing internal s_billing; // We assume that the token contract is correct. This contract is not written // to handle misbehaving ERC20 tokens! LinkTokenInterface internal s_linkToken; AccessControllerInterface internal s_billingAccessController; // ith element is number of observation rewards due to ith process, plus one. // This is expected to saturate after an oracle has submitted 65,535 // observations, or about 65535/(3*24*20) = 45 days, given a transmission // every 3 minutes. // // This is always one greater than the actual value, so that when the value is // reset to zero, we don't end up with a zero value in storage (which would // result in a higher gas cost, the next time the value is incremented.) // Calculations using this variable need to take that offset into account. uint16[maxNumOracles] internal s_oracleObservationsCounts; // Addresses at which oracles want to receive payments, by transmitter address mapping (address /* transmitter */ => address /* payment address */) internal s_payees; // Payee addresses which must be approved by the owner mapping (address /* transmitter */ => address /* payment address */) internal s_proposedPayees; // LINK-wei-denominated reimbursements for gas used by transmitters. // // This is always one greater than the actual value, so that when the value is // reset to zero, we don't end up with a zero value in storage (which would // result in a higher gas cost, the next time the value is incremented.) // Calculations using this variable need to take that offset into account. // // Argument for overflow safety: // We have the following maximum intermediate values: // - 2**40 additions to this variable (epochAndRound is a uint40) // - 2**32 gas price in ethgwei/gas // - 1e9 ethwei/ethgwei // - 2**32 gas since the block gas limit is at ~20 million // - 2**32 (microlink/eth) // And we have 2**40 * 2**32 * 1e9 * 2**32 * 2**32 < 2**166 // (we also divide in some places, but that only makes the value smaller) // We can thus safely use uint256 intermediate values for the computation // updating this variable. uint256[maxNumOracles] internal s_gasReimbursementsLinkWei; // Used for s_oracles[a].role, where a is an address, to track the purpose // of the address, or to indicate that the address is unset. enum Role { // No oracle role has been set for address a Unset, // Signing address for the s_oracles[a].index'th oracle. I.e., report // signatures from this oracle should ecrecover back to address a. Signer, // Transmission address for the s_oracles[a].index'th oracle. I.e., if a // report is received by OffchainAggregator.transmit in which msg.sender is // a, it is attributed to the s_oracles[a].index'th oracle. Transmitter } struct Oracle { uint8 index; // Index of oracle in s_signers/s_transmitters Role role; // Role of the address which mapped to this struct } mapping (address /* signer OR transmitter address */ => Oracle) internal s_oracles; // s_signers contains the signing address of each oracle address[] internal s_signers; // s_transmitters contains the transmission address of each oracle, // i.e. the address the oracle actually sends transactions to the contract from address[] internal s_transmitters; uint256 constant private maxUint16 = (1 << 16) - 1; uint256 constant internal maxUint128 = (1 << 128) - 1; constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, LinkTokenInterface _link, AccessControllerInterface _billingAccessController ) { setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); s_linkToken = _link; emit LinkTokenSet(LinkTokenInterface(address(0)), _link); setBillingAccessControllerInternal(_billingAccessController); uint16[maxNumOracles] memory counts; // See s_oracleObservationsCounts docstring uint256[maxNumOracles] memory gas; // see s_gasReimbursementsLinkWei docstring for (uint8 i = 0; i < maxNumOracles; i++) { counts[i] = 1; gas[i] = 1; } s_oracleObservationsCounts = counts; s_gasReimbursementsLinkWei = gas; } /* * @notice emitted when the LINK token contract is set * @param _oldLinkToken the address of the old LINK token contract * @param _newLinkToken the address of the new LINK token contract */ event LinkTokenSet( LinkTokenInterface indexed _oldLinkToken, LinkTokenInterface indexed _newLinkToken ); /* * @notice sets the LINK token contract used for paying oracles * @param _linkToken the address of the LINK token contract * @param _recipient remaining funds from the previous token contract are transfered * here * @dev this function will return early (without an error) without changing any state * if _linkToken equals getLinkToken(). * @dev this will trigger a payout so that a malicious owner cannot take from oracles * what is already owed to them. * @dev we assume that the token contract is correct. This contract is not written * to handle misbehaving ERC20 tokens! */ function setLinkToken( LinkTokenInterface _linkToken, address _recipient ) external onlyOwner() { LinkTokenInterface oldLinkToken = s_linkToken; if (_linkToken == oldLinkToken) { // No change, nothing to be done return; } // call balanceOf as a sanity check on whether we're talking to a token // contract _linkToken.balanceOf(address(this)); // we break CEI here, but that's okay because we're dealing with a correct // token contract (by assumption). payOracles(); uint256 remainingBalance = oldLinkToken.balanceOf(address(this)); require(oldLinkToken.transfer(_recipient, remainingBalance), "transfer remaining funds failed"); s_linkToken = _linkToken; emit LinkTokenSet(oldLinkToken, _linkToken); } /* * @notice gets the LINK token contract used for paying oracles * @return linkToken the address of the LINK token contract */ function getLinkToken() external view returns(LinkTokenInterface linkToken) { return s_linkToken; } /** * @notice emitted when billing parameters are set * @param maximumGasPrice highest gas price for which transmitter will be compensated * @param reasonableGasPrice transmitter will receive reward for gas prices under this value * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units */ event BillingSet( uint32 maximumGasPrice, uint32 reasonableGasPrice, uint32 microLinkPerEth, uint32 linkGweiPerObservation, uint32 linkGweiPerTransmission ); function setBillingInternal( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission ) internal { s_billing = Billing(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); emit BillingSet(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); } /** * @notice sets billing parameters * @param _maximumGasPrice highest gas price for which transmitter will be compensated * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units * @dev access control provided by billingAccessController */ function setBilling( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission ) external { AccessControllerInterface access = s_billingAccessController; require(msg.sender == owner || access.hasAccess(msg.sender, msg.data), "Only owner&billingAdmin can call"); payOracles(); setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); } /** * @notice gets billing parameters * @param maximumGasPrice highest gas price for which transmitter will be compensated * @param reasonableGasPrice transmitter will receive reward for gas prices under this value * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units */ function getBilling() external view returns ( uint32 maximumGasPrice, uint32 reasonableGasPrice, uint32 microLinkPerEth, uint32 linkGweiPerObservation, uint32 linkGweiPerTransmission ) { Billing memory billing = s_billing; return ( billing.maximumGasPrice, billing.reasonableGasPrice, billing.microLinkPerEth, billing.linkGweiPerObservation, billing.linkGweiPerTransmission ); } /** * @notice emitted when a new access-control contract is set * @param old the address prior to the current setting * @param current the address of the new access-control contract */ event BillingAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current); function setBillingAccessControllerInternal(AccessControllerInterface _billingAccessController) internal { AccessControllerInterface oldController = s_billingAccessController; if (_billingAccessController != oldController) { s_billingAccessController = _billingAccessController; emit BillingAccessControllerSet( oldController, _billingAccessController ); } } /** * @notice sets billingAccessController * @param _billingAccessController new billingAccessController contract address * @dev only owner can call this */ function setBillingAccessController(AccessControllerInterface _billingAccessController) external onlyOwner { setBillingAccessControllerInternal(_billingAccessController); } /** * @notice gets billingAccessController * @return address of billingAccessController contract */ function billingAccessController() external view returns (AccessControllerInterface) { return s_billingAccessController; } /** * @notice withdraws an oracle's payment from the contract * @param _transmitter the transmitter address of the oracle * @dev must be called by oracle's payee address */ function withdrawPayment(address _transmitter) external { require(msg.sender == s_payees[_transmitter], "Only payee can withdraw"); payOracle(_transmitter); } /** * @notice query an oracle's payment amount * @param _transmitter the transmitter address of the oracle */ function owedPayment(address _transmitter) public view returns (uint256) { Oracle memory oracle = s_oracles[_transmitter]; if (oracle.role == Role.Unset) { return 0; } Billing memory billing = s_billing; uint256 linkWeiAmount = uint256(s_oracleObservationsCounts[oracle.index] - 1) * uint256(billing.linkGweiPerObservation) * (1 gwei); linkWeiAmount += s_gasReimbursementsLinkWei[oracle.index] - 1; return linkWeiAmount; } /** * @notice emitted when an oracle has been paid LINK * @param transmitter address from which the oracle sends reports to the transmit method * @param payee address to which the payment is sent * @param amount amount of LINK sent * @param linkToken address of the LINK token contract */ event OraclePaid( address indexed transmitter, address indexed payee, uint256 amount, LinkTokenInterface indexed linkToken ); // payOracle pays out _transmitter's balance to the corresponding payee, and zeros it out function payOracle(address _transmitter) internal { Oracle memory oracle = s_oracles[_transmitter]; uint256 linkWeiAmount = owedPayment(_transmitter); if (linkWeiAmount > 0) { address payee = s_payees[_transmitter]; // Poses no re-entrancy issues, because LINK.transfer does not yield // control flow. require(s_linkToken.transfer(payee, linkWeiAmount), "insufficient funds"); s_oracleObservationsCounts[oracle.index] = 1; // "zero" the counts. see var's docstring s_gasReimbursementsLinkWei[oracle.index] = 1; // "zero" the counts. see var's docstring emit OraclePaid(_transmitter, payee, linkWeiAmount, s_linkToken); } } // payOracles pays out all transmitters, and zeros out their balances. // // It's much more gas-efficient to do this as a single operation, to avoid // hitting storage too much. function payOracles() internal { Billing memory billing = s_billing; LinkTokenInterface linkToken = s_linkToken; uint16[maxNumOracles] memory observationsCounts = s_oracleObservationsCounts; uint256[maxNumOracles] memory gasReimbursementsLinkWei = s_gasReimbursementsLinkWei; address[] memory transmitters = s_transmitters; for (uint transmitteridx = 0; transmitteridx < transmitters.length; transmitteridx++) { uint256 reimbursementAmountLinkWei = gasReimbursementsLinkWei[transmitteridx] - 1; uint256 obsCount = observationsCounts[transmitteridx] - 1; uint256 linkWeiAmount = obsCount * uint256(billing.linkGweiPerObservation) * (1 gwei) + reimbursementAmountLinkWei; if (linkWeiAmount > 0) { address payee = s_payees[transmitters[transmitteridx]]; // Poses no re-entrancy issues, because LINK.transfer does not yield // control flow. require(linkToken.transfer(payee, linkWeiAmount), "insufficient funds"); observationsCounts[transmitteridx] = 1; // "zero" the counts. gasReimbursementsLinkWei[transmitteridx] = 1; // "zero" the counts. emit OraclePaid(transmitters[transmitteridx], payee, linkWeiAmount, linkToken); } } // "Zero" the accounting storage variables s_oracleObservationsCounts = observationsCounts; s_gasReimbursementsLinkWei = gasReimbursementsLinkWei; } function oracleRewards( bytes memory observers, uint16[maxNumOracles] memory observations ) internal pure returns (uint16[maxNumOracles] memory) { // reward each observer-participant with the observer reward for (uint obsIdx = 0; obsIdx < observers.length; obsIdx++) { uint8 observer = uint8(observers[obsIdx]); observations[observer] = saturatingAddUint16(observations[observer], 1); } return observations; } // This value needs to change if maxNumOracles is increased, or the accounting // calculations at the bottom of reimburseAndRewardOracles change. // // To recalculate it, run the profiler as described in // ../../profile/README.md, and add up the gas-usage values reported for the // lines in reimburseAndRewardOracles following the "gasLeft = gasleft()" // line. E.g., you will see output like this: // // 7 uint256 gasLeft = gasleft(); // 29 uint256 gasCostEthWei = transmitterGasCostEthWei( // 9 uint256(initialGas), // 3 gasPrice, // 3 callDataGasCost, // 3 gasLeft // . // . // . // 59 uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6; // . // . // . // 5047 s_gasReimbursementsLinkWei[txOracle.index] = // 856 s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei + // 26 uint256(billing.linkGweiPerTransmission) * (1 gwei); // // If those were the only lines to be accounted for, you would add up // 29+9+3+3+3+59+5047+856+26=6035. uint256 internal constant accountingGasCost = 6035; // Uncomment the following declaration to compute the remaining gas cost after // above gasleft(). (This must exist in a base class to OffchainAggregator, so // it can't go in TestOffchainAggregator.) // // uint256 public gasUsedInAccounting; // Gas price at which the transmitter should be reimbursed, in ETH-gwei/gas function impliedGasPrice( uint256 txGasPrice, // ETH-gwei/gas units uint256 reasonableGasPrice, // ETH-gwei/gas units uint256 maximumGasPrice // ETH-gwei/gas units ) internal pure returns (uint256) { // Reward the transmitter for choosing an efficient gas price: if they manage // to come in lower than considered reasonable, give them half the savings. // // The following calculations are all in units of gwei/gas, i.e. 1e-9ETH/gas uint256 gasPrice = txGasPrice; if (txGasPrice < reasonableGasPrice) { // Give transmitter half the savings for coming in under the reasonable gas price gasPrice += (reasonableGasPrice - txGasPrice) / 2; } // Don't reimburse a gas price higher than maximumGasPrice return min(gasPrice, maximumGasPrice); } // gas reimbursement due the transmitter, in ETH-wei // // If this function is changed, accountingGasCost needs to change, too. See // its docstring function transmitterGasCostEthWei( uint256 initialGas, uint256 gasPrice, // ETH-gwei/gas units uint256 callDataCost, // gas units uint256 gasLeft ) internal pure returns (uint128 gasCostEthWei) { require(initialGas >= gasLeft, "gasLeft cannot exceed initialGas"); uint256 gasUsed = // gas units initialGas - gasLeft + // observed gas usage callDataCost + accountingGasCost; // estimated gas usage // gasUsed is in gas units, gasPrice is in ETH-gwei/gas units; convert to ETH-wei uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei); assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128... return uint128(fullGasCostEthWei); } /** * @notice withdraw any available funds left in the contract, up to _amount, after accounting for the funds due to participants in past reports * @param _recipient address to send funds to * @param _amount maximum amount to withdraw, denominated in LINK-wei. * @dev access control provided by billingAccessController */ function withdrawFunds(address _recipient, uint256 _amount) external { require(msg.sender == owner || s_billingAccessController.hasAccess(msg.sender, msg.data), "Only owner&billingAdmin can call"); uint256 linkDue = totalLINKDue(); uint256 linkBalance = s_linkToken.balanceOf(address(this)); require(linkBalance >= linkDue, "insufficient balance"); require(s_linkToken.transfer(_recipient, min(linkBalance - linkDue, _amount)), "insufficient funds"); } // Total LINK due to participants in past reports. function totalLINKDue() internal view returns (uint256 linkDue) { // Argument for overflow safety: We do all computations in // uint256s. The inputs to linkDue are: // - the <= 31 observation rewards each of which has less than // 64 bits (32 bits for billing.linkGweiPerObservation, 32 bits // for wei/gwei conversion). Hence 69 bits are sufficient for this part. // - the <= 31 gas reimbursements, each of which consists of at most 166 // bits (see s_gasReimbursementsLinkWei docstring). Hence 171 bits are // sufficient for this part // In total, 172 bits are enough. uint16[maxNumOracles] memory observationCounts = s_oracleObservationsCounts; for (uint i = 0; i < maxNumOracles; i++) { linkDue += observationCounts[i] - 1; // Stored value is one greater than actual value } Billing memory billing = s_billing; // Convert linkGweiPerObservation to uint256, or this overflows! linkDue *= uint256(billing.linkGweiPerObservation) * (1 gwei); address[] memory transmitters = s_transmitters; uint256[maxNumOracles] memory gasReimbursementsLinkWei = s_gasReimbursementsLinkWei; for (uint i = 0; i < transmitters.length; i++) { linkDue += uint256(gasReimbursementsLinkWei[i]-1); // Stored value is one greater than actual value } } /** * @notice allows oracles to check that sufficient LINK balance is available * @return availableBalance LINK available on this contract, after accounting for outstanding obligations. can become negative */ function linkAvailableForPayment() external view returns (int256 availableBalance) { // there are at most one billion LINK, so this cast is safe int256 balance = int256(s_linkToken.balanceOf(address(this))); // according to the argument in the definition of totalLINKDue, // totalLINKDue is never greater than 2**172, so this cast is safe int256 due = int256(totalLINKDue()); // safe from overflow according to above sizes return int256(balance) - int256(due); } /** * @notice number of observations oracle is due to be reimbursed for * @param _signerOrTransmitter address used by oracle for signing or transmitting reports */ function oracleObservationCount(address _signerOrTransmitter) external view returns (uint16) { Oracle memory oracle = s_oracles[_signerOrTransmitter]; if (oracle.role == Role.Unset) { return 0; } return s_oracleObservationsCounts[oracle.index] - 1; } function reimburseAndRewardOracles( uint32 initialGas, bytes memory observers ) internal { Oracle memory txOracle = s_oracles[msg.sender]; Billing memory billing = s_billing; // Reward oracles for providing observations. Oracles are not rewarded // for providing signatures, because signing is essentially free. s_oracleObservationsCounts = oracleRewards(observers, s_oracleObservationsCounts); // Reimburse transmitter of the report for gas usage require(txOracle.role == Role.Transmitter, "sent by undesignated transmitter" ); uint256 gasPrice = impliedGasPrice( tx.gasprice / (1 gwei), // convert to ETH-gwei units billing.reasonableGasPrice, billing.maximumGasPrice ); // The following is only an upper bound, as it ignores the cheaper cost for // 0 bytes. Safe from overflow, because calldata just isn't that long. uint256 callDataGasCost = 16 * msg.data.length; // If any changes are made to subsequent calculations, accountingGasCost // needs to change, too. uint256 gasLeft = gasleft(); uint256 gasCostEthWei = transmitterGasCostEthWei( uint256(initialGas), gasPrice, callDataGasCost, gasLeft ); // microLinkPerEth is 1e-6LINK/ETH units, gasCostEthWei is 1e-18ETH units // (ETH-wei), product is 1e-24LINK-wei units, dividing by 1e6 gives // 1e-18LINK units, i.e. LINK-wei units // Safe from over/underflow, since all components are non-negative, // gasCostEthWei will always fit into uint128 and microLinkPerEth is a // uint32 (128+32 < 256!). uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6; // Safe from overflow, because gasCostLinkWei < 2**160 and // billing.linkGweiPerTransmission * (1 gwei) < 2**64 and we increment // s_gasReimbursementsLinkWei[txOracle.index] at most 2**40 times. s_gasReimbursementsLinkWei[txOracle.index] = s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei + uint256(billing.linkGweiPerTransmission) * (1 gwei); // convert from linkGwei to linkWei // Uncomment next line to compute the remaining gas cost after above gasleft(). // See OffchainAggregatorBilling.accountingGasCost docstring for more information. // // gasUsedInAccounting = gasLeft - gasleft(); } /* * Payee management */ /** * @notice emitted when a transfer of an oracle's payee address has been initiated * @param transmitter address from which the oracle sends reports to the transmit method * @param current the payeee address for the oracle, prior to this setting * @param proposed the proposed new payee address for the oracle */ event PayeeshipTransferRequested( address indexed transmitter, address indexed current, address indexed proposed ); /** * @notice emitted when a transfer of an oracle's payee address has been completed * @param transmitter address from which the oracle sends reports to the transmit method * @param current the payeee address for the oracle, prior to this setting */ event PayeeshipTransferred( address indexed transmitter, address indexed previous, address indexed current ); /** * @notice sets the payees for transmitting addresses * @param _transmitters addresses oracles use to transmit the reports * @param _payees addresses of payees corresponding to list of transmitters * @dev must be called by owner * @dev cannot be used to change payee addresses, only to initially populate them */ function setPayees( address[] calldata _transmitters, address[] calldata _payees ) external onlyOwner() { require(_transmitters.length == _payees.length, "transmitters.size != payees.size"); for (uint i = 0; i < _transmitters.length; i++) { address transmitter = _transmitters[i]; address payee = _payees[i]; address currentPayee = s_payees[transmitter]; bool zeroedOut = currentPayee == address(0); require(zeroedOut || currentPayee == payee, "payee already set"); s_payees[transmitter] = payee; if (currentPayee != payee) { emit PayeeshipTransferred(transmitter, currentPayee, payee); } } } /** * @notice first step of payeeship transfer (safe transfer pattern) * @param _transmitter transmitter address of oracle whose payee is changing * @param _proposed new payee address * @dev can only be called by payee address */ function transferPayeeship( address _transmitter, address _proposed ) external { require(msg.sender == s_payees[_transmitter], "only current payee can update"); require(msg.sender != _proposed, "cannot transfer to self"); address previousProposed = s_proposedPayees[_transmitter]; s_proposedPayees[_transmitter] = _proposed; if (previousProposed != _proposed) { emit PayeeshipTransferRequested(_transmitter, msg.sender, _proposed); } } /** * @notice second step of payeeship transfer (safe transfer pattern) * @param _transmitter transmitter address of oracle whose payee is changing * @dev can only be called by proposed new payee address */ function acceptPayeeship( address _transmitter ) external { require(msg.sender == s_proposedPayees[_transmitter], "only proposed payees can accept"); address currentPayee = s_payees[_transmitter]; s_payees[_transmitter] = msg.sender; s_proposedPayees[_transmitter] = address(0); emit PayeeshipTransferred(_transmitter, currentPayee, msg.sender); } /* * Helper functions */ function saturatingAddUint16(uint16 _x, uint16 _y) internal pure returns (uint16) { return uint16(min(uint256(_x)+uint256(_y), maxUint16)); } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } return b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./SimpleWriteAccessController.sol"; /** * @title SimpleReadAccessController * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev SimpleReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * SimpleWriteAccessController for that. */ contract SimpleReadAccessController is SimpleWriteAccessController { /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory _calldata ) public view virtual override returns (bool) { return super.hasAccess(_user, _calldata) || _user == tx.origin; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./Owned.sol"; import "./AccessControllerInterface.sol"; /** * @title SimpleWriteAccessController * @notice Gives access to accounts explicitly added to an access list by the * controller's owner. * @dev does not make any special permissions for externally, see * SimpleReadAccessController for that. */ contract SimpleWriteAccessController is AccessControllerInterface, Owned { bool public checkEnabled; mapping(address => bool) internal accessList; event AddedAccess(address user); event RemovedAccess(address user); event CheckAccessEnabled(); event CheckAccessDisabled(); constructor() { checkEnabled = true; } /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory ) public view virtual override returns (bool) { return accessList[_user] || !checkEnabled; } /** * @notice Adds an address to the access list * @param _user The address to add */ function addAccess(address _user) external onlyOwner() { addAccessInternal(_user); } function addAccessInternal(address _user) internal { if (!accessList[_user]) { accessList[_user] = true; emit AddedAccess(_user); } } /** * @notice Removes an address from the access list * @param _user The address to remove */ function removeAccess(address _user) external onlyOwner() { if (accessList[_user]) { accessList[_user] = false; emit RemovedAccess(_user); } } /** * @notice makes the access check enforced */ function enableAccessCheck() external onlyOwner() { if (!checkEnabled) { checkEnabled = true; emit CheckAccessEnabled(); } } /** * @notice makes the access check unenforced */ function disableAccessCheck() external onlyOwner() { if (checkEnabled) { checkEnabled = false; emit CheckAccessDisabled(); } } /** * @dev reverts if the caller does not have access */ modifier checkAccess() { require(hasAccess(msg.sender, msg.data), "No access"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; abstract contract TypeAndVersionInterface{ function typeAndVersion() external pure virtual returns (string memory); }
File 6 of 7: NameWrapper
// 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.7.0) (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\\{id\\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @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 amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` 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 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../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 caller. * * 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @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); } // 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 v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./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); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @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); } import "../registry/ENS.sol"; import "./IBaseRegistrar.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IBaseRegistrar is IERC721 { event ControllerAdded(address indexed controller); event ControllerRemoved(address indexed controller); event NameMigrated( uint256 indexed id, address indexed owner, uint256 expires ); event NameRegistered( uint256 indexed id, address indexed owner, uint256 expires ); event NameRenewed(uint256 indexed id, uint256 expires); // Authorises a controller, who can register and renew domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Set the resolver for the TLD this registrar manages. function setResolver(address resolver) external; // Returns the expiration timestamp of the specified label hash. function nameExpires(uint256 id) external view returns (uint256); // Returns true iff the specified name is available for registration. function available(uint256 id) external view returns (bool); /** * @dev Register a name. */ function register( uint256 id, address owner, uint256 duration ) external returns (uint256); function renew(uint256 id, uint256 duration) external returns (uint256); /** * @dev Reclaim ownership of a name in ENS, if you own it in the registrar. */ function reclaim(uint256 id, address owner) external; } pragma solidity >=0.8.4; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setSubnodeRecord( bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl ) external; function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external returns (bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll( address owner, address operator ) external view returns (bool); } pragma solidity >=0.8.4; interface IReverseRegistrar { function setDefaultResolver(address resolver) external; function claim(address owner) external returns (bytes32); function claimForAddr( address addr, address owner, address resolver ) external returns (bytes32); function claimWithResolver( address owner, address resolver ) external returns (bytes32); function setName(string memory name) external returns (bytes32); function setNameForAddr( address addr, address owner, address resolver, string memory name ) external returns (bytes32); function node(address addr) external pure returns (bytes32); } //SPDX-License-Identifier: MIT pragma solidity >=0.8.17 <0.9.0; import {ENS} from "../registry/ENS.sol"; import {IReverseRegistrar} from "../reverseRegistrar/IReverseRegistrar.sol"; contract ReverseClaimer { bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; constructor(ENS ens, address claimant) { IReverseRegistrar reverseRegistrar = IReverseRegistrar( ens.owner(ADDR_REVERSE_NODE) ); reverseRegistrar.claim(claimant); } } //SPDX-License-Identifier: MIT pragma solidity >=0.8.17 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @notice Contract is used to recover ERC20 tokens sent to the contract by mistake. */ contract ERC20Recoverable is Ownable { /** @notice Recover ERC20 tokens sent to the contract by mistake. @dev The contract is Ownable and only the owner can call the recover function. @param _to The address to send the tokens to. @param _token The address of the ERC20 token to recover @param _amount The amount of tokens to recover. */ function recoverFunds( address _token, address _to, uint256 _amount ) external onlyOwner { IERC20(_token).transfer(_to, _amount); } } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak( bytes memory self, uint256 offset, uint256 len ) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /** * @dev Returns the ENS namehash of a DNS-encoded name. * @param self The DNS-encoded name to hash. * @param offset The offset at which to start hashing. * @return The namehash of the name. */ function namehash( bytes memory self, uint256 offset ) internal pure returns (bytes32) { (bytes32 labelhash, uint256 newOffset) = readLabel(self, offset); if (labelhash == bytes32(0)) { require(offset == self.length - 1, "namehash: Junk at end of name"); return bytes32(0); } return keccak256(abi.encodePacked(namehash(self, newOffset), labelhash)); } /** * @dev Returns the keccak-256 hash of a DNS-encoded label, and the offset to the start of the next label. * @param self The byte string to read a label from. * @param idx The index to read a label at. * @return labelhash The hash of the label at the specified index, or 0 if it is the last label. * @return newIdx The index of the start of the next label. */ function readLabel( bytes memory self, uint256 idx ) internal pure returns (bytes32 labelhash, uint256 newIdx) { require(idx < self.length, "readLabel: Index out of bounds"); uint256 len = uint256(uint8(self[idx])); if (len > 0) { labelhash = keccak(self, idx + 1, len); } else { labelhash = bytes32(0); } newIdx = idx + len + 1; } } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "@openzeppelin/contracts/access/Ownable.sol"; contract Controllable is Ownable { mapping(address => bool) public controllers; event ControllerChanged(address indexed controller, bool active); function setController(address controller, bool active) public onlyOwner { controllers[controller] = active; emit ControllerChanged(controller, active); } modifier onlyController() { require( controllers[msg.sender], "Controllable: Caller is not a controller" ); _; } } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /* This contract is a variation on ERC1155 with the additions of _setData, getData and _beforeTransfer and ownerOf. _setData and getData allows the use of the other 96 bits next to the address of the owner for extra data. We use this to store 'fuses' that control permissions that can be burnt. 32 bits are used for the fuses themselves and 64 bits are used for the expiry of the name. When a name has expired, its fuses will be be set back to 0 */ abstract contract ERC1155Fuse is ERC165, IERC1155, IERC1155MetadataURI { using Address for address; /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); mapping(uint256 => uint256) public _tokens; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Mapping from token ID to approved address mapping(uint256 => address) internal _tokenApprovals; /************************************************************************** * ERC721 methods *************************************************************************/ function ownerOf(uint256 id) public view virtual returns (address) { (address owner, , ) = getData(id); return owner; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not token owner or approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved( uint256 tokenId ) public view virtual returns (address) { return _tokenApprovals[tokenId]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf( address account, uint256 id ) public view virtual override returns (uint256) { require( account != address(0), "ERC1155: balance query for the zero address" ); address owner = ownerOf(id); if (owner == account) { return 1; } return 0; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "ERC1155: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll( address operator, bool approved ) public virtual override { require( msg.sender != operator, "ERC1155: setting approval status for self" ); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll( address account, address operator ) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev Returns the Name's owner address and fuses */ function getData( uint256 tokenId ) public view virtual returns (address owner, uint32 fuses, uint64 expiry) { uint256 t = _tokens[tokenId]; owner = address(uint160(t)); expiry = uint64(t >> 192); fuses = uint32(t >> 160); } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == msg.sender || isApprovedForAll(from, msg.sender), "ERC1155: caller is not owner nor approved" ); _transfer(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( ids.length == amounts.length, "ERC1155: ids and amounts length mismatch" ); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == msg.sender || isApprovedForAll(from, msg.sender), "ERC1155: transfer caller is not owner nor approved" ); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; (address oldOwner, uint32 fuses, uint64 expiry) = getData(id); _beforeTransfer(id, fuses, expiry); require( amount == 1 && oldOwner == from, "ERC1155: insufficient balance for transfer" ); _setData(id, to, fuses, expiry); } emit TransferBatch(msg.sender, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck( msg.sender, from, to, ids, amounts, data ); } /************************************************************************** * Internal/private methods *************************************************************************/ /** * @dev Sets the Name's owner address and fuses */ function _setData( uint256 tokenId, address owner, uint32 fuses, uint64 expiry ) internal virtual { _tokens[tokenId] = uint256(uint160(owner)) | (uint256(fuses) << 160) | (uint256(expiry) << 192); } function _beforeTransfer( uint256 id, uint32 fuses, uint64 expiry ) internal virtual; function _clearOwnerAndFuses( address owner, uint32 fuses, uint64 expiry ) internal virtual returns (address, uint32); function _mint( bytes32 node, address owner, uint32 fuses, uint64 expiry ) internal virtual { uint256 tokenId = uint256(node); (address oldOwner, uint32 oldFuses, uint64 oldExpiry) = getData( uint256(node) ); uint32 parentControlledFuses = (uint32(type(uint16).max) << 16) & oldFuses; if (oldExpiry > expiry) { expiry = oldExpiry; } if (oldExpiry >= block.timestamp) { fuses = fuses | parentControlledFuses; } require(oldOwner == address(0), "ERC1155: mint of existing token"); require(owner != address(0), "ERC1155: mint to the zero address"); require( owner != address(this), "ERC1155: newOwner cannot be the NameWrapper contract" ); _setData(tokenId, owner, fuses, expiry); emit TransferSingle(msg.sender, address(0x0), owner, tokenId, 1); _doSafeTransferAcceptanceCheck( msg.sender, address(0), owner, tokenId, 1, "" ); } function _burn(uint256 tokenId) internal virtual { (address oldOwner, uint32 fuses, uint64 expiry) = ERC1155Fuse.getData( tokenId ); (, fuses) = _clearOwnerAndFuses(oldOwner, fuses, expiry); // Clear approvals delete _tokenApprovals[tokenId]; // Fuses and expiry are kept on burn _setData(tokenId, address(0x0), fuses, expiry); emit TransferSingle(msg.sender, oldOwner, address(0x0), tokenId, 1); } function _transfer( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { (address oldOwner, uint32 fuses, uint64 expiry) = getData(id); _beforeTransfer(id, fuses, expiry); require( amount == 1 && oldOwner == from, "ERC1155: insufficient balance for transfer" ); if (oldOwner == to) { return; } _setData(id, to, fuses, expiry); emit TransferSingle(msg.sender, from, to, id, amount); _doSafeTransferAcceptanceCheck(msg.sender, from, to, id, amount, data); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if ( response != IERC1155Receiver(to).onERC1155Received.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver(to).onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } /* ERC721 internal functions */ /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; interface IMetadataService { function uri(uint256) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import "../registry/ENS.sol"; import "../ethregistrar/IBaseRegistrar.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "./IMetadataService.sol"; import "./INameWrapperUpgrade.sol"; uint32 constant CANNOT_UNWRAP = 1; uint32 constant CANNOT_BURN_FUSES = 2; uint32 constant CANNOT_TRANSFER = 4; uint32 constant CANNOT_SET_RESOLVER = 8; uint32 constant CANNOT_SET_TTL = 16; uint32 constant CANNOT_CREATE_SUBDOMAIN = 32; uint32 constant CANNOT_APPROVE = 64; //uint16 reserved for parent controlled fuses from bit 17 to bit 32 uint32 constant PARENT_CANNOT_CONTROL = 1 << 16; uint32 constant IS_DOT_ETH = 1 << 17; uint32 constant CAN_EXTEND_EXPIRY = 1 << 18; uint32 constant CAN_DO_EVERYTHING = 0; uint32 constant PARENT_CONTROLLED_FUSES = 0xFFFF0000; // all fuses apart from IS_DOT_ETH uint32 constant USER_SETTABLE_FUSES = 0xFFFDFFFF; interface INameWrapper is IERC1155 { event NameWrapped( bytes32 indexed node, bytes name, address owner, uint32 fuses, uint64 expiry ); event NameUnwrapped(bytes32 indexed node, address owner); event FusesSet(bytes32 indexed node, uint32 fuses); event ExpiryExtended(bytes32 indexed node, uint64 expiry); function ens() external view returns (ENS); function registrar() external view returns (IBaseRegistrar); function metadataService() external view returns (IMetadataService); function names(bytes32) external view returns (bytes memory); function name() external view returns (string memory); function upgradeContract() external view returns (INameWrapperUpgrade); function supportsInterface(bytes4 interfaceID) external view returns (bool); function wrap( bytes calldata name, address wrappedOwner, address resolver ) external; function wrapETH2LD( string calldata label, address wrappedOwner, uint16 ownerControlledFuses, address resolver ) external returns (uint64 expires); function registerAndWrapETH2LD( string calldata label, address wrappedOwner, uint256 duration, address resolver, uint16 ownerControlledFuses ) external returns (uint256 registrarExpiry); function renew( uint256 labelHash, uint256 duration ) external returns (uint256 expires); function unwrap(bytes32 node, bytes32 label, address owner) external; function unwrapETH2LD( bytes32 label, address newRegistrant, address newController ) external; function upgrade(bytes calldata name, bytes calldata extraData) external; function setFuses( bytes32 node, uint16 ownerControlledFuses ) external returns (uint32 newFuses); function setChildFuses( bytes32 parentNode, bytes32 labelhash, uint32 fuses, uint64 expiry ) external; function setSubnodeRecord( bytes32 node, string calldata label, address owner, address resolver, uint64 ttl, uint32 fuses, uint64 expiry ) external returns (bytes32); function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setSubnodeOwner( bytes32 node, string calldata label, address newOwner, uint32 fuses, uint64 expiry ) external returns (bytes32); function extendExpiry( bytes32 node, bytes32 labelhash, uint64 expiry ) external returns (uint64); function canModifyName( bytes32 node, address addr ) external view returns (bool); function setResolver(bytes32 node, address resolver) external; function setTTL(bytes32 node, uint64 ttl) external; function ownerOf(uint256 id) external view returns (address owner); function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address); function getData( uint256 id ) external view returns (address, uint32, uint64); function setMetadataService(IMetadataService _metadataService) external; function uri(uint256 tokenId) external view returns (string memory); function setUpgradeContract(INameWrapperUpgrade _upgradeAddress) external; function allFusesBurned( bytes32 node, uint32 fuseMask ) external view returns (bool); function isWrapped(bytes32) external view returns (bool); function isWrapped(bytes32, bytes32) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; interface INameWrapperUpgrade { function wrapFromUpgrade( bytes calldata name, address wrappedOwner, uint32 fuses, uint64 expiry, address approved, bytes calldata extraData ) external; } //SPDX-License-Identifier: MIT pragma solidity ~0.8.17; import {ERC1155Fuse, IERC165, IERC1155MetadataURI} from "./ERC1155Fuse.sol"; import {Controllable} from "./Controllable.sol"; import {INameWrapper, CANNOT_UNWRAP, CANNOT_BURN_FUSES, CANNOT_TRANSFER, CANNOT_SET_RESOLVER, CANNOT_SET_TTL, CANNOT_CREATE_SUBDOMAIN, CANNOT_APPROVE, PARENT_CANNOT_CONTROL, CAN_DO_EVERYTHING, IS_DOT_ETH, CAN_EXTEND_EXPIRY, PARENT_CONTROLLED_FUSES, USER_SETTABLE_FUSES} from "./INameWrapper.sol"; import {INameWrapperUpgrade} from "./INameWrapperUpgrade.sol"; import {IMetadataService} from "./IMetadataService.sol"; import {ENS} from "../registry/ENS.sol"; import {IReverseRegistrar} from "../reverseRegistrar/IReverseRegistrar.sol"; import {ReverseClaimer} from "../reverseRegistrar/ReverseClaimer.sol"; import {IBaseRegistrar} from "../ethregistrar/IBaseRegistrar.sol"; import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {BytesUtils} from "./BytesUtils.sol"; import {ERC20Recoverable} from "../utils/ERC20Recoverable.sol"; error Unauthorised(bytes32 node, address addr); error IncompatibleParent(); error IncorrectTokenType(); error LabelMismatch(bytes32 labelHash, bytes32 expectedLabelhash); error LabelTooShort(); error LabelTooLong(string label); error IncorrectTargetOwner(address owner); error CannotUpgrade(); error OperationProhibited(bytes32 node); error NameIsNotWrapped(); error NameIsStillExpired(); contract NameWrapper is Ownable, ERC1155Fuse, INameWrapper, Controllable, IERC721Receiver, ERC20Recoverable, ReverseClaimer { using BytesUtils for bytes; ENS public immutable ens; IBaseRegistrar public immutable registrar; IMetadataService public metadataService; mapping(bytes32 => bytes) public names; string public constant name = "NameWrapper"; uint64 private constant GRACE_PERIOD = 90 days; bytes32 private constant ETH_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; bytes32 private constant ETH_LABELHASH = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0; bytes32 private constant ROOT_NODE = 0x0000000000000000000000000000000000000000000000000000000000000000; INameWrapperUpgrade public upgradeContract; uint64 private constant MAX_EXPIRY = type(uint64).max; constructor( ENS _ens, IBaseRegistrar _registrar, IMetadataService _metadataService ) ReverseClaimer(_ens, msg.sender) { ens = _ens; registrar = _registrar; metadataService = _metadataService; /* Burn PARENT_CANNOT_CONTROL and CANNOT_UNWRAP fuses for ROOT_NODE and ETH_NODE and set expiry to max */ _setData( uint256(ETH_NODE), address(0), uint32(PARENT_CANNOT_CONTROL | CANNOT_UNWRAP), MAX_EXPIRY ); _setData( uint256(ROOT_NODE), address(0), uint32(PARENT_CANNOT_CONTROL | CANNOT_UNWRAP), MAX_EXPIRY ); names[ROOT_NODE] = "\\x00"; names[ETH_NODE] = "\\x03eth\\x00"; } function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC1155Fuse, INameWrapper) returns (bool) { return interfaceId == type(INameWrapper).interfaceId || interfaceId == type(IERC721Receiver).interfaceId || super.supportsInterface(interfaceId); } /* ERC1155 Fuse */ /** * @notice Gets the owner of a name * @param id Label as a string of the .eth domain to wrap * @return owner The owner of the name */ function ownerOf( uint256 id ) public view override(ERC1155Fuse, INameWrapper) returns (address owner) { return super.ownerOf(id); } /** * @notice Gets the owner of a name * @param id Namehash of the name * @return operator Approved operator of a name */ function getApproved( uint256 id ) public view override(ERC1155Fuse, INameWrapper) returns (address operator) { address owner = ownerOf(id); if (owner == address(0)) { return address(0); } return super.getApproved(id); } /** * @notice Approves an address for a name * @param to address to approve * @param tokenId name to approve */ function approve( address to, uint256 tokenId ) public override(ERC1155Fuse, INameWrapper) { (, uint32 fuses, ) = getData(tokenId); if (fuses & CANNOT_APPROVE == CANNOT_APPROVE) { revert OperationProhibited(bytes32(tokenId)); } super.approve(to, tokenId); } /** * @notice Gets the data for a name * @param id Namehash of the name * @return owner Owner of the name * @return fuses Fuses of the name * @return expiry Expiry of the name */ function getData( uint256 id ) public view override(ERC1155Fuse, INameWrapper) returns (address owner, uint32 fuses, uint64 expiry) { (owner, fuses, expiry) = super.getData(id); (owner, fuses) = _clearOwnerAndFuses(owner, fuses, expiry); } /* Metadata service */ /** * @notice Set the metadata service. Only the owner can do this * @param _metadataService The new metadata service */ function setMetadataService( IMetadataService _metadataService ) public onlyOwner { metadataService = _metadataService; } /** * @notice Get the metadata uri * @param tokenId The id of the token * @return string uri of the metadata service */ function uri( uint256 tokenId ) public view override(INameWrapper, IERC1155MetadataURI) returns (string memory) { return metadataService.uri(tokenId); } /** * @notice Set the address of the upgradeContract of the contract. only admin can do this * @dev The default value of upgradeContract is the 0 address. Use the 0 address at any time * to make the contract not upgradable. * @param _upgradeAddress address of an upgraded contract */ function setUpgradeContract( INameWrapperUpgrade _upgradeAddress ) public onlyOwner { if (address(upgradeContract) != address(0)) { registrar.setApprovalForAll(address(upgradeContract), false); ens.setApprovalForAll(address(upgradeContract), false); } upgradeContract = _upgradeAddress; if (address(upgradeContract) != address(0)) { registrar.setApprovalForAll(address(upgradeContract), true); ens.setApprovalForAll(address(upgradeContract), true); } } /** * @notice Checks if msg.sender is the owner or operator of the owner of a name * @param node namehash of the name to check */ modifier onlyTokenOwner(bytes32 node) { if (!canModifyName(node, msg.sender)) { revert Unauthorised(node, msg.sender); } _; } /** * @notice Checks if owner or operator of the owner * @param node namehash of the name to check * @param addr which address to check permissions for * @return whether or not is owner or operator */ function canModifyName( bytes32 node, address addr ) public view returns (bool) { (address owner, uint32 fuses, uint64 expiry) = getData(uint256(node)); return (owner == addr || isApprovedForAll(owner, addr)) && !_isETH2LDInGracePeriod(fuses, expiry); } /** * @notice Checks if owner/operator or approved by owner * @param node namehash of the name to check * @param addr which address to check permissions for * @return whether or not is owner/operator or approved */ function canExtendSubnames( bytes32 node, address addr ) public view returns (bool) { (address owner, uint32 fuses, uint64 expiry) = getData(uint256(node)); return (owner == addr || isApprovedForAll(owner, addr) || getApproved(uint256(node)) == addr) && !_isETH2LDInGracePeriod(fuses, expiry); } /** * @notice Wraps a .eth domain, creating a new token and sending the original ERC721 token to this contract * @dev Can be called by the owner of the name on the .eth registrar or an authorised caller on the registrar * @param label Label as a string of the .eth domain to wrap * @param wrappedOwner Owner of the name in this contract * @param ownerControlledFuses Initial owner-controlled fuses to set * @param resolver Resolver contract address */ function wrapETH2LD( string calldata label, address wrappedOwner, uint16 ownerControlledFuses, address resolver ) public returns (uint64 expiry) { uint256 tokenId = uint256(keccak256(bytes(label))); address registrant = registrar.ownerOf(tokenId); if ( registrant != msg.sender && !registrar.isApprovedForAll(registrant, msg.sender) ) { revert Unauthorised( _makeNode(ETH_NODE, bytes32(tokenId)), msg.sender ); } // transfer the token from the user to this contract registrar.transferFrom(registrant, address(this), tokenId); // transfer the ens record back to the new owner (this contract) registrar.reclaim(tokenId, address(this)); expiry = uint64(registrar.nameExpires(tokenId)) + GRACE_PERIOD; _wrapETH2LD( label, wrappedOwner, ownerControlledFuses, expiry, resolver ); } /** * @dev Registers a new .eth second-level domain and wraps it. * Only callable by authorised controllers. * @param label The label to register (Eg, 'foo' for 'foo.eth'). * @param wrappedOwner The owner of the wrapped name. * @param duration The duration, in seconds, to register the name for. * @param resolver The resolver address to set on the ENS registry (optional). * @param ownerControlledFuses Initial owner-controlled fuses to set * @return registrarExpiry The expiry date of the new name on the .eth registrar, in seconds since the Unix epoch. */ function registerAndWrapETH2LD( string calldata label, address wrappedOwner, uint256 duration, address resolver, uint16 ownerControlledFuses ) external onlyController returns (uint256 registrarExpiry) { uint256 tokenId = uint256(keccak256(bytes(label))); registrarExpiry = registrar.register(tokenId, address(this), duration); _wrapETH2LD( label, wrappedOwner, ownerControlledFuses, uint64(registrarExpiry) + GRACE_PERIOD, resolver ); } /** * @notice Renews a .eth second-level domain. * @dev Only callable by authorised controllers. * @param tokenId The hash of the label to register (eg, `keccak256('foo')`, for 'foo.eth'). * @param duration The number of seconds to renew the name for. * @return expires The expiry date of the name on the .eth registrar, in seconds since the Unix epoch. */ function renew( uint256 tokenId, uint256 duration ) external onlyController returns (uint256 expires) { bytes32 node = _makeNode(ETH_NODE, bytes32(tokenId)); uint256 registrarExpiry = registrar.renew(tokenId, duration); // Do not set anything in wrapper if name is not wrapped try registrar.ownerOf(tokenId) returns (address registrarOwner) { if ( registrarOwner != address(this) || ens.owner(node) != address(this) ) { return registrarExpiry; } } catch { return registrarExpiry; } // Set expiry in Wrapper uint64 expiry = uint64(registrarExpiry) + GRACE_PERIOD; // Use super to allow names expired on the wrapper, but not expired on the registrar to renew() (address owner, uint32 fuses, ) = super.getData(uint256(node)); _setData(node, owner, fuses, expiry); return registrarExpiry; } /** * @notice Wraps a non .eth domain, of any kind. Could be a DNSSEC name vitalik.xyz or a subdomain * @dev Can be called by the owner in the registry or an authorised caller in the registry * @param name The name to wrap, in DNS format * @param wrappedOwner Owner of the name in this contract * @param resolver Resolver contract */ function wrap( bytes calldata name, address wrappedOwner, address resolver ) public { (bytes32 labelhash, uint256 offset) = name.readLabel(0); bytes32 parentNode = name.namehash(offset); bytes32 node = _makeNode(parentNode, labelhash); names[node] = name; if (parentNode == ETH_NODE) { revert IncompatibleParent(); } address owner = ens.owner(node); if (owner != msg.sender && !ens.isApprovedForAll(owner, msg.sender)) { revert Unauthorised(node, msg.sender); } if (resolver != address(0)) { ens.setResolver(node, resolver); } ens.setOwner(node, address(this)); _wrap(node, name, wrappedOwner, 0, 0); } /** * @notice Unwraps a .eth domain. e.g. vitalik.eth * @dev Can be called by the owner in the wrapper or an authorised caller in the wrapper * @param labelhash Labelhash of the .eth domain * @param registrant Sets the owner in the .eth registrar to this address * @param controller Sets the owner in the registry to this address */ function unwrapETH2LD( bytes32 labelhash, address registrant, address controller ) public onlyTokenOwner(_makeNode(ETH_NODE, labelhash)) { if (registrant == address(this)) { revert IncorrectTargetOwner(registrant); } _unwrap(_makeNode(ETH_NODE, labelhash), controller); registrar.safeTransferFrom( address(this), registrant, uint256(labelhash) ); } /** * @notice Unwraps a non .eth domain, of any kind. Could be a DNSSEC name vitalik.xyz or a subdomain * @dev Can be called by the owner in the wrapper or an authorised caller in the wrapper * @param parentNode Parent namehash of the name e.g. vitalik.xyz would be namehash('xyz') * @param labelhash Labelhash of the name, e.g. vitalik.xyz would be keccak256('vitalik') * @param controller Sets the owner in the registry to this address */ function unwrap( bytes32 parentNode, bytes32 labelhash, address controller ) public onlyTokenOwner(_makeNode(parentNode, labelhash)) { if (parentNode == ETH_NODE) { revert IncompatibleParent(); } if (controller == address(0x0) || controller == address(this)) { revert IncorrectTargetOwner(controller); } _unwrap(_makeNode(parentNode, labelhash), controller); } /** * @notice Sets fuses of a name * @param node Namehash of the name * @param ownerControlledFuses Owner-controlled fuses to burn * @return Old fuses */ function setFuses( bytes32 node, uint16 ownerControlledFuses ) public onlyTokenOwner(node) operationAllowed(node, CANNOT_BURN_FUSES) returns (uint32) { // owner protected by onlyTokenOwner (address owner, uint32 oldFuses, uint64 expiry) = getData( uint256(node) ); _setFuses(node, owner, ownerControlledFuses | oldFuses, expiry, expiry); return oldFuses; } /** * @notice Extends expiry for a name * @param parentNode Parent namehash of the name e.g. vitalik.xyz would be namehash('xyz') * @param labelhash Labelhash of the name, e.g. vitalik.xyz would be keccak256('vitalik') * @param expiry When the name will expire in seconds since the Unix epoch * @return New expiry */ function extendExpiry( bytes32 parentNode, bytes32 labelhash, uint64 expiry ) public returns (uint64) { bytes32 node = _makeNode(parentNode, labelhash); if (!_isWrapped(node)) { revert NameIsNotWrapped(); } // this flag is used later, when checking fuses bool canExtendSubname = canExtendSubnames(parentNode, msg.sender); // only allow the owner of the name or owner of the parent name if (!canExtendSubname && !canModifyName(node, msg.sender)) { revert Unauthorised(node, msg.sender); } (address owner, uint32 fuses, uint64 oldExpiry) = getData( uint256(node) ); // Either CAN_EXTEND_EXPIRY must be set, or the caller must have permission to modify the parent name if (!canExtendSubname && fuses & CAN_EXTEND_EXPIRY == 0) { revert OperationProhibited(node); } // Max expiry is set to the expiry of the parent (, , uint64 maxExpiry) = getData(uint256(parentNode)); expiry = _normaliseExpiry(expiry, oldExpiry, maxExpiry); _setData(node, owner, fuses, expiry); emit ExpiryExtended(node, expiry); return expiry; } /** * @notice Upgrades a domain of any kind. Could be a .eth name vitalik.eth, a DNSSEC name vitalik.xyz, or a subdomain * @dev Can be called by the owner or an authorised caller * @param name The name to upgrade, in DNS format * @param extraData Extra data to pass to the upgrade contract */ function upgrade(bytes calldata name, bytes calldata extraData) public { bytes32 node = name.namehash(0); if (address(upgradeContract) == address(0)) { revert CannotUpgrade(); } if (!canModifyName(node, msg.sender)) { revert Unauthorised(node, msg.sender); } (address currentOwner, uint32 fuses, uint64 expiry) = getData( uint256(node) ); address approved = getApproved(uint256(node)); _burn(uint256(node)); upgradeContract.wrapFromUpgrade( name, currentOwner, fuses, expiry, approved, extraData ); } /** /* @notice Sets fuses of a name that you own the parent of * @param parentNode Parent namehash of the name e.g. vitalik.xyz would be namehash('xyz') * @param labelhash Labelhash of the name, e.g. vitalik.xyz would be keccak256('vitalik') * @param fuses Fuses to burn * @param expiry When the name will expire in seconds since the Unix epoch */ function setChildFuses( bytes32 parentNode, bytes32 labelhash, uint32 fuses, uint64 expiry ) public { bytes32 node = _makeNode(parentNode, labelhash); _checkFusesAreSettable(node, fuses); (address owner, uint32 oldFuses, uint64 oldExpiry) = getData( uint256(node) ); if (owner == address(0) || ens.owner(node) != address(this)) { revert NameIsNotWrapped(); } // max expiry is set to the expiry of the parent (, uint32 parentFuses, uint64 maxExpiry) = getData(uint256(parentNode)); if (parentNode == ROOT_NODE) { if (!canModifyName(node, msg.sender)) { revert Unauthorised(node, msg.sender); } } else { if (!canModifyName(parentNode, msg.sender)) { revert Unauthorised(parentNode, msg.sender); } } _checkParentFuses(node, fuses, parentFuses); expiry = _normaliseExpiry(expiry, oldExpiry, maxExpiry); // if PARENT_CANNOT_CONTROL has been burned and fuses have changed if ( oldFuses & PARENT_CANNOT_CONTROL != 0 && oldFuses | fuses != oldFuses ) { revert OperationProhibited(node); } fuses |= oldFuses; _setFuses(node, owner, fuses, oldExpiry, expiry); } /** * @notice Sets the subdomain owner in the registry and then wraps the subdomain * @param parentNode Parent namehash of the subdomain * @param label Label of the subdomain as a string * @param owner New owner in the wrapper * @param fuses Initial fuses for the wrapped subdomain * @param expiry When the name will expire in seconds since the Unix epoch * @return node Namehash of the subdomain */ function setSubnodeOwner( bytes32 parentNode, string calldata label, address owner, uint32 fuses, uint64 expiry ) public onlyTokenOwner(parentNode) returns (bytes32 node) { bytes32 labelhash = keccak256(bytes(label)); node = _makeNode(parentNode, labelhash); _checkCanCallSetSubnodeOwner(parentNode, node); _checkFusesAreSettable(node, fuses); bytes memory name = _saveLabel(parentNode, node, label); expiry = _checkParentFusesAndExpiry(parentNode, node, fuses, expiry); if (!_isWrapped(node)) { ens.setSubnodeOwner(parentNode, labelhash, address(this)); _wrap(node, name, owner, fuses, expiry); } else { _updateName(parentNode, node, label, owner, fuses, expiry); } } /** * @notice Sets the subdomain owner in the registry with records and then wraps the subdomain * @param parentNode parent namehash of the subdomain * @param label label of the subdomain as a string * @param owner new owner in the wrapper * @param resolver resolver contract in the registry * @param ttl ttl in the registry * @param fuses initial fuses for the wrapped subdomain * @param expiry When the name will expire in seconds since the Unix epoch * @return node Namehash of the subdomain */ function setSubnodeRecord( bytes32 parentNode, string memory label, address owner, address resolver, uint64 ttl, uint32 fuses, uint64 expiry ) public onlyTokenOwner(parentNode) returns (bytes32 node) { bytes32 labelhash = keccak256(bytes(label)); node = _makeNode(parentNode, labelhash); _checkCanCallSetSubnodeOwner(parentNode, node); _checkFusesAreSettable(node, fuses); _saveLabel(parentNode, node, label); expiry = _checkParentFusesAndExpiry(parentNode, node, fuses, expiry); if (!_isWrapped(node)) { ens.setSubnodeRecord( parentNode, labelhash, address(this), resolver, ttl ); _storeNameAndWrap(parentNode, node, label, owner, fuses, expiry); } else { ens.setSubnodeRecord( parentNode, labelhash, address(this), resolver, ttl ); _updateName(parentNode, node, label, owner, fuses, expiry); } } /** * @notice Sets records for the name in the ENS Registry * @param node Namehash of the name to set a record for * @param owner New owner in the registry * @param resolver Resolver contract * @param ttl Time to live in the registry */ function setRecord( bytes32 node, address owner, address resolver, uint64 ttl ) public onlyTokenOwner(node) operationAllowed( node, CANNOT_TRANSFER | CANNOT_SET_RESOLVER | CANNOT_SET_TTL ) { ens.setRecord(node, address(this), resolver, ttl); if (owner == address(0)) { (, uint32 fuses, ) = getData(uint256(node)); if (fuses & IS_DOT_ETH == IS_DOT_ETH) { revert IncorrectTargetOwner(owner); } _unwrap(node, address(0)); } else { address oldOwner = ownerOf(uint256(node)); _transfer(oldOwner, owner, uint256(node), 1, ""); } } /** * @notice Sets resolver contract in the registry * @param node namehash of the name * @param resolver the resolver contract */ function setResolver( bytes32 node, address resolver ) public onlyTokenOwner(node) operationAllowed(node, CANNOT_SET_RESOLVER) { ens.setResolver(node, resolver); } /** * @notice Sets TTL in the registry * @param node Namehash of the name * @param ttl TTL in the registry */ function setTTL( bytes32 node, uint64 ttl ) public onlyTokenOwner(node) operationAllowed(node, CANNOT_SET_TTL) { ens.setTTL(node, ttl); } /** * @dev Allows an operation only if none of the specified fuses are burned. * @param node The namehash of the name to check fuses on. * @param fuseMask A bitmask of fuses that must not be burned. */ modifier operationAllowed(bytes32 node, uint32 fuseMask) { (, uint32 fuses, ) = getData(uint256(node)); if (fuses & fuseMask != 0) { revert OperationProhibited(node); } _; } /** * @notice Check whether a name can call setSubnodeOwner/setSubnodeRecord * @dev Checks both CANNOT_CREATE_SUBDOMAIN and PARENT_CANNOT_CONTROL and whether not they have been burnt * and checks whether the owner of the subdomain is 0x0 for creating or already exists for * replacing a subdomain. If either conditions are true, then it is possible to call * setSubnodeOwner * @param parentNode Namehash of the parent name to check * @param subnode Namehash of the subname to check */ function _checkCanCallSetSubnodeOwner( bytes32 parentNode, bytes32 subnode ) internal view { ( address subnodeOwner, uint32 subnodeFuses, uint64 subnodeExpiry ) = getData(uint256(subnode)); // check if the registry owner is 0 and expired // check if the wrapper owner is 0 and expired // If either, then check parent fuses for CANNOT_CREATE_SUBDOMAIN bool expired = subnodeExpiry < block.timestamp; if ( expired && // protects a name that has been unwrapped with PCC and doesn't allow the parent to take control by recreating it if unexpired (subnodeOwner == address(0) || // protects a name that has been burnt and doesn't allow the parent to take control by recreating it if unexpired ens.owner(subnode) == address(0)) ) { (, uint32 parentFuses, ) = getData(uint256(parentNode)); if (parentFuses & CANNOT_CREATE_SUBDOMAIN != 0) { revert OperationProhibited(subnode); } } else { if (subnodeFuses & PARENT_CANNOT_CONTROL != 0) { revert OperationProhibited(subnode); } } } /** * @notice Checks all Fuses in the mask are burned for the node * @param node Namehash of the name * @param fuseMask The fuses you want to check * @return Boolean of whether or not all the selected fuses are burned */ function allFusesBurned( bytes32 node, uint32 fuseMask ) public view returns (bool) { (, uint32 fuses, ) = getData(uint256(node)); return fuses & fuseMask == fuseMask; } /** * @notice Checks if a name is wrapped * @param node Namehash of the name * @return Boolean of whether or not the name is wrapped */ function isWrapped(bytes32 node) public view returns (bool) { bytes memory name = names[node]; if (name.length == 0) { return false; } (bytes32 labelhash, uint256 offset) = name.readLabel(0); bytes32 parentNode = name.namehash(offset); return isWrapped(parentNode, labelhash); } /** * @notice Checks if a name is wrapped in a more gas efficient way * @param parentNode Namehash of the name * @param labelhash Namehash of the name * @return Boolean of whether or not the name is wrapped */ function isWrapped( bytes32 parentNode, bytes32 labelhash ) public view returns (bool) { bytes32 node = _makeNode(parentNode, labelhash); bool wrapped = _isWrapped(node); if (parentNode != ETH_NODE) { return wrapped; } try registrar.ownerOf(uint256(labelhash)) returns (address owner) { return owner == address(this); } catch { return false; } } function onERC721Received( address to, address, uint256 tokenId, bytes calldata data ) public returns (bytes4) { //check if it's the eth registrar ERC721 if (msg.sender != address(registrar)) { revert IncorrectTokenType(); } ( string memory label, address owner, uint16 ownerControlledFuses, address resolver ) = abi.decode(data, (string, address, uint16, address)); bytes32 labelhash = bytes32(tokenId); bytes32 labelhashFromData = keccak256(bytes(label)); if (labelhashFromData != labelhash) { revert LabelMismatch(labelhashFromData, labelhash); } // transfer the ens record back to the new owner (this contract) registrar.reclaim(uint256(labelhash), address(this)); uint64 expiry = uint64(registrar.nameExpires(tokenId)) + GRACE_PERIOD; _wrapETH2LD(label, owner, ownerControlledFuses, expiry, resolver); return IERC721Receiver(to).onERC721Received.selector; } /***** Internal functions */ function _beforeTransfer( uint256 id, uint32 fuses, uint64 expiry ) internal override { // For this check, treat .eth 2LDs as expiring at the start of the grace period. if (fuses & IS_DOT_ETH == IS_DOT_ETH) { expiry -= GRACE_PERIOD; } if (expiry < block.timestamp) { // Transferable if the name was not emancipated if (fuses & PARENT_CANNOT_CONTROL != 0) { revert("ERC1155: insufficient balance for transfer"); } } else { // Transferable if CANNOT_TRANSFER is unburned if (fuses & CANNOT_TRANSFER != 0) { revert OperationProhibited(bytes32(id)); } } // delete token approval if CANNOT_APPROVE has not been burnt if (fuses & CANNOT_APPROVE == 0) { delete _tokenApprovals[id]; } } function _clearOwnerAndFuses( address owner, uint32 fuses, uint64 expiry ) internal view override returns (address, uint32) { if (expiry < block.timestamp) { if (fuses & PARENT_CANNOT_CONTROL == PARENT_CANNOT_CONTROL) { owner = address(0); } fuses = 0; } return (owner, fuses); } function _makeNode( bytes32 node, bytes32 labelhash ) private pure returns (bytes32) { return keccak256(abi.encodePacked(node, labelhash)); } function _addLabel( string memory label, bytes memory name ) internal pure returns (bytes memory ret) { if (bytes(label).length < 1) { revert LabelTooShort(); } if (bytes(label).length > 255) { revert LabelTooLong(label); } return abi.encodePacked(uint8(bytes(label).length), label, name); } function _mint( bytes32 node, address owner, uint32 fuses, uint64 expiry ) internal override { _canFusesBeBurned(node, fuses); (address oldOwner, , ) = super.getData(uint256(node)); if (oldOwner != address(0)) { // burn and unwrap old token of old owner _burn(uint256(node)); emit NameUnwrapped(node, address(0)); } super._mint(node, owner, fuses, expiry); } function _wrap( bytes32 node, bytes memory name, address wrappedOwner, uint32 fuses, uint64 expiry ) internal { _mint(node, wrappedOwner, fuses, expiry); emit NameWrapped(node, name, wrappedOwner, fuses, expiry); } function _storeNameAndWrap( bytes32 parentNode, bytes32 node, string memory label, address owner, uint32 fuses, uint64 expiry ) internal { bytes memory name = _addLabel(label, names[parentNode]); _wrap(node, name, owner, fuses, expiry); } function _saveLabel( bytes32 parentNode, bytes32 node, string memory label ) internal returns (bytes memory) { bytes memory name = _addLabel(label, names[parentNode]); names[node] = name; return name; } function _updateName( bytes32 parentNode, bytes32 node, string memory label, address owner, uint32 fuses, uint64 expiry ) internal { (address oldOwner, uint32 oldFuses, uint64 oldExpiry) = getData( uint256(node) ); bytes memory name = _addLabel(label, names[parentNode]); if (names[node].length == 0) { names[node] = name; } _setFuses(node, oldOwner, oldFuses | fuses, oldExpiry, expiry); if (owner == address(0)) { _unwrap(node, address(0)); } else { _transfer(oldOwner, owner, uint256(node), 1, ""); } } // wrapper function for stack limit function _checkParentFusesAndExpiry( bytes32 parentNode, bytes32 node, uint32 fuses, uint64 expiry ) internal view returns (uint64) { (, , uint64 oldExpiry) = getData(uint256(node)); (, uint32 parentFuses, uint64 maxExpiry) = getData(uint256(parentNode)); _checkParentFuses(node, fuses, parentFuses); return _normaliseExpiry(expiry, oldExpiry, maxExpiry); } function _checkParentFuses( bytes32 node, uint32 fuses, uint32 parentFuses ) internal pure { bool isBurningParentControlledFuses = fuses & PARENT_CONTROLLED_FUSES != 0; bool parentHasNotBurnedCU = parentFuses & CANNOT_UNWRAP == 0; if (isBurningParentControlledFuses && parentHasNotBurnedCU) { revert OperationProhibited(node); } } function _normaliseExpiry( uint64 expiry, uint64 oldExpiry, uint64 maxExpiry ) private pure returns (uint64) { // Expiry cannot be more than maximum allowed // .eth names will check registrar, non .eth check parent if (expiry > maxExpiry) { expiry = maxExpiry; } // Expiry cannot be less than old expiry if (expiry < oldExpiry) { expiry = oldExpiry; } return expiry; } function _wrapETH2LD( string memory label, address wrappedOwner, uint32 fuses, uint64 expiry, address resolver ) private { bytes32 labelhash = keccak256(bytes(label)); bytes32 node = _makeNode(ETH_NODE, labelhash); // hardcode dns-encoded eth string for gas savings bytes memory name = _addLabel(label, "\\x03eth\\x00"); names[node] = name; _wrap( node, name, wrappedOwner, fuses | PARENT_CANNOT_CONTROL | IS_DOT_ETH, expiry ); if (resolver != address(0)) { ens.setResolver(node, resolver); } } function _unwrap(bytes32 node, address owner) private { if (allFusesBurned(node, CANNOT_UNWRAP)) { revert OperationProhibited(node); } // Burn token and fuse data _burn(uint256(node)); ens.setOwner(node, owner); emit NameUnwrapped(node, owner); } function _setFuses( bytes32 node, address owner, uint32 fuses, uint64 oldExpiry, uint64 expiry ) internal { _setData(node, owner, fuses, expiry); emit FusesSet(node, fuses); if (expiry > oldExpiry) { emit ExpiryExtended(node, expiry); } } function _setData( bytes32 node, address owner, uint32 fuses, uint64 expiry ) internal { _canFusesBeBurned(node, fuses); super._setData(uint256(node), owner, fuses, expiry); } function _canFusesBeBurned(bytes32 node, uint32 fuses) internal pure { // If a non-parent controlled fuse is being burned, check PCC and CU are burnt if ( fuses & ~PARENT_CONTROLLED_FUSES != 0 && fuses & (PARENT_CANNOT_CONTROL | CANNOT_UNWRAP) != (PARENT_CANNOT_CONTROL | CANNOT_UNWRAP) ) { revert OperationProhibited(node); } } function _checkFusesAreSettable(bytes32 node, uint32 fuses) internal pure { if (fuses | USER_SETTABLE_FUSES != USER_SETTABLE_FUSES) { // Cannot directly burn other non-user settable fuses revert OperationProhibited(node); } } function _isWrapped(bytes32 node) internal view returns (bool) { return ownerOf(uint256(node)) != address(0) && ens.owner(node) == address(this); } function _isETH2LDInGracePeriod( uint32 fuses, uint64 expiry ) internal view returns (bool) { return fuses & IS_DOT_ETH == IS_DOT_ETH && expiry - GRACE_PERIOD < block.timestamp; } }
File 7 of 7: ENSRegistryWithFallback
// File: @ensdomains/ens/contracts/ENS.sol pragma solidity >=0.4.24; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } // File: @ensdomains/ens/contracts/ENSRegistry.sol pragma solidity ^0.5.0; /** * The ENS registry contract. */ contract ENSRegistry is ENS { struct Record { address owner; address resolver; uint64 ttl; } mapping (bytes32 => Record) records; mapping (address => mapping(address => bool)) operators; // Permits modifications only by the owner of the specified node. modifier authorised(bytes32 node) { address owner = records[node].owner; require(owner == msg.sender || operators[owner][msg.sender]); _; } /** * @dev Constructs a new ENS registrar. */ constructor() public { records[0x0].owner = msg.sender; } /** * @dev Sets the record for a node. * @param node The node to update. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external { setOwner(node, owner); _setResolverAndTTL(node, resolver, ttl); } /** * @dev Sets the record for a subnode. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external { bytes32 subnode = setSubnodeOwner(node, label, owner); _setResolverAndTTL(subnode, resolver, ttl); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) public authorised(node) { _setOwner(node, owner); emit Transfer(node, owner); } /** * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(node, label)); _setOwner(subnode, owner); emit NewOwner(node, label, owner); return subnode; } /** * @dev Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) public authorised(node) { emit NewResolver(node, resolver); records[node].resolver = resolver; } /** * @dev Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) public authorised(node) { emit NewTTL(node, ttl); records[node].ttl = ttl; } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s ENS records. Emits the ApprovalForAll event. * @param operator Address to add to the set of authorized operators. * @param approved True if the operator is approved, false to revoke approval. */ function setApprovalForAll(address operator, bool approved) external { operators[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public view returns (address) { address addr = records[node].owner; if (addr == address(this)) { return address(0x0); } return addr; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public view returns (address) { return records[node].resolver; } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; } /** * @dev Returns whether a record has been imported to the registry. * @param node The specified node. * @return Bool if record exists */ function recordExists(bytes32 node) public view returns (bool) { return records[node].owner != address(0x0); } /** * @dev Query if an address is an authorized operator for another address. * @param owner The address that owns the records. * @param operator The address that acts on behalf of the owner. * @return True if `operator` is an approved operator for `owner`, false otherwise. */ function isApprovedForAll(address owner, address operator) external view returns (bool) { return operators[owner][operator]; } function _setOwner(bytes32 node, address owner) internal { records[node].owner = owner; } function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal { if(resolver != records[node].resolver) { records[node].resolver = resolver; emit NewResolver(node, resolver); } if(ttl != records[node].ttl) { records[node].ttl = ttl; emit NewTTL(node, ttl); } } } // File: @ensdomains/ens/contracts/ENSRegistryWithFallback.sol pragma solidity ^0.5.0; /** * The ENS registry contract. */ contract ENSRegistryWithFallback is ENSRegistry { ENS public old; /** * @dev Constructs a new ENS registrar. */ constructor(ENS _old) public ENSRegistry() { old = _old; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public view returns (address) { if (!recordExists(node)) { return old.resolver(node); } return super.resolver(node); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public view returns (address) { if (!recordExists(node)) { return old.owner(node); } return super.owner(node); } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public view returns (uint64) { if (!recordExists(node)) { return old.ttl(node); } return super.ttl(node); } function _setOwner(bytes32 node, address owner) internal { address addr = owner; if (addr == address(0x0)) { addr = address(this); } super._setOwner(node, addr); } }