├── LICENSE ├── README.md ├── Serverless Gateway ├── index.js └── package.json └── packages └── contracts ├── .gitignore ├── .npmignore ├── .yarn └── install-state.gz ├── .yarnrc.yml ├── README.md ├── contracts ├── IExtendedResolver.sol ├── OffchainResolver.sol ├── SignatureVerifier.sol ├── eccdomains.sol └── imports.sol ├── deploy ├── 00_ens.js ├── 10_offchain_resolver.js └── 11_set_resolver.js ├── hardhat.config.js ├── package.json ├── test └── TestOffchainResolver.js └── yarn.lock /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Ethereum Name Service (ENS) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ENS Optimism Resolver 2 | ![CI](https://github.com/ensdomains/offchain-resolver/actions/workflows/main.yml/badge.svg) 3 | 4 | 5 | This repository contains smart contracts and a node.js serverless gateway that together allow hosting ENS names offchain using [EIP 3668](https://eips.ethereum.org/EIPS/eip-3668) and [ENSIP 10](https://docs.ens.domains/ens-improvement-proposals/ensip-10-wildcard-resolution). 6 | 7 | ## Overview 8 | 9 | ENS resolution requests to the resolver implemented in this repository are responded to with a directive to query a gateway server for the answer. The gateway server generates and signs a response, which is sent back to the original resolver for decoding and verification. Full details of this request flow can be found in EIP 3668. 10 | 11 | All of this happens transparently in supported clients (such as ethers.js with the ethers-ccip-read-provider plugin, or future versions of ethers.js which will have this functionality built-in). 12 | 13 | ## [Serverless CCIP Gateway](https://github.com/stevegachau/optimismresover/tree/main/Serverless%20Gateway) 14 | 15 | The severless gateway server implements CCIP Read (EIP 3668), and answers requests by looking up the names in a backing store. By default this is a JSON file, but the backend is pluggable and alternate backends can be provided by implementing a simple interface. Once a record is retrieved, it is signed using a user-provided key to assert its validity, and both record and signature are returned to the caller so they can be provided to the contract that initiated the request. 16 | 17 | ## [Contracts](packages/contracts) 18 | 19 | The smart contract provides a resolver stub that implement CCIP Read (EIP 3668) and ENS wildcard resolution (ENSIP 10). When queried for a name, it directs the client to query the gateway server. When called back with the gateway server response, the resolver verifies the signature was produced by an authorised signer, and returns the response to the client. 20 | 21 | 22 | ## Real-world usage 23 | 24 | There are 5 main steps to using this in production: 25 | 26 | 1. Optionally, write a new backend for the gateway that queries your own data store. 27 | 2. Generate one or more signing keys. Secure these appropriately; posession of the signing keys makes it possible to forge name resolution responses! 28 | 3. Start up a gateway server using your name database and a signing key. Publish it on a publicly-accessible URL. 29 | 4. Deploy `OffchainResolver` to Ethereum, providing it with the gateway URL (format: https://*GATEWAY-URL*?sender={sender}&data={data}) and list of signing key addresses. 30 | 5. Set the newly deployed resolver as the resolver for one or more ENS names. 31 | -------------------------------------------------------------------------------- /Serverless Gateway/index.js: -------------------------------------------------------------------------------- 1 | const MongoClient = require('mongodb').MongoClient; 2 | const uri = "..."; //Database URI 3 | let client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); 4 | const clientPromise = client.connect(); 5 | 6 | 7 | exports.helloWorld = async (req, res) => { 8 | 9 | res.set('Access-Control-Allow-Origin', '*'); 10 | 11 | if (req.method === 'OPTIONS') { 12 | // Send response to OPTIONS requests 13 | res.set('Access-Control-Allow-Methods', 'POST'); 14 | res.set('Access-Control-Allow-Headers', 'Content-Type'); 15 | res.set('Access-Control-Max-Age', '3600'); 16 | res.status(204).send(''); 17 | } 18 | 19 | else { 20 | 21 | 22 | var sender = req.query.sender; 23 | var resolverdata = req.query.data; 24 | const Web3 = require('web3'); 25 | const ethers = require('ethers'); 26 | const InputDataDecoder = require('ethereum-input-data-decoder'); 27 | var domainaddress; 28 | var domaincontract; 29 | var web3; 30 | var mongoaddr; 31 | web3 = new Web3('.....'); //Optimism RPC 32 | 33 | 34 | //ABI to decode the ETH Calldata 35 | const decoderabi = [{"inputs": [{"internalType": "string", "name": "_url","type": "string"},{"internalType": "address[]", "name": "_signers", "type": "address[]"}],"stateMutability": "nonpayable", "type": "constructor"},{"inputs": [{"internalType": "address", "name": "sender","type": "address"},{"internalType": "string[]", "name": "urls","type": "string[]"},{"internalType": "bytes", "name": "callData", "type": "bytes"},{"internalType": "bytes4", "name": "callbackFunction", "type": "bytes4"},{"internalType": "bytes", "name": "extraData", "type": "bytes"}],"name": "OffchainLookup", "type": "error"},{"anonymous": false, "inputs": [{"indexed": false,"internalType": "address[]", "name": "signers","type": "address[]"}],"name": "NewSigners", "type": "event"},{"inputs": [{"internalType": "address", "name": "target","type": "address"},{"internalType": "uint64", "name": "expires","type": "uint64"},{"internalType": "bytes", "name": "request","type": "bytes"},{"internalType": "bytes", "name": "result","type": "bytes"}],"name": "makeSignatureHash", "outputs": [{"internalType": "bytes32", "name": "","type": "bytes32"}],"stateMutability": "pure", "type": "function"},{"inputs": [{"internalType": "bytes", "name": "name","type": "bytes"},{"internalType": "bytes", "name": "data","type": "bytes"}],"name": "resolve","outputs": [{"internalType": "bytes", "name": "","type": "bytes"}],"stateMutability": "view", "type": "function"},{"inputs": [{"internalType": "bytes", "name": "response", "type": "bytes"},{"internalType": "bytes", "name": "extraData", "type": "bytes"}],"name": "resolveWithProof", "outputs": [{"internalType": "bytes", "name": "","type": "bytes"}],"stateMutability": "view", "type": "function"},{"inputs": [{"internalType": "address", "name": "","type": "address"}],"name": "signers","outputs": [{"internalType": "bool", "name": "","type": "bool"}],"stateMutability": "view", "type": "function"},{"inputs": [{"internalType": "bytes4", "name": "interfaceID", "type": "bytes4"}],"name": "supportsInterface", "outputs": [{"internalType": "bool", "name": "","type": "bool"}],"stateMutability": "pure", "type": "function"},{"inputs": [],"name": "url","outputs": [{"internalType": "string", "name": "","type": "string"}],"stateMutability": "view", "type": "function"}]; 36 | const decoder = new InputDataDecoder(decoderabi); 37 | 38 | 39 | //ABI of the deployed offchainresolver contract 40 | const Resolver_abi = [{"inputs":[{"internalType":"contract ENS","name":"_ens","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"contentType","type":"uint256"}],"name":"ABIChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"address","name":"a","type":"address"}],"name":"AddrChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"coinType","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"newAddress","type":"bytes"}],"name":"AddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"bool","name":"isAuthorised","type":"bool"}],"name":"AuthorisationChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"hash","type":"bytes"}],"name":"ContenthashChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"name","type":"bytes"},{"indexed":false,"internalType":"uint16","name":"resource","type":"uint16"},{"indexed":false,"internalType":"bytes","name":"record","type":"bytes"}],"name":"DNSRecordChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"name","type":"bytes"},{"indexed":false,"internalType":"uint16","name":"resource","type":"uint16"}],"name":"DNSRecordDeleted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"}],"name":"DNSZoneCleared","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":true,"internalType":"bytes4","name":"interfaceID","type":"bytes4"},{"indexed":false,"internalType":"address","name":"implementer","type":"address"}],"name":"InterfaceChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"string","name":"name","type":"string"}],"name":"NameChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"x","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"y","type":"bytes32"}],"name":"PubkeyChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"node","type":"bytes32"},{"indexed":true,"internalType":"string","name":"indexedKey","type":"string"},{"indexed":false,"internalType":"string","name":"key","type":"string"}],"name":"TextChanged","type":"event"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"uint256","name":"contentTypes","type":"uint256"}],"name":"ABI","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"}],"name":"addr","outputs":[{"internalType":"address payable","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"uint256","name":"coinType","type":"uint256"}],"name":"addr","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"authorisations","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"}],"name":"clearDNSZone","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"}],"name":"contenthash","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes32","name":"name","type":"bytes32"},{"internalType":"uint16","name":"resource","type":"uint16"}],"name":"dnsRecord","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes32","name":"name","type":"bytes32"}],"name":"hasDNSRecords","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes4","name":"interfaceID","type":"bytes4"}],"name":"interfaceImplementer","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"}],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"}],"name":"pubkey","outputs":[{"internalType":"bytes32","name":"x","type":"bytes32"},{"internalType":"bytes32","name":"y","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"uint256","name":"contentType","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"setABI","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"uint256","name":"coinType","type":"uint256"},{"internalType":"bytes","name":"a","type":"bytes"}],"name":"setAddr","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"address","name":"a","type":"address"}],"name":"setAddr","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bool","name":"isAuthorised","type":"bool"}],"name":"setAuthorisation","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes","name":"hash","type":"bytes"}],"name":"setContenthash","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"setDNSRecords","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes4","name":"interfaceID","type":"bytes4"},{"internalType":"address","name":"implementer","type":"address"}],"name":"setInterface","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"string","name":"name","type":"string"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"bytes32","name":"x","type":"bytes32"},{"internalType":"bytes32","name":"y","type":"bytes32"}],"name":"setPubkey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"string","name":"key","type":"string"},{"internalType":"string","name":"value","type":"string"}],"name":"setText","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes4","name":"interfaceID","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"node","type":"bytes32"},{"internalType":"string","name":"key","type":"string"}],"name":"text","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]; 41 | const Resolver = new ethers.utils.Interface(Resolver_abi); 42 | 43 | 44 | //ABI of the deployed Subdomain NFT on L2 45 | const domainabi = [{"inputs": [{"internalType": "string","name": "baseURI","type": "string"}],"stateMutability": "nonpayable","type": "constructor"},{"anonymous": false,"inputs": [{"indexed": true,"internalType": "address","name": "owner","type": "address"},{"indexed": true,"internalType": "address","name": "approved","type": "address"},{"indexed": true,"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "Approval","type": "event"},{"anonymous": false,"inputs": [{"indexed": true,"internalType": "address","name": "owner","type": "address"},{"indexed": true,"internalType": "address","name": "operator","type": "address"},{"indexed": false,"internalType": "bool","name": "approved","type": "bool"}],"name": "ApprovalForAll","type": "event"},{"anonymous": false,"inputs": [{"indexed": true,"internalType": "address","name": "previousOwner","type": "address"},{"indexed": true,"internalType": "address","name": "newOwner","type": "address"}],"name": "OwnershipTransferred","type": "event"},{"anonymous": false,"inputs": [{"indexed": true,"internalType": "address","name": "from","type": "address"},{"indexed": true,"internalType": "address","name": "to","type": "address"},{"indexed": true,"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "Transfer","type": "event"},{"inputs": [{"internalType": "string","name": "","type": "string"}],"name": "addrOf","outputs": [{"internalType": "uint256","name": "id","type": "uint256"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "address","name": "to","type": "address"},{"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "approve","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "address","name": "owner","type": "address"}],"name": "balanceOf","outputs": [{"internalType": "uint256","name": "","type": "uint256"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "getApproved","outputs": [{"internalType": "address","name": "","type": "address"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "address","name": "owner","type": "address"},{"internalType": "address","name": "operator","type": "address"}],"name": "isApprovedForAll","outputs": [{"internalType": "bool","name": "","type": "bool"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "address","name": "subDomainOwner","type": "address"},{"internalType": "string","name": "subDomain","type": "string"}],"name": "mintSubdomain","outputs": [{"internalType": "uint256","name": "","type": "uint256"}],"stateMutability": "nonpayable","type": "function"},{"inputs": [],"name": "name","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "uint256","name": "","type": "uint256"}],"name": "nameOf","outputs": [{"internalType": "string","name": "ensname","type": "string"}],"stateMutability": "view","type": "function"},{"inputs": [],"name": "owner","outputs": [{"internalType": "address","name": "","type": "address"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "ownerOf","outputs": [{"internalType": "address","name": "","type": "address"}],"stateMutability": "view","type": "function"},{"inputs": [],"name": "renounceOwnership","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "string","name": "subDomain","type": "string"}],"name": "resolve","outputs": [{"internalType": "address","name": "","type": "address"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "address","name": "from","type": "address"},{"internalType": "address","name": "to","type": "address"},{"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "safeTransferFrom","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "address","name": "from","type": "address"},{"internalType": "address","name": "to","type": "address"},{"internalType": "uint256","name": "tokenId","type": "uint256"},{"internalType": "bytes","name": "_data","type": "bytes"}],"name": "safeTransferFrom","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "address","name": "operator","type": "address"},{"internalType": "bool","name": "approved","type": "bool"}],"name": "setApprovalForAll","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "string","name": "baseURI","type": "string"}],"name": "setBaseTokenURI","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "bytes4","name": "interfaceId","type": "bytes4"}],"name": "supportsInterface","outputs": [{"internalType": "bool","name": "","type": "bool"}],"stateMutability": "view","type": "function"},{"inputs": [],"name": "symbol","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "string","name": "str","type": "string"}],"name": "testAlphaNumeric","outputs": [{"internalType": "bool","name": "","type": "bool"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "tokenURI","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"},{"inputs": [],"name": "totalSupply","outputs": [{"internalType": "uint256","name": "","type": "uint256"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "address","name": "from","type": "address"},{"internalType": "address","name": "to","type": "address"},{"internalType": "uint256","name": "tokenId","type": "uint256"}],"name": "transferFrom","outputs": [],"stateMutability": "nonpayable","type": "function"},{"inputs": [{"internalType": "address","name": "newOwner","type": "address"}],"name": "transferOwnership","outputs": [],"stateMutability": "nonpayable","type": "function"}]; 46 | 47 | 48 | 49 | var dataresult = await decoder.decodeData(resolverdata); 50 | var hexname = dataresult.inputs[0]; 51 | var data = dataresult.inputs[1]; 52 | var utf8 = await web3.utils.hexToUtf8(hexname); 53 | var sliced = utf8.slice(1); 54 | var domain = sliced.replace(/[\x00\x01\x02\x03\x04\x05]/g," "); 55 | var fulldomain = domain.trim().split(/\s+/); 56 | 57 | var sub = fulldomain[0]; 58 | var tld = fulldomain[1]; 59 | var ext = fulldomain[2]; 60 | 61 | var name = sub+"."+tld+"."+ext; 62 | console.log(name); 63 | 64 | const privateKey = "...."; //priv key 65 | const signer = new ethers.utils.SigningKey(privateKey); 66 | 67 | if (tld == "ecc"){ 68 | 69 | domainaddress = "0x9fb848300E736075eD568147259bF8a8eeFe4fEf"; 70 | web3 = new Web3('......'); //optimism rpc 71 | const account = web3.eth.accounts.wallet.add(privateKey); 72 | web3.eth.defaultAccount = account.address; 73 | domaincontract = new web3.eth.Contract(domainabi, domainaddress, { 74 | from: '....' //from address 75 | }) 76 | } 77 | 78 | 79 | if (tld == "-id"){ 80 | 81 | client = await clientPromise; 82 | const collection = client.db("names").collection("subs"); 83 | const find = await collection.countDocuments({ens:name}) 84 | if(find == 0) {mongoaddr = "0x0000000000000000000000000000000000000000"} 85 | else{ 86 | const records = await collection.findOne({ens:name}); 87 | mongoaddr = records.address; 88 | } 89 | } 90 | 91 | 92 | 93 | async function handler(args) { 94 | 95 | if (args.length == 1){ 96 | if (tld == "-id"){ var addr = mongoaddr;} 97 | else{ 98 | var addr = await domaincontract.methods.resolve(sub).call(); 99 | } 100 | return { result: [addr] }; 101 | } 102 | 103 | else if (args[1].toString() == 60 ) { 104 | if (tld == "-id"){ var addr = mongoaddr;} 105 | else{ 106 | var addr = await domaincontract.methods.resolve(sub).call(); 107 | } 108 | return { result: [addr] }; 109 | } 110 | else if (args[1].toString() == 0 ) { var addr = "0x0000000000000000000000000000000000000000"; return { result: [addr] }; } 111 | else if (args[1].toString() == 2 ) { var addr = "0x0000000000000000000000000000000000000000"; return { result: [addr] }; } 112 | else if (args[1].toString() == 3 ) { var addr = "0x0000000000000000000000000000000000000000"; return { result: [addr] }; } 113 | else if (args[1] == "url") { var addr = ""; return { result: [addr] }; } 114 | else if (args[1] == "email") { var addr = ""; return { result: [addr] }; } 115 | else if (args[1] == "avatar") { var addr = ""; return { result: [addr] }; } 116 | else if (args[1] == "description") { var addr = ""; return { result: [addr] }; } 117 | else if (args[1] == "notice") { var addr = ""; return { result: [addr] }; } 118 | else if (args[1] == "keywords") { var addr = ""; return { result: [addr] }; } 119 | else if (args[1] == "com.discord") { var addr = ""; return { result: [addr] }; } 120 | else if (args[1] == "com.twitter") { var addr = ""; return { result: [addr] }; } 121 | else if (args[1] == "com.github") { var addr = ""; return { result: [addr] }; } 122 | else if (args[1] == "com.reddit") { var addr = ""; return { result: [addr] }; } 123 | else if (args[1] == "org.telegram") { var addr = ""; return { result: [addr] }; } 124 | else if (args[1] == "eth.ens.delegate") { var addr = ""; return { result: [addr] }; } 125 | else { 126 | console.log(args); 127 | res.status(200).send();} 128 | }; 129 | 130 | 131 | async function query(name, data){ 132 | 133 | const { signature, args } = Resolver.parseTransaction({ data }); 134 | const { result } = await handler(args); 135 | 136 | return { 137 | result: Resolver.encodeFunctionResult(signature, result), 138 | validUntil: Math.floor(Date.now() / 1000 ), 139 | }; 140 | 141 | } 142 | 143 | 144 | const { result, validUntil } = await query(name, data); 145 | 146 | let messageHash = ethers.utils.solidityKeccak256( 147 | ['bytes', 'address', 'uint64', 'bytes32', 'bytes32'], 148 | [ 149 | '0x1900', 150 | sender, 151 | validUntil, 152 | ethers.utils.keccak256(resolverdata || '0x'), 153 | ethers.utils.keccak256(result), 154 | ] 155 | ); 156 | 157 | 158 | const sig = signer.signDigest(messageHash); 159 | const sigData = ethers.utils.hexConcat([sig.r, sig._vs]); 160 | const returndata = web3.eth.abi.encodeParameters(['bytes','uint64','bytes'], [result, validUntil, sigData]); 161 | 162 | 163 | res.status(200).send({"data":returndata}); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /Serverless Gateway/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gateway", 3 | "version": "0.0.1", 4 | "dependencies": { 5 | "web3": "latest", 6 | "ethereum-input-data-decoder": "latest", 7 | "ethers": "5.6.2", 8 | "mongodb":"3.7.3" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /packages/contracts/.gitignore: -------------------------------------------------------------------------------- 1 | deployments 2 | artifacts 3 | -------------------------------------------------------------------------------- /packages/contracts/.npmignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | node_modules/ 3 | 4 | #Hardhat files 5 | cache/ 6 | -------------------------------------------------------------------------------- /packages/contracts/.yarn/install-state.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/touchasky/optimismresolver/b115eb0fd5e67237437fc261132c72423c65db26/packages/contracts/.yarn/install-state.gz -------------------------------------------------------------------------------- /packages/contracts/.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | -------------------------------------------------------------------------------- /packages/contracts/README.md: -------------------------------------------------------------------------------- 1 | # ENS Offchain Resolver Contracts 2 | 3 | This package contains Solidity contracts you can customise and deploy to provide offchain resolution of ENS names. 4 | 5 | These contracts implement [ENSIP 10](https://docs.ens.domains/ens-improvement-proposals/ensip-10-wildcard-resolution) (wildcard resolution support) and [EIP 3668](https://eips.ethereum.org/EIPS/eip-3668) (CCIP Read). Together this means that the resolver contract can be very straightforward; it simply needs to respond to all resolution requests with a redirect to your gateway, and verify gateway responses by checking the signature on the returned message. 6 | 7 | These contracts can also be used as a starting point for other verification methods, such as allowing the owner of the name to sign the records themselves, or relying on another verification mechanism such as a merkle tree or an L2 such as Optimism. To do so, start by replacing the calls to `SignatureVerifier` in `OffchainResolver` with your own solution. 8 | 9 | ## Contracts 10 | 11 | ### [IExtendedResolver.sol](contracts/IExtendedResolver.sol) 12 | This is the interface for wildcard resolution specified in ENSIP 10. In time this will likely be moved to the [@ensdomains/ens-contracts](https://github.com/ensdomains/ens-contracts) repository. 13 | 14 | ### [SignatureVerifier.sol](contracts/SignatureVerifier.sol) 15 | This library facilitates checking signatures over CCIP read responses. 16 | 17 | ### [OffchainResolver.sol](contracts/OffchainResolver.sol) 18 | This contract implements the offchain resolution system. Set this contract as the resolver for a name, and that name and all its subdomains that are not present in the ENS registry will be resolved via the provided gateway by supported clients. 19 | -------------------------------------------------------------------------------- /packages/contracts/contracts/IExtendedResolver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | interface IExtendedResolver { 5 | function resolve(bytes memory name, bytes memory data) external view returns(bytes memory); 6 | } 7 | -------------------------------------------------------------------------------- /packages/contracts/contracts/OffchainResolver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | import "@ensdomains/ens-contracts/contracts/resolvers/SupportsInterface.sol"; 5 | import "./IExtendedResolver.sol"; 6 | import "./SignatureVerifier.sol"; 7 | 8 | interface IResolverService { 9 | function resolve(bytes calldata name, bytes calldata data) external view returns(bytes memory result, uint64 expires, bytes memory sig); 10 | } 11 | 12 | /** 13 | * Implements an ENS resolver that directs all queries to a CCIP read gateway. 14 | * Callers must implement EIP 3668 and ENSIP 10. 15 | */ 16 | contract OffchainResolver is IExtendedResolver, SupportsInterface { 17 | string public url; 18 | mapping(address=>bool) public signers; 19 | 20 | event NewSigners(address[] signers); 21 | error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData); 22 | 23 | constructor(string memory _url, address[] memory _signers) { 24 | url = _url; 25 | for(uint i = 0; i < _signers.length; i++) { 26 | signers[_signers[i]] = true; 27 | } 28 | emit NewSigners(_signers); 29 | } 30 | 31 | function makeSignatureHash(address target, uint64 expires, bytes memory request, bytes memory result) external pure returns(bytes32) { 32 | return SignatureVerifier.makeSignatureHash(target, expires, request, result); 33 | } 34 | 35 | /** 36 | * Resolves a name, as specified by ENSIP 10. 37 | * @param name The DNS-encoded name to resolve. 38 | * @param data The ABI encoded data for the underlying resolution function (Eg, addr(bytes32), text(bytes32,string), etc). 39 | * @return The return data, ABI encoded identically to the underlying function. 40 | */ 41 | function resolve(bytes calldata name, bytes calldata data) external override view returns(bytes memory) { 42 | bytes memory callData = abi.encodeWithSelector(IResolverService.resolve.selector, name, data); 43 | string[] memory urls = new string[](1); 44 | urls[0] = url; 45 | revert OffchainLookup( 46 | address(this), 47 | urls, 48 | callData, 49 | OffchainResolver.resolveWithProof.selector, 50 | callData 51 | ); 52 | } 53 | 54 | /** 55 | * Callback used by CCIP read compatible clients to verify and parse the response. 56 | */ 57 | function resolveWithProof(bytes calldata response, bytes calldata extraData) external view returns(bytes memory) { 58 | (address signer, bytes memory result) = SignatureVerifier.verify(extraData, response); 59 | require( 60 | signers[signer], 61 | "SignatureVerifier: Invalid sigature"); 62 | return result; 63 | } 64 | 65 | function supportsInterface(bytes4 interfaceID) public pure override returns(bool) { 66 | return interfaceID == type(IExtendedResolver).interfaceId || super.supportsInterface(interfaceID); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /packages/contracts/contracts/SignatureVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.4; 4 | 5 | import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; 6 | 7 | library SignatureVerifier { 8 | /** 9 | * @dev Generates a hash for signing/verifying. 10 | * @param target: The address the signature is for. 11 | * @param request: The original request that was sent. 12 | * @param result: The `result` field of the response (not including the signature part). 13 | */ 14 | function makeSignatureHash(address target, uint64 expires, bytes memory request, bytes memory result) internal pure returns(bytes32) { 15 | return keccak256(abi.encodePacked(hex"1900", target, expires, keccak256(request), keccak256(result))); 16 | } 17 | 18 | /** 19 | * @dev Verifies a signed message returned from a callback. 20 | * @param request: The original request that was sent. 21 | * @param response: An ABI encoded tuple of `(bytes result, uint64 expires, bytes sig)`, where `result` is the data to return 22 | * to the caller, and `sig` is the (r,s,v) encoded message signature. 23 | * @return signer: The address that signed this message. 24 | * @return result: The `result` decoded from `response`. 25 | */ 26 | function verify(bytes calldata request, bytes calldata response) internal view returns(address, bytes memory) { 27 | (bytes memory result, uint64 expires, bytes memory sig) = abi.decode(response, (bytes, uint64, bytes)); 28 | address signer = ECDSA.recover(makeSignatureHash(address(this), expires, request, result), sig); 29 | require( 30 | expires >= block.timestamp, 31 | "SignatureVerifier: Signature expired"); 32 | return (signer, result); 33 | } 34 | } -------------------------------------------------------------------------------- /packages/contracts/contracts/eccdomains.sol: -------------------------------------------------------------------------------- 1 | /** 2 | *Submitted for verification at Optimistic.Etherscan.io on 2022-08-10 3 | */ 4 | 5 | //SPDX-License-Identifier: MIT 6 | pragma solidity ^0.8.0; 7 | 8 | /** 9 | * @title Counters 10 | * @author Matt Condon (@shrugs) 11 | * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number 12 | * of elements in a mapping, issuing ERC721 ids, or counting request ids. 13 | * 14 | * Include with `using Counters for Counters.Counter;` 15 | */ 16 | library Counters { 17 | struct Counter { 18 | // This variable should never be directly accessed by users of the library: interactions must be restricted to 19 | // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add 20 | // this feature: see https://github.com/ethereum/solidity/issues/4637 21 | uint256 _value; // default: 0 22 | } 23 | 24 | function current(Counter storage counter) internal view returns (uint256) { 25 | return counter._value; 26 | } 27 | 28 | function increment(Counter storage counter) internal { 29 | unchecked { 30 | counter._value += 1; 31 | } 32 | } 33 | 34 | function decrement(Counter storage counter) internal { 35 | uint256 value = counter._value; 36 | require(value > 0, "Counter: decrement overflow"); 37 | unchecked { 38 | counter._value = value - 1; 39 | } 40 | } 41 | 42 | function reset(Counter storage counter) internal { 43 | counter._value = 0; 44 | } 45 | } 46 | 47 | // File: @openzeppelin/contracts/utils/Strings.sol 48 | 49 | 50 | // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) 51 | 52 | pragma solidity ^0.8.0; 53 | 54 | /** 55 | * @dev String operations. 56 | */ 57 | library Strings { 58 | bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 59 | 60 | /** 61 | * @dev Converts a `uint256` to its ASCII `string` decimal representation. 62 | */ 63 | function toString(uint256 value) internal pure returns (string memory) { 64 | // Inspired by OraclizeAPI's implementation - MIT licence 65 | // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol 66 | 67 | if (value == 0) { 68 | return "0"; 69 | } 70 | uint256 temp = value; 71 | uint256 digits; 72 | while (temp != 0) { 73 | digits++; 74 | temp /= 10; 75 | } 76 | bytes memory buffer = new bytes(digits); 77 | while (value != 0) { 78 | digits -= 1; 79 | buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); 80 | value /= 10; 81 | } 82 | return string(buffer); 83 | } 84 | 85 | /** 86 | * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. 87 | */ 88 | function toHexString(uint256 value) internal pure returns (string memory) { 89 | if (value == 0) { 90 | return "0x00"; 91 | } 92 | uint256 temp = value; 93 | uint256 length = 0; 94 | while (temp != 0) { 95 | length++; 96 | temp >>= 8; 97 | } 98 | return toHexString(value, length); 99 | } 100 | 101 | /** 102 | * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. 103 | */ 104 | function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { 105 | bytes memory buffer = new bytes(2 * length + 2); 106 | buffer[0] = "0"; 107 | buffer[1] = "x"; 108 | for (uint256 i = 2 * length + 1; i > 1; --i) { 109 | buffer[i] = _HEX_SYMBOLS[value & 0xf]; 110 | value >>= 4; 111 | } 112 | require(value == 0, "Strings: hex length insufficient"); 113 | return string(buffer); 114 | } 115 | } 116 | 117 | // File: @openzeppelin/contracts/utils/Context.sol 118 | 119 | 120 | // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) 121 | 122 | pragma solidity ^0.8.0; 123 | 124 | /** 125 | * @dev Provides information about the current execution context, including the 126 | * sender of the transaction and its data. While these are generally available 127 | * via msg.sender and msg.data, they should not be accessed in such a direct 128 | * manner, since when dealing with meta-transactions the account sending and 129 | * paying for execution may not be the actual sender (as far as an application 130 | * is concerned). 131 | * 132 | * This contract is only required for intermediate, library-like contracts. 133 | */ 134 | abstract contract Context { 135 | function _msgSender() internal view virtual returns (address) { 136 | return msg.sender; 137 | } 138 | 139 | function _msgData() internal view virtual returns (bytes calldata) { 140 | return msg.data; 141 | } 142 | } 143 | 144 | // File: @openzeppelin/contracts/access/Ownable.sol 145 | 146 | 147 | // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 148 | 149 | pragma solidity ^0.8.0; 150 | 151 | 152 | /** 153 | * @dev Contract module which provides a basic access control mechanism, where 154 | * there is an account (an owner) that can be granted exclusive access to 155 | * specific functions. 156 | * 157 | * By default, the owner account will be the one that deploys the contract. This 158 | * can later be changed with {transferOwnership}. 159 | * 160 | * This module is used through inheritance. It will make available the modifier 161 | * `onlyOwner`, which can be applied to your functions to restrict their use to 162 | * the owner. 163 | */ 164 | abstract contract Ownable is Context { 165 | address private _owner; 166 | 167 | event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); 168 | 169 | /** 170 | * @dev Initializes the contract setting the deployer as the initial owner. 171 | */ 172 | constructor() { 173 | _transferOwnership(_msgSender()); 174 | } 175 | 176 | /** 177 | * @dev Returns the address of the current owner. 178 | */ 179 | function owner() public view virtual returns (address) { 180 | return _owner; 181 | } 182 | 183 | /** 184 | * @dev Throws if called by any account other than the owner. 185 | */ 186 | modifier onlyOwner() { 187 | require(owner() == _msgSender(), "Ownable: caller is not the owner"); 188 | _; 189 | } 190 | 191 | /** 192 | * @dev Leaves the contract without owner. It will not be possible to call 193 | * `onlyOwner` functions anymore. Can only be called by the current owner. 194 | * 195 | * NOTE: Renouncing ownership will leave the contract without an owner, 196 | * thereby removing any functionality that is only available to the owner. 197 | */ 198 | function renounceOwnership() public virtual onlyOwner { 199 | _transferOwnership(address(0)); 200 | } 201 | 202 | /** 203 | * @dev Transfers ownership of the contract to a new account (`newOwner`). 204 | * Can only be called by the current owner. 205 | */ 206 | function transferOwnership(address newOwner) public virtual onlyOwner { 207 | require(newOwner != address(0), "Ownable: new owner is the zero address"); 208 | _transferOwnership(newOwner); 209 | } 210 | 211 | /** 212 | * @dev Transfers ownership of the contract to a new account (`newOwner`). 213 | * Internal function without access restriction. 214 | */ 215 | function _transferOwnership(address newOwner) internal virtual { 216 | address oldOwner = _owner; 217 | _owner = newOwner; 218 | emit OwnershipTransferred(oldOwner, newOwner); 219 | } 220 | } 221 | 222 | // File: @openzeppelin/contracts/utils/Address.sol 223 | 224 | 225 | // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) 226 | 227 | pragma solidity ^0.8.1; 228 | 229 | /** 230 | * @dev Collection of functions related to the address type 231 | */ 232 | library Address { 233 | /** 234 | * @dev Returns true if `account` is a contract. 235 | * 236 | * [IMPORTANT] 237 | * ==== 238 | * It is unsafe to assume that an address for which this function returns 239 | * false is an externally-owned account (EOA) and not a contract. 240 | * 241 | * Among others, `isContract` will return false for the following 242 | * types of addresses: 243 | * 244 | * - an externally-owned account 245 | * - a contract in construction 246 | * - an address where a contract will be created 247 | * - an address where a contract lived, but was destroyed 248 | * ==== 249 | * 250 | * [IMPORTANT] 251 | * ==== 252 | * You shouldn't rely on `isContract` to protect against flash loan attacks! 253 | * 254 | * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets 255 | * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract 256 | * constructor. 257 | * ==== 258 | */ 259 | function isContract(address account) internal view returns (bool) { 260 | // This method relies on extcodesize/address.code.length, which returns 0 261 | // for contracts in construction, since the code is only stored at the end 262 | // of the constructor execution. 263 | 264 | return account.code.length > 0; 265 | } 266 | 267 | /** 268 | * @dev Replacement for Solidity's `transfer`: sends `amount` wei to 269 | * `recipient`, forwarding all available gas and reverting on errors. 270 | * 271 | * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost 272 | * of certain opcodes, possibly making contracts go over the 2300 gas limit 273 | * imposed by `transfer`, making them unable to receive funds via 274 | * `transfer`. {sendValue} removes this limitation. 275 | * 276 | * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. 277 | * 278 | * IMPORTANT: because control is transferred to `recipient`, care must be 279 | * taken to not create reentrancy vulnerabilities. Consider using 280 | * {ReentrancyGuard} or the 281 | * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. 282 | */ 283 | function sendValue(address payable recipient, uint256 amount) internal { 284 | require(address(this).balance >= amount, "Address: insufficient balance"); 285 | 286 | (bool success, ) = recipient.call{value: amount}(""); 287 | require(success, "Address: unable to send value, recipient may have reverted"); 288 | } 289 | 290 | /** 291 | * @dev Performs a Solidity function call using a low level `call`. A 292 | * plain `call` is an unsafe replacement for a function call: use this 293 | * function instead. 294 | * 295 | * If `target` reverts with a revert reason, it is bubbled up by this 296 | * function (like regular Solidity function calls). 297 | * 298 | * Returns the raw returned data. To convert to the expected return value, 299 | * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. 300 | * 301 | * Requirements: 302 | * 303 | * - `target` must be a contract. 304 | * - calling `target` with `data` must not revert. 305 | * 306 | * _Available since v3.1._ 307 | */ 308 | function functionCall(address target, bytes memory data) internal returns (bytes memory) { 309 | return functionCall(target, data, "Address: low-level call failed"); 310 | } 311 | 312 | /** 313 | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with 314 | * `errorMessage` as a fallback revert reason when `target` reverts. 315 | * 316 | * _Available since v3.1._ 317 | */ 318 | function functionCall( 319 | address target, 320 | bytes memory data, 321 | string memory errorMessage 322 | ) internal returns (bytes memory) { 323 | return functionCallWithValue(target, data, 0, errorMessage); 324 | } 325 | 326 | /** 327 | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], 328 | * but also transferring `value` wei to `target`. 329 | * 330 | * Requirements: 331 | * 332 | * - the calling contract must have an ETH balance of at least `value`. 333 | * - the called Solidity function must be `payable`. 334 | * 335 | * _Available since v3.1._ 336 | */ 337 | function functionCallWithValue( 338 | address target, 339 | bytes memory data, 340 | uint256 value 341 | ) internal returns (bytes memory) { 342 | return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); 343 | } 344 | 345 | /** 346 | * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but 347 | * with `errorMessage` as a fallback revert reason when `target` reverts. 348 | * 349 | * _Available since v3.1._ 350 | */ 351 | function functionCallWithValue( 352 | address target, 353 | bytes memory data, 354 | uint256 value, 355 | string memory errorMessage 356 | ) internal returns (bytes memory) { 357 | require(address(this).balance >= value, "Address: insufficient balance for call"); 358 | require(isContract(target), "Address: call to non-contract"); 359 | 360 | (bool success, bytes memory returndata) = target.call{value: value}(data); 361 | return verifyCallResult(success, returndata, errorMessage); 362 | } 363 | 364 | /** 365 | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], 366 | * but performing a static call. 367 | * 368 | * _Available since v3.3._ 369 | */ 370 | function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { 371 | return functionStaticCall(target, data, "Address: low-level static call failed"); 372 | } 373 | 374 | /** 375 | * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], 376 | * but performing a static call. 377 | * 378 | * _Available since v3.3._ 379 | */ 380 | function functionStaticCall( 381 | address target, 382 | bytes memory data, 383 | string memory errorMessage 384 | ) internal view returns (bytes memory) { 385 | require(isContract(target), "Address: static call to non-contract"); 386 | 387 | (bool success, bytes memory returndata) = target.staticcall(data); 388 | return verifyCallResult(success, returndata, errorMessage); 389 | } 390 | 391 | /** 392 | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], 393 | * but performing a delegate call. 394 | * 395 | * _Available since v3.4._ 396 | */ 397 | function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { 398 | return functionDelegateCall(target, data, "Address: low-level delegate call failed"); 399 | } 400 | 401 | /** 402 | * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], 403 | * but performing a delegate call. 404 | * 405 | * _Available since v3.4._ 406 | */ 407 | function functionDelegateCall( 408 | address target, 409 | bytes memory data, 410 | string memory errorMessage 411 | ) internal returns (bytes memory) { 412 | require(isContract(target), "Address: delegate call to non-contract"); 413 | 414 | (bool success, bytes memory returndata) = target.delegatecall(data); 415 | return verifyCallResult(success, returndata, errorMessage); 416 | } 417 | 418 | /** 419 | * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the 420 | * revert reason using the provided one. 421 | * 422 | * _Available since v4.3._ 423 | */ 424 | function verifyCallResult( 425 | bool success, 426 | bytes memory returndata, 427 | string memory errorMessage 428 | ) internal pure returns (bytes memory) { 429 | if (success) { 430 | return returndata; 431 | } else { 432 | // Look for revert reason and bubble it up if present 433 | if (returndata.length > 0) { 434 | // The easiest way to bubble the revert reason is using memory via assembly 435 | 436 | assembly { 437 | let returndata_size := mload(returndata) 438 | revert(add(32, returndata), returndata_size) 439 | } 440 | } else { 441 | revert(errorMessage); 442 | } 443 | } 444 | } 445 | } 446 | 447 | // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol 448 | 449 | 450 | // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) 451 | 452 | pragma solidity ^0.8.0; 453 | 454 | /** 455 | * @title ERC721 token receiver interface 456 | * @dev Interface for any contract that wants to support safeTransfers 457 | * from ERC721 asset contracts. 458 | */ 459 | interface IERC721Receiver { 460 | /** 461 | * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} 462 | * by `operator` from `from`, this function is called. 463 | * 464 | * It must return its Solidity selector to confirm the token transfer. 465 | * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. 466 | * 467 | * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. 468 | */ 469 | function onERC721Received( 470 | address operator, 471 | address from, 472 | uint256 tokenId, 473 | bytes calldata data 474 | ) external returns (bytes4); 475 | } 476 | 477 | // File: @openzeppelin/contracts/utils/introspection/IERC165.sol 478 | 479 | 480 | // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) 481 | 482 | pragma solidity ^0.8.0; 483 | 484 | /** 485 | * @dev Interface of the ERC165 standard, as defined in the 486 | * https://eips.ethereum.org/EIPS/eip-165[EIP]. 487 | * 488 | * Implementers can declare support of contract interfaces, which can then be 489 | * queried by others ({ERC165Checker}). 490 | * 491 | * For an implementation, see {ERC165}. 492 | */ 493 | interface IERC165 { 494 | /** 495 | * @dev Returns true if this contract implements the interface defined by 496 | * `interfaceId`. See the corresponding 497 | * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] 498 | * to learn more about how these ids are created. 499 | * 500 | * This function call must use less than 30 000 gas. 501 | */ 502 | function supportsInterface(bytes4 interfaceId) external view returns (bool); 503 | } 504 | 505 | // File: @openzeppelin/contracts/utils/introspection/ERC165.sol 506 | 507 | 508 | // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 509 | 510 | pragma solidity ^0.8.0; 511 | 512 | 513 | /** 514 | * @dev Implementation of the {IERC165} interface. 515 | * 516 | * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check 517 | * for the additional interface id that will be supported. For example: 518 | * 519 | * ```solidity 520 | * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { 521 | * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); 522 | * } 523 | * ``` 524 | * 525 | * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. 526 | */ 527 | abstract contract ERC165 is IERC165 { 528 | /** 529 | * @dev See {IERC165-supportsInterface}. 530 | */ 531 | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { 532 | return interfaceId == type(IERC165).interfaceId; 533 | } 534 | } 535 | 536 | // File: @openzeppelin/contracts/token/ERC721/IERC721.sol 537 | 538 | 539 | // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol) 540 | 541 | pragma solidity ^0.8.0; 542 | 543 | 544 | /** 545 | * @dev Required interface of an ERC721 compliant contract. 546 | */ 547 | interface IERC721 is IERC165 { 548 | /** 549 | * @dev Emitted when `tokenId` token is transferred from `from` to `to`. 550 | */ 551 | event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); 552 | 553 | /** 554 | * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. 555 | */ 556 | event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); 557 | 558 | /** 559 | * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. 560 | */ 561 | event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 562 | 563 | /** 564 | * @dev Returns the number of tokens in ``owner``'s account. 565 | */ 566 | function balanceOf(address owner) external view returns (uint256 balance); 567 | 568 | /** 569 | * @dev Returns the owner of the `tokenId` token. 570 | * 571 | * Requirements: 572 | * 573 | * - `tokenId` must exist. 574 | */ 575 | function ownerOf(uint256 tokenId) external view returns (address owner); 576 | 577 | /** 578 | * @dev Safely transfers `tokenId` token from `from` to `to`. 579 | * 580 | * Requirements: 581 | * 582 | * - `from` cannot be the zero address. 583 | * - `to` cannot be the zero address. 584 | * - `tokenId` token must exist and be owned by `from`. 585 | * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. 586 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. 587 | * 588 | * Emits a {Transfer} event. 589 | */ 590 | function safeTransferFrom( 591 | address from, 592 | address to, 593 | uint256 tokenId, 594 | bytes calldata data 595 | ) external; 596 | 597 | /** 598 | * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients 599 | * are aware of the ERC721 protocol to prevent tokens from being forever locked. 600 | * 601 | * Requirements: 602 | * 603 | * - `from` cannot be the zero address. 604 | * - `to` cannot be the zero address. 605 | * - `tokenId` token must exist and be owned by `from`. 606 | * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. 607 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. 608 | * 609 | * Emits a {Transfer} event. 610 | */ 611 | function safeTransferFrom( 612 | address from, 613 | address to, 614 | uint256 tokenId 615 | ) external; 616 | 617 | /** 618 | * @dev Transfers `tokenId` token from `from` to `to`. 619 | * 620 | * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. 621 | * 622 | * Requirements: 623 | * 624 | * - `from` cannot be the zero address. 625 | * - `to` cannot be the zero address. 626 | * - `tokenId` token must be owned by `from`. 627 | * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. 628 | * 629 | * Emits a {Transfer} event. 630 | */ 631 | function transferFrom( 632 | address from, 633 | address to, 634 | uint256 tokenId 635 | ) external; 636 | 637 | /** 638 | * @dev Gives permission to `to` to transfer `tokenId` token to another account. 639 | * The approval is cleared when the token is transferred. 640 | * 641 | * Only a single account can be approved at a time, so approving the zero address clears previous approvals. 642 | * 643 | * Requirements: 644 | * 645 | * - The caller must own the token or be an approved operator. 646 | * - `tokenId` must exist. 647 | * 648 | * Emits an {Approval} event. 649 | */ 650 | function approve(address to, uint256 tokenId) external; 651 | 652 | /** 653 | * @dev Approve or remove `operator` as an operator for the caller. 654 | * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. 655 | * 656 | * Requirements: 657 | * 658 | * - The `operator` cannot be the caller. 659 | * 660 | * Emits an {ApprovalForAll} event. 661 | */ 662 | function setApprovalForAll(address operator, bool _approved) external; 663 | 664 | /** 665 | * @dev Returns the account approved for `tokenId` token. 666 | * 667 | * Requirements: 668 | * 669 | * - `tokenId` must exist. 670 | */ 671 | function getApproved(uint256 tokenId) external view returns (address operator); 672 | 673 | /** 674 | * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. 675 | * 676 | * See {setApprovalForAll} 677 | */ 678 | function isApprovedForAll(address owner, address operator) external view returns (bool); 679 | } 680 | 681 | // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol 682 | 683 | 684 | // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 685 | 686 | pragma solidity ^0.8.0; 687 | 688 | 689 | /** 690 | * @title ERC-721 Non-Fungible Token Standard, optional metadata extension 691 | * @dev See https://eips.ethereum.org/EIPS/eip-721 692 | */ 693 | interface IERC721Metadata is IERC721 { 694 | /** 695 | * @dev Returns the token collection name. 696 | */ 697 | function name() external view returns (string memory); 698 | 699 | /** 700 | * @dev Returns the token collection symbol. 701 | */ 702 | function symbol() external view returns (string memory); 703 | 704 | /** 705 | * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. 706 | */ 707 | function tokenURI(uint256 tokenId) external view returns (string memory); 708 | } 709 | 710 | // File: @openzeppelin/contracts/token/ERC721/ERC721.sol 711 | 712 | 713 | // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/ERC721.sol) 714 | 715 | pragma solidity ^0.8.0; 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | /** 725 | * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including 726 | * the Metadata extension, but not including the Enumerable extension, which is available separately as 727 | * {ERC721Enumerable}. 728 | */ 729 | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { 730 | using Address for address; 731 | using Strings for uint256; 732 | 733 | // Token name 734 | string private _name; 735 | 736 | // Token symbol 737 | string private _symbol; 738 | 739 | // Mapping from token ID to owner address 740 | mapping(uint256 => address) private _owners; 741 | 742 | // Mapping owner address to token count 743 | mapping(address => uint256) private _balances; 744 | 745 | // Mapping from token ID to approved address 746 | mapping(uint256 => address) private _tokenApprovals; 747 | 748 | // Mapping from owner to operator approvals 749 | mapping(address => mapping(address => bool)) private _operatorApprovals; 750 | 751 | /** 752 | * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. 753 | */ 754 | constructor(string memory name_, string memory symbol_) { 755 | _name = name_; 756 | _symbol = symbol_; 757 | } 758 | 759 | /** 760 | * @dev See {IERC165-supportsInterface}. 761 | */ 762 | function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { 763 | return 764 | interfaceId == type(IERC721).interfaceId || 765 | interfaceId == type(IERC721Metadata).interfaceId || 766 | super.supportsInterface(interfaceId); 767 | } 768 | 769 | /** 770 | * @dev See {IERC721-balanceOf}. 771 | */ 772 | function balanceOf(address owner) public view virtual override returns (uint256) { 773 | require(owner != address(0), "ERC721: balance query for the zero address"); 774 | return _balances[owner]; 775 | } 776 | 777 | /** 778 | * @dev See {IERC721-ownerOf}. 779 | */ 780 | function ownerOf(uint256 tokenId) public view virtual override returns (address) { 781 | address owner = _owners[tokenId]; 782 | require(owner != address(0), "ERC721: owner query for nonexistent token"); 783 | return owner; 784 | } 785 | 786 | /** 787 | * @dev See {IERC721Metadata-name}. 788 | */ 789 | function name() public view virtual override returns (string memory) { 790 | return _name; 791 | } 792 | 793 | /** 794 | * @dev See {IERC721Metadata-symbol}. 795 | */ 796 | function symbol() public view virtual override returns (string memory) { 797 | return _symbol; 798 | } 799 | 800 | /** 801 | * @dev See {IERC721Metadata-tokenURI}. 802 | */ 803 | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { 804 | require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); 805 | 806 | string memory baseURI = _baseURI(); 807 | return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; 808 | } 809 | 810 | /** 811 | * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each 812 | * token will be the concatenation of the `baseURI` and the `tokenId`. Empty 813 | * by default, can be overridden in child contracts. 814 | */ 815 | function _baseURI() internal view virtual returns (string memory) { 816 | return ""; 817 | } 818 | 819 | /** 820 | * @dev See {IERC721-approve}. 821 | */ 822 | function approve(address to, uint256 tokenId) public virtual override { 823 | address owner = ERC721.ownerOf(tokenId); 824 | require(to != owner, "ERC721: approval to current owner"); 825 | 826 | require( 827 | _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 828 | "ERC721: approve caller is not owner nor approved for all" 829 | ); 830 | 831 | _approve(to, tokenId); 832 | } 833 | 834 | /** 835 | * @dev See {IERC721-getApproved}. 836 | */ 837 | function getApproved(uint256 tokenId) public view virtual override returns (address) { 838 | require(_exists(tokenId), "ERC721: approved query for nonexistent token"); 839 | 840 | return _tokenApprovals[tokenId]; 841 | } 842 | 843 | /** 844 | * @dev See {IERC721-setApprovalForAll}. 845 | */ 846 | function setApprovalForAll(address operator, bool approved) public virtual override { 847 | _setApprovalForAll(_msgSender(), operator, approved); 848 | } 849 | 850 | /** 851 | * @dev See {IERC721-isApprovedForAll}. 852 | */ 853 | function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { 854 | return _operatorApprovals[owner][operator]; 855 | } 856 | 857 | /** 858 | * @dev See {IERC721-transferFrom}. 859 | */ 860 | function transferFrom( 861 | address from, 862 | address to, 863 | uint256 tokenId 864 | ) public virtual override { 865 | //solhint-disable-next-line max-line-length 866 | require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); 867 | 868 | _transfer(from, to, tokenId); 869 | } 870 | 871 | /** 872 | * @dev See {IERC721-safeTransferFrom}. 873 | */ 874 | function safeTransferFrom( 875 | address from, 876 | address to, 877 | uint256 tokenId 878 | ) public virtual override { 879 | safeTransferFrom(from, to, tokenId, ""); 880 | } 881 | 882 | /** 883 | * @dev See {IERC721-safeTransferFrom}. 884 | */ 885 | function safeTransferFrom( 886 | address from, 887 | address to, 888 | uint256 tokenId, 889 | bytes memory _data 890 | ) public virtual override { 891 | require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); 892 | _safeTransfer(from, to, tokenId, _data); 893 | } 894 | 895 | /** 896 | * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients 897 | * are aware of the ERC721 protocol to prevent tokens from being forever locked. 898 | * 899 | * `_data` is additional data, it has no specified format and it is sent in call to `to`. 900 | * 901 | * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. 902 | * implement alternative mechanisms to perform token transfer, such as signature-based. 903 | * 904 | * Requirements: 905 | * 906 | * - `from` cannot be the zero address. 907 | * - `to` cannot be the zero address. 908 | * - `tokenId` token must exist and be owned by `from`. 909 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. 910 | * 911 | * Emits a {Transfer} event. 912 | */ 913 | function _safeTransfer( 914 | address from, 915 | address to, 916 | uint256 tokenId, 917 | bytes memory _data 918 | ) internal virtual { 919 | _transfer(from, to, tokenId); 920 | require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); 921 | } 922 | 923 | /** 924 | * @dev Returns whether `tokenId` exists. 925 | * 926 | * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. 927 | * 928 | * Tokens start existing when they are minted (`_mint`), 929 | * and stop existing when they are burned (`_burn`). 930 | */ 931 | function _exists(uint256 tokenId) internal view virtual returns (bool) { 932 | return _owners[tokenId] != address(0); 933 | } 934 | 935 | /** 936 | * @dev Returns whether `spender` is allowed to manage `tokenId`. 937 | * 938 | * Requirements: 939 | * 940 | * - `tokenId` must exist. 941 | */ 942 | function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { 943 | require(_exists(tokenId), "ERC721: operator query for nonexistent token"); 944 | address owner = ERC721.ownerOf(tokenId); 945 | return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); 946 | } 947 | 948 | /** 949 | * @dev Safely mints `tokenId` and transfers it to `to`. 950 | * 951 | * Requirements: 952 | * 953 | * - `tokenId` must not exist. 954 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. 955 | * 956 | * Emits a {Transfer} event. 957 | */ 958 | function _safeMint(address to, uint256 tokenId) internal virtual { 959 | _safeMint(to, tokenId, ""); 960 | } 961 | 962 | /** 963 | * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is 964 | * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. 965 | */ 966 | function _safeMint( 967 | address to, 968 | uint256 tokenId, 969 | bytes memory _data 970 | ) internal virtual { 971 | _mint(to, tokenId); 972 | require( 973 | _checkOnERC721Received(address(0), to, tokenId, _data), 974 | "ERC721: transfer to non ERC721Receiver implementer" 975 | ); 976 | } 977 | 978 | /** 979 | * @dev Mints `tokenId` and transfers it to `to`. 980 | * 981 | * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible 982 | * 983 | * Requirements: 984 | * 985 | * - `tokenId` must not exist. 986 | * - `to` cannot be the zero address. 987 | * 988 | * Emits a {Transfer} event. 989 | */ 990 | function _mint(address to, uint256 tokenId) internal virtual { 991 | require(to != address(0), "ERC721: mint to the zero address"); 992 | require(!_exists(tokenId), "ERC721: token already minted"); 993 | 994 | _beforeTokenTransfer(address(0), to, tokenId); 995 | 996 | _balances[to] += 1; 997 | _owners[tokenId] = to; 998 | 999 | emit Transfer(address(0), to, tokenId); 1000 | 1001 | _afterTokenTransfer(address(0), to, tokenId); 1002 | } 1003 | 1004 | /** 1005 | * @dev Destroys `tokenId`. 1006 | * The approval is cleared when the token is burned. 1007 | * 1008 | * Requirements: 1009 | * 1010 | * - `tokenId` must exist. 1011 | * 1012 | * Emits a {Transfer} event. 1013 | */ 1014 | function _burn(uint256 tokenId) internal virtual { 1015 | address owner = ERC721.ownerOf(tokenId); 1016 | 1017 | _beforeTokenTransfer(owner, address(0), tokenId); 1018 | 1019 | // Clear approvals 1020 | _approve(address(0), tokenId); 1021 | 1022 | _balances[owner] -= 1; 1023 | delete _owners[tokenId]; 1024 | 1025 | emit Transfer(owner, address(0), tokenId); 1026 | 1027 | _afterTokenTransfer(owner, address(0), tokenId); 1028 | } 1029 | 1030 | /** 1031 | * @dev Transfers `tokenId` from `from` to `to`. 1032 | * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. 1033 | * 1034 | * Requirements: 1035 | * 1036 | * - `to` cannot be the zero address. 1037 | * - `tokenId` token must be owned by `from`. 1038 | * 1039 | * Emits a {Transfer} event. 1040 | */ 1041 | function _transfer( 1042 | address from, 1043 | address to, 1044 | uint256 tokenId 1045 | ) internal virtual { 1046 | require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); 1047 | require(to != address(0), "ERC721: transfer to the zero address"); 1048 | 1049 | _beforeTokenTransfer(from, to, tokenId); 1050 | 1051 | // Clear approvals from the previous owner 1052 | _approve(address(0), tokenId); 1053 | 1054 | _balances[from] -= 1; 1055 | _balances[to] += 1; 1056 | _owners[tokenId] = to; 1057 | 1058 | emit Transfer(from, to, tokenId); 1059 | 1060 | _afterTokenTransfer(from, to, tokenId); 1061 | } 1062 | 1063 | /** 1064 | * @dev Approve `to` to operate on `tokenId` 1065 | * 1066 | * Emits a {Approval} event. 1067 | */ 1068 | function _approve(address to, uint256 tokenId) internal virtual { 1069 | _tokenApprovals[tokenId] = to; 1070 | emit Approval(ERC721.ownerOf(tokenId), to, tokenId); 1071 | } 1072 | 1073 | /** 1074 | * @dev Approve `operator` to operate on all of `owner` tokens 1075 | * 1076 | * Emits a {ApprovalForAll} event. 1077 | */ 1078 | function _setApprovalForAll( 1079 | address owner, 1080 | address operator, 1081 | bool approved 1082 | ) internal virtual { 1083 | require(owner != operator, "ERC721: approve to caller"); 1084 | _operatorApprovals[owner][operator] = approved; 1085 | emit ApprovalForAll(owner, operator, approved); 1086 | } 1087 | 1088 | /** 1089 | * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. 1090 | * The call is not executed if the target address is not a contract. 1091 | * 1092 | * @param from address representing the previous owner of the given token ID 1093 | * @param to target address that will receive the tokens 1094 | * @param tokenId uint256 ID of the token to be transferred 1095 | * @param _data bytes optional data to send along with the call 1096 | * @return bool whether the call correctly returned the expected magic value 1097 | */ 1098 | function _checkOnERC721Received( 1099 | address from, 1100 | address to, 1101 | uint256 tokenId, 1102 | bytes memory _data 1103 | ) private returns (bool) { 1104 | if (to.isContract()) { 1105 | try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { 1106 | return retval == IERC721Receiver.onERC721Received.selector; 1107 | } catch (bytes memory reason) { 1108 | if (reason.length == 0) { 1109 | revert("ERC721: transfer to non ERC721Receiver implementer"); 1110 | } else { 1111 | assembly { 1112 | revert(add(32, reason), mload(reason)) 1113 | } 1114 | } 1115 | } 1116 | } else { 1117 | return true; 1118 | } 1119 | } 1120 | 1121 | 1122 | function _beforeTokenTransfer( 1123 | address from, 1124 | address to, 1125 | uint256 tokenId 1126 | ) internal virtual {} 1127 | 1128 | /** 1129 | * @dev Hook that is called after any transfer of tokens. This includes 1130 | * minting and burning. 1131 | * 1132 | * Calling conditions: 1133 | * 1134 | * - when `from` and `to` are both non-zero. 1135 | * - `from` and `to` are never both zero. 1136 | * 1137 | * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. 1138 | */ 1139 | function _afterTokenTransfer( 1140 | address from, 1141 | address to, 1142 | uint256 tokenId 1143 | ) internal virtual {} 1144 | } 1145 | 1146 | contract ECCDomains is ERC721, Ownable { 1147 | 1148 | using Counters for Counters.Counter; 1149 | Counters.Counter private _tokenIds; 1150 | string private _baseTokenURI; 1151 | 1152 | constructor(string memory baseURI) ERC721("ECC Domains", "ECC") 1153 | { 1154 | _baseTokenURI = baseURI; 1155 | _tokenIds.increment(); 1156 | } 1157 | 1158 | struct ensdomain {uint256 id;} 1159 | mapping(string => ensdomain) public addrOf; 1160 | 1161 | struct linkedname {string ensname;} 1162 | mapping(uint256 => linkedname) public nameOf; 1163 | 1164 | 1165 | function _toLower(string memory str) 1166 | internal pure 1167 | returns (string memory) 1168 | { 1169 | bytes memory bStr = bytes(str); 1170 | bytes memory bLower = new bytes(bStr.length); 1171 | for (uint i = 0; i < bStr.length; i++) { 1172 | // Uppercase character... 1173 | if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { 1174 | // So we add 32 to make it lowercase 1175 | bLower[i] = bytes1(uint8(bStr[i]) + 32); 1176 | } else { 1177 | bLower[i] = bStr[i]; 1178 | } 1179 | } 1180 | return string(bLower); 1181 | } 1182 | 1183 | function testAlphaNumeric(string memory str) 1184 | public view 1185 | returns (bool) 1186 | { 1187 | bytes memory b = bytes(str); 1188 | for(uint i; i 0x2F && char < 0x3A) && !(char > 0x60 && char < 0x7B)) return false; 1192 | } 1193 | return true; 1194 | } 1195 | 1196 | 1197 | 1198 | function mintSubdomain(address subDomainOwner, string memory subDomain) 1199 | public 1200 | returns (uint256) 1201 | { 1202 | string memory domain = _toLower(subDomain); 1203 | uint256 newItemId = _tokenIds.current(); 1204 | require(addrOf[domain].id == 0, "Sub-domain has already been registered"); 1205 | require(bytes(domain).length != 0, "Sub-domain cannot be null"); 1206 | require(testAlphaNumeric(domain) == true, "Sub-domain contains unsupported characters"); 1207 | 1208 | 1209 | addrOf[domain].id = newItemId; 1210 | nameOf[newItemId].ensname = domain; 1211 | 1212 | _mint(subDomainOwner, newItemId); 1213 | _tokenIds.increment(); 1214 | 1215 | return newItemId; 1216 | } 1217 | 1218 | function resolve(string memory subDomain) 1219 | external view 1220 | returns (address) 1221 | { 1222 | string memory domain = _toLower(subDomain); 1223 | if(addrOf[domain].id == 0) { return address(0);} 1224 | address owner = ownerOf(addrOf[domain].id); 1225 | return owner; 1226 | } 1227 | 1228 | 1229 | 1230 | function setBaseTokenURI(string memory baseURI) 1231 | external onlyOwner 1232 | returns (string memory) 1233 | { 1234 | _baseTokenURI = baseURI; 1235 | return _baseTokenURI; 1236 | } 1237 | 1238 | 1239 | function tokenURI(uint256 tokenId) 1240 | public view override 1241 | returns (string memory) 1242 | { 1243 | string memory domain = nameOf[tokenId].ensname; 1244 | string memory tokenlink = string(abi.encodePacked(_baseTokenURI, domain)); 1245 | return tokenlink; 1246 | } 1247 | 1248 | 1249 | function totalSupply() 1250 | external view 1251 | returns (uint256) 1252 | { 1253 | uint256 supply = _tokenIds.current() - 1; 1254 | return supply; 1255 | } 1256 | 1257 | } 1258 | -------------------------------------------------------------------------------- /packages/contracts/contracts/imports.sol: -------------------------------------------------------------------------------- 1 | import "@ensdomains/ens-contracts/contracts/registry/ENSRegistry.sol"; -------------------------------------------------------------------------------- /packages/contracts/deploy/00_ens.js: -------------------------------------------------------------------------------- 1 | const { ethers } = require("hardhat"); 2 | 3 | module.exports = async ({deployments}) => { 4 | const {deploy} = deployments; 5 | const signers = await ethers.getSigners(); 6 | const owner = signers[0].address; 7 | await deploy('ENSRegistry', { 8 | from: owner, 9 | args: [], 10 | log: true, 11 | }); 12 | }; 13 | module.exports.tags = ['test']; 14 | -------------------------------------------------------------------------------- /packages/contracts/deploy/10_offchain_resolver.js: -------------------------------------------------------------------------------- 1 | const { ethers } = require("hardhat"); 2 | 3 | module.exports = async ({getNamedAccounts, deployments, network}) => { 4 | const {deploy} = deployments; 5 | const {deployer, signer} = await getNamedAccounts(); 6 | if(!network.config.gatewayurl){ 7 | throw("gatewayurl is missing on hardhat.config.js"); 8 | } 9 | await deploy('OffchainResolver', { 10 | from: deployer, 11 | args: [network.config.gatewayurl, [signer]], 12 | log: true, 13 | }); 14 | }; 15 | module.exports.tags = ['test', 'demo']; 16 | -------------------------------------------------------------------------------- /packages/contracts/deploy/11_set_resolver.js: -------------------------------------------------------------------------------- 1 | const { ethers } = require("hardhat"); 2 | module.exports = async ({deployments}) => { 3 | const {deploy} = deployments; 4 | const signers = await ethers.getSigners(); 5 | const owner = signers[0].address; 6 | const registry = await ethers.getContract('ENSRegistry'); 7 | const resolver = await ethers.getContract('OffchainResolver'); 8 | await registry.setSubnodeOwner("0x0000000000000000000000000000000000000000000000000000000000000000", ethers.utils.id('eth'), owner, {from: owner}); 9 | await registry.setSubnodeOwner(ethers.utils.namehash('eth'), ethers.utils.id('test'), owner, {from: owner}); 10 | await registry.setResolver(ethers.utils.namehash('test.eth'), resolver.address, {from: owner}); 11 | }; 12 | module.exports.tags = ['test']; 13 | -------------------------------------------------------------------------------- /packages/contracts/hardhat.config.js: -------------------------------------------------------------------------------- 1 | const { task } = require("hardhat/config"); 2 | 3 | require("@nomiclabs/hardhat-etherscan"); 4 | require('@nomiclabs/hardhat-ethers'); 5 | require('@nomiclabs/hardhat-waffle'); 6 | require('hardhat-deploy'); 7 | require('hardhat-deploy-ethers'); 8 | 9 | real_accounts = undefined; 10 | if(process.env.DEPLOYER_KEY && process.env.OWNER_KEY) { 11 | real_accounts = [process.env.OWNER_KEY, process.env.DEPLOYER_KEY]; 12 | } 13 | const gatewayurl = "https://offchain-resolver-example.uc.r.appspot.com/{sender}/{data}.json" 14 | /** 15 | * @type import('hardhat/config').HardhatUserConfig 16 | */ 17 | 18 | module.exports = { 19 | solidity: "0.8.10", 20 | networks: { 21 | hardhat: { 22 | throwOnCallFailures: false, 23 | chainId: 1337, 24 | gatewayurl:'http://localhost:8080/{sender}/{data}.json', 25 | }, 26 | ropsten: { 27 | url: `https://ropsten.infura.io/v3/${process.env.INFURA_ID}`, 28 | tags: ["test", "demo"], 29 | chainId: 3, 30 | accounts: real_accounts, 31 | gatewayurl, 32 | }, 33 | rinkeby: { 34 | url: `https://rinkeby.infura.io/v3/${process.env.INFURA_ID}`, 35 | tags: ["test", "demo"], 36 | chainId: 4, 37 | accounts: real_accounts, 38 | gatewayurl, 39 | }, 40 | goerli: { 41 | url: `https://goerli.infura.io/v3/${process.env.INFURA_ID}`, 42 | tags: ["test", "demo"], 43 | chainId: 5, 44 | accounts: real_accounts, 45 | gatewayurl, 46 | }, 47 | mainnet: { 48 | url: `https://mainnet.infura.io/v3/${process.env.INFURA_ID}`, 49 | tags: ["demo"], 50 | chainId: 1, 51 | accounts: real_accounts, 52 | gatewayurl, 53 | } 54 | }, 55 | etherscan: { 56 | apiKey: process.env.ETHERSCAN_API_KEY 57 | }, 58 | namedAccounts: { 59 | signer: { 60 | default: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 61 | }, 62 | deployer: { 63 | default: 1, 64 | }, 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /packages/contracts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ensdomains/offchain-resolver-contracts", 3 | "version": "0.2.1", 4 | "repository": "git@github.com:ensdomains/offchain-resolver.git", 5 | "author": "Nick Johnson ", 6 | "license": "MIT", 7 | "files": [ 8 | "contracts/*.sol", 9 | "artifacts/contracts/**/*.json" 10 | ], 11 | "scripts": { 12 | "test": "run() { npx hardhat test; }; run", 13 | "lint": "npx hardhat check", 14 | "build": "npx hardhat compile", 15 | "prepublishOnly": "yarn build", 16 | "pub": "yarn publish --access public", 17 | "clean": "rm -fr node_modules artifacts cache" 18 | }, 19 | "devDependencies": { 20 | "@nomiclabs/hardhat-ethers": "^2.0.3", 21 | "@nomiclabs/hardhat-waffle": "^2.0.1", 22 | "chai": "^4.3.4", 23 | "ethereum-waffle": "^3.4.0", 24 | "ethers": "^5.6.2", 25 | "hardhat": "^2.8.0", 26 | "hardhat-deploy": "^0.9.24" 27 | }, 28 | "dependencies": { 29 | "@ensdomains/ens-contracts": "^0.0.8", 30 | "@nomiclabs/hardhat-etherscan": "^3.0.0", 31 | "hardhat-deploy-ethers": "^0.3.0-beta.13" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /packages/contracts/test/TestOffchainResolver.js: -------------------------------------------------------------------------------- 1 | const { expect } = require("chai"); 2 | const { ethers } = require("hardhat"); 3 | const namehash = require('eth-ens-namehash'); 4 | const { defaultAbiCoder, SigningKey, arrayify, hexConcat } = require("ethers/lib/utils"); 5 | 6 | const TEST_ADDRESS = "0xCAfEcAfeCAfECaFeCaFecaFecaFECafECafeCaFe"; 7 | 8 | describe('OffchainResolver', function (accounts) { 9 | let signer, address, resolver, snapshot, signingKey, signingAddress; 10 | 11 | async function fetcher(url, json) { 12 | console.log({url, json}); 13 | return { 14 | jobRunId: "1", 15 | statusCode: 200, 16 | data: { 17 | result: "0x" 18 | } 19 | }; 20 | } 21 | 22 | before(async () => { 23 | signingKey = new SigningKey(ethers.utils.randomBytes(32)); 24 | signingAddress = ethers.utils.computeAddress(signingKey.privateKey); 25 | signer = await ethers.provider.getSigner(); 26 | address = await signer.getAddress(); 27 | const OffchainResolver = await ethers.getContractFactory("OffchainResolver"); 28 | resolver = await OffchainResolver.deploy("http://localhost:8080/", [signingAddress]); 29 | }); 30 | 31 | beforeEach(async () => { 32 | snapshot = await ethers.provider.send("evm_snapshot", []); 33 | }); 34 | 35 | afterEach(async () => { 36 | await ethers.provider.send("evm_revert", [snapshot]); 37 | }) 38 | 39 | describe('supportsInterface()', async () => { 40 | it('supports known interfaces', async () => { 41 | expect(await resolver.supportsInterface("0x9061b923")).to.equal(true); // IExtendedResolver 42 | }); 43 | 44 | it('does not support a random interface', async () => { 45 | expect(await resolver.supportsInterface("0x3b3b57df")).to.equal(false); 46 | }); 47 | }); 48 | 49 | describe('resolve()', async () => { 50 | it('returns a CCIP-read error', async () => { 51 | await expect(resolver.resolve(dnsName('test.eth'), '0x')).to.be.revertedWith('OffchainLookup'); 52 | }); 53 | }); 54 | 55 | describe('resolveWithProof()', async () => { 56 | let name, expires, iface, callData, resultData, sig; 57 | 58 | before(async () => { 59 | name = 'test.eth'; 60 | expires = Math.floor(Date.now() / 1000 + 3600); 61 | // Encode the nested call to 'addr' 62 | iface = new ethers.utils.Interface(["function addr(bytes32) returns(address)"]); 63 | const addrData = iface.encodeFunctionData("addr", [namehash.hash('test.eth')]); 64 | 65 | // Encode the outer call to 'resolve' 66 | callData = resolver.interface.encodeFunctionData("resolve", [dnsName('test.eth'), addrData]); 67 | 68 | // Encode the result data 69 | resultData = iface.encodeFunctionResult("addr", [TEST_ADDRESS]); 70 | 71 | // Generate a signature hash for the response from the gateway 72 | const callDataHash = await resolver.makeSignatureHash(resolver.address, expires, callData, resultData); 73 | 74 | // Sign it 75 | sig = signingKey.signDigest(callDataHash); 76 | }) 77 | 78 | it('resolves an address given a valid signature', async () => { 79 | // Generate the response data 80 | const response = defaultAbiCoder.encode(['bytes', 'uint64', 'bytes'], [resultData, expires, hexConcat([sig.r, sig._vs])]); 81 | 82 | // Call the function with the request and response 83 | const [result] = iface.decodeFunctionResult("addr", await resolver.resolveWithProof(response, callData)); 84 | expect(result).to.equal(TEST_ADDRESS); 85 | }); 86 | 87 | it('reverts given an invalid signature', async () => { 88 | // Corrupt the sig 89 | const deadsig = arrayify(hexConcat([sig.r, sig._vs])).slice(); 90 | deadsig[0] = deadsig[0] + 1; 91 | 92 | // Generate the response data 93 | const response = defaultAbiCoder.encode(['bytes', 'uint64', 'bytes'], [resultData, expires, deadsig]); 94 | 95 | // Call the function with the request and response 96 | await expect(resolver.resolveWithProof(response, callData)).to.be.reverted; 97 | }); 98 | 99 | it('reverts given an expired signature', async () => { 100 | // Generate the response data 101 | const response = defaultAbiCoder.encode(['bytes', 'uint64', 'bytes'], [resultData, Math.floor(Date.now() / 1000 - 1), hexConcat([sig.r, sig._vs])]); 102 | 103 | // Call the function with the request and response 104 | await expect(resolver.resolveWithProof(response, callData)).to.be.reverted; 105 | }); 106 | }); 107 | }); 108 | 109 | function dnsName(name) { 110 | // strip leading and trailing . 111 | const n = name.replace(/^\.|\.$/gm, ''); 112 | 113 | var bufLen = (n === '') ? 1 : n.length + 2; 114 | var buf = Buffer.allocUnsafe(bufLen); 115 | 116 | offset = 0; 117 | if (n.length) { 118 | const list = n.split('.'); 119 | for (let i = 0; i < list.length; i++) { 120 | const len = buf.write(list[i], offset + 1) 121 | buf[offset] = len; 122 | offset += len + 1; 123 | } 124 | } 125 | buf[offset++] = 0; 126 | return '0x' + buf.reduce((output, elem) => (output + ('0' + elem.toString(16)).slice(-2)), ''); 127 | } 128 | --------------------------------------------------------------------------------