Verified contractExactMIT
ERC3668Resolver
Address0xc9bf092673b3a066df088a2a911e23e9b69b82f2
- Balance
0 ETH
- Transactions
9
- Compiler
solc 0.8.17
- Same code
Only this contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- No
- EVM version
- london
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 18,532,885
- Creation transaction
- 0x01bcaa3e37…92ef74c1ee
17 files
- contracts/ERC3668Resolver.solmain16.4 KB
- @ensdomains/ens-contracts/contracts/ethregistrar/IBaseRegistrar.sol1.6 KB
- @ensdomains/ens-contracts/contracts/registry/ENS.sol1.79 KB
- @ensdomains/ens-contracts/contracts/registry/ENSRegistry.sol6.43 KB
- @ensdomains/ens-contracts/contracts/wrapper/BytesUtils.sol2.12 KB
- @ensdomains/ens-contracts/contracts/wrapper/IMetadataService.sol153 B
- @ensdomains/ens-contracts/contracts/wrapper/INameWrapper.sol4.47 KB
- @ensdomains/ens-contracts/contracts/wrapper/INameWrapperUpgrade.sol274 B
- @openzeppelin/contracts/token/ERC1155/IERC1155.sol4.03 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.88 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- contracts/IExtendedResolver.sol391 B
- contracts/IMetadataResolver.sol1 KB
- contracts/SupportsInterface.sol405 B
- contracts/verifier/CcipResponseVerifier.sol4.09 KB
- contracts/verifier/ICcipResponseVerifier.sol558 B
- solidity-bytes-utils/contracts/BytesLib.sol19.28 KB
contracts/ERC3668Resolver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {IExtendedResolver, IResolverService} from "./IExtendedResolver.sol";
import {IMetadataResolver} from "./IMetadataResolver.sol";
import {SupportsInterface} from "./SupportsInterface.sol";
import {CcipResponseVerifier, ICcipResponseVerifier} from "./verifier/CcipResponseVerifier.sol";
import {ENSRegistry} from "@ensdomains/ens-contracts/contracts/registry/ENSRegistry.sol";
import {INameWrapper} from "@ensdomains/ens-contracts/contracts/wrapper/INameWrapper.sol";
import {BytesUtils} from "@ensdomains/ens-contracts/contracts/wrapper/BytesUtils.sol";
import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol";
/*
* Implements an ENS resolver that directs all queries to a CCIP read gateway.
* Callers must implement EIP 3668 and ENSIP 10.
*/
contract ERC3668Resolver is IExtendedResolver, IMetadataResolver, SupportsInterface {
using BytesUtils for bytes;
struct CcipVerifier {
string[] gatewayUrls;
ICcipResponseVerifier verifierAddress;
}
/**
* The idnetifier to store the default verifier
*/
bytes32 private constant DEFAULT_VERIFIER = bytes32(0);
/*
* --------------------------------------------------
* EVENTS
* --------------------------------------------------
*/
event VerifierAdded(bytes32 indexed node, address verifierAddress, string[] gatewayUrls);
/*
* --------------------------------------------------
* Errors
* --------------------------------------------------
*/
error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);
/*
* --------------------------------------------------
* State Variables
* --------------------------------------------------
*/
ENSRegistry public immutable ensRegistry;
INameWrapper public immutable nameWrapper;
mapping(bytes32 => CcipVerifier) public ccipVerifier;
/*
* --------------------------------------------------
* Constructor
* --------------------------------------------------
*/
constructor(
// The ENS registry
ENSRegistry _ensRegistry,
// The name wrapper
INameWrapper _nameWrapper,
//Address of the default CCIP Verifier
address _defaultVerifier,
string[] memory _gatewayUrls
) {
ensRegistry = _ensRegistry;
nameWrapper = _nameWrapper;
/**
* If a default verifier is set, that verifier will be used by every child address that doesn't have a specific verifier set.
*
*/
if (_defaultVerifier != address(0)) {
_setVerifierForDomain(DEFAULT_VERIFIER, _defaultVerifier, _gatewayUrls);
}
}
/*
* --------------------------------------------------
* External functions
* --------------------------------------------------
*/
/**
* @notice Sets a Cross-chain Information Protocol (CCIP) Verifier for a specific domain node.
* @param node The domain node for which the CCIP Verifier is set.
* @param verifierAddress The address of the CcipResponseVerifier contract.
* @param urls The gateway url that should handle the OffchainLookup.
*/
function setVerifierForDomain(bytes32 node, address verifierAddress, string[] memory urls) external {
/*
* Only the node owner can set the verifier for a node. NameWrapper profiles are supported too.
*/
require(node != bytes32(0), "node is 0x0");
require(msg.sender == getNodeOwner(node), "only node owner");
_setVerifierForDomain(node, verifierAddress, urls);
}
/**
* Resolves arbitrary data for a particular name, as specified by ENSIP 10.
* @param name The DNS-encoded name to resolve.
* @param data The ABI encoded data for the underlying resolution function (Eg, addr(bytes32), text(bytes32,string), etc).
* @return The return data, ABI encoded identically to the underlying function.
*/
function resolve(bytes calldata name, bytes calldata data) external view override returns (bytes memory) {
/*
* Get the verifier for the given name.
* reverts if no verifier was set in advance
*/
(CcipVerifier memory _verifier, bytes32 node) = getVerifierOfDomain(name);
/*
* Retrieves the owner of the node. NameWrapper profiles are supported too. This will be the context of the request.
*/
address nodeOwner = getNameOwner(name, 0);
bytes memory context = abi.encodePacked(nodeOwner);
/*
* The calldata the gateway has to resolve
*/
bytes memory callData = abi.encodeWithSelector(
IResolverService.resolveWithContext.selector,
name,
data,
context
);
revert OffchainLookup(
address(this),
_verifier.gatewayUrls,
callData,
ERC3668Resolver.resolveWithProof.selector,
callData
);
}
/**
* @dev Function to resolve a domain name with proof using an off-chain callback mechanism.
* @param response The response received from off-chain resolution.
* @param extraData The actual calldata that was called on the gateway.
* @return the result of the offchain lookup
*/
function resolveWithProof(bytes calldata response, bytes calldata extraData) external view returns (bytes memory) {
/*
* decode the calldata that was encoded in the resolve function for IResolverService.resolveWithContext()
* bytes memory callData = abi.encodeWithSelector(IResolverService.resolveWithContext.selector, name, data context);
*/
(bytes memory name, bytes memory data) = abi.decode(extraData[4:], (bytes, bytes));
/*
* Get the verifier for the given name.
* reverts if no verifier was set in advance
*/
(CcipVerifier memory _ccipVerifier, ) = getVerifierOfDomain(name);
/*
* to enable the ERC3668Resolver to return data other than bytes it might be possible to override the
* resolvewithProofCallback function.
*/
bytes4 callBackSelector = ICcipResponseVerifier(_ccipVerifier.verifierAddress).onResolveWithProof(name, data);
/*
* reverts when no callback selector was found. This should normally never happen because setVerifier() checks * that the verifierAddress implements the ICcipResponseVerifier interface. However, it might be possible by
* overriding the onResolveWithProof function and return 0x. In that case, the contract reverts here.
*/
require(callBackSelector != bytes4(0), "No callback selector found");
/*
* staticcall to the callback function on the verifier contract.
* This function always returns bytes even the called function returns a Fixed type due to the return type of staticcall in solidity.
* So you might want to decode the result using abi.decode(resolveWithProofResponse, (bytes))
*/
(bool success, bytes memory resolveWithProofResponse) = address(_ccipVerifier.verifierAddress).staticcall(
abi.encodeWithSelector(callBackSelector, response, extraData)
);
/*
* Reverts if the call is not successful
*/
require(success, "staticcall to verifier failed");
return resolveWithProofResponse;
}
/**
* @notice Get metadata about the CCIP Resolver
* @dev This function provides metadata about the CCIP Resolver, including its name, coin type, GraphQL URL, storage type, and encoded information.
* @param name The domain name in format (dnsEncoded)
* @return name The name of the resolver ("CCIP RESOLVER")
* @return coinType Resolvers coin type (60 for Ethereum)
* @return graphqlUrl The GraphQL URL used by the resolver
* @return storageType Storage Type (0 for EVM)
* @return storageLocation The storage identifier. For EVM chains, this is the address of the resolver contract.
* @return context can be l2 resolver contract address for evm chain but can be any l2 storage identifier for non-evm chain
*/
function metadata(
bytes calldata name
) external view returns (string memory, uint256, string memory, uint8, bytes memory, bytes memory) {
/*
* Get the verifier for the given name.
* reverts if no verifier was set in advance
*/
(CcipVerifier memory _ccipVerifier, ) = getVerifierOfDomain(name);
/*
* Get the metadata from the verifier contract
*/
(
string memory resolverName,
uint256 coinType,
string memory graphqlUrl,
uint8 storageType,
bytes memory storageLocation,
) = ICcipResponseVerifier(_ccipVerifier.verifierAddress).metadata(name);
/*
* To determine the context of the request, we need to get the owner of the node.
*/
address nodeOwner = getNameOwner(name, 0);
bytes memory context = abi.encodePacked(nodeOwner);
return (resolverName, coinType, graphqlUrl, storageType, storageLocation, context);
}
/*
* --------------------------------------------------
* Public Functions
* --------------------------------------------------
*/
/**
* @notice Get the CCIP Verifier and node for a given domain name
* @dev This function allows retrieving the CCIP Verifier and its associated node for a given domain name. For subdomains, it will return the CCIP Verifier of the closest parent.
* @param name The domain name in bytes (dnsEncoded)
* @return _ccipVerifier The CCIP Verifier associated with the given domain name
* @return node The node associated with the given domain name
*/
function getVerifierOfDomain(bytes memory name) public view returns (CcipVerifier memory, bytes32) {
return getVerifierOfSegment(name, 0, name.namehash(0));
}
/**
* @notice Check if the contract supports a specific interface
* @dev Implements the ERC-165 standard to check for interface support.
* @param interfaceID The interface identifier to check
* @return True if the contract supports the given interface, otherwise false
*/
function supportsInterface(bytes4 interfaceID) public pure override returns (bool) {
return interfaceID == type(IExtendedResolver).interfaceId || super.supportsInterface(interfaceID);
}
/*
* --------------------------------------------------
* Internal Functions
* --------------------------------------------------
*/
/**
* @notice Get the owner of the ENS node either from the ENS registry or the NameWrapper contract
* @dev This function adds support for ENS nodes owned by the NameWrapper contract.
* @param node The ENS node to query for the owner
* @return nodeOwner The address of the owner of the ENS node
*/
function getNodeOwner(bytes32 node) internal view returns (address nodeOwner) {
nodeOwner = ensRegistry.owner(node);
if (nodeOwner == address(nameWrapper)) {
nodeOwner = nameWrapper.ownerOf(uint256(node));
}
}
/**
* @notice Get the owner of the ENS name either from the ENS registry or the NameWrapper contract
* @dev This function adds support for ENS nodes owned by the NameWrapper contract.
* @param name The domain name in bytes (dnsEncoded)
* @param offset The current offset in the name being processed
* @return nodeOwner The address of the owner of the ENS node
*/
function getNameOwner(bytes memory name, uint256 offset) internal view returns (address nodeOwner) {
bytes32 node = name.namehash(offset);
(, offset) = name.readLabel(offset);
nodeOwner = ensRegistry.owner(node);
if(offset >= name.length) {
return address(0);
}else if (nodeOwner == address(0)){
return getNameOwner(name, offset);
}else if(nodeOwner == address(nameWrapper)){
return nameWrapper.ownerOf(uint256(node));
}
return nodeOwner;
}
/*
* --------------------------------------------------
* Private Functions
* --------------------------------------------------
*
*/
/**
* @notice Sets a Cross-chain Information Protocol (CCIP) Verifier for a specific domain node.
* @param node The domain node for which the CCIP Verifier is set.
* @param verifierAddress The address of the CcipResponseVerifier contract.
* @param urls The gateway url that should handle the OffchainLookup.
*/
function _setVerifierForDomain(bytes32 node, address verifierAddress, string[] memory urls) private {
require(verifierAddress != address(0), "verifierAddress is 0x0");
/*
* We're doing a staticcall here to check if the verifierAddress implements the ICcipResponseVerifier interface.
* This is done to prevent the user from setting an arbitrary address as the verifierAddress.
*/
(bool success, bytes memory response) = verifierAddress.staticcall(
abi.encodeWithSignature("supportsInterface(bytes4)", type(ICcipResponseVerifier).interfaceId)
);
/*
* A successful static call will return 0x0000000000000000000000000000000000000000000000000000000000000001
* Hence we've to check that the last bit is set.
*/
require(
success && response.length == 32 && (response[response.length - 1] & 0x01) == 0x01,
"verifierAddress is not a CCIP Verifier"
);
/*
* Check that the url is non-null.
* Although it may not be a sufficient url check, it prevents users from passing undefined or empty strings.
*/
require(urls.length > 0, "at least one gateway url has to be provided");
/*
* Set the new verifier for the given node.
*/
CcipVerifier memory _ccipVerifier = CcipVerifier(urls, ICcipResponseVerifier(verifierAddress));
ccipVerifier[node] = _ccipVerifier;
emit VerifierAdded(node, verifierAddress, urls);
}
/**
* @dev Recursively searches for a verifier associated with a segment of the given domain name.
* If a verifier is found, it returns the verifier and the corresponding node.
*
* @param name The domain name in bytes
* @param offset The current offset in the name being processed
* @param node The current node being processed
* @return The CcipVerifier associated with the domain segment, and the corresponding node
*
* @notice This function searches for a verifier starting from the given offset in the domain name.
* It checks if a verifier is set for the current node, and if not, it continues with the next label.
* If the end of the name is reached and no verifier is found, it reverts with an UnknownVerifier error.
*/
function getVerifierOfSegment(
bytes memory name,
uint256 offset,
bytes32 node
) private view returns (CcipVerifier memory, bytes32) {
/*
* If we reached the root node and there is no verifier set, we revert with UnknownVerifier
*/
if (offset >= name.length - 1) {
/*
*If no specific verifier is set for the given node, we return the default verifier
*/
CcipVerifier memory defaultCcipVerifier = ccipVerifier[DEFAULT_VERIFIER];
return (defaultCcipVerifier, name.namehash(0));
}
CcipVerifier memory _ccipVerifier = ccipVerifier[node];
/*
* If the verifier is set for the given node, we return it and break the recursion
*/
if (address(_ccipVerifier.verifierAddress) != address(0)) {
return (_ccipVerifier, name.namehash(0));
}
/*
* Otherwise, continue with the next label
*/
(, offset) = name.readLabel(offset);
return getVerifierOfSegment(name, offset, name.namehash(offset));
}
}
@ensdomains/ens-contracts/contracts/ethregistrar/IBaseRegistrar.sol
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;
}
@ensdomains/ens-contracts/contracts/registry/ENS.sol
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);
}
@ensdomains/ens-contracts/contracts/registry/ENSRegistry.sol
pragma solidity >=0.8.4;
import "./ENS.sol";
/**
* 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 registry.
*/
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 virtual override {
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 virtual override {
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 virtual override 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 virtual override 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 virtual override 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 virtual override 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 virtual override {
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 virtual override 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 virtual override 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 virtual override 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 virtual override 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 virtual override returns (bool) {
return operators[owner][operator];
}
function _setOwner(bytes32 node, address owner) internal virtual {
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);
}
}
}
@ensdomains/ens-contracts/contracts/wrapper/BytesUtils.sol
//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;
}
}
@ensdomains/ens-contracts/contracts/wrapper/IMetadataService.sol
//SPDX-License-Identifier: MIT
pragma solidity ~0.8.17;
interface IMetadataService {
function uri(uint256) external view returns (string memory);
}
@ensdomains/ens-contracts/contracts/wrapper/INameWrapper.sol
//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;
//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;
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 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);
}
@ensdomains/ens-contracts/contracts/wrapper/INameWrapperUpgrade.sol
//SPDX-License-Identifier: MIT
pragma solidity ~0.8.17;
interface INameWrapperUpgrade {
function wrapFromUpgrade(
bytes calldata name,
address wrappedOwner,
uint32 fuses,
uint64 expiry,
bytes calldata extraData
) external;
}
@openzeppelin/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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;
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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);
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
contracts/IExtendedResolver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface IExtendedResolver {
function resolve(bytes memory name, bytes memory data) external view returns (bytes memory);
}
interface IResolverService {
function resolveWithContext(
bytes calldata name,
bytes calldata data,
bytes calldata context
) external view returns (bytes memory result);
}
contracts/IMetadataResolver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface IMetadataResolver {
/**
* @notice Get metadata about the CCIP Resolver
* @dev This function provides metadata about the CCIP Resolver, including its name, coin type, GraphQL URL, storage type, and encoded information.
* @param name The domain name in format (dnsEncoded)
* @return name The name of the resolver ("CCIP RESOLVER")
* @return coinType Resolvers coin type (60 for Ethereum)
* @return graphqlUrl The GraphQL URL used by the resolver
* @return storageType Storage Type (0 for EVM)
* @return storageLocation The storage identifier. For EVM chains, this is the address of the resolver contract.
* @return context can be l2 resolver contract address for evm chain but can be any l2 storage identifier for non evm chain
*
*/
function metadata(bytes calldata name) external view returns (string memory, uint256, string memory, uint8, bytes memory, bytes memory);
}
contracts/SupportsInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface ISupportsInterface {
function supportsInterface(bytes4 interfaceID) external pure returns (bool);
}
abstract contract SupportsInterface is ISupportsInterface {
function supportsInterface(bytes4 interfaceID) public pure virtual override returns (bool) {
return interfaceID == type(ISupportsInterface).interfaceId;
}
}
contracts/verifier/CcipResponseVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {ICcipResponseVerifier} from "./ICcipResponseVerifier.sol";
import {SupportsInterface, ISupportsInterface} from "../SupportsInterface.sol";
abstract contract CcipResponseVerifier is ICcipResponseVerifier, SupportsInterface {
/*
* --------------------------------------------------
* EVENTS
* --------------------------------------------------
*/
event GraphQlUrlChanged(string newGraphQlUrl);
event OwnerChanged(address newOwner);
/*
* --------------------------------------------------
* State Variables
* --------------------------------------------------
*/
/**
* @notice The owner of the contract
* The owner of the contract can set the graphQlUrl and determine a new owner
*/
address public owner;
/**
* @notice The graphql endpoint url
* The graphQlUrl is used to provide metadata of the resolver
*/
string public graphqlUrl;
/**
* @notice The resolver name
* The name of the resolver
*/
string public resolverName;
/**
* @notice the chainId at which the resolver resolves data from
* @dev should be 0 if storageLocation is offChain
*/
uint256 public l2ResolverChainID;
/*
* --------------------------------------------------
* Constructor
* --------------------------------------------------
*/
constructor(address _owner, string memory _graphqlUrl, string memory _resolverName, uint256 _l2ResolverChainID) {
owner = _owner;
graphqlUrl = _graphqlUrl;
resolverName = _resolverName;
l2ResolverChainID = _l2ResolverChainID;
}
/*
* --------------------------------------------------
* Modifier
* --------------------------------------------------
*/
modifier onlyOwner() {
require(msg.sender == owner, "only owner");
_;
}
/**
* @notice Set the GraphQL endpoint URL for the contract
* @dev This function can only be called by the current owner.
* @param _graphqlUrl The new GraphQL endpoint URL to be set
*/
function setGraphUrl(string memory _graphqlUrl) external onlyOwner {
graphqlUrl = _graphqlUrl;
emit GraphQlUrlChanged(_graphqlUrl);
}
/**
* @notice Set the new owner of the contract
* @dev This function can only be called by the current owner.
* @param _owner The address of the new owner
*/
function setOwner(address _owner) external onlyOwner {
owner = _owner;
emit OwnerChanged(_owner);
}
/*
* --------------------------------------------------
* External functions
* --------------------------------------------------
*/
/**
* @notice Check if the contract supports the given interface
* @dev This function checks if the contract supports the provided interface by comparing the `interfaceID` with the supported interface IDs.
* @param interfaceID The interface ID to check for support
* @return true if the contract supports the interface, false otherwise
*/
function supportsInterface(
bytes4 interfaceID
) public pure override(SupportsInterface, ISupportsInterface) returns (bool) {
/*
* Supports both ICcipResponseVerifier and ISupportsInterfacef
*/
return interfaceID == type(ICcipResponseVerifier).interfaceId || super.supportsInterface(interfaceID);
}
/**
* @notice To support other to be resolved than just bytes it is possible to override this function. In that case the function selector of the overridden function should be returned. The default implementation returns the function selector of the `resolveWithProof` function.
* @return The function selector of the `resolveWithProof` function
*/
function onResolveWithProof(bytes calldata, bytes calldata) public pure virtual override returns (bytes4) {
return this.resolveWithProof.selector;
}
}
contracts/verifier/ICcipResponseVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {ISupportsInterface} from "../SupportsInterface.sol";
interface ICcipResponseVerifier is ISupportsInterface {
function resolveWithProof(bytes calldata response, bytes calldata extraData) external view returns (bytes memory);
function onResolveWithProof(bytes calldata name, bytes calldata data) external pure returns (bytes4);
function metadata(
bytes calldata name
) external view returns (string memory, uint256, string memory, uint8, bytes memory, bytes memory);
}
solidity-bytes-utils/contracts/BytesLib.sol
// SPDX-License-Identifier: Unlicense
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.8.0 <0.9.0;
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (bytes memory)
{
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 200,
"details": {
"cse": true,
"yul": true,
"inliner": true,
"peephole": true,
"yulDetails": {
"optimizerSteps": "u",
"stackAllocation": true
},
"deduplicate": true,
"orderLiterals": true,
"jumpdestRemover": true,
"constantOptimizer": true
}
},
"evmVersion": "london",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.