nico 2 years ago
parent 60f5e52266
commit c2b5e15106
  1. 113
      .gitignore
  2. 900
      LICENSE
  3. 151
      README.md
  4. 62
      contracts/DegenForbiddenTlds.sol
  5. 9
      contracts/factories/README.md
  6. 66
      contracts/factories/flexi/FlexiDegenMetadata.sol
  7. 285
      contracts/factories/flexi/FlexiDegenTLD.sol
  8. 174
      contracts/factories/flexi/FlexiDegenTLDFactory.sol
  9. 9
      contracts/factories/flexi/README.md
  10. 8
      contracts/factories/flexi/interfaces/IFlexiDegenMetadata.sol
  11. 247
      contracts/factories/standard/DegenTLD.sol
  12. 170
      contracts/factories/standard/DegenTLDFactory.sol
  13. 42
      contracts/factories/standard/interfaces/IDegenTLD.sol
  14. 8
      contracts/factories/standard/interfaces/IDegenTLDFactory.sol
  15. 47
      contracts/interfaces/IBaseDegenTLD.sol
  16. 18
      contracts/interfaces/IBaseDegenTLDFactory.sol
  17. 10
      contracts/interfaces/IDegenForbiddenTlds.sol
  18. 741
      contracts/lib/strings.sol
  19. 16
      contracts/mock/MockErc20Token.sol
  20. 20
      contracts/mock/MockErc20TokenDecimals.sol
  21. 29
      contracts/mock/MockErc721Token.sol
  22. 206
      contracts/nft/anon/DegenAnonMetadata.sol
  23. 169
      contracts/nft/anon/DegenAnonMinter.sol
  24. 65
      contracts/nft/anon/DegenAnonWhitelist.sol
  25. 18
      contracts/nft/anon/interfaces/ICipherPunkMetadata.sol
  26. 16
      contracts/nft/anon/interfaces/IFlexiCipherTLD.sol
  27. 241
      contracts/resolver/DegenResolverV1.sol
  28. 43
      hardhat.config.js
  29. 27
      package.json
  30. 42
      scripts/deploy.js
  31. 48
      scripts/factories/flexi/deployFactoryOnly.js
  32. 27
      scripts/factories/flexi/deployForbiddenTlds.js
  33. 27
      scripts/factories/flexi/deployMetadata.js
  34. 29
      scripts/nft/anon/deployMetadata.js
  35. 46
      scripts/nft/anon/deployMinter.js
  36. 26
      scripts/nft/anon/deployWhitelist.js
  37. 38
      scripts/resolver/1_deploy.js
  38. 27
      scripts/resolver/2_upgrade_with_gnosis_safe.js
  39. 51
      scripts/resolver/other/addFactory.js
  40. 42
      scripts/resolver/other/changeProxyAdminOwner.js
  41. 88
      scripts/temp/addForbiddenTlds.js
  42. 11
      scripts/temp/arguments.js
  43. 12
      scripts/temp/argumentsFlexiTld.js
  44. 36
      scripts/temp/deployFactoryOnly.js
  45. 57
      scripts/temp/deployFlexiTld.js
  46. 28
      scripts/temp/deployMockNft.js
  47. 46
      scripts/temp/deployMockToken.js
  48. 37
      scripts/temp/deployMockTokenDecimals.js
  49. 56
      scripts/temp/deployTld.js
  50. 77
      scripts/temp/mintDomains.js
  51. 235
      test/factories/flexi/FlexiTLD.owner.test.js
  52. 743
      test/factories/flexi/FlexiTLD.test.js
  53. 203
      test/factories/flexi/FlexiTLDFactory.owner.test.js
  54. 274
      test/factories/flexi/FlexiTLDFactory.test.js
  55. 185
      test/factories/standard/TLD.owner.test.js
  56. 341
      test/factories/standard/TLD.test.js
  57. 200
      test/factories/standard/TLDFactory.owner.test.js
  58. 271
      test/factories/standard/TLDFactory.test.js
  59. 469
      test/nft/anon/anon.test.js
  60. 45
      test/nft/anon/anonMetadata.test.js
  61. 118
      test/nft/anon/anonWhitelist.test.js
  62. 484
      test/resolver/proxy.test.js
  63. 37
      test/resolver/resolver.v1.test.js
  64. 7979
      yarn.lock

113
.gitignore vendored

@ -0,0 +1,113 @@
.idea
flattened
venv
.openzeppelin
#Hardhat files
cache
artifacts
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port

@ -1,232 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

@ -1,3 +1,150 @@
# degen-contracts
# Degen Domain Name Service contracts
Contracts for Degen Domain Name Service
Degen Domain Name Service (DegenDNS) allows anyone to create a top-level domain (TLD) such as `.pepe` or a normal domain such as `degen.pepe`. In addition, users can add some other data to their domain:
- description
- redirect URL (useful together with the DegenDNS browser extension)
- profile picture (an address and token ID of an NFT)
See instructions below to run the code on localhost and for blockchain deployment.
### .env
Create a `.env` file with the following keys:
```bash
ALCHEMY_API_KEY_MUMBAI=enter-key-here
ALCHEMY_API_KEY_OPTIMISM=enter-key-here
ALCHEMY_API_KEY_RINKEBY=enter-key-here
ALCHEMY_API_KEY_ROPSTEN=enter-key-here
DEPLOYER_PRIVATE_KEY=enter-key-here
ETHERSCAN_API_KEY=enter-key-here
POLYGONSCAN_API_KEY=enter-key-here
OPTIMISTIC_ETHERSCAN_API_KEY=enter-key-here
ARBISCAN_API_KEY=enter-key-here
```
### Compile
```bash
npx hardhat compile
```
### Test
```bash
npx hardhat test
```
Run tests in a specific folder:
```bash
npx hardhat test test/factories/flexi/*test.js
```
Run a specific test:
```bash
npx hardhat test test/factories/flexi/TLD.owner.test.js
```
### Run on localhost
Start a localhost node:
```bash
npx hardhat node
```
Make sure to add one of the private keys presented as deployer key in `.env` file.
In a separate terminal tab then run the following command:
```bash
npx hardhat run scripts/deploy.js --network localhost
```
### Deploy to testnets
```bash
npx hardhat run scripts/deploy.js --network polygonMumbai
```
```bash
npx hardhat run scripts/deploy.js --network ropsten
```
### Verify contract on Etherscan/Polygonscan:
Make sure to enter correct network names ([see here](https://hardhat.org/plugins/nomiclabs-hardhat-etherscan.html#multiple-api-keys-and-alternative-block-explorers)):
```bash
etherscan: {
apiKey: {
polygonMumbai: process.env.POLYGONSCAN_API_KEY,
ropsten: process.env.ETHERSCAN_API_KEY
}
},
```
Then run this command:
```bash
npx hardhat verify --network mumbai <contract-address> "argument"
```
### Verify TLD contracts
Verifying TLD contracts generated through the factory is a bit tricky, but there is a way around the issue. See `scripts/temp/deployTld.js` for instructions.
## Audit tools
### Flatten the contracts
Most audit tools will require you to flatten the contracts. This means that all contracts that are defined under the imports will actually be imported into one .sol file, so all code is in one place.
First create a new folder called flattened:
```bash
mkdir flattened
```
To flatten a contract, run this command:
```bash
npx hardhat flatten <path-to-contract> >> flattened/<flat-contract-name>.sol
```
You may also need to give all contracts in the flattened file the same Solidity version. And you may need to delete all SPDX lines except the very first one.
### Mythrill
```bash
myth -v4 analyze flattened/DegenForbiddenTlds.sol
```
Flags:
- `v4`: verbose
- `o`: output
- `a`: address onchain
- `l`: automatically retrieve dependencies
- `max-depth`: maximum recursion depth
Docs: https://mythril-classic.readthedocs.io/en/master/security-analysis.html
### Slither
Install Slither:
```bash
pip3 install slither-analyzer --user
```
Run it in the `flattened` folder:
```bash
slither .
```
Docs: https://github.com/crytic/slither

@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
contract DegenForbiddenTlds is Ownable {
// The purpose of this contract is to hold a registry TLD names that are either forbidden or have been already created/used.
// There may be multiple Degen TLD Factory contracts and they need a joint registry of used or forbidden TLDs.
mapping (string => bool) public forbidden; // forbidden TLDs
mapping (address => bool) public factoryAddresses; // list of TLD factories that are allowed to add forbidden TLDs
event ForbiddenTldAdded(address indexed sender, string indexed tldName);
event ForbiddenTldRemoved(address indexed sender, string indexed tldName);
event FactoryAddressAdded(address indexed sender, address indexed fAddress);
event FactoryAddressRemoved(address indexed sender, address indexed fAddress);
modifier onlyFactory {
require(factoryAddresses[msg.sender] == true, "Caller is not a factory address.");
_;
}
constructor() {
forbidden[".eth"] = true;
forbidden[".com"] = true;
forbidden[".org"] = true;
forbidden[".net"] = true;
}
// PUBLIC
function isTldForbidden(string memory _name) public view returns (bool) {
return forbidden[_name];
}
// FACTORY
function addForbiddenTld(string memory _name) external onlyFactory {
forbidden[_name] = true;
emit ForbiddenTldAdded(msg.sender, _name);
}
// OWNER
function ownerAddForbiddenTld(string memory _name) external onlyOwner {
forbidden[_name] = true;
emit ForbiddenTldAdded(msg.sender, _name);
}
function removeForbiddenTld(string memory _name) external onlyOwner {
forbidden[_name] = false;
emit ForbiddenTldRemoved(msg.sender, _name);
}
function addFactoryAddress(address _fAddr) external onlyOwner {
factoryAddresses[_fAddr] = true;
emit FactoryAddressAdded(msg.sender, _fAddr);
}
function removeFactoryAddress(address _fAddr) external onlyOwner {
factoryAddresses[_fAddr] = false;
emit FactoryAddressRemoved(msg.sender, _fAddr);
}
}

@ -0,0 +1,9 @@
# TLD Factories
Factories are contracts that produce new TLD contracts. Each factory can produce any number of TLDs. In order to avoid TLD name collisions, factories coordinate through the `DegenForbiddenTlds` contract, which holds a list of all existing TLDs and TLDs that are used by other services (ENS & UD).
Each factory contains a TLD template that needs to follow standard TLD methods (see `IBaseDegenTLD` interface), but it can implement them in a different way or add new methods.
The first factory to launch was the `standard` factory, followed by the `flexi` factory a couple of months later.
In order to easily resolve domains without being aware of all existing factories, use the unified resolver called `DegenResolver`.

@ -0,0 +1,66 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "base64-sol/base64.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Degen Domain Service TLD Metadata contract (Flexi)
/// @author Degen Labs
/// @notice Contract that stores metadata for TLD contracts.
contract FlexiDegenMetadata {
mapping (address => string) public descriptions; // TLD-specific descriptions, mapping(tldAddress => description)
mapping (address => string) public brands; // TLD-specific brand names, mapping(tldAddress => brandName)
// EVENTS
event BrandChanged(address indexed user, string brand);
event DescriptionChanged(address indexed user, string description);
// READ
function getMetadata(string calldata _domainName, string calldata _tld, uint256 _tokenId) public view returns(string memory) {
string memory fullDomainName = string(abi.encodePacked(_domainName, _tld));
return string(
abi.encodePacked("data:application/json;base64,", Base64.encode(bytes(abi.encodePacked(
'{"name": "', fullDomainName, '", ',
'"description": "', descriptions[msg.sender], '", ',
'"image": "', _getImage(fullDomainName, brands[msg.sender]), '"}'))))
);
}
function _getImage(string memory _fullDomainName, string memory _brandName) internal pure returns (string memory) {
string memory svgBase64Encoded = Base64.encode(bytes(string(abi.encodePacked(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="500" height="500">',
'<defs><linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="0%">',
'<stop offset="0%" style="stop-color:rgb(68,67,241);stop-opacity:1" />',
'<stop offset="100%" style="stop-color:rgb(144,85,247);stop-opacity:1" /></linearGradient></defs>',
'<rect x="0" y="0" width="500" height="500" fill="url(#grad)"/>',
'<text x="50%" y="50%" dominant-baseline="middle" fill="white" text-anchor="middle" font-size="x-large">',
_fullDomainName,'</text><text x="50%" y="70%" dominant-baseline="middle" fill="white" text-anchor="middle">',
_brandName,'</text>',
'</svg>'
))));
return string(abi.encodePacked("data:image/svg+xml;base64,", svgBase64Encoded));
}
function getTldOwner(address _tldAddress) public view returns(address) {
Ownable tld = Ownable(_tldAddress);
return tld.owner();
}
// WRITE (TLD OWNERS)
/// @notice Only TLD contract owner can call this function.
function changeBrand(address _tldAddress, string calldata _brand) external {
require(msg.sender == getTldOwner(_tldAddress), "Sender not TLD owner");
brands[_tldAddress] = _brand;
emit BrandChanged(msg.sender, _brand);
}
/// @notice Only TLD contract owner can call this function.
function changeDescription(address _tldAddress, string calldata _description) external {
require(msg.sender == getTldOwner(_tldAddress), "Sender not TLD owner");
descriptions[_tldAddress] = _description;
emit DescriptionChanged(msg.sender, _description);
}
}

@ -0,0 +1,285 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./interfaces/IFlexiDegenMetadata.sol";
import "../../interfaces/IBaseDegenTLD.sol";
import "../../lib/strings.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "base64-sol/base64.sol";
/// @title Degen Domain Service TLD contract (Flexi)
/// @author Degen Labs
/// @notice Dynamically generated NFT contract which represents a top-level domain
contract FlexiDegenTLD is IBaseDegenTLD, ERC721, Ownable, ReentrancyGuard {
using strings for string;
// Domain struct is defined in IBaseDegenTLD
address public immutable factoryAddress; // FlexiDegenTLDFactory address
address public metadataAddress; // FlexiDegenMetadata address
address public minter; // address which is allowed to mint domains even if contract is paused
address public royaltyFeeUpdater; // address which is allowed to change the royalty fee
address public royaltyFeeReceiver; // address which receives the royalty fee
bool public buyingEnabled = false; // buying domains enabled
bool public buyingDisabledForever = false; // buying domains disabled forever
bool public metadataFrozen = false; // metadata address frozen forever
uint256 public totalSupply;
uint256 public idCounter = 1; // up only
uint256 public override price; // domain price
uint256 public royalty; // share of each domain purchase (in bips) that goes to Degen Domain Service
uint256 public override referral = 1000; // share of each domain purchase (in bips) that goes to the referrer (referral fee)
uint256 public nameMaxLength = 140; // max length of a domain name
mapping (string => Domain) public override domains; // mapping (domain name => Domain struct); Domain struct is defined in IBaseDegenTLD
mapping (uint256 => string) public domainIdsNames; // mapping (tokenId => domain name)
mapping (address => string) public override defaultNames; // user's default domain
event MintingDisabledForever(address user);
constructor(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled,
uint256 _royalty,
address _factoryAddress,
address _metadataAddress
) ERC721(_name, _symbol) {
price = _domainPrice;
buyingEnabled = _buyingEnabled;
royalty = _royalty;
metadataAddress = _metadataAddress;
Ownable factory = Ownable(_factoryAddress);
factoryAddress = _factoryAddress;
royaltyFeeUpdater = factory.owner();
royaltyFeeReceiver = factory.owner();
transferOwnership(_tldOwner);
}
// READ
// Domain getters - you can also get all Domain data by calling the auto-generated domains(domainName) method
function getDomainHolder(string calldata _domainName) public override view returns(address) {
return domains[strings.lower(_domainName)].holder;
}
function getDomainData(string calldata _domainName) public override view returns(string memory) {
return domains[strings.lower(_domainName)].data; // should be a JSON object
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
return IFlexiDegenMetadata(metadataAddress).getMetadata(
domains[domainIdsNames[_tokenId]].name,
name(),
_tokenId
);
}
// WRITE
/// @notice Flexi-specific function
function burn(string calldata _domainName) external {
string memory dName = strings.lower(_domainName);
require(domains[dName].holder == _msgSender(), "You do not own the selected domain");
uint256 tokenId = domains[dName].tokenId;
delete domainIdsNames[tokenId]; // delete tokenId => domainName mapping
delete domains[dName]; // delete string => Domain struct mapping
if (keccak256(bytes(defaultNames[_msgSender()])) == keccak256(bytes(dName))) {
delete defaultNames[_msgSender()];
}
_burn(tokenId); // burn the token
--totalSupply;
emit DomainBurned(_msgSender(), dName);
}
/// @notice Default domain is the domain name that reverse resolver returns for a given address.
function editDefaultDomain(string calldata _domainName) external {
string memory dName = strings.lower(_domainName);
require(domains[dName].holder == _msgSender(), "You do not own the selected domain");
defaultNames[_msgSender()] = dName;
emit DefaultDomainChanged(_msgSender(), dName);
}
/// @notice Edit domain custom data. Make sure to not accidentally delete previous data. Fetch previous data first.
/// @param _domainName Only domain name, no TLD/extension.
/// @param _data Custom data needs to be in a JSON object format.
function editData(string calldata _domainName, string calldata _data) external {
string memory dName = strings.lower(_domainName);
require(domains[dName].holder == _msgSender(), "Only domain holder can edit their data");
domains[dName].data = _data;
emit DataChanged(_msgSender());
}
/// @notice Mint a new domain name as NFT (no dots and spaces allowed).
/// @param _domainName Enter domain name without TLD and make sure letters are in lowercase form.
/// @return token ID
function mint(
string memory _domainName,
address _domainHolder,
address _referrer
) external payable override nonReentrant returns(uint256) {
require(!buyingDisabledForever, "Domain minting disabled forever");
require(buyingEnabled || _msgSender() == owner() || _msgSender() == minter, "Buying domains disabled");
require(msg.value >= price, "Value below price");
_sendPayment(msg.value, _referrer);
return _mintDomain(_domainName, _domainHolder, "");
}
function _mintDomain(
string memory _domainNameRaw,
address _domainHolder,
string memory _data
) internal returns(uint256) {
// convert domain name to lowercase (only works for ascii, clients should enforce ascii domains only)
string memory _domainName = strings.lower(_domainNameRaw);
require(strings.len(strings.toSlice(_domainName)) > 0, "Domain name empty");
require(bytes(_domainName).length < nameMaxLength, "Domain name is too long");
require(strings.count(strings.toSlice(_domainName), strings.toSlice(".")) == 0, "There should be no dots in the name");
require(strings.count(strings.toSlice(_domainName), strings.toSlice(" ")) == 0, "There should be no spaces in the name");
require(domains[_domainName].holder == address(0), "Domain with this name already exists");
_mint(_domainHolder, idCounter);
Domain memory newDomain; // Domain struct is defined in IBaseDegenTLD
// store data in Domain struct
newDomain.name = _domainName;
newDomain.tokenId = idCounter;
newDomain.holder = _domainHolder;
newDomain.data = _data;
// add to both mappings
domains[_domainName] = newDomain;
domainIdsNames[idCounter] = _domainName;
if (bytes(defaultNames[_domainHolder]).length == 0) {
defaultNames[_domainHolder] = _domainName; // if default domain name is not set for that holder, set it now
}
emit DomainCreated(_msgSender(), _domainHolder, string(abi.encodePacked(_domainName, name())));
++idCounter;
++totalSupply;
return idCounter-1;
}
function _sendPayment(uint256 _paymentAmount, address _referrer) internal {
if (royalty > 0 && royalty < 5000) {
// send royalty - must be less than 50% (5000 bips)
(bool sentRoyalty, ) = payable(royaltyFeeReceiver).call{value: ((_paymentAmount * royalty) / 10000)}("");
require(sentRoyalty, "Failed to send royalty to factory owner");
}
if (_referrer != address(0) && referral > 0 && referral < 5000) {
// send referral fee - must be less than 50% (5000 bips)
(bool sentReferralFee, ) = payable(_referrer).call{value: ((_paymentAmount * referral) / 10000)}("");
require(sentReferralFee, "Failed to send referral fee");
}
// send the rest to TLD owner
(bool sent, ) = payable(owner()).call{value: address(this).balance}("");
require(sent, "Failed to send domain payment to TLD owner");
}
///@dev Hook that is called before any token transfer. This includes minting and burning.
function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override virtual {
if (from != address(0)) { // run on every transfer but not on mint
domains[domainIdsNames[tokenId]].holder = to; // change holder address in Domain struct
if (bytes(defaultNames[to]).length == 0 && to != address(0)) {
defaultNames[to] = domains[domainIdsNames[tokenId]].name; // if default domain name is not set for that holder, set it now
}
if (strings.equals(strings.toSlice(domains[domainIdsNames[tokenId]].name), strings.toSlice(defaultNames[from]))) {
delete defaultNames[from]; // if previous owner had this domain name as default, unset it as default
}
}
}
// OWNER
/// @notice Only TLD contract owner can call this function. Flexi-specific function.
function changeMetadataAddress(address _metadataAddress) external onlyOwner {
require(!metadataFrozen, "Cannot change metadata address anymore");
metadataAddress = _metadataAddress;
}
/// @notice Only TLD contract owner can call this function. Flexi-specific function.
function changeMinter(address _minter) external onlyOwner {
minter = _minter;
}
/// @notice Only TLD contract owner can call this function.
function changeNameMaxLength(uint256 _maxLength) external override onlyOwner {
nameMaxLength = _maxLength;
}
/// @notice Only TLD contract owner can call this function.
function changePrice(uint256 _price) external override onlyOwner {
price = _price;
emit TldPriceChanged(_msgSender(), _price);
}
/// @notice Only TLD contract owner can call this function.
function changeReferralFee(uint256 _referral) external override onlyOwner {
require(_referral < 5000, "Referral fee cannot be 50% or higher");
referral = _referral; // referral must be in bips
emit ReferralFeeChanged(_msgSender(), _referral);
}
/// @notice Only TLD contract owner can call this function. Flexi-specific function.
function disableBuyingForever() external onlyOwner {
buyingDisabledForever = true; // this action is irreversible
emit MintingDisabledForever(_msgSender());
}
/// @notice Freeze metadata address. Only TLD contract owner can call this function.
function freezeMetadata() external onlyOwner {
metadataFrozen = true; // this action is irreversible
}
/// @notice Only TLD contract owner can call this function.
function toggleBuyingDomains() external onlyOwner {
buyingEnabled = !buyingEnabled;
emit DomainBuyingToggle(_msgSender(), buyingEnabled);
}
// ROYALTY FEE UPDATER
/// @notice This changes royalty fee in the wrapper contract
function changeRoyalty(uint256 _royalty) external {
require(_royalty <= 5000, "Cannot exceed 50%");
require(_msgSender() == royaltyFeeUpdater, "Sender is not royalty fee updater");
royalty = _royalty;
emit TldRoyaltyChanged(_msgSender(), _royalty);
}
/// @notice This changes royalty fee receiver address. Flexi-specific function.
function changeRoyaltyFeeReceiver(address _newReceiver) external {
require(_msgSender() == royaltyFeeReceiver, "Sender is not royalty fee receiver");
royaltyFeeReceiver = _newReceiver;
}
/// @notice This changes royalty fee updater address. Flexi-specific function.
function changeRoyaltyFeeUpdater(address _newUpdater) external {
require(_msgSender() == royaltyFeeUpdater, "Sender is not royalty fee updater");
royaltyFeeUpdater = _newUpdater;
}
}

@ -0,0 +1,174 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../../lib/strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./FlexiDegenTLD.sol";
import "../../interfaces/IBaseDegenTLDFactory.sol";
import "../../interfaces/IDegenForbiddenTlds.sol";
/// @title Degen Domain Service TLD Factory contract (Flexi)
/// @author Degen Labs
/// @notice Factory contract dynamically generates new TLD contracts.
contract FlexiDegenTLDFactory is IBaseDegenTLDFactory, Ownable, ReentrancyGuard {
using strings for string;
string[] public tlds; // existing TLDs
mapping (string => address) public override tldNamesAddresses; // a mapping of TLDs (string => TLDaddress)
address public forbiddenTlds; // address of the contract that stores the list of forbidden TLDs
address public metadataAddress; // default FlexiDegenMetadata address
uint256 public price; // price for creating a new TLD
uint256 public royalty = 0; // royalty for Degen Domain Service when new domain is minted
bool public buyingEnabled = false; // buying TLDs enabled (true/false)
uint256 public nameMaxLength = 40; // the maximum length of a TLD name
event TldCreated(address indexed user, address indexed owner, string tldName, address tldAddress);
event ChangeTldPrice(address indexed user, uint256 tldPrice);
constructor(
uint256 _price,
address _forbiddenTlds,
address _metadataAddress
) {
price = _price;
forbiddenTlds = _forbiddenTlds;
metadataAddress = _metadataAddress;
}
// READ
function getTldsArray() public override view returns(string[] memory) {
return tlds;
}
function _validTldName(string memory _name) view internal {
// ex-modifier turned into internal function to optimize contract size
require(strings.len(strings.toSlice(_name)) > 1, "TLD too short"); // at least two chars, which is a dot and a letter
require(bytes(_name).length < nameMaxLength, "TLD too long");
require(strings.count(strings.toSlice(_name), strings.toSlice(".")) == 1, "Name must have 1 dot");
require(strings.count(strings.toSlice(_name), strings.toSlice(" ")) == 0, "Name must have no spaces");
require(strings.startsWith(strings.toSlice(_name), strings.toSlice(".")) == true, "Name must start with dot");
IDegenForbiddenTlds forbidden = IDegenForbiddenTlds(forbiddenTlds);
require(forbidden.isTldForbidden(_name) == false, "TLD already exists or forbidden");
}
// WRITE
/// @notice Create a new top-level domain contract (ERC-721).
/// @param _name Enter TLD name starting with a dot and make sure letters are in lowercase form.
/// @return TLD contract address
function createTld(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) external payable override nonReentrant returns(address) {
require(buyingEnabled == true, "Buying TLDs disabled");
require(msg.value >= price, "Value below price");
(bool sent, ) = payable(owner()).call{value: address(this).balance}("");
require(sent, "Failed to send TLD payment to factory owner");
return _createTld(
_name,
_symbol,
_tldOwner,
_domainPrice,
_buyingEnabled
);
}
// create a new TLD (internal non-payable)
function _createTld(
string memory _nameRaw,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) internal returns(address) {
string memory _name = strings.lower(_nameRaw);
_validTldName(_name);
FlexiDegenTLD tld = new FlexiDegenTLD(
_name,
_symbol,
_tldOwner,
_domainPrice,
_buyingEnabled,
royalty,
address(this),
metadataAddress
);
IDegenForbiddenTlds forbidden = IDegenForbiddenTlds(forbiddenTlds);
forbidden.addForbiddenTld(_name);
tldNamesAddresses[_name] = address(tld); // store TLD name and address into mapping
tlds.push(_name); // store TLD name into array
emit TldCreated(_msgSender(), _tldOwner, _name, address(tld));
return address(tld);
}
// OWNER
/// @notice Factory contract owner can change the ForbiddenTlds contract address.
function changeForbiddenTldsAddress(address _forbiddenTlds) external onlyOwner {
forbiddenTlds = _forbiddenTlds;
}
/// @notice Factory contract owner can change the metadata contract address.
function changeMetadataAddress(address _mAddr) external onlyOwner {
metadataAddress = _mAddr;
}
/// @notice Factory contract owner can change TLD max name length.
function changeNameMaxLength(uint256 _maxLength) external onlyOwner {
nameMaxLength = _maxLength;
}
/// @notice Factory contract owner can change price for minting new TLDs.
function changePrice(uint256 _price) external onlyOwner {
price = _price;
emit ChangeTldPrice(_msgSender(), _price);
}
/// @notice Factory contract owner can change royalty fee for future contracts.
function changeRoyalty(uint256 _royalty) external onlyOwner {
royalty = _royalty;
}
/// @notice Factory owner can create a new TLD for a specified address for free
/// @param _name Enter TLD name starting with a dot and make sure letters are in lowercase form.
/// @return TLD contract address
function ownerCreateTld(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) external onlyOwner returns(address) {
return _createTld(
_name,
_symbol,
_tldOwner,
_domainPrice,
_buyingEnabled
);
}
/// @notice Factory contract owner can enable or disable public minting of new TLDs.
function toggleBuyingTlds() external onlyOwner {
buyingEnabled = !buyingEnabled;
}
}

@ -0,0 +1,9 @@
# Flexi Degen Contracts
Flexi is an alternative Degen TLD Factory which provides TLD owners with more flexibility, especially when it comes to metadata such as the default domain image SVG.
Metadata is stored in a separate contract and TLD owner can change it (except the domain name, of course).
Flexi TLD contract also has a role called "minter", which is an address that is allowed to mint new domains even if the TLD contract is paused.
Another role is the royalty fee updater. Buy default this is the factory owner, but can be changed to any other address.

@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
interface IFlexiDegenMetadata {
function getMetadata(string calldata _domainName, string calldata _tld, uint256 _tokenId) external view returns(string memory);
}

@ -0,0 +1,247 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./interfaces/IDegenTLDFactory.sol";
import "../../lib/strings.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "base64-sol/base64.sol";
/// @title Degen Domain Service TLD contract (v2)
/// @author Degen Labs
/// @notice Dynamically generated NFT contract which represents a top-level domain
contract DegenTLD is ERC721, Ownable, ReentrancyGuard {
using strings for string;
uint256 public price; // domain price
bool public buyingEnabled; // buying domains enabled
address public factoryAddress; // DegenTLDFactory address
uint256 public royalty; // share of each domain purchase (in bips) that goes to Degen Domain Service
uint256 public referral = 1000; // share of each domain purchase (in bips) that goes to the referrer (referral fee)
uint256 public totalSupply;
uint256 public nameMaxLength = 140; // max length of a domain name
string public description = "Degen Domain Service. Visit https://degendomains.io/";
struct Domain {
string name; // domain name that goes before the TLD name; example: "tempetechie" in "tempetechie.web3"
uint256 tokenId;
address holder;
string data; // stringified JSON object, example: {"description": "Some text", "twitter": "@techie1239", "friends": ["0x123..."], "url": "https://degendomains.io"}
}
mapping (string => Domain) public domains; // mapping (domain name => Domain struct)
mapping (uint256 => string) public domainIdsNames; // mapping (tokenId => domain name)
mapping (address => string) public defaultNames; // user's default domain
event DomainCreated(address indexed user, address indexed owner, string fullDomainName);
event DefaultDomainChanged(address indexed user, string defaultDomain);
event DataChanged(address indexed user);
event TldPriceChanged(address indexed user, uint256 tldPrice);
event ReferralFeeChanged(address indexed user, uint256 referralFee);
event TldRoyaltyChanged(address indexed user, uint256 tldRoyalty);
event DomainBuyingToggle(address indexed user, bool domainBuyingToggle);
constructor(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled,
uint256 _royalty,
address _factoryAddress
) ERC721(_name, _symbol) {
price = _domainPrice;
buyingEnabled = _buyingEnabled;
royalty = _royalty;
factoryAddress = _factoryAddress;
transferOwnership(_tldOwner);
}
// READ
// Domain getters - you can also get all Domain data by calling the auto-generated domains(domainName) method
function getDomainHolder(string calldata _domainName) public view returns(address) {
return domains[strings.lower(_domainName)].holder;
}
function getDomainData(string calldata _domainName) public view returns(string memory) {
return domains[strings.lower(_domainName)].data; // should be a JSON object
}
function getFactoryOwner() public view returns(address) {
Ownable factory = Ownable(factoryAddress);
return factory.owner();
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
IDegenTLDFactory factory = IDegenTLDFactory(factoryAddress);
string memory fullDomainName = string(abi.encodePacked(domains[domainIdsNames[_tokenId]].name, name()));
return string(
abi.encodePacked("data:application/json;base64,",Base64.encode(bytes(abi.encodePacked(
'{"name": "', fullDomainName, '", ',
'"description": "', description, '", ',
'"image": "', _getImage(fullDomainName, factory.projectName()), '"}'))))
);
}
function _getImage(string memory _fullDomainName, string memory _projectName) internal pure returns (string memory) {
string memory svgBase64Encoded = Base64.encode(bytes(string(abi.encodePacked(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="500" height="500"><defs><linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" style="stop-color:rgb(58,17,116);stop-opacity:1" /><stop offset="100%" style="stop-color:rgb(116,25,17);stop-opacity:1" /></linearGradient></defs><rect x="0" y="0" width="500" height="500" fill="url(#grad)"/><text x="50%" y="50%" dominant-baseline="middle" fill="white" text-anchor="middle" font-size="x-large">',
_fullDomainName,'</text><text x="50%" y="70%" dominant-baseline="middle" fill="white" text-anchor="middle">',
_projectName,'</text>',
'</svg>'
))));
return string(abi.encodePacked("data:image/svg+xml;base64,",svgBase64Encoded));
}
// WRITE
function editDefaultDomain(string calldata _domainName) external {
require(domains[_domainName].holder == msg.sender, "You do not own the selected domain");
defaultNames[msg.sender] = _domainName;
emit DefaultDomainChanged(msg.sender, _domainName);
}
/// @notice Edit domain custom data. Make sure to not accidentally delete previous data. Fetch previous data first.
/// @param _domainName Only domain name, no TLD/extension.
/// @param _data Custom data needs to be in a JSON object format.
function editData(string calldata _domainName, string calldata _data) external {
require(domains[_domainName].holder == msg.sender, "Only domain holder can edit their data");
domains[_domainName].data = _data;
emit DataChanged(msg.sender);
}
/// @notice Mint a new domain name as NFT (no dots and spaces allowed).
/// @param _domainName Enter domain name without TLD and make sure letters are in lowercase form.
/// @return token ID
function mint(
string memory _domainName,
address _domainHolder,
address _referrer
) external payable nonReentrant returns(uint256) {
require(buyingEnabled || msg.sender == owner(), "Buying TLDs disabled");
require(msg.value >= price, "Value below price");
_sendPayment(msg.value, _referrer);
return _mintDomain(_domainName, _domainHolder, "");
}
function _mintDomain(
string memory _domainNameRaw,
address _domainHolder,
string memory _data
) internal returns(uint256) {
// convert domain name to lowercase (only works for ascii, clients should enforce ascii domains only)
string memory _domainName = strings.lower(_domainNameRaw);
require(strings.len(strings.toSlice(_domainName)) > 1, "Domain must be longer than 1 char");
require(bytes(_domainName).length < nameMaxLength, "Domain name is too long");
require(strings.count(strings.toSlice(_domainName), strings.toSlice(".")) == 0, "There should be no dots in the name");
require(strings.count(strings.toSlice(_domainName), strings.toSlice(" ")) == 0, "There should be no spaces in the name");
require(domains[_domainName].holder == address(0), "Domain with this name already exists");
_safeMint(_domainHolder, totalSupply);
Domain memory newDomain;
// store data in Domain struct
newDomain.name = _domainName;
newDomain.tokenId = totalSupply;
newDomain.holder = _domainHolder;
newDomain.data = _data;
// add to both mappings
domains[_domainName] = newDomain;
domainIdsNames[totalSupply] = _domainName;
if (bytes(defaultNames[_domainHolder]).length == 0) {
defaultNames[_domainHolder] = _domainName; // if default domain name is not set for that holder, set it now
}
emit DomainCreated(msg.sender, _domainHolder, string(abi.encodePacked(_domainName, name())));
++totalSupply;
return totalSupply-1;
}
function _sendPayment(uint256 _paymentAmount, address _referrer) internal {
if (royalty > 0 && royalty < 5000) {
// send royalty - must be less than 50% (5000 bips)
(bool sentRoyalty, ) = payable(getFactoryOwner()).call{value: ((_paymentAmount * royalty) / 10000)}("");
require(sentRoyalty, "Failed to send royalty to factory owner");
}
if (_referrer != address(0) && referral > 0 && referral < 5000) {
// send referral fee - must be less than 50% (5000 bips)
(bool sentReferralFee, ) = payable(_referrer).call{value: ((_paymentAmount * referral) / 10000)}("");
require(sentReferralFee, "Failed to send referral fee");
}
// send the rest to TLD owner
(bool sent, ) = payable(owner()).call{value: address(this).balance}("");
require(sent, "Failed to send domain payment to TLD owner");
}
///@dev Hook that is called before any token transfer. This includes minting and burning.
function _beforeTokenTransfer(address from,address to,uint256 tokenId) internal override virtual {
if (from != address(0)) { // run on every transfer but not on mint
domains[domainIdsNames[tokenId]].holder = to; // change holder address in Domain struct
domains[domainIdsNames[tokenId]].data = ""; // reset custom data
if (bytes(defaultNames[to]).length == 0) {
defaultNames[to] = domains[domainIdsNames[tokenId]].name; // if default domain name is not set for that holder, set it now
}
if (strings.equals(strings.toSlice(domains[domainIdsNames[tokenId]].name), strings.toSlice(defaultNames[from]))) {
defaultNames[from] = ""; // if previous owner had this domain name as default, unset it as default
}
}
}
// OWNER
/// @notice Only TLD contract owner can call this function.
function changeDescription(string calldata _description) external onlyOwner {
description = _description;
}
/// @notice Only TLD contract owner can call this function.
function changeNameMaxLength(uint256 _maxLength) external onlyOwner {
nameMaxLength = _maxLength;
}
/// @notice Only TLD contract owner can call this function.
function changePrice(uint256 _price) external onlyOwner {
price = _price;
emit TldPriceChanged(msg.sender, _price);
}
/// @notice Only TLD contract owner can call this function.
function changeReferralFee(uint256 _referral) external onlyOwner {
require(_referral < 5000, "Referral fee cannot be 50% or higher");
referral = _referral; // referral must be in bips
emit ReferralFeeChanged(msg.sender, _referral);
}
/// @notice Only TLD contract owner can call this function.
function toggleBuyingDomains() external onlyOwner {
buyingEnabled = !buyingEnabled;
emit DomainBuyingToggle(msg.sender, buyingEnabled);
}
// FACTORY OWNER (current owner address of DegenTLDFactory)
/// @notice Only Factory contract owner can call this function.
function changeRoyalty(uint256 _royalty) external {
require(getFactoryOwner() == msg.sender, "Sender not factory owner");
require(_royalty < 5000, "Royalty cannot be 50% or higher");
royalty = _royalty; // royalty is in bips
emit TldRoyaltyChanged(msg.sender, _royalty);
}
}

@ -0,0 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../../lib/strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./DegenTLD.sol";
import "../../interfaces/IDegenForbiddenTlds.sol";
/// @title Degen Domain Service TLD Factory contract (v2)
/// @author Degen Labs
/// @notice Factory contract dynamically generates new TLD contracts.
contract DegenTLDFactory is Ownable, ReentrancyGuard {
using strings for string;
string public projectName = "Degen Domain Service";
string[] public tlds; // existing TLDs
mapping (string => address) public tldNamesAddresses; // a mapping of TLDs (string => TLDaddress)
address public forbiddenTlds; // address of the contract that stores the list of forbidden TLDs
uint256 public price; // price for creating a new TLD
uint256 public royalty = 0; // royalty for Degen Domain Service when new domain is minted
bool public buyingEnabled = false; // buying TLDs enabled (true/false)
uint256 public nameMaxLength = 40; // the maximum length of a TLD name
event TldCreated(address indexed user, address indexed owner, string tldName, address tldAddress);
event ChangeTldPrice(address indexed user, uint256 tldPrice);
constructor(uint256 _price, address _forbiddenTlds) {
price = _price;
forbiddenTlds = _forbiddenTlds;
}
// READ
function getTldsArray() public view returns(string[] memory) {
return tlds;
}
function _validTldName(string memory _name) view internal {
// ex-modifier turned into internal function to optimize contract size
require(strings.len(strings.toSlice(_name)) > 1, "TLD too short");
require(bytes(_name).length < nameMaxLength, "TLD too long");
require(strings.count(strings.toSlice(_name), strings.toSlice(".")) == 1, "Name must have 1 dot");
require(strings.count(strings.toSlice(_name), strings.toSlice(" ")) == 0, "Name must have no spaces");
require(strings.startsWith(strings.toSlice(_name), strings.toSlice(".")) == true, "Name must start with dot");
IDegenForbiddenTlds forbidden = IDegenForbiddenTlds(forbiddenTlds);
require(forbidden.isTldForbidden(_name) == false, "TLD already exists or forbidden");
}
// WRITE
/// @notice Create a new top-level domain contract (ERC-721).
/// @param _name Enter TLD name starting with a dot and make sure letters are in lowercase form.
/// @return TLD contract address
function createTld(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) external payable nonReentrant returns(address) {
require(buyingEnabled == true, "Buying TLDs disabled");
require(msg.value >= price, "Value below price");
(bool sent, ) = payable(owner()).call{value: address(this).balance}("");
require(sent, "Failed to send TLD payment to factory owner");
return _createTld(
_name,
_symbol,
_tldOwner,
_domainPrice,
_buyingEnabled
);
}
// create a new TLD (internal non-payable)
function _createTld(
string memory _nameRaw,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) internal returns(address) {
string memory _name = strings.lower(_nameRaw);
_validTldName(_name);
DegenTLD tld = new DegenTLD(
_name,
_symbol,
_tldOwner,
_domainPrice,
_buyingEnabled,
royalty,
address(this)
);
IDegenForbiddenTlds forbidden = IDegenForbiddenTlds(forbiddenTlds);
forbidden.addForbiddenTld(_name);
tldNamesAddresses[_name] = address(tld); // store TLD name and address into mapping
tlds.push(_name); // store TLD name into array
emit TldCreated(msg.sender, _tldOwner, _name, address(tld));
return address(tld);
}
// OWNER
/// @notice Only Factory contract owner can call this function.
function changeForbiddenTldsAddress(address _forbiddenTlds) external onlyOwner {
forbiddenTlds = _forbiddenTlds;
}
/// @notice Only Factory contract owner can call this function.
function changeNameMaxLength(uint256 _maxLength) external onlyOwner {
nameMaxLength = _maxLength;
}
/// @notice Only Factory contract owner can call this function.
function changePrice(uint256 _price) external onlyOwner {
price = _price;
emit ChangeTldPrice(msg.sender, _price);
}
/// @notice Only Factory contract owner can call this function.
function changeProjectName(string calldata _newProjectName) external onlyOwner {
// visible in each domain NFT image (SVG)
projectName = _newProjectName;
}
/// @notice Only Factory contract owner can call this function.
function changeRoyalty(uint256 _royalty) external onlyOwner {
require(_royalty < 5000, "Royalty cannot be 50% or higher");
royalty = _royalty;
}
/// @notice Factory owner can create a new TLD for a specified address for free
/// @param _name Enter TLD name starting with a dot and make sure letters are in lowercase form.
/// @return TLD contract address
function ownerCreateTld(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) external onlyOwner returns(address) {
return _createTld(
_name,
_symbol,
_tldOwner,
_domainPrice,
_buyingEnabled
);
}
/// @notice Only Factory contract owner can call this function.
function toggleBuyingTlds() external onlyOwner {
buyingEnabled = !buyingEnabled;
}
}

@ -0,0 +1,42 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IDegenTLD is IERC721 {
struct Domain {
string name; // domain name that goes before the TLD name; example: "king" in "king.doge"
uint256 tokenId;
address holder;
string data; // stringified JSON object, example: {"description": "Some text", "twitter": "@yourtwitter", "friends": ["0x123..."], "url": "https://degendomains.io"}
}
event DomainCreated(address indexed user, address indexed owner, string fullDomainName);
event DefaultDomainChanged(address indexed user, string defaultDomain);
function domains(string calldata _domainName) external view returns(string memory, uint256, address, string memory);
function getDomainHolder(string calldata _domainName) external view returns(address);
function getFactoryOwner() external view returns(address);
function price() external view returns (uint256);
function referral() external view returns (uint256);
function changeDescription(string calldata _description) external;
function changeNameMaxLength(uint256 _maxLength) external;
function changePrice(uint256 _price) external;
function changeReferralFee(uint256 _referral) external;
function mint(
string memory _domainName,
address _domainHolder,
address _referrer
) external payable returns(uint256);
function transferOwnership(address newOwner) external;
}

@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
interface IDegenTLDFactory {
function projectName() external view returns (string memory);
}

@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IBaseDegenTLD is IERC721 {
struct Domain {
string name; // domain name that goes before the TLD name; example: "tempetechie" in "tempetechie.web3"
uint256 tokenId;
address holder;
string data; // stringified JSON object, example: {"description": "Some text", "twitter": "@techie1239", "friends": ["0x123..."], "url": "https://degendomains.io"}
}
event DomainCreated(address indexed user, address indexed owner, string fullDomainName);
event DomainBurned(address indexed user, string fullDomainName);
event DefaultDomainChanged(address indexed user, string defaultDomain);
event DataChanged(address indexed user);
event TldPriceChanged(address indexed user, uint256 tldPrice);
event ReferralFeeChanged(address indexed user, uint256 referralFee);
event TldRoyaltyChanged(address indexed user, uint256 tldRoyalty);
event DomainBuyingToggle(address indexed user, bool domainBuyingToggle);
function domains(string calldata _domainName) external view returns(string memory, uint256, address, string memory);
function defaultNames(address) external view returns(string memory);
function getDomainData(string calldata _domainName) external view returns(string memory);
function getDomainHolder(string calldata _domainName) external view returns(address);
function price() external view returns (uint256);
function referral() external view returns (uint256);
function changeNameMaxLength(uint256 _maxLength) external;
function changePrice(uint256 _price) external;
function changeReferralFee(uint256 _referral) external;
function mint(
string memory _domainName,
address _domainHolder,
address _referrer
) external payable returns(uint256);
}

@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
interface IBaseDegenTLDFactory {
function getTldsArray() external view returns(string[] memory);
function tldNamesAddresses(string memory) external view returns(address);
function createTld(
string memory _name,
string memory _symbol,
address _tldOwner,
uint256 _domainPrice,
bool _buyingEnabled
) external payable returns(address);
}

@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
interface IDegenForbiddenTlds {
function isTldForbidden(string memory _name) external view returns (bool);
function addForbiddenTld(string memory _name) external;
}

@ -0,0 +1,741 @@
// SPDX-License-Identifier: Apache-2.0
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <arachnid@notdot.net>
*/
pragma solidity ^0.8.0;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint _len) private pure {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = type(uint).max;
if (_len > 0) {
mask = 256 ** (32 - _len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & type(uint128).max == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & type(uint64).max == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & type(uint32).max == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & type(uint16).max == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & type(uint8).max == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask = type(uint).max; // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
unchecked {
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask;
if (needlelen > 0) {
mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
}
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask;
if (needlelen > 0) {
mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
}
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1) + 32);
}
return _b1;
}
}

@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// Mock token contract for testing purposes only
contract MockErc20Token is ERC20 {
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
mint(msg.sender, 1000*(10**18)); // 1000 mock tokens to deployer
}
function mint(address receiver, uint amount) public {
_mint(receiver, amount);
}
}

@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@rari-capital/solmate/src/tokens/ERC20.sol";
// Mock token contract for testing purposes only
contract MockErc20TokenDecimals is ERC20 {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) ERC20(_name, _symbol, _decimals) {
mint(msg.sender, 1000*(10**_decimals)); // 1000 mock tokens to deployer
}
function mint(address receiver, uint amount) public {
_mint(receiver, amount);
}
}

@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
// Mock NFT contract for testing purposes only
contract MockErc721Token is ERC721, ERC721Enumerable {
uint256 public counter;
constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {
counter = 0;
_safeMint(msg.sender, counter);
counter++;
}
function mint(address receiver) public {
_safeMint(receiver, counter);
counter++;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}

File diff suppressed because one or more lines are too long

@ -0,0 +1,169 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IFlexiDegenTLD.sol";
import "./interfaces/IDegenAnonMetadata.sol";
import "../../lib/strings.sol";
contract DegenAnonMinter is Ownable, ReentrancyGuard {
bool public paused = true;
uint256 public referralFee = 1_000; // share of each domain purchase (in bips) that goes to the referrer
uint256 public constant MAX_BPS = 10_000;
uint256 public maxTotalPayments;
uint256 public totalPayments; // total amount of payments in the payment token
uint256 public price1char; // 1 char domain price
uint256 public price2char; // 2 chars domain price
uint256 public price3char; // 3 chars domain price
uint256 public price4char; // 4 chars domain price
uint256 public price5char; // 5+ chars domain price
// TLD contract (.degen)
IERC20 public immutable paymentToken; // payment token
IFlexiDegenTLD public immutable tldContract; // TLD contract
IDegenAnonMetadata public metadataContract; // metadata contract
// EVENTS
event FeatureMinted(string indexed featureId_);
// CONSTRUCTOR
constructor(
address _tokenAddress,
address _tldAddress,
address _metadataAddress,
uint256 _maxTotalPayments,
uint256 _price1char,
uint256 _price2char,
uint256 _price3char,
uint256 _price4char,
uint256 _price5char
) {
paymentToken = IERC20(_tokenAddress);
tldContract = IFlexiDegenTLD(_tldAddress);
metadataContract = IDegenAnonMetadata(_metadataAddress);
maxTotalPayments = _maxTotalPayments;
price1char = _price1char;
price2char = _price2char;
price3char = _price3char;
price4char = _price4char;
price5char = _price5char;
}
// WRITE
/// @notice payment token approval transaction needs to be made before minting
function mint(
string memory _domainName,
address _domainHolder,
address _referrer,
string[] calldata _featureIds
) external nonReentrant returns(uint256 tokenId) {
require(!paused || _msgSender() == owner(), "Minting paused");
require(totalPayments < maxTotalPayments, "Max total payments reached");
// find price
uint256 domainLength = strings.len(strings.toSlice(_domainName));
uint256 selectedPrice;
if (domainLength == 1) {
selectedPrice = price1char;
} else if (domainLength == 2) {
selectedPrice = price2char;
} else if (domainLength == 3) {
selectedPrice = price3char;
} else if (domainLength == 4) {
selectedPrice = price4char;
} else {
selectedPrice = price5char;
}
// mint a domain
tokenId = tldContract.mint{value: 0}(_domainName, _domainHolder, address(0));
// mint a feature
string memory selFeature = metadataContract.setUniqueFeaturesId(tokenId, _featureIds, selectedPrice);
emit FeatureMinted(selFeature);
// send referral fee
if (referralFee > 0 && _referrer != address(0)) {
uint256 referralPayment = (selectedPrice * referralFee) / MAX_BPS;
selectedPrice -= referralPayment;
paymentToken.transferFrom(_msgSender(), _referrer, referralPayment);
}
// send the rest to the owner
paymentToken.transferFrom(_msgSender(), tldContract.owner(), selectedPrice);
// update total payments
totalPayments += selectedPrice;
if (totalPayments >= maxTotalPayments) {
paused = true;
}
}
// OWNER
/// @notice This changes referral fee in the minter contract
function changeMaxTotalPayments(uint256 _maxPay) external onlyOwner {
maxTotalPayments = _maxPay;
}
/// @notice This changes metadata contract in the minter contract
function changeMetadataContract(address _metadataAddress) external onlyOwner {
metadataContract = IDegenAnonMetadata(_metadataAddress);
}
/// @notice This changes price in the minter contract
function changePrice(uint256 _price, uint256 _chars) external onlyOwner {
require(_price > 0, "Cannot be zero");
if (_chars == 1) {
price1char = _price;
} else if (_chars == 2) {
price2char = _price;
} else if (_chars == 3) {
price3char = _price;
} else if (_chars == 4) {
price4char = _price;
} else if (_chars == 5) {
price5char = _price;
}
}
/// @notice This changes referral fee in the minter contract
function changeReferralFee(uint256 _referral) external onlyOwner {
require(_referral <= 2000, "Cannot exceed 20%");
referralFee = _referral;
}
/// @notice Recover any ERC-20 token mistakenly sent to this contract address
function recoverERC20(address tokenAddress_, uint256 tokenAmount_, address recipient_) external onlyOwner {
IERC20(tokenAddress_).transfer(recipient_, tokenAmount_);
}
/// @notice Recover any ERC-721 token mistakenly sent to this contract address
function recoverERC721(address tokenAddress_, uint256 tokenId_, address recipient_) external onlyOwner {
IERC721(tokenAddress_).transferFrom(address(this), recipient_, tokenId_);
}
function togglePaused() external onlyOwner {
paused = !paused;
}
// withdraw ETH from contract
function withdraw() external onlyOwner {
(bool success, ) = owner().call{value: address(this).balance}("");
require(success, "Failed to withdraw ETH from contract");
}
// RECEIVE & FALLBACK
receive() external payable {}
fallback() external payable {}
}

@ -0,0 +1,65 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
contract DegenAnonWhitelist is Ownable {
bool public paused = false;
uint256 public totalAddresses = 0;
uint256 public totalAmount = 0;
mapping (address => bool) public whitelisted;
mapping (address => uint256) public expectedAmount;
address[] public whitelistedAddresses;
// EVENTS
event UserJoinWhitelist(address user, uint256 amount);
// READ
function isWhitelisted(address _user) external view returns(bool) {
return whitelisted[_user];
}
// WRITE
function joinWhitelist(uint256 _amount) external {
require(!paused || msg.sender == owner(), "Whitelisting is paused.");
require(_amount <= 50_000, "Amount is too high.");
_addToWhitelist(msg.sender, _amount);
}
function _addToWhitelist(address _addr, uint256 _amount) internal {
if (whitelisted[_addr]) {
// if user already whitelisted
totalAmount -= expectedAmount[_addr]; // subtract the previous amount from total
expectedAmount[_addr] = _amount; // store new amount
totalAmount += _amount; // add new amount to total
} else {
// if not yet whitelisted
whitelisted[_addr] = true;
expectedAmount[_addr] = _amount;
whitelistedAddresses.push(_addr);
++totalAddresses;
totalAmount += _amount;
}
emit UserJoinWhitelist(_addr, _amount);
}
// OWNER
function ownerAddToWhitelist(address[] calldata _addresses, uint256[] calldata _amounts) external onlyOwner {
uint256 length = _addresses.length;
for (uint256 i = 0; i < length;) {
_addToWhitelist(_addresses[i], _amounts[i]);
unchecked { ++i; }
}
}
function togglePaused() external onlyOwner {
paused = !paused;
}
}

@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
interface IDegenAnonMetadata {
function getMetadata(
string calldata _domainName,
string calldata _tld,
uint256 _tokenId
) external view returns(string memory);
function setUniqueFeaturesId(
uint256 _tokenId,
string[] calldata _unqs,
uint256 _price
) external returns(string memory selectedFeatureId);
}

@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IFlexiDegenTLD is IERC721 {
function owner() external view returns(address);
function mint(
string memory _domainName,
address _domainHolder,
address _referrer
) external payable returns(uint256);
}

@ -0,0 +1,241 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IBaseDegenTLDFactory.sol";
import "../interfaces/IBaseDegenTLD.sol";
import "../lib/strings.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
/// @title Degen Domain Service Resolver v1
/// @author Degen Labs
/// @notice This contract resolves all degen domain service domains and TLDs on the particular blockchain where it is deployed
contract DegenResolverV1 is Initializable, OwnableUpgradeable {
using strings for string;
mapping (address => bool) public isTldDeprecated; // deprecate an address, not TLD name
address[] public factories;
event FactoryAddressAdded(address user, address fAddr);
event DeprecatedTldAdded(address user, address tAddr);
event DeprecatedTldRemoved(address user, address tAddr);
// initializer (only for V1!)
function initialize() public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
// READ
// reverse resolver: get user's default name for a given TLD
function getDefaultDomain(address _addr, string calldata _tld) public view returns(string memory) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(_tld);
if (tldAddr != address(0) && !isTldDeprecated[tldAddr]) {
return string(IBaseDegenTLD(tldAddr).defaultNames(_addr));
}
unchecked { ++i; }
}
return "";
}
// reverse resolver: get user's default names (all TLDs)
function getDefaultDomains(address _addr) public view returns(string memory) {
bytes memory result;
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
string[] memory tldNames = IBaseDegenTLDFactory(factories[i]).getTldsArray();
for (uint256 j = 0; j < tldNames.length; ++j) {
string memory tldName = tldNames[j];
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(tldName);
string memory defaultName = IBaseDegenTLD(tldAddr).defaultNames(_addr);
if (
strings.len(strings.toSlice(defaultName)) > 0 &&
!isTldDeprecated[tldAddr]
) {
if (j == (tldNames.length-1)) { // last TLD (do not include space at the end)
result = abi.encodePacked(result, defaultName, tldName);
} else {
result = abi.encodePacked(result, defaultName, tldName, " ");
}
}
}
unchecked { ++i; }
}
return string(result);
}
/// @notice domain resolver
function getDomainHolder(string calldata _domainName, string calldata _tld) public view returns(address) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(_tld);
if (tldAddr != address(0) && !isTldDeprecated[tldAddr]) {
return address(IBaseDegenTLD(tldAddr).getDomainHolder(_domainName));
}
unchecked { ++i; }
}
return address(0);
}
/// @notice fetch domain data for a given domain
function getDomainData(string calldata _domainName, string calldata _tld) public view returns(string memory) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(_tld);
if (tldAddr != address(0) && !isTldDeprecated[tldAddr]) {
return string(IBaseDegenTLD(tldAddr).getDomainData(_domainName));
}
unchecked { ++i; }
}
return "";
}
/// @notice fetch domain metadata for a given domain (tokenURI)
function getDomainTokenUri(string calldata _domainName, string calldata _tld) public view returns(string memory) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(_tld);
if (tldAddr != address(0) && !isTldDeprecated[tldAddr]) {
(, uint256 _tokenId, , ) = IBaseDegenTLD(tldAddr).domains(_domainName);
return IERC721Metadata(tldAddr).tokenURI(_tokenId);
}
unchecked { ++i; }
}
return "";
}
function getFactoriesArray() public view returns(address[] memory) {
return factories;
}
/// @notice reverse resolver: get single user's default name, the first that comes (all TLDs)
function getFirstDefaultDomain(address _addr) public view returns(string memory) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
string[] memory tldNames = IBaseDegenTLDFactory(factories[i]).getTldsArray();
for (uint256 j = 0; j < tldNames.length; ++j) {
string memory tldName = tldNames[j];
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(tldName);
string memory defaultName = IBaseDegenTLD(tldAddr).defaultNames(_addr);
if (
strings.len(strings.toSlice(defaultName)) > 0 &&
!isTldDeprecated[tldAddr]
) {
return string(abi.encodePacked(defaultName, tldName));
}
}
unchecked { ++i; }
}
return "";
}
/// @notice get the address of a given TLD name
function getTldAddress(string calldata _tldName) public view returns(address) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(_tldName);
if (tldAddr != address(0) && !isTldDeprecated[tldAddr]) {
return tldAddr;
} else if (isTldDeprecated[tldAddr]) {
return address(0);
}
unchecked { ++i; }
}
return address(0);
}
/// @notice get the address of the factory contract through which a given TLD was created
function getTldFactoryAddress(string calldata _tldName) public view returns(address) {
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(_tldName);
if (tldAddr != address(0) && !isTldDeprecated[tldAddr]) {
return factories[i];
} else if (isTldDeprecated[tldAddr]) {
return address(0);
}
unchecked { ++i; }
}
return address(0);
}
/// @notice get a stringified CSV of all active TLDs (name,address) across all factories
function getTlds() public view returns(string memory) {
bytes memory result;
uint256 fLength = factories.length;
for (uint256 i = 0; i < fLength;) {
string[] memory tldNames = IBaseDegenTLDFactory(factories[i]).getTldsArray();
for (uint256 j = 0; j < tldNames.length; ++j) {
string memory tldName = tldNames[j];
address tldAddr = IBaseDegenTLDFactory(factories[i]).tldNamesAddresses(tldName);
if (!isTldDeprecated[tldAddr]) {
result = abi.encodePacked(
result,
abi.encodePacked(tldName, ',', Strings.toHexString(uint256(uint160(tldAddr)), 20), '\n')
);
}
}
unchecked { ++i; }
}
return string(result);
}
// OWNER
function addFactoryAddress(address _factoryAddress) external onlyOwner {
factories.push(_factoryAddress);
emit FactoryAddressAdded(_msgSender(), _factoryAddress);
}
function addDeprecatedTldAddress(address _deprecatedTldAddress) external onlyOwner {
isTldDeprecated[_deprecatedTldAddress] = true;
emit DeprecatedTldAdded(_msgSender(), _deprecatedTldAddress);
}
function removeFactoryAddress(uint _addrIndex) external onlyOwner {
factories[_addrIndex] = factories[factories.length - 1];
factories.pop();
}
function removeDeprecatedTldAddress(address _deprecatedTldAddress) external onlyOwner {
isTldDeprecated[_deprecatedTldAddress] = false;
emit DeprecatedTldRemoved(_msgSender(), _deprecatedTldAddress);
}
}

@ -0,0 +1,43 @@
require("@nomiclabs/hardhat-waffle");
require("@nomiclabs/hardhat-etherscan");
require('@openzeppelin/hardhat-upgrades');
require('dotenv').config();
/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
defaultNetwork: 'hardhat',
networks: {
localhost: {
url: 'http://127.0.0.1:8545/',
chainId: 31337
},
polygonMumbai: {
url: 'https://polygon-mumbai.g.alchemy.com/v2/' + process.env.ALCHEMY_API_KEY_MUMBAI,
chainId: 80001,
accounts: [process.env.DEPLOYER_PRIVATE_KEY],
gas: "auto", // gas limit
gasPrice: 2000000000, // 2 gwei
},
},
etherscan: {
apiKey: { // all possible key names here: https://gist.github.com/tempe-techie/95a3ad4e81b46c895928a0524fc2b7ac
polygonMumbai: process.env.POLYGONSCAN_API_KEY,
}
},
solidity: {
version: "0.8.4",
settings: {
optimizer: {
enabled: true,
runs: 200
}
}
}
};

@ -0,0 +1,27 @@
{
"name": "degen-doamin-service-contracts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@nomiclabs/hardhat-ethers": "^2.0.3",
"@nomiclabs/hardhat-etherscan": "^3.0.0",
"@nomiclabs/hardhat-waffle": "^2.0.1",
"@openzeppelin/contracts": "^4.4.1",
"@openzeppelin/contracts-upgradeable": "^4.6.0",
"@openzeppelin/hardhat-upgrades": "^1.18.0",
"@rari-capital/solmate": "^6.4.0",
"base64-sol": "1.0.1",
"chai": "^4.3.4",
"dotenv": "^10.0.0",
"ethereum-waffle": "^3.4.0",
"ethers": "^5.5.2",
"hardhat": "^2.8.0"
}
}

@ -0,0 +1,42 @@
const contractNameForb = "DegenForbiddenTlds";
const contractNameFactory = "DegenTLDFactory";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract1
const contractForb = await ethers.getContractFactory(contractNameForb);
const contractFactory = await ethers.getContractFactory(contractNameFactory);
const instanceForb = await contractForb.deploy();
console.log("ForbiddenTlds contract address:", instanceForb.address);
const tldPrice = ethers.utils.parseUnits("0.01", "ether");
const instanceFactory = await contractFactory.deploy(tldPrice, instanceForb.address);
await instanceForb.addFactoryAddress(instanceFactory.address);
console.log("Factory contract address:", instanceFactory.address);
console.log("Wait a minute and then run these two commands to verify contracts on Etherscan:");
console.log("Command 1 (verify Forbiddent TLDs contract):");
console.log("npx hardhat verify --network " + network.name + " " + instanceForb.address);
console.log("Command 2 (verify Factory contract):");
console.log("npx hardhat verify --network " + network.name + " " + instanceFactory.address + ' "' + tldPrice + '" ' + instanceForb.address);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,48 @@
// Deploy factory contract only (ForbiddenTlds and FlexiDegenMetadata need to be already deployed)
// after deployment, add factory address to the ForbiddenTlds whitelist and to the Resolver
// npx hardhat run scripts/factories/flexi/deployFactoryOnly.js --network bsc
async function main() {
const contractNameFactory = "FlexiDegenTLDFactory";
const forbAddress = "<enter-forbidden-tlds-contract-address>";
const metaAddress = "<enter-metadata-address>";
let tldPrice = "0.01"; // in ETH or MATIC on testnets
// mainnet prices
if (network.config.chainId === 1 || network.config.chainId === 10 || network.config.chainId === 42161) {
tldPrice = "40"; // ETH
} else if (network.config.chainId === 137) {
tldPrice = "80000"; // MATIC
} else if (network.config.chainId === 100) {
tldPrice = "75000"; // XDAI
} else if (network.config.chainId === 56) {
tldPrice = "250"; // BNB
}
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract1
const contractFactory = await ethers.getContractFactory(contractNameFactory);
console.log("ForbiddenTlds contract address:", forbAddress);
console.log("FlexiDegenMetadata contract address:", metaAddress);
const tldPriceWei = ethers.utils.parseUnits(tldPrice, "ether");
const instanceFactory = await contractFactory.deploy(tldPriceWei, forbAddress, metaAddress);
console.log("Factory contract address:", instanceFactory.address);
console.log("Wait a minute and then run this command to verify contracts on Etherscan:");
console.log("npx hardhat verify --network " + network.name + " " + instanceFactory.address + ' "' + tldPriceWei + '" ' + forbAddress + ' ' + metaAddress);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,27 @@
// Deploy forbidden contract & factory contract (you'll need to deploy metadata contract beforehand)
// after deployment, add factory address to the ForbiddenTlds whitelist and to the Resolver
// npx hardhat run scripts/factories/flexi/deployForbiddenTlds.js --network bsc
async function main() {
const contractNameForb = "DegenForbiddenTlds";
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const contractForb = await ethers.getContractFactory(contractNameForb);
const instanceForb = await contractForb.deploy();
console.log("ForbiddenTlds contract address:", instanceForb.address);
console.log("Wait a minute and then run this command to verify contracts on block explorer:");
console.log("npx hardhat verify --network " + network.name + " " + instanceForb.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,27 @@
// Deploy FlexiDegenMetadata contract
// npx hardhat run scripts/factories/flexi/deployMetadata.js --network bsc
async function main() {
const contractName = "FlexiDegenMetadata";
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract
const contract = await ethers.getContractFactory(contractName);
const instance = await contract.deploy();
console.log("Metadata contract address:", instance.address);
console.log("Wait a minute and then run this command to verify contracts on Etherscan:");
console.log("npx hardhat verify --network " + network.name + " " + instance.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,29 @@
// npx hardhat run scripts/nft/angel/deployMetadata.js --network polygonMumbai
// TODO after deployment:
// 1) Deploy minter contract and add minter address to the metadata contract through changeMinter() function
// 2) Add metadata address to the TLD contract through the changeMetadataAddress() function
const contractNameFactory = "DegenAnonMetadata";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract
const contract = await ethers.getContractFactory(contractNameFactory);
const instance = await contract.deploy();
console.log("Contract address:", instance.address);
console.log("Wait a minute and then run this command to verify contract on the block explorer:");
console.log("npx hardhat verify --network " + network.name + " " + instance.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,46 @@
// npx hardhat run scripts/nft/angel/deployMinter.js --network polygonMumbai
// add minter address to:
// 1) TLD contract as minter
// 2) metadata contract as minter
const contractNameFactory = "DegenAnonMinter";
const tldAddress = "";
const metadataAddress = "";
const paymentTokenAddress = ""; // USDC
const paymentTokenDecimals = 6;
const maxTotalPayments = ethers.utils.parseUnits("400000", paymentTokenDecimals); // 400k
const price1char = ethers.utils.parseUnits("10000", paymentTokenDecimals); // 10k
const price2char = ethers.utils.parseUnits("3000", paymentTokenDecimals); // 3k
const price3char = ethers.utils.parseUnits("999", paymentTokenDecimals);
const price4char = ethers.utils.parseUnits("199", paymentTokenDecimals);
const price5char = ethers.utils.parseUnits("69", paymentTokenDecimals);
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract
const contract = await ethers.getContractFactory(contractNameFactory);
const instance = await contract.deploy(
paymentTokenAddress,
tldAddress,
metadataAddress,
maxTotalPayments,
price1char, price2char, price3char, price4char, price5char
);
console.log("Contract address:", instance.address);
console.log("Wait a minute and then run this command to verify contract on the block explorer:");
console.log("npx hardhat verify --network " + network.name + " " + instance.address + " " + paymentTokenAddress + " " + tldAddress + " " + metadataAddress + ' "' + maxTotalPayments + '"' + ' "' + price1char + '"' + ' "' + price2char + '"' + ' "' + price3char + '"' + ' "' + price4char + '"' + ' "' + price5char + '"');
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,26 @@
// npx hardhat run scripts/nft/angel/deployWhitelist.js --network xdai
const contractNameFactory = "DegenAnonWhitelist";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract
const contract = await ethers.getContractFactory(contractNameFactory);
const instance = await contract.deploy();
console.log("Contract address:", instance.address);
console.log("Wait a minute and then run this command to verify contract on the block explorer:");
console.log("npx hardhat verify --network " + network.name + " " + instance.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,38 @@
// npx hardhat run scripts/resolver/1_deploy.js --network bsc
// after deployment:
// - Mark proxy contract as proxy on Etherscan-based explorers (Contract > More options > Is this a proxy)
// - Add factory addresses to the Resolver
// - Check if there's any TLD to deprecate
// - Move ownership to Gnosis Safe (2 things):
// - transferOwnership() function -> this allows owner to add/remove factories and deprecated TLDs (note that you'll need to manually add implementation ABI to Gnosis Safe to find these methods)
// - transfer the ownership of the ProxyAdmin -> this allows owner to do contract upgrades
// - find the ProxyAdmin address in the .openzeppelin folder
const contractName = "DegenResolverV1";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const contract = await ethers.getContractFactory(contractName);
const instance = await upgrades.deployProxy(contract, {initializer: 'initialize'});
await instance.deployed();
console.log("Proxy address:", instance.address);
const impAddress = await hre.upgrades.erc1967.getImplementationAddress(instance.address);
console.log("Implementation address:", impAddress);
console.log("Wait a minute and then run this command to verify contract on the block explorer:");
console.log("npx hardhat verify --network " + network.name + " " + impAddress);
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,27 @@
// npx hardhat run scripts/resolver/2_upgrade_with_gnosis_safe.js --network polygonMumbai
// see instructions here: https://github.com/tempe-techie/upgradable-contracts#b-upgrades-with-gnosis-safe
const contractName = "DegenResolverV2";
const proxyAddress = "<check-the-docs>";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const contract = await ethers.getContractFactory(contractName);
const impAddress = await upgrades.prepareUpgrade(proxyAddress, contract); // note: prepareUpgrade instead of upgradeProxy!
console.log("Implementation address:", impAddress);
console.log("Wait a minute and then run this command to verify contract on the block explorer:");
console.log("npx hardhat verify --network " + network.name + " " + impAddress);
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,51 @@
// npx hardhat run scripts/resolver/other/addFactory.js --network polygon
// If you can't do it through a block explorer, you can add factory to Resolver through this script
const resolverAddress = "<enter-resolver-proxy-address>"; // proxy
const factoryAddress = "<enter-factory-address>";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Using account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const intfc = new ethers.utils.Interface([
"function addFactoryAddress(address) external",
"function getFactoriesArray() public view returns(address[] memory)",
]);
const contract = new ethers.Contract(resolverAddress, intfc, deployer);
// check factories array
const factoriesArrayBefore = await contract.getFactoriesArray();
console.log("Factories array before: " + factoriesArrayBefore);
let exists = false;
for (let fAddr of factoriesArrayBefore) {
if (String(fAddr).toLowerCase() === factoryAddress.toLowerCase()) {
console.log("This factory address has already been added.");
exists = true;
break;
}
}
if (!exists) {
// add factory address
await contract.addFactoryAddress(factoryAddress);
console.log("Added!");
// check factories array again
const factoriesArrayAfter = await contract.getFactoriesArray();
console.log("Factories array after: " + factoriesArrayAfter);
console.log("Note that the address may be missing in the above array due to a data fetching lag.")
}
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,42 @@
// npx hardhat run scripts/resolver/other/changeProxyAdminOwner.js --network polygon
// If you can't do it through a block explorer, you can change ProxyAdmin owner here
const proxyAdminAddress = "<enter-proxy-admin-address>"; // ProxyADMIN
const newOwnerAddress = "<enter-new-owner>"; // probably your Gnosis Safe address
async function main() {
const [signer] = await ethers.getSigners();
console.log("Using account:", signer.address);
console.log("Account balance:", (await signer.getBalance()).toString());
const intfc = new ethers.utils.Interface([
"function transferOwnership(address) external",
"function owner() public view returns (address)"
]);
const contract = new ethers.Contract(proxyAdminAddress, intfc, signer);
const ownerBefore = await contract.owner();
console.log("ProxyAdmin owner before: " + ownerBefore);
if (ownerBefore === signer.address) {
console.log("Signer is ProxyAdmin owner. We can proceed with transfering ownership.")
// change owner
await contract.transferOwnership(newOwnerAddress);
console.log("Ownership changed!");
const ownerAfter = await contract.owner();
console.log("ProxyAdmin owner after: " + ownerAfter);
console.log("Note that it may still show the old owner due to a data fetching lag.")
}
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,88 @@
// Add forbidden TLDs to the Forbidden contract
// npx hardhat run scripts/temp/addForbiddenTlds.js --network localhost
const maxFee = 2500000000; // 2500000000 - set the correct fee for eip-1559 style transactions (otherwise make txs legacy type)
let forbAddress;
switch (network.config.chainId) {
case 100: // gnosis chain
forbAddress = "0xf51f7a532a2aadfe8e2320bf5ba8275503bb3789";
break;
case 10: // optimism
forbAddress = "0xc6c17896fa051083324f2ad0ed4555dc46d96e7f";
break;
case 137: // polygon
forbAddress = "0xc6c17896fa051083324f2ad0ed4555dc46d96e7f";
break;
case 42161: // arbitrum
forbAddress = "0xf51f7a532a2aadfe8e2320bf5ba8275503bb3789";
break;
case 77: // gnosis chain testnet (sokol)
forbAddress = "0xea2f99fe93e5d07f61334c5eb9c54c5d5c957a6a";
break;
case 69: // optimism testnet
forbAddress = "0xc6c17896fa051083324f2ad0ed4555dc46d96e7f";
break;
case 80001: // mumbai
forbAddress = "0xf81dfed588af7be10ba095fb9e31ce3333b8618c";
break;
case 421611: // arbitrum testnet
forbAddress = "0xf6a44f61030115b5da382b198b711130d98390d9";
break;
}
console.log("Forbidden address: " + forbAddress);
const tlds = [
".eth", ".x", ".crypto", ".coin", ".wallet", ".bitcoin", ".888", ".nft", ".dao", ".zil", ".blockchain",
".gnosis", ".xdai", ".bright", ".wagmi", ".optimism", ".spartan", ".web3", ".polygon", ".ape", ".poly",
".degen", ".arbitrum", ".arbi"
];
async function main() {
const [signer] = await ethers.getSigners();
console.log("Adding forbidden TLDs with the account:", signer.address);
console.log("Account balance:", (await signer.getBalance()).toString());
const forbInterface = new ethers.utils.Interface([
"function isTldForbidden(string memory _name) public view returns (bool)",
"function ownerAddForbiddenTld(string memory _name) external"
]);
const forbContract = new ethers.Contract(forbAddress, forbInterface, signer);
for (let tld of tlds) {
console.log(tld);
const alreadyAdded = await forbContract.isTldForbidden(tld);
console.log(tld + " already added? " + alreadyAdded);
if (!alreadyAdded) {
const tx = await forbContract.ownerAddForbiddenTld(tld, {
//type: 2, // eip-1559
//maxFeePerGas: maxFee,
//maxPriorityFeePerGas: maxFee
});
const receipt = await tx.wait();
if (receipt.status === 1) {
console.log(tld + " successfully added to forbidden list!");
} else {
console.log("ERROR! " + tld + " was not added to forbidden list...");
console.log(receipt);
}
//break;
}
}
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,11 @@
/* needed only for deployTld.js purposes */
module.exports = [
".test",
"TEST",
"<enter-owner-address>",
"100000000000000000",
false,
0,
"<enter-factory-address>"
];

@ -0,0 +1,12 @@
/* needed only for deployTld.js purposes */
module.exports = [
".test",
"TEST",
"0xb29050965A5AC70ab487aa47546cdCBc97dAE45D", //depolyer address
"100000000000000000",
false,
0,
"<enter-factory-address>",
"<enter-metadata-address>"
];

@ -0,0 +1,36 @@
// Use if the Forbidden contract was deployed, but factory was not
// npx hardhat run scripts/temp/deployFactoryOnly.js --network localhost
const contractNameFactory = "DegenTLDFactory";
const forbAddress = "<enter-forbidden-address>";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract1
const contractFactory = await ethers.getContractFactory(contractNameFactory);
console.log("ForbiddenTlds contract address:", forbAddress);
const tldPrice = ethers.utils.parseUnits("10", "ether");
const instanceFactory = await contractFactory.deploy(tldPrice, forbAddress);
console.log("Factory contract address:", instanceFactory.address);
console.log("Wait a minute and then run this command to verify contracts on Etherscan:");
console.log("npx hardhat verify --network " + network.name + " " + instanceFactory.address + ' "' + tldPrice + '" ' + forbAddress);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,57 @@
/*
This script is needed to verify contracts that are generated through contract factory.
How to use:
- First deploy the Factory contract
- Then in deployTld.js replace the owner and factory addresses with the ones you want
- Then deploy the DegenTLD contract: npx hardhat run scripts/temp/deployFlexiTld.js --network optimisticKovan
- Go to arguments.js file and enter correct addresses (and other data if changed in deployTld.js)
- Verify it (see command line for the Verify command). Something like: npx hardhat verify --network polygonMumbai --constructor-args scripts/arguments.js <deployed-contract-address>
- After successful verification, every TLD contract created through the factory will show contract code.
- The DegenTLD contract that you deployed using this script can be ignored (factory does not know about it). It
was only needed for the verification purposes.
*/
const contractName1 = "FlexiDegenTLD";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract1
const contract1 = await ethers.getContractFactory(contractName1);
const tldName = ".test";
const tldSymbol = "TEST";
const tldOwner = "<enter-owner-address>";
const tldPrice = ethers.utils.parseUnits("0.1", "ether");
const buyingEnabled = false;
const royalty = 0;
const factoryAddress = "<enter-factory-address>";
const metadataAddress = "<enter-metadata-address>";
const instance1 = await contract1.deploy(
tldName, tldSymbol, tldOwner, tldPrice, buyingEnabled, royalty, factoryAddress, metadataAddress
);
console.log("Contract address:", instance1.address);
console.log("Wait a minute and then run this command:");
console.log(
"npx hardhat verify --network " + network.name + " --constructor-args scripts/temp/argumentsFlexiTld.js " + instance1.address
);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,28 @@
// npx hardhat run scripts/temp/deployMockNft.js --network localhost
const contractNameFactory = "MockErc721Token";
const nftName = "Mock NFT";
const symbol = "MOCKNFT";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract
const contract = await ethers.getContractFactory(contractNameFactory);
const instance = await contract.deploy(nftName, symbol);
console.log("Contract address:", instance.address);
console.log("Wait a minute and then run this command to verify contracts on Etherscan:");
console.log("npx hardhat verify --network " + network.name + " " + instance.address + ' "' + nftName + '" "' + symbol + '"');
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,46 @@
/*
Mock tokens for testnet purposes.
npx hardhat run scripts/temp/deployMockToken.js --network optimisticKovan
*/
const contractName = "MockErc20Token";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const contract1 = await ethers.getContractFactory(contractName); // mock DAI
const contract2 = await ethers.getContractFactory(contractName); // mock AAVE
const tokenName1 = "Mock Dai";
const tokenSymbol1 = "MDAI";
const tokenName2 = "Mock Aave";
const tokenSymbol2 = "MAAVE";
const instance1 = await contract1.deploy(tokenName1, tokenSymbol1);
const instance2 = await contract2.deploy(tokenName2, tokenSymbol2);
console.log("Contract 1 address:", instance1.address);
console.log("Contract 2 address:", instance2.address);
console.log("Wait a minute and then run these commands:");
console.log("npx hardhat verify --network " + network.name + " " + instance1.address + ' "' + tokenName1 + '" "' + tokenSymbol1 + '"');
console.log("npx hardhat verify --network " + network.name + " " + instance2.address + ' "' + tokenName2 + '" "' + tokenSymbol2 + '"');
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,37 @@
/*
Mock tokens for testnet purposes.
npx hardhat run scripts/temp/deployMockTokenDecimals.js --network arbitrumTestnet
*/
const contractName = "MockErc20TokenDecimals";
const tokenName = "Mock Token";
const tokenSymbol = "MTKN";
const tokenDecimals = 4;
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const contract = await ethers.getContractFactory(contractName);
const instance = await contract.deploy(tokenName, tokenSymbol, tokenDecimals);
console.log("Contract address:", instance.address);
console.log("Wait a minute and then run this command:");
console.log("npx hardhat verify --network " + network.name + " " + instance.address + ' "' + tokenName + '" "' + tokenSymbol + '" ' + tokenDecimals);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,56 @@
/*
This script is needed to verify contracts that are generated through contract factory.
How to use:
- First deploy the Factory contract
- Then in deployTld.js replace the owner and factory addresses with the ones you want
- Then deploy the DegenTLD contract: npx hardhat run scripts/temp/deployTld.js --network polygonMumbai
- Go to arguments.js file and enter correct addresses (and other data if changed in deployTld.js)
- Verify it (see command line for the Verify command). Something like: npx hardhat verify --network polygonMumbai --constructor-args scripts/arguments.js <deployed-contract-address>
- After successful verification, every TLD contract created through the factory will show contract code.
- The DegenTLD contract that you deployed using this script can be ignored (factory does not know about it). It
was only needed for the verification purposes.
*/
const contractName1 = "DegenTLD";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
// deploy contract1
const contract1 = await ethers.getContractFactory(contractName1);
const tldName = ".test";
const tldSymbol = "TEST";
const tldOwner = "<enter-owner-address>";
const tldPrice = ethers.utils.parseUnits("0.1", "ether");
const buyingEnabled = false;
const royalty = 0;
const factoryAddress = "<enter-factory-address>";
const instance1 = await contract1.deploy(
tldName, tldSymbol, tldOwner, tldPrice, buyingEnabled, royalty, factoryAddress
);
console.log("Contract address:", instance1.address);
console.log("Wait a minute and then run this command:");
console.log(
"npx hardhat verify --network " + network.name + " --constructor-args scripts/temp/arguments.js " + instance1.address
);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,77 @@
// V2 migration: a script which mints domains for existing holders
// npx hardhat run scripts/temp/mintDomains.js --network localhost
const oldTldAddress = "<old-tld-address>"; // <old-tld-address>
const newTldAddress = "<new-tld-address>"; // <new-tld-address>
//const maxFee = 0; // 2500000000 - set the correct fee for eip-1559 style transactions (otherwise make txs legacy type)
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Minting domains with the account:", deployer.address);
console.log("Account balance:", (await deployer.getBalance()).toString());
const tldInterface = new ethers.utils.Interface([
"function totalSupply() public view returns (uint256)",
"function price() public view returns (uint256)",
"function domainIdsNames(uint256) public view returns (string)",
"function getDomainHolder(string memory _domainName) public view returns(address)",
"function mint(string memory _domainName, address _domainHolder,address _referrer) external payable returns(uint256)"
]);
const tldContractOld = new ethers.Contract(oldTldAddress, tldInterface, deployer);
const tldContractNew = new ethers.Contract(newTldAddress, tldInterface, deployer);
const totalSupplyOld = await tldContractOld.totalSupply();
console.log("totalSupplyOld: " + totalSupplyOld.toNumber());
const totalSupplyNewBefore = await tldContractNew.totalSupply();
console.log("totalSupplyNewBefore: " + totalSupplyNewBefore.toNumber());
const price = await tldContractNew.price();
console.log("Domain price in wei: " + price);
for (let i = totalSupplyNewBefore.toNumber(); i < totalSupplyOld; i++) {
let domainName = await tldContractOld.domainIdsNames(i);
let domainHolder = await tldContractOld.getDomainHolder(domainName);
console.log(domainName + " --> " + domainHolder + " (OLD)");
// check if domain name already exists on new TLD...
let prevOwner = await tldContractNew.getDomainHolder(domainName);
console.log("Has the domain been already minted? " + prevOwner);
// ... if not, mint it
if (prevOwner == ethers.constants.AddressZero) {
await tldContractNew.mint(
domainName.toLowerCase(), domainHolder, ethers.constants.AddressZero,
{
//type: 2, // eip-1559
//maxFeePerGas: maxFee,
//maxPriorityFeePerGas: maxFee,
value: price // pay for the domain
}
);
console.log("New domain minted");
let domainHolderNew = await tldContractNew.getDomainHolder(domainName.toLowerCase());
console.log(domainName + " --> " + domainHolderNew + " (NEW)");
}
}
console.log("totalSupplyOld: " + totalSupplyOld.toNumber());
const totalSupplyNewAfter = await tldContractNew.totalSupply();
console.log("totalSupplyNewAfter: " + totalSupplyNewAfter.toNumber());
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

@ -0,0 +1,235 @@
// npx hardhat test test/factories/flexi/FlexiTLD.owner.test.js
const { expect } = require("chai");
describe("FlexiDegenTLD (onlyOwner)", function () {
let contract;
let factoryContract;
let signer;
let anotherUser;
let metadataContract1;
let metadataContract2;
const domainName = ".web3";
const domainSymbol = "WEB3";
const domainPrice = ethers.utils.parseUnits("1", "ether");
const domainRoyalty = 0; // royalty in bips
beforeEach(async function () {
[signer, anotherUser] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
const forbTldsContract = await DegenForbiddenTlds.deploy();
const FlexiDegenMetadata = await ethers.getContractFactory("FlexiDegenMetadata");
metadataContract1 = await FlexiDegenMetadata.deploy();
metadataContract2 = await FlexiDegenMetadata.deploy();
const DegenTLDFactory = await ethers.getContractFactory("FlexiDegenTLDFactory");
factoryContract = await DegenTLDFactory.deploy(domainPrice, forbTldsContract.address, metadataContract1.address);
await forbTldsContract.addFactoryAddress(factoryContract.address);
const DegenTLD = await ethers.getContractFactory("FlexiDegenTLD");
contract = await DegenTLD.deploy(
domainName,
domainSymbol,
signer.address, // TLD owner
domainPrice,
false, // buying enabled
domainRoyalty,
factoryContract.address,
metadataContract1.address
);
});
it("should create a new valid domain as owner even if buying is disabled", async function () {
// buying domains should be disabled
const buyingEnabled = await contract.buyingEnabled();
expect(buyingEnabled).to.be.false;
const newDomainName = "techie";
// mint a new valid domain as TLD owner
await expect(contract.mint(
newDomainName, // domain name (without TLD)
signer.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get domain name by token ID
const firstDomainName = await contract.domainIdsNames(1); // token ID 1
expect(firstDomainName).to.equal(newDomainName);
// get domain data by domain name
const firstDomainData = await contract.domains(newDomainName);
expect(firstDomainData.name).to.equal(newDomainName);
expect(firstDomainData.holder).to.equal(signer.address);
});
it("should fail to create a new valid domain if user is not TLD owner and buying is disabled", async function () {
// buying domains should be disabled
const buyingEnabled = await contract.buyingEnabled();
expect(buyingEnabled).to.be.false;
const newDomainName = "techie";
await expect(contract.connect(anotherUser).mint(
newDomainName, // domain name (without TLD)
anotherUser.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)).to.be.revertedWith('Buying domains disabled');
});
it("should fail to create a new valid domain if buying is disabled forever", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
// buying domains should be enabled
const buyingEnabled = await contract.buyingEnabled();
expect(buyingEnabled).to.be.true;
const newDomainName = "techie";
await contract.connect(anotherUser).mint(
newDomainName, // domain name (without TLD)
anotherUser.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)
// disable buying forever
await contract.disableBuyingForever();
// fail at minting new domains
await expect(contract.mint(
"test1domain", // domain name (without TLD)
anotherUser.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)).to.be.revertedWith('Domain minting disabled forever');
await expect(contract.connect(anotherUser).mint(
"test2domain", // domain name (without TLD)
anotherUser.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)).to.be.revertedWith('Domain minting disabled forever');
});
it("should change the price of a domain", async function () {
const priceBefore = await contract.price();
expect(priceBefore).to.equal(domainPrice);
const newPrice = ethers.utils.parseUnits("2", "ether");
await contract.changePrice(newPrice);
const priceAfter = await contract.price();
expect(priceAfter).to.equal(newPrice);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changePrice(domainPrice)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the referral fee", async function () {
const referralBefore = await contract.referral();
expect(referralBefore).to.equal(1000); // 10% by default
const newReferral = 500; // 500 bips or 5%
await contract.changeReferralFee(newReferral);
const referralAfter = await contract.referral();
expect(referralAfter).to.equal(newReferral);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeReferralFee(200)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should prevent setting referral fee to 50% or higher", async function () {
const referralBefore = await contract.referral();
expect(referralBefore).to.equal(1000); // 10% by default
// if referral fee is set to 50%, the tx should fail
await expect(contract.changeReferralFee(5000)).to.be.revertedWith('Referral fee cannot be 50% or higher');
// if referral fee is set to higher than 50%, the tx should fail
await expect(contract.changeReferralFee(8000)).to.be.revertedWith('Referral fee cannot be 50% or higher');
const referralAfter = await contract.referral();
expect(referralAfter).to.equal(1000); // should remain the same as before
});
it("should toggle buying domains", async function () {
const buyingEnabledBefore = await contract.buyingEnabled();
expect(buyingEnabledBefore).to.be.false;
await contract.toggleBuyingDomains(); // enable buying domains
const buyingEnabledAfter = await contract.buyingEnabled();
expect(buyingEnabledAfter).to.be.true;
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).toggleBuyingDomains()).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change max length for a domain name", async function () {
const nameMaxLengthBefore = await contract.nameMaxLength();
expect(nameMaxLengthBefore).to.equal(140);
const newMaxLength = 180;
await contract.changeNameMaxLength(newMaxLength);
const nameMaxLengthAfter = await contract.nameMaxLength();
expect(nameMaxLengthAfter).to.equal(newMaxLength);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeNameMaxLength(70)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the royalty amount", async function () {
const royaltyBefore = await contract.royalty();
expect(royaltyBefore).to.equal(0);
const newRoyalty = 10;
await contract.changeRoyalty(newRoyalty);
const royaltyAfter = await contract.royalty();
expect(royaltyAfter).to.equal(10);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeRoyalty(20)).to.be.revertedWith('Sender is not royalty fee updater');
});
it("should change metadata contract address and then freeze it", async function () {
const mtdAddrBefore = await contract.metadataAddress();
expect(mtdAddrBefore).to.equal(metadataContract1.address);
await contract.changeMetadataAddress(metadataContract2.address);
const mtdAddrAfter = await contract.metadataAddress();
expect(mtdAddrAfter).to.equal(metadataContract2.address);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeMetadataAddress(metadataContract1.address)).to.be.revertedWith('Ownable: caller is not the owner');
await contract.freezeMetadata();
await expect(contract.changeMetadataAddress(metadataContract1.address)).to.be.revertedWith('Cannot change metadata address anymore');
});
});

@ -0,0 +1,743 @@
// npx hardhat test test/factories/flexi/FlexiTLD.test.js
const { expect } = require("chai");
function calculateGasCosts(testName, receipt) {
console.log(testName + " gasUsed: " + receipt.gasUsed);
// coin prices in USD
const matic = 0.5;
const eth = 1000;
const gasCostMatic = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("35", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostEthereum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("21", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostArbitrum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("1.25", "gwei")) * Number(receipt.gasUsed)), "ether");
console.log(testName + " gas cost (Ethereum): $" + String(Number(gasCostEthereum)*eth));
console.log(testName + " gas cost (Arbitrum): $" + String(Number(gasCostArbitrum)*eth));
console.log(testName + " gas cost (Polygon): $" + String(Number(gasCostMatic)*matic));
}
describe("FlexiDegenTLD", function () {
let contract;
let factoryContract;
let metadataContract;
let signer;
let anotherUser;
let referrer;
const provider = waffle.provider;
const domainName = ".web3";
const domainSymbol = "WEB3";
const domainPrice = ethers.utils.parseUnits("1", "ether");
const domainRoyalty = 10; // royalty in bips (10 bips is 0.1%)
beforeEach(async function () {
[signer, anotherUser, referrer] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
const forbTldsContract = await DegenForbiddenTlds.deploy();
const FlexiDegenMetadata = await ethers.getContractFactory("FlexiDegenMetadata");
metadataContract = await FlexiDegenMetadata.deploy();
const DegenTLDFactory = await ethers.getContractFactory("FlexiDegenTLDFactory");
factoryContract = await DegenTLDFactory.deploy(domainPrice, forbTldsContract.address, metadataContract.address);
await forbTldsContract.addFactoryAddress(factoryContract.address);
const DegenTLD = await ethers.getContractFactory("FlexiDegenTLD");
contract = await DegenTLD.deploy(
domainName,
domainSymbol,
signer.address, // TLD owner
domainPrice,
false, // buying enabled
domainRoyalty,
factoryContract.address,
metadataContract.address
);
});
it("should confirm the correct TLD name", async function () {
const name = await contract.name();
expect(name).to.equal(domainName);
});
it("should create a new valid domain", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// get referrer's balance BEFORE
const balanceReferrerBefore = await provider.getBalance(referrer.address);
const totalSupplyBefore = await contract.totalSupply();
expect(totalSupplyBefore).to.equal(0);
const tx = await contract["mint(string,address,address)"]( // this approach is better for getting gasUsed value from receipt
newDomainName, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const receipt = await tx.wait();
calculateGasCosts("Mint", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DomainCreated");
const totalSupplyAfter = await contract.totalSupply();
expect(totalSupplyAfter).to.equal(1);
// get referrer's balance AFTER
const balanceReferrerAfter = await provider.getBalance(referrer.address);
expect(ethers.BigNumber.from(balanceReferrerAfter).sub(balanceReferrerBefore)).to.equal(ethers.BigNumber.from("100000000000000000"));
// get domain name by token ID
const firstDomainName = await contract.domainIdsNames(1);
expect(firstDomainName).to.equal(newDomainName);
// get domain data by domain name
const firstDomainData = await contract.domains(newDomainName);
expect(firstDomainData.name).to.equal(newDomainName);
expect(firstDomainData.holder).to.equal(signer.address);
expect(firstDomainData.tokenId).to.equal(1);
// mint another domain
await contract["mint(string,address,address)"](
"second", // domain name (without TLD)
referrer.address, // domain owner
ethers.constants.AddressZero, // no referrer in this case
{
value: domainPrice // pay for the domain
}
);
// check total supply of tokens
const totalSupplyAfterSecond = await contract.totalSupply();
expect(totalSupplyAfterSecond).to.equal(2);
// get domain data by domain name
const secondDomainData = await contract.domains("second");
expect(secondDomainData.name).to.equal("second");
expect(secondDomainData.holder).to.equal(referrer.address);
expect(secondDomainData.tokenId).to.equal(2);
// mint a 1-letter domain
await contract.connect(anotherUser).mint(
"a", // domain name (without TLD)
anotherUser.address, // domain owner
ethers.constants.AddressZero, // no referrer in this case
{
value: domainPrice // pay for the domain
}
);
// check total supply of tokens
const totalSupplyAfterA = await contract.totalSupply();
expect(totalSupplyAfterA).to.equal(3);
// get domain data by domain name
const aDomainData = await contract.domains("a");
expect(aDomainData.name).to.equal("a");
expect(aDomainData.holder).to.equal(anotherUser.address);
expect(aDomainData.tokenId).to.equal(3);
// fail at minting an empty domain
await expect(contract.mint( // this approach is better for getting gasUsed value from receipt
"", // empty domain name (without TLD)
anotherUser.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
)).to.be.revertedWith('Domain name empty');
});
it("should transfer domain to another user", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const newDomainName = "techie";
const tokenId = 1;
await expect(contract["mint(string,address,address)"](
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get owner
const domainOwnerBefore = await contract.ownerOf(tokenId);
expect(domainOwnerBefore).to.equal(signer.address);
// get domain data by domain name
const firstDomainDataBefore = await contract.domains(newDomainName);
expect(firstDomainDataBefore.name).to.equal(newDomainName);
expect(firstDomainDataBefore.holder).to.equal(signer.address);
// transfer domain from signer to another user
/*
await expect(contract.transferFrom(
signer.address, // from
anotherUser.address, // to
tokenId // token ID
)).to.emit(contract, "Transfer");
*/
const tx = await contract.transferFrom( // this approach is better for getting gasUsed value from receipt
signer.address, // from
anotherUser.address, // to
tokenId // token ID
);
const receipt = await tx.wait()
calculateGasCosts("Transfer", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("Transfer");
// get default name (after)
const defaultNameAfterSigner = await contract.defaultNames(signer.address);
expect(defaultNameAfterSigner).to.be.empty;
const defaultNameAfterAnother = await contract.defaultNames(anotherUser.address);
expect(defaultNameAfterAnother).to.equal(newDomainName);
// get owner
const domainOwnerAfter = await contract.ownerOf(tokenId);
expect(domainOwnerAfter).to.equal(anotherUser.address);
// get domain data by domain name
const firstDomainDataAfter = await contract.domains(newDomainName);
expect(firstDomainDataAfter.name).to.equal(newDomainName);
expect(firstDomainDataAfter.holder).to.equal(anotherUser.address);
});
it("should change default domain", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// mint domain
await expect(contract["mint(string,address,address)"](
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get default name (before)
const defaultNameBefore = await contract.defaultNames(signer.address);
expect(defaultNameBefore).to.equal(newDomainName);
const anotherDomainName = "tempe";
// mint domain
await expect(contract["mint(string,address,address)"](
anotherDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get default name (after 1)
const defaultNameAfter = await contract.defaultNames(signer.address);
expect(defaultNameAfter).to.equal(newDomainName); // default domain name should remain the first domain (techie)
// change default domain to tempe
await expect(contract.editDefaultDomain(anotherDomainName)).to.emit(contract, "DefaultDomainChanged");
// get default name (after change)
const defaultNameAfterChange = await contract.defaultNames(signer.address);
expect(defaultNameAfterChange).to.equal(anotherDomainName); // default domain name should change to tempe
// fail at changing default domain if msg.sender is not domain holder
await expect(contract.connect(anotherUser).editDefaultDomain(
newDomainName // trying to change back to techie (but msg.sender is not domain holder)
)).to.be.revertedWith('You do not own the selected domain');
});
it("should change domain data", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// mint domain
await expect(contract["mint(string,address,address)"](
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get domain data by domain name (before)
const firstDomainDataBefore = await contract.domains(newDomainName);
expect(firstDomainDataBefore.data).to.equal("");
const newData = "{'description': 'This is my NEW domain description'}";
// set new data
const tx = await contract.editData(
newDomainName, // domain name (without TLD)
newData
);
const receipt = await tx.wait();
calculateGasCosts("DataChanged", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DataChanged");
// get domain data by domain name (after)
const firstDomainDataAfter = await contract.domains(newDomainName);
expect(firstDomainDataAfter.data).to.equal(newData);
// fail at changing data if msg.sender is not domain holder
await expect(contract.connect(anotherUser).editData(
newDomainName, // domain name (without TLD)
"No change"
)).to.be.revertedWith('Only domain holder can edit their data');
});
it("should change metadata", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// mint domain
await expect(contract.mint(
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get domain token ID
const domainData = await contract.domains(newDomainName);
expect(domainData.tokenId).to.equal(1);
// get domain metadata
const domainMetadata = await contract.tokenURI(domainData.tokenId);
const mdJson = Buffer.from(domainMetadata.substring(29), "base64");
const mdResult = JSON.parse(mdJson);
expect(mdResult.name).to.equal(newDomainName+domainName);
expect(mdResult.description).to.equal("");
// change description in the metadata contract
const newDesc = "The best top-level domain";
await metadataContract.changeDescription(
contract.address,
newDesc
);
// get domain metadata
const domainMetadata2 = await contract.tokenURI(domainData.tokenId);
const mdJson2 = Buffer.from(domainMetadata2.substring(29), "base64");
const mdResult2 = JSON.parse(mdJson2);
expect(mdResult2.name).to.equal(newDomainName+domainName);
expect(mdResult2.description).to.equal(newDesc);
// fail at changing metadata description if sender is not TLD owner
await expect(metadataContract.connect(anotherUser).changeDescription(
contract.address,
newDesc
)).to.be.revertedWith('Sender not TLD owner');
});
it("should create a new valid domain, but with non-ascii letters input", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "poɯSnᴉǝ";
const tx = await contract["mint(string,address,address)"]( // this approach is better for getting gasUsed value from receipt
newDomainName, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const receipt = await tx.wait();
calculateGasCosts("Mint " + newDomainName, receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DomainCreated");
const totalSupplyAfter = await contract.totalSupply();
expect(totalSupplyAfter).to.equal(1);
const getDomainName = await contract.domainIdsNames(1);
console.log(getDomainName);
expect(getDomainName).to.equal(newDomainName.toLowerCase()); // should be lowercase
});
it("should mint a token and burn it and mint it again", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const totalSupplyBeforeMint = await contract.totalSupply();
expect(totalSupplyBeforeMint).to.equal(0);
const balanceBeforeMint = await contract.balanceOf(signer.address);
expect(balanceBeforeMint).to.equal(0);
const getDomainNameBeforeMint = await contract.domainIdsNames(1); // token ID 1
expect(getDomainNameBeforeMint).to.equal(""); // should be empty string
const price = await contract.price();
expect(price).to.equal(domainPrice);
// MINT DOMAIN
const newDomainName = "signer";
await contract["mint(string,address,address)"]( // this approach is better for getting gasUsed value from receipt
newDomainName, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const totalSupplyAfterMint = await contract.totalSupply();
expect(totalSupplyAfterMint).to.equal(1);
const balanceAfterMint = await contract.balanceOf(signer.address);
expect(balanceAfterMint).to.equal(1);
const getDomainDataAfterMint = await contract.domains(newDomainName);
expect(getDomainDataAfterMint.name).to.equal(newDomainName);
expect(getDomainDataAfterMint.tokenId).to.equal(1);
expect(getDomainDataAfterMint.holder).to.equal(signer.address);
expect(getDomainDataAfterMint.data).to.equal("");
const getDomainNameAfterMint = await contract.domainIdsNames(1);
expect(getDomainNameAfterMint).to.equal(newDomainName);
// BURN DOMAIN
const tx = await contract.burn(newDomainName);
const receipt = await tx.wait();
calculateGasCosts("Burn domain", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DomainBurned");
const totalSupplyAfterBurn = await contract.totalSupply();
expect(totalSupplyAfterBurn).to.equal(0);
const balanceAfterBurn = await contract.balanceOf(signer.address);
expect(balanceAfterBurn).to.equal(0);
const getDomainDataAfterBurn = await contract.domains(newDomainName);
expect(getDomainDataAfterBurn.holder).to.equal(ethers.constants.AddressZero);
expect(getDomainDataAfterBurn.name).to.equal("");
expect(getDomainDataAfterBurn.data).to.equal("");
expect(getDomainDataAfterBurn.tokenId).to.equal(0);
const getDomainNameAfterBurn = await contract.domainIdsNames(1);
expect(getDomainNameAfterBurn).to.equal(""); // should be empty
const getDefaultDomainNameAfterBurn = await contract.defaultNames(signer.address);
expect(getDefaultDomainNameAfterBurn).to.equal(""); // should be empty
// MINT AGAIN
await contract["mint(string,address,address)"]( // this approach is better for getting gasUsed value from receipt
newDomainName, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const totalSupplyAfterMintAgain = await contract.totalSupply();
expect(totalSupplyAfterMintAgain).to.equal(1);
const balanceAfterMintAgain = await contract.balanceOf(signer.address);
expect(balanceAfterMintAgain).to.equal(1);
const getDomainDataAfterMintAgain = await contract.domains(newDomainName);
expect(getDomainDataAfterMintAgain.name).to.equal(newDomainName);
expect(getDomainDataAfterMintAgain.tokenId).to.equal(2); // token ID is now 2, because burned IDs still count as used
expect(getDomainDataAfterMintAgain.holder).to.equal(signer.address);
expect(getDomainDataAfterMintAgain.data).to.equal("");
// token ID 1 still burned
const getDomainNameAfterMintAgain0 = await contract.domainIdsNames(1); // token ID 1 is burned and will not be used again
expect(getDomainNameAfterMintAgain0).to.equal("");
// new NFT has now ID 2
const getDomainNameAfterMintAgain1 = await contract.domainIdsNames(2); // new domain has ID 2
expect(getDomainNameAfterMintAgain1).to.equal(newDomainName);
});
it("should mint multiple tokens, burn one and mint it again", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const totalSupplyBeforeMint = await contract.totalSupply();
expect(totalSupplyBeforeMint).to.equal(0);
const idCounterBeforeMint = await contract.idCounter();
expect(idCounterBeforeMint).to.equal(1);
const balanceBeforeMint = await contract.balanceOf(signer.address);
expect(balanceBeforeMint).to.equal(0);
const getDomainNameBeforeMint = await contract.domainIdsNames(1);
expect(getDomainNameBeforeMint).to.equal(""); // should be empty string
const price = await contract.price();
expect(price).to.equal(domainPrice);
// MINT 3 DOMAINs
const newDomainName1 = "signer";
const newDomainName2 = "anotheruser";
const newDomainName3 = "referrer";
await contract.mint( // this approach is better for getting gasUsed value from receipt
newDomainName1, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
await contract.mint( // this approach is better for getting gasUsed value from receipt
newDomainName2, // domain name (without TLD)
anotherUser.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
await contract.mint( // this approach is better for getting gasUsed value from receipt
newDomainName3, // domain name (without TLD)
referrer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const totalSupplyAfterMint = await contract.totalSupply();
expect(totalSupplyAfterMint).to.equal(3);
const idCounterAfterMint = await contract.idCounter();
expect(idCounterAfterMint).to.equal(4); // 3 token IDs has been created. The next domain will have ID 4.
const balanceAfterMint = await contract.balanceOf(signer.address);
expect(balanceAfterMint).to.equal(1);
const balanceAfterMint2 = await contract.balanceOf(anotherUser.address);
expect(balanceAfterMint2).to.equal(1);
const balanceAfterMint3 = await contract.balanceOf(referrer.address);
expect(balanceAfterMint3).to.equal(1);
const getDefaultDomainAfterMint = await contract.defaultNames(anotherUser.address);
expect(getDefaultDomainAfterMint).to.equal(newDomainName2);
const getDomainDataAfterMint = await contract.domains(newDomainName1);
expect(getDomainDataAfterMint.name).to.equal(newDomainName1);
const getDomainDataAfterMint2 = await contract.domains(newDomainName2);
expect(getDomainDataAfterMint2.name).to.equal(newDomainName2);
expect(getDomainDataAfterMint2.tokenId).to.equal(2);
expect(getDomainDataAfterMint2.holder).to.equal(anotherUser.address);
expect(getDomainDataAfterMint2.data).to.equal("");
const getDomainNameAfterMint = await contract.domainIdsNames(2);
expect(getDomainNameAfterMint).to.equal(newDomainName2);
// fail at minting the existing domain before burning it
await expect(contract.mint( // this approach is better for getting gasUsed value from receipt
newDomainName2, // domain name (without TLD)
anotherUser.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
)).to.be.revertedWith('Domain with this name already exists');
// set domain data
const domainDataString = "{'url': 'https://ethereum.org'}";
await contract.connect(anotherUser).editData(
newDomainName2,
domainDataString
);
// check domain data before burn
const domainDataBeforeBurn = await contract.getDomainData(newDomainName2);
expect(domainDataBeforeBurn).to.equal(domainDataString);
// BURN DOMAIN
const tx = await contract.connect(anotherUser).burn(newDomainName2);
const receipt = await tx.wait();
calculateGasCosts("Burn second domain", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DomainBurned");
const totalSupplyAfterBurn = await contract.totalSupply();
expect(totalSupplyAfterBurn).to.equal(2);
const idCounterAfterBurn = await contract.idCounter();
expect(idCounterAfterBurn).to.equal(4);
// check domain data after burn
const domainDataAfterBurn = await contract.getDomainData(newDomainName2);
expect(domainDataAfterBurn).to.equal("");
const balanceAfterBurn = await contract.balanceOf(signer.address);
expect(balanceAfterBurn).to.equal(1);
const balanceAfterBurn1 = await contract.balanceOf(anotherUser.address);
expect(balanceAfterBurn1).to.equal(0);
const balanceAfterBurn2 = await contract.balanceOf(referrer.address);
expect(balanceAfterBurn2).to.equal(1);
const getDomainDataAfterBurn = await contract.domains(newDomainName1);
expect(getDomainDataAfterBurn.holder).to.equal(signer.address);
expect(getDomainDataAfterBurn.name).to.equal("signer");
expect(getDomainDataAfterBurn.data).to.equal("");
expect(getDomainDataAfterBurn.tokenId).to.equal(1);
const getDomainDataAfterBurn2 = await contract.domains(newDomainName2);
expect(getDomainDataAfterBurn2.holder).to.equal(ethers.constants.AddressZero);
expect(getDomainDataAfterBurn2.name).to.equal("");
expect(getDomainDataAfterBurn2.data).to.equal("");
expect(getDomainDataAfterBurn2.tokenId).to.equal(0);
const getDomainDataAfterBurn3 = await contract.domains(newDomainName3);
expect(getDomainDataAfterBurn3.holder).to.equal(referrer.address);
expect(getDomainDataAfterBurn3.name).to.equal("referrer");
expect(getDomainDataAfterBurn3.data).to.equal("");
expect(getDomainDataAfterBurn3.tokenId).to.equal(3);
const getDomainNameAfterBurn = await contract.domainIdsNames(1);
expect(getDomainNameAfterBurn).to.equal("signer");
const getDomainNameAfterBurn2 = await contract.domainIdsNames(2);
expect(getDomainNameAfterBurn2).to.equal(""); // should be empty
const getDomainNameAfterBurn3 = await contract.domainIdsNames(3);
expect(getDomainNameAfterBurn3).to.equal("referrer");
// MINT AGAIN
await contract.mint( // this approach is better for getting gasUsed value from receipt
newDomainName2, // domain name (without TLD)
anotherUser.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const totalSupplyAfterMintAgain = await contract.totalSupply();
expect(totalSupplyAfterMintAgain).to.equal(3);
const idCounterAfterMintAgain = await contract.idCounter();
expect(idCounterAfterMintAgain).to.equal(5);
const balanceAfterMintAgain = await contract.balanceOf(signer.address);
expect(balanceAfterMintAgain).to.equal(1);
const balanceAfterMintAgain2 = await contract.balanceOf(anotherUser.address);
expect(balanceAfterMintAgain2).to.equal(1);
const balanceAfterMintAgain3 = await contract.balanceOf(referrer.address);
expect(balanceAfterMintAgain3).to.equal(1);
const getDomainDataAfterMintAgain = await contract.domains(newDomainName2);
expect(getDomainDataAfterMintAgain.name).to.equal(newDomainName2);
expect(getDomainDataAfterMintAgain.tokenId).to.equal(4); // token ID is now 4, because burned IDs still count as used
expect(getDomainDataAfterMintAgain.holder).to.equal(anotherUser.address);
expect(getDomainDataAfterMintAgain.data).to.equal("");
// token ID 2 still burned
const getDomainNameAfterMintAgain1 = await contract.domainIdsNames(2);
expect(getDomainNameAfterMintAgain1).to.equal("");
// new NFT has now ID 4
const getDomainNameAfterMintAgain3 = await contract.domainIdsNames(4);
expect(getDomainNameAfterMintAgain3).to.equal(newDomainName2);
});
});

@ -0,0 +1,203 @@
const { expect } = require("chai");
describe("FlexiDegenTLDFactory (onlyOwner)", function () {
let contract;
let forbTldsContract;
let owner;
let nonOwner;
const tldPrice = ethers.utils.parseUnits("1", "ether");
beforeEach(async function () {
[owner, nonOwner] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
forbTldsContract = await DegenForbiddenTlds.deploy();
const FlexiDegenMetadata = await ethers.getContractFactory("FlexiDegenMetadata");
const metadataContract = await FlexiDegenMetadata.deploy();
const DegenTLDFactory = await ethers.getContractFactory("FlexiDegenTLDFactory");
contract = await DegenTLDFactory.deploy(tldPrice, forbTldsContract.address, metadataContract.address);
await forbTldsContract.addFactoryAddress(contract.address);
});
it("should create a new valid TLD through ownerCreateTld()", async function () {
await expect(contract.ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.emit(contract, "TldCreated");
});
it("should fail to create a new valid TLD if user is not owner", async function () {
await expect(contract.connect(nonOwner).ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
nonOwner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should fail to create a new valid TLD if more than 1 dot in the name", async function () {
await expect(contract.ownerCreateTld(
".web.3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if no dot in the name", async function () {
await expect(contract.ownerCreateTld(
"web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if name does not start with dot", async function () {
await expect(contract.ownerCreateTld(
"web.3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Name must start with dot');
});
it("should fail to create a new valid TLD if name is of length 1", async function () {
await expect(contract.ownerCreateTld(
".", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD with empty name", async function () {
await expect(contract.ownerCreateTld(
"", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD if TLD already exists", async function () {
// create a valid TLD
await expect(contract.ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.emit(contract, "TldCreated");
// try to create a TLD with the same name
await expect(contract.ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD already exists or forbidden');
});
it("should fail to create a new valid TLD if TLD name is too long", async function () {
// try to create a TLD with the same name
await expect(contract.ownerCreateTld(
".web3dfferopfmeomeriovneriovneriovndferfgergf", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD too long');
});
it("should change the TLD price", async function () {
const priceBefore = await contract.price();
expect(priceBefore).to.equal(tldPrice);
const newPrice = ethers.utils.parseUnits("2", "ether");
await contract.changePrice(newPrice);
const priceAfter = await contract.price();
expect(priceAfter).to.equal(newPrice);
// fail if sender is not owner
await expect(contract.connect(nonOwner).changePrice(
ethers.utils.parseUnits("2", "ether")
)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should add a new forbidden domain", async function () {
const tld = ".co";
const forbiddenTldBefore = await forbTldsContract.forbidden(tld);
expect(forbiddenTldBefore).to.be.false;
await forbTldsContract.ownerAddForbiddenTld(tld);
const forbiddenTldAfter = await forbTldsContract.forbidden(tld);
expect(forbiddenTldAfter).to.be.true;
// fail if sender is not owner
await expect(forbTldsContract.connect(nonOwner).ownerAddForbiddenTld(".io")).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should remove a forbidden domain", async function () {
const tld = ".eth";
const forbiddenTldBefore = await forbTldsContract.forbidden(tld);
expect(forbiddenTldBefore).to.be.true;
await forbTldsContract.removeForbiddenTld(tld);
const forbiddenTldAfter = await forbTldsContract.forbidden(tld);
expect(forbiddenTldAfter).to.be.false;
// fail if sender is not owner
await expect(forbTldsContract.connect(nonOwner).removeForbiddenTld(".net")).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change max length for a TLD name", async function () {
const nameMaxLengthBefore = await contract.nameMaxLength();
expect(nameMaxLengthBefore).to.equal(40);
await contract.changeNameMaxLength(52);
const nameMaxLengthAfter = await contract.nameMaxLength();
expect(nameMaxLengthAfter).to.equal(52);
// fail if sender is not owner
await expect(contract.connect(nonOwner).changeNameMaxLength(60)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the royalty amount", async function () {
const royaltyBefore = await contract.royalty();
expect(royaltyBefore).to.equal(0);
const newRoyalty = 10;
await contract.changeRoyalty(newRoyalty);
const royaltyAfter = await contract.royalty();
expect(royaltyAfter).to.equal(10);
// if user is not owner, the tx should revert
await expect(contract.connect(nonOwner).changeRoyalty(20)).to.be.revertedWith('Ownable: caller is not the owner');
});
});

@ -0,0 +1,274 @@
const { expect } = require("chai");
const { ethers, waffle} = require("hardhat");
describe("FlexiDegenTLDFactory", function () {
let contract;
let forbTldsContract;
let signer;
let anotherUser;
const provider = waffle.provider;
const tldPrice = ethers.utils.parseUnits("1", "ether");
beforeEach(async function () {
[signer, anotherUser] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
forbTldsContract = await DegenForbiddenTlds.deploy();
const FlexiDegenMetadata = await ethers.getContractFactory("FlexiDegenMetadata");
const metadataContract = await FlexiDegenMetadata.deploy();
const DegenTLDFactory = await ethers.getContractFactory("FlexiDegenTLDFactory");
contract = await DegenTLDFactory.deploy(tldPrice, forbTldsContract.address, metadataContract.address);
await forbTldsContract.addFactoryAddress(contract.address);
});
it("should confirm forbidden TLD names defined in the constructor", async function () {
const forbiddenCom = await forbTldsContract.forbidden(".com");
expect(forbiddenCom).to.be.true;
const forbiddenEth = await forbTldsContract.forbidden(".eth");
expect(forbiddenEth).to.be.true;
});
it("should create a new valid TLD", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// get user&signer balances BEFORE
const balanceSignerBefore = await provider.getBalance(signer.address); // signer is the factory owner
const balanceUserBefore = await provider.getBalance(anotherUser.address);
await expect(contract.connect(anotherUser).createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.emit(contract, "TldCreated");
// get another user's balance AFTER (should be smaller by 1 ETH + gas)
const balanceUserAfter = await provider.getBalance(anotherUser.address);
const balUsrBef = Number(ethers.utils.formatEther(balanceUserBefore))
const balUsrAft = Number(ethers.utils.formatEther(balanceUserAfter))
expect(balUsrBef-balUsrAft).to.be.greaterThan(1); // diff: 1 ETH + gas
// get signer's balance after (should be bigger by exactly 1 ETH)
const balanceSignerAfter = await provider.getBalance(signer.address);
const balSigBef = Number(ethers.utils.formatEther(balanceSignerBefore))
const balSigAft = Number(ethers.utils.formatEther(balanceSignerAfter))
expect(balSigAft-balSigBef).to.equal(1); // diff: 1 ETH exactly
// get TLD from array by index
const firstTld = await contract.tlds(0);
expect(firstTld).to.equal(".web3");
// get TLD address by name
const firstTldAddress = await contract.tldNamesAddresses(".web3");
expect(firstTldAddress.startsWith("0x")).to.be.true;
});
it("should fail to create a new valid TLD if Buying TLDs disabled", async function () {
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Buying TLDs disabled');
});
it("should fail to create a new valid TLD if payment is too low", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: ethers.utils.parseUnits("0.9", "ether") // pay 0.9 ETH for the TLD - TOO LOW!
}
)).to.be.revertedWith('Value below price');
});
it("should fail to create a new valid TLD if more than 1 dot in the name", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".web.3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if no dot in the name", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
"web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if name does not start with dot", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
"web.3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Name must start with dot');
});
it("should fail to create a new valid TLD if name is of length 1", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD with empty name", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
"", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD if TLD already exists", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// create a valid TLD
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.emit(contract, "TldCreated");
// try to create a TLD with the same name
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD already exists or forbidden');
});
it("should fail to create a new valid TLD if TLD name is too long", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// try to create a TLD with the same name
await expect(contract.createTld(
".web3dfferopfmeomeriovneriovneriovndferfgergf", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD too long');
});
it("should fail to create a new valid TLD if TLD name is forbidden", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// try to create a TLD that's on the forbidden list
await expect(contract.createTld(
".com", // TLD
"COM", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD already exists or forbidden');
});
});

@ -0,0 +1,185 @@
const { expect } = require("chai");
describe("DegenTLD (onlyOwner)", function () {
let contract;
let factoryContract;
let signer;
let anotherUser;
const domainName = ".web3";
const domainSymbol = "WEB3";
const domainPrice = ethers.utils.parseUnits("1", "ether");
const domainRoyalty = 0; // royalty in bips
beforeEach(async function () {
[signer, anotherUser] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
const forbTldsContract = await DegenForbiddenTlds.deploy();
const DegenTLDFactory = await ethers.getContractFactory("DegenTLDFactory");
factoryContract = await DegenTLDFactory.deploy(domainPrice, forbTldsContract.address);
await forbTldsContract.addFactoryAddress(factoryContract.address);
const DegenTLD = await ethers.getContractFactory("DegenTLD");
contract = await DegenTLD.deploy(
domainName,
domainSymbol,
signer.address, // TLD owner
domainPrice,
false, // buying enabled
domainRoyalty,
factoryContract.address
);
});
it("should create a new valid domain even if buying is disabled", async function () {
// buying domains should be disabled
const buyingEnabled = await contract.buyingEnabled();
expect(buyingEnabled).to.be.false;
const newDomainName = "techie";
// mint a new valid domain as TLD owner
await expect(contract.mint(
newDomainName, // domain name (without TLD)
signer.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get domain name by token ID
const firstDomainName = await contract.domainIdsNames(0);
expect(firstDomainName).to.equal(newDomainName);
// get domain data by domain name
const firstDomainData = await contract.domains(newDomainName);
expect(firstDomainData.name).to.equal(newDomainName);
expect(firstDomainData.holder).to.equal(signer.address);
});
it("should fail to create a new valid domain if user is not TLD owner and buying is disabled", async function () {
// buying domains should be disabled
const buyingEnabled = await contract.buyingEnabled();
expect(buyingEnabled).to.be.false;
const newDomainName = "techie";
// mint a new valid domain as TLD owner
await expect(contract.connect(anotherUser).mint(
newDomainName, // domain name (without TLD)
anotherUser.address, // domain holder
ethers.constants.AddressZero, // referrer
{
value: domainPrice // pay for the domain
}
)).to.be.revertedWith('Buying TLDs disabled');
});
it("should change the price of a domain", async function () {
const priceBefore = await contract.price();
expect(priceBefore).to.equal(domainPrice);
const newPrice = ethers.utils.parseUnits("2", "ether");
await contract.changePrice(newPrice);
const priceAfter = await contract.price();
expect(priceAfter).to.equal(newPrice);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changePrice(domainPrice)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the referral fee", async function () {
const referralBefore = await contract.referral();
expect(referralBefore).to.equal(1000); // 10% by default
const newReferral = 500; // 500 bips or 5%
await contract.changeReferralFee(newReferral);
const referralAfter = await contract.referral();
expect(referralAfter).to.equal(newReferral);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeReferralFee(200)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should prevent setting referral fee to 50% or higher", async function () {
const referralBefore = await contract.referral();
expect(referralBefore).to.equal(1000); // 10% by default
// if referral fee is set to 50%, the tx should fail
await expect(contract.changeReferralFee(5000)).to.be.revertedWith('Referral fee cannot be 50% or higher');
// if referral fee is set to higher than 50%, the tx should fail
await expect(contract.changeReferralFee(8000)).to.be.revertedWith('Referral fee cannot be 50% or higher');
const referralAfter = await contract.referral();
expect(referralAfter).to.equal(1000); // should remain the same as before
});
it("should toggle buying domains", async function () {
const buyingEnabledBefore = await contract.buyingEnabled();
expect(buyingEnabledBefore).to.be.false;
await contract.toggleBuyingDomains(); // enable buying domains
const buyingEnabledAfter = await contract.buyingEnabled();
expect(buyingEnabledAfter).to.be.true;
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).toggleBuyingDomains()).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change max length for a domain name", async function () {
const nameMaxLengthBefore = await contract.nameMaxLength();
expect(nameMaxLengthBefore).to.equal(140);
const newMaxLength = 180;
await contract.changeNameMaxLength(newMaxLength);
const nameMaxLengthAfter = await contract.nameMaxLength();
expect(nameMaxLengthAfter).to.equal(newMaxLength);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeNameMaxLength(70)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the NFT metadata description", async function () {
const descBefore = await contract.description();
expect(descBefore).to.equal("Degen Domain Service. Visit https://degendomains.io/");
const newDesc = "New description";
await contract.changeDescription(newDesc);
const descAfter = await contract.description();
expect(descAfter).to.equal(newDesc);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeDescription(20)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the royalty amount", async function () {
const royaltyBefore = await contract.royalty();
expect(royaltyBefore).to.equal(0);
const newRoyalty = 10;
await contract.changeRoyalty(newRoyalty);
const royaltyAfter = await contract.royalty();
expect(royaltyAfter).to.equal(10);
// if user is not owner, the tx should revert
await expect(contract.connect(anotherUser).changeRoyalty(20)).to.be.revertedWith('Sender not factory owner');
});
});

@ -0,0 +1,341 @@
const { expect } = require("chai");
function calculateGasCosts(testName, receipt) {
console.log(testName + " gasUsed: " + receipt.gasUsed);
// coin prices in USD
const matic = 2;
const eth = 3000;
const gasCostMatic = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("35", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostEthereum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("100", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostArbitrum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("1.25", "gwei")) * Number(receipt.gasUsed)), "ether");
console.log(testName + " gas cost (Ethereum): $" + String(Number(gasCostEthereum)*eth));
console.log(testName + " gas cost (Arbitrum): $" + String(Number(gasCostArbitrum)*eth));
console.log(testName + " gas cost (Polygon): $" + String(Number(gasCostMatic)*matic));
}
describe("DegenTLD", function () {
let contract;
let factoryContract;
let signer;
let anotherUser;
let referrer;
const provider = waffle.provider;
const domainName = ".web3";
const domainSymbol = "WEB3";
const domainPrice = ethers.utils.parseUnits("1", "ether");
const domainRoyalty = 10; // royalty in bips (10 bips is 0.1%)
beforeEach(async function () {
[signer, anotherUser, referrer] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
const forbTldsContract = await DegenForbiddenTlds.deploy();
const DegenTLDFactory = await ethers.getContractFactory("DegenTLDFactory");
factoryContract = await DegenTLDFactory.deploy(domainPrice, forbTldsContract.address);
await forbTldsContract.addFactoryAddress(factoryContract.address);
const DegenTLD = await ethers.getContractFactory("DegenTLD");
contract = await DegenTLD.deploy(
domainName,
domainSymbol,
signer.address, // TLD owner
domainPrice,
false, // buying enabled
domainRoyalty,
factoryContract.address
);
});
it("should confirm the correct TLD name", async function () {
const name = await contract.name();
expect(name).to.equal(domainName);
});
it("should create a new valid domain", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// get referrer's balance BEFORE
const balanceReferrerBefore = await provider.getBalance(referrer.address);
const totalSupplyBefore = await contract.totalSupply();
expect(totalSupplyBefore).to.equal(0);
const tx = await contract["mint(string,address,address)"]( // this approach is better for getting gasUsed value from receipt
newDomainName, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const receipt = await tx.wait();
calculateGasCosts("Mint", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DomainCreated");
const totalSupplyAfter = await contract.totalSupply();
expect(totalSupplyAfter).to.equal(1);
// get referrer's balance AFTER
const balanceReferrerAfter = await provider.getBalance(referrer.address);
expect(ethers.BigNumber.from(balanceReferrerAfter).sub(balanceReferrerBefore)).to.equal(ethers.BigNumber.from("100000000000000000"));
// get domain name by token ID
const firstDomainName = await contract.domainIdsNames(0);
expect(firstDomainName).to.equal(newDomainName);
// get domain data by domain name
const firstDomainData = await contract.domains(newDomainName);
expect(firstDomainData.name).to.equal(newDomainName);
expect(firstDomainData.holder).to.equal(signer.address);
expect(firstDomainData.tokenId).to.equal(0);
// mint another domain
await contract["mint(string,address,address)"](
"second", // domain name (without TLD)
referrer.address, // domain owner
ethers.constants.AddressZero, // no referrer in this case
{
value: domainPrice // pay for the domain
}
);
// check total supply of tokens
const totalSupplyAfterSecond = await contract.totalSupply();
expect(totalSupplyAfterSecond).to.equal(2);
// get domain data by domain name
const secondDomainData = await contract.domains("second");
expect(secondDomainData.name).to.equal("second");
expect(secondDomainData.holder).to.equal(referrer.address);
expect(secondDomainData.tokenId).to.equal(1);
});
it("should transfer domain to another user", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const newDomainName = "techie";
const tokenId = 0;
await expect(contract["mint(string,address,address)"](
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get owner
const domainOwnerBefore = await contract.ownerOf(tokenId);
expect(domainOwnerBefore).to.equal(signer.address);
// get domain data by domain name
const firstDomainDataBefore = await contract.domains(newDomainName);
expect(firstDomainDataBefore.name).to.equal(newDomainName);
expect(firstDomainDataBefore.holder).to.equal(signer.address);
// transfer domain from signer to another user
/*
await expect(contract.transferFrom(
signer.address, // from
anotherUser.address, // to
tokenId // token ID
)).to.emit(contract, "Transfer");
*/
const tx = await contract.transferFrom( // this approach is better for getting gasUsed value from receipt
signer.address, // from
anotherUser.address, // to
tokenId // token ID
);
const receipt = await tx.wait()
calculateGasCosts("Transfer", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("Transfer");
// get default name (after)
const defaultNameAfterSigner = await contract.defaultNames(signer.address);
expect(defaultNameAfterSigner).to.be.empty;
const defaultNameAfterAnother = await contract.defaultNames(anotherUser.address);
expect(defaultNameAfterAnother).to.equal(newDomainName);
// get owner
const domainOwnerAfter = await contract.ownerOf(tokenId);
expect(domainOwnerAfter).to.equal(anotherUser.address);
// get domain data by domain name
const firstDomainDataAfter = await contract.domains(newDomainName);
expect(firstDomainDataAfter.name).to.equal(newDomainName);
expect(firstDomainDataAfter.holder).to.equal(anotherUser.address);
});
it("should change default domain", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// mint domain
await expect(contract["mint(string,address,address)"](
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get default name (before)
const defaultNameBefore = await contract.defaultNames(signer.address);
expect(defaultNameBefore).to.equal(newDomainName);
const anotherDomainName = "tempe";
// mint domain
await expect(contract["mint(string,address,address)"](
anotherDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get default name (after 1)
const defaultNameAfter = await contract.defaultNames(signer.address);
expect(defaultNameAfter).to.equal(newDomainName); // default domain name should remain the first domain (techie)
// change default domain to tempe
await expect(contract.editDefaultDomain(anotherDomainName)).to.emit(contract, "DefaultDomainChanged");
// get default name (after change)
const defaultNameAfterChange = await contract.defaultNames(signer.address);
expect(defaultNameAfterChange).to.equal(anotherDomainName); // default domain name should change to tempe
// fail at changing default domain if msg.sender is not domain holder
await expect(contract.connect(anotherUser).editDefaultDomain(
newDomainName // trying to change back to techie (but msg.sender is not domain holder)
)).to.be.revertedWith('You do not own the selected domain');
});
it("should change domain data", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "techie";
// mint domain
await expect(contract["mint(string,address,address)"](
newDomainName, // domain name (without TLD)
signer.address, // domain owner
ethers.constants.AddressZero,
{
value: domainPrice // pay for the domain
}
)).to.emit(contract, "DomainCreated");
// get domain data by domain name (before)
const firstDomainDataBefore = await contract.domains(newDomainName);
expect(firstDomainDataBefore.data).to.equal("");
const newData = "{'description': 'This is my NEW domain description'}";
// set new data
const tx = await contract.editData(
newDomainName, // domain name (without TLD)
newData
);
const receipt = await tx.wait();
calculateGasCosts("DataChanged", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DataChanged");
// get domain data by domain name (after)
const firstDomainDataAfter = await contract.domains(newDomainName);
expect(firstDomainDataAfter.data).to.equal(newData);
// fail at changing data if msg.sender is not domain holder
await expect(contract.connect(anotherUser).editData(
newDomainName, // domain name (without TLD)
"No change"
)).to.be.revertedWith('Only domain holder can edit their data');
});
it("should create a new valid domain, but with uppercase and non-ascii letters input", async function () {
await contract.toggleBuyingDomains(); // enable buying domains
const price = await contract.price();
expect(price).to.equal(domainPrice);
const newDomainName = "poɯSnᴉǝ";
const tx = await contract["mint(string,address,address)"]( // this approach is better for getting gasUsed value from receipt
newDomainName, // domain name (without TLD)
signer.address, // domain owner
referrer.address, // referrer is set, so 0.1 ETH referral fee will go to referrers address
{
value: domainPrice // pay for the domain
}
);
const receipt = await tx.wait();
calculateGasCosts("Mint " + newDomainName, receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("DomainCreated");
const totalSupplyAfter = await contract.totalSupply();
expect(totalSupplyAfter).to.equal(1);
const getDomainName = await contract.domainIdsNames(0);
console.log(getDomainName);
//expect(getDomainName).to.equal(newDomainName.toLowerCase()); // should be lowercase
});
});

@ -0,0 +1,200 @@
const { expect } = require("chai");
describe("DegenTLDFactory (onlyOwner)", function () {
let contract;
let forbTldsContract;
let owner;
let nonOwner;
const tldPrice = ethers.utils.parseUnits("1", "ether");
beforeEach(async function () {
[owner, nonOwner] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
forbTldsContract = await DegenForbiddenTlds.deploy();
const DegenTLDFactory = await ethers.getContractFactory("DegenTLDFactory");
contract = await DegenTLDFactory.deploy(tldPrice, forbTldsContract.address);
await forbTldsContract.addFactoryAddress(contract.address);
});
it("should create a new valid TLD through ownerCreateTld()", async function () {
await expect(contract.ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.emit(contract, "TldCreated");
});
it("should fail to create a new valid TLD if user is not owner", async function () {
await expect(contract.connect(nonOwner).ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
nonOwner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should fail to create a new valid TLD if more than 1 dot in the name", async function () {
await expect(contract.ownerCreateTld(
".web.3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if no dot in the name", async function () {
await expect(contract.ownerCreateTld(
"web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if name does not start with dot", async function () {
await expect(contract.ownerCreateTld(
"web.3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('Name must start with dot');
});
it("should fail to create a new valid TLD if name is of length 1", async function () {
await expect(contract.ownerCreateTld(
".", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD with empty name", async function () {
await expect(contract.ownerCreateTld(
"", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD if TLD already exists", async function () {
// create a valid TLD
await expect(contract.ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.emit(contract, "TldCreated");
// try to create a TLD with the same name
await expect(contract.ownerCreateTld(
".web3", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD already exists or forbidden');
});
it("should fail to create a new valid TLD if TLD name is too long", async function () {
// try to create a TLD with the same name
await expect(contract.ownerCreateTld(
".web3dfferopfmeomeriovneriovneriovndferfgergf", // TLD
"WEB3", // symbol
owner.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false // buying enabled
)).to.be.revertedWith('TLD too long');
});
it("should change the TLD price", async function () {
const priceBefore = await contract.price();
expect(priceBefore).to.equal(tldPrice);
const newPrice = ethers.utils.parseUnits("2", "ether");
await contract.changePrice(newPrice);
const priceAfter = await contract.price();
expect(priceAfter).to.equal(newPrice);
// fail if sender is not owner
await expect(contract.connect(nonOwner).changePrice(
ethers.utils.parseUnits("2", "ether")
)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should add a new forbidden domain", async function () {
const tld = ".co";
const forbiddenTldBefore = await forbTldsContract.forbidden(tld);
expect(forbiddenTldBefore).to.be.false;
await forbTldsContract.ownerAddForbiddenTld(tld);
const forbiddenTldAfter = await forbTldsContract.forbidden(tld);
expect(forbiddenTldAfter).to.be.true;
// fail if sender is not owner
await expect(forbTldsContract.connect(nonOwner).ownerAddForbiddenTld(".io")).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should remove a forbidden domain", async function () {
const tld = ".eth";
const forbiddenTldBefore = await forbTldsContract.forbidden(tld);
expect(forbiddenTldBefore).to.be.true;
await forbTldsContract.removeForbiddenTld(tld);
const forbiddenTldAfter = await forbTldsContract.forbidden(tld);
expect(forbiddenTldAfter).to.be.false;
// fail if sender is not owner
await expect(forbTldsContract.connect(nonOwner).removeForbiddenTld(".net")).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change max length for a TLD name", async function () {
const nameMaxLengthBefore = await contract.nameMaxLength();
expect(nameMaxLengthBefore).to.equal(40);
await contract.changeNameMaxLength(52);
const nameMaxLengthAfter = await contract.nameMaxLength();
expect(nameMaxLengthAfter).to.equal(52);
// fail if sender is not owner
await expect(contract.connect(nonOwner).changeNameMaxLength(60)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change the royalty amount", async function () {
const royaltyBefore = await contract.royalty();
expect(royaltyBefore).to.equal(0);
const newRoyalty = 10;
await contract.changeRoyalty(newRoyalty);
const royaltyAfter = await contract.royalty();
expect(royaltyAfter).to.equal(10);
// if user is not owner, the tx should revert
await expect(contract.connect(nonOwner).changeRoyalty(20)).to.be.revertedWith('Ownable: caller is not the owner');
});
});

@ -0,0 +1,271 @@
const { expect } = require("chai");
const { ethers, waffle} = require("hardhat");
describe("DegenTLDFactory", function () {
let contract;
let forbTldsContract;
let signer;
let anotherUser;
const provider = waffle.provider;
const tldPrice = ethers.utils.parseUnits("1", "ether");
beforeEach(async function () {
[signer, anotherUser] = await ethers.getSigners();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
forbTldsContract = await DegenForbiddenTlds.deploy();
const DegenTLDFactory = await ethers.getContractFactory("DegenTLDFactory");
contract = await DegenTLDFactory.deploy(tldPrice, forbTldsContract.address);
await forbTldsContract.addFactoryAddress(contract.address);
});
it("should confirm forbidden TLD names defined in the constructor", async function () {
const forbiddenCom = await forbTldsContract.forbidden(".com");
expect(forbiddenCom).to.be.true;
const forbiddenEth = await forbTldsContract.forbidden(".eth");
expect(forbiddenEth).to.be.true;
});
it("should create a new valid TLD", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// get user&signer balances BEFORE
const balanceSignerBefore = await provider.getBalance(signer.address); // signer is the factory owner
const balanceUserBefore = await provider.getBalance(anotherUser.address);
await expect(contract.connect(anotherUser).createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.emit(contract, "TldCreated");
// get another user's balance AFTER (should be smaller by 1 ETH + gas)
const balanceUserAfter = await provider.getBalance(anotherUser.address);
const balUsrBef = Number(ethers.utils.formatEther(balanceUserBefore))
const balUsrAft = Number(ethers.utils.formatEther(balanceUserAfter))
expect(balUsrBef-balUsrAft).to.be.greaterThan(1); // diff: 1 ETH + gas
// get signer's balance after (should be bigger by exactly 1 ETH)
const balanceSignerAfter = await provider.getBalance(signer.address);
const balSigBef = Number(ethers.utils.formatEther(balanceSignerBefore))
const balSigAft = Number(ethers.utils.formatEther(balanceSignerAfter))
expect(balSigAft-balSigBef).to.equal(1); // diff: 1 ETH exactly
// get TLD from array by index
const firstTld = await contract.tlds(0);
expect(firstTld).to.equal(".web3");
// get TLD address by name
const firstTldAddress = await contract.tldNamesAddresses(".web3");
expect(firstTldAddress.startsWith("0x")).to.be.true;
});
it("should fail to create a new valid TLD if Buying TLDs disabled", async function () {
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Buying TLDs disabled');
});
it("should fail to create a new valid TLD if payment is too low", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: ethers.utils.parseUnits("0.9", "ether") // pay 0.9 ETH for the TLD - TOO LOW!
}
)).to.be.revertedWith('Value below price');
});
it("should fail to create a new valid TLD if more than 1 dot in the name", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".web.3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if no dot in the name", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
"web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Name must have 1 dot');
});
it("should fail to create a new valid TLD if name does not start with dot", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
"web.3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('Name must start with dot');
});
it("should fail to create a new valid TLD if name is of length 1", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
".", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD with empty name", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
await expect(contract.createTld(
"", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD too short');
});
it("should fail to create a new valid TLD if TLD already exists", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// create a valid TLD
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.emit(contract, "TldCreated");
// try to create a TLD with the same name
await expect(contract.createTld(
".web3", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD already exists or forbidden');
});
it("should fail to create a new valid TLD if TLD name is too long", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// try to create a TLD with the same name
await expect(contract.createTld(
".web3dfferopfmeomeriovneriovneriovndferfgergf", // TLD
"WEB3", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD too long');
});
it("should fail to create a new valid TLD if TLD name is forbidden", async function () {
await contract.toggleBuyingTlds(); // enable buying TLDs
const price = await contract.price();
expect(price).to.equal(tldPrice);
// try to create a TLD that's on the forbidden list
await expect(contract.createTld(
".com", // TLD
"COM", // symbol
signer.address, // TLD owner
ethers.utils.parseUnits("0.2", "ether"), // domain price
false, // buying enabled
{
value: tldPrice // pay 1 ETH for the TLD
}
)).to.be.revertedWith('TLD already exists or forbidden');
});
});

@ -0,0 +1,469 @@
// Run tests:
// npx hardhat test test/nft/angel/angel.test.js
const { expect } = require("chai");
function calculateGasCosts(testName, receipt) {
console.log(testName + " gasUsed: " + receipt.gasUsed);
// coin prices in USD
const eth = 1000;
const gasCostEthereum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("20", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostArbitrum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("1.25", "gwei")) * Number(receipt.gasUsed)), "ether");
console.log(testName + " gas cost (Ethereum): $" + String(Number(gasCostEthereum)*eth));
console.log(testName + " gas cost (Arbitrum): $" + String(Number(gasCostArbitrum)*eth));
}
describe("Degen Anon minting contract", function () {
let tldContract;
const tldName = ".anon";
const tldSymbol = ".ANON";
const tldPrice = 0;
const tldRoyalty = 0;
const tldReferral = 0;
let paymentTokenContract;
const paymentTokenDecimals = 6;
const paymentTokenName = "USDC";
const paymentTokenSymbol = "USDC";
let mintContract;
const maxTotalPayments = ethers.utils.parseUnits("100000", paymentTokenDecimals); // $100k
const price1char = ethers.utils.parseUnits("10000", paymentTokenDecimals); // $10k
const price2char = ethers.utils.parseUnits("3000", paymentTokenDecimals);
const price3char = ethers.utils.parseUnits("999", paymentTokenDecimals);
const price4char = ethers.utils.parseUnits("199", paymentTokenDecimals);
const price5char = ethers.utils.parseUnits("69", paymentTokenDecimals);
let metadataContract;
let signer;
let user1;
let user2;
beforeEach(async function () {
[signer, user1, user2] = await ethers.getSigners();
//----
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
const forbTldsContract = await DegenForbiddenTlds.deploy();
const FlexiDegenMetadata = await ethers.getContractFactory("FlexiDegenMetadata");
const flexiMetadataContract = await FlexiDegenMetadata.deploy();
const DegenTLDFactory = await ethers.getContractFactory("FlexiDegenTLDFactory");
const priceToCreateTld = ethers.utils.parseUnits("100", "ether");
const factoryContract = await DegenTLDFactory.deploy(priceToCreateTld, forbTldsContract.address, flexiMetadataContract.address);
await forbTldsContract.addFactoryAddress(factoryContract.address);
const DegenTLD = await ethers.getContractFactory("FlexiDegenTLD");
tldContract = await DegenTLD.deploy(
tldName,
tldSymbol,
signer.address, // TLD owner
tldPrice,
false, // buying enabled
tldRoyalty,
factoryContract.address,
flexiMetadataContract.address
);
// Create mock payment token
const Erc20ContractDecimals = await ethers.getContractFactory("MockErc20TokenDecimals");
paymentTokenContract = await Erc20ContractDecimals.deploy(paymentTokenName, paymentTokenSymbol, paymentTokenDecimals);
// transfer all signer's tokens to user1
paymentTokenContract.transfer(user1.address, ethers.utils.parseUnits("1000", paymentTokenDecimals));
// deploy Degen Anons metadata contract
const DegenAnonMetadata = await ethers.getContractFactory("DegenAnonMetadata");
metadataContract = await DegenAnonMetadata.deploy();
// add it to the TLD contract
await tldContract.changeMetadataAddress(metadataContract.address);
// Minter contract
const minterCode = await ethers.getContractFactory("DegenAnonMinter");
mintContract = await minterCode.deploy(
paymentTokenContract.address, // payment token address
tldContract.address, // TLD address
metadataContract.address, // metadata contract
maxTotalPayments,
price1char, price2char, price3char, price4char, price5char
);
// set minter contract as TLD minter address
await tldContract.changeMinter(mintContract.address);
// set minter contract in the metadata contract
await metadataContract.changeMinter(mintContract.address);
});
it("should confirm TLD name & symbol", async function () {
const _tldName = await tldContract.name();
expect(_tldName).to.equal(tldName);
const _tldSymbol = await tldContract.symbol();
expect(_tldSymbol).to.equal(tldSymbol);
});
it("should mint two 5+ char domains", async function () {
const featureIds = ["3A1174741911F257FFCA965A000000231", "3A1174741911F257FFCA965A000000121", "3A1174741911F257FFCA965A000000020"];
await mintContract.togglePaused();
// user1 has 1000 payment tokens
// should fail at minting before allowance is set
await expect(mintContract.connect(user1).mint(
"1234", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
featureIds
)).to.be.reverted;
// Give payment token allowance
await paymentTokenContract.connect(user1).approve(
mintContract.address, // spender
price5char // amount
);
// how many domains user1 has before minting
const balanceDomainBefore = await tldContract.balanceOf(user1.address);
expect(balanceDomainBefore).to.equal(0);
// TLD contract owner's balance before minting
const ownerBalanceBefore = await paymentTokenContract.balanceOf(signer.address);
expect(ownerBalanceBefore).to.equal(0);
console.log("Signer's payment token balance before first mint: " + ethers.utils.formatUnits(ownerBalanceBefore, paymentTokenDecimals) + " " + paymentTokenSymbol);
// Mint a domain
const tx = await mintContract.connect(user1).mint(
"user12", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
featureIds
);
const receipt = await tx.wait();
calculateGasCosts("Mint", receipt);
// get metadata
const metadata1 = await tldContract.tokenURI(1);
const mdJson1 = Buffer.from(metadata1.substring(29), "base64");
const mdResult1 = JSON.parse(mdJson1);
expect(mdResult1.name).to.equal("user12.degen");
//console.log(mdResult1.image);
const balanceDomainAfter = await tldContract.balanceOf(user1.address);
expect(balanceDomainAfter).to.equal(1);
const domainHolder = await tldContract.getDomainHolder("user12");
expect(domainHolder).to.equal(user1.address);
// TLD contract owner's balance after minting
const ownerBalanceAfter = await paymentTokenContract.balanceOf(signer.address);
expect(ownerBalanceAfter).to.equal(price5char); // signer gets both royalty and the rest of the domain payment
console.log("Signer's payment token balance after first mint: " + ethers.utils.formatUnits(ownerBalanceAfter, paymentTokenDecimals) + " " + paymentTokenSymbol);
// Give payment token allowance
await paymentTokenContract.connect(user1).approve(
mintContract.address, // spender
price5char // amount
);
// should not fail at minting another domain
await mintContract.connect(user1).mint(
"user1second", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
featureIds
);
const balanceDomainAfter2 = await tldContract.balanceOf(user1.address);
expect(balanceDomainAfter2).to.equal(2);
// get metadata2
const metadata2 = await tldContract.tokenURI(2);
const mdJson2 = Buffer.from(metadata2.substring(29), "base64");
const mdResult2 = JSON.parse(mdJson2);
expect(mdResult2.name).to.equal("user1second.degen");
//console.log(mdResult1.image);
// should FAIL at minting a domain with 4 chars
// Give payment token allowance
await paymentTokenContract.connect(user1).approve(
mintContract.address, // spender
price5char // amount
);
// should fail if domain is 4 chars, but payment is for 5 chars (too low)
await expect(mintContract.connect(user1).mint(
"user", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
featureIds
)).to.be.reverted;
const balanceDomainAfter3 = await tldContract.balanceOf(user1.address);
expect(balanceDomainAfter3).to.equal(2);
// should revert becuase feature IDs is already taken
await expect(mintContract.connect(user1).mint(
"hello", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
["3A1174741911F257FFCA965A000000231", "3A1174741911F257FFCA965A000000121"] // already used feature IDs
)).to.be.revertedWith("Feature IDs already used");
const balanceDomainAfter4 = await tldContract.balanceOf(user1.address);
expect(balanceDomainAfter4).to.equal(2);
});
it("should pause minting when max payment amount is reached", async function () {
// max payment amount is $100k
// 10 domains (1 char for $10k)
const featureIds = [
"3A1174741911F257FFCA965A000000231",
"3A1174741911F257FFCA965A000000121",
"3A1174741911F257FFCA965A000000120",
"3A1174741911F257FFCA965A000000110",
"3A1174741911F257FFCA965A000000000",
"3A1174741911F257FFCA965A000000100",
"3A1174741911F257FFCA965A000000210",
"3A1174741911F257FFCA965A000000200",
"3A1174741911F257FFCA965A000000220",
"3A1174741911F257FFCA965A000000221"
];
const pausedBefore1 = await mintContract.paused();
expect(pausedBefore1).to.be.true;
await mintContract.togglePaused();
const pausedBefore2 = await mintContract.paused();
expect(pausedBefore2).to.be.false;
// mint new payment tokens for user1
await paymentTokenContract.connect(user1).mint(
user1.address,
maxTotalPayments
);
// Give payment token allowance
await paymentTokenContract.connect(user1).approve(
mintContract.address, // spender
maxTotalPayments // amount
);
// how many domains user1 has before minting
const balanceDomainBefore = await tldContract.balanceOf(user1.address);
expect(balanceDomainBefore).to.equal(0);
// TLD contract owner's balance before minting
const ownerBalanceBefore = await paymentTokenContract.balanceOf(signer.address);
expect(ownerBalanceBefore).to.equal(0);
console.log("Signer's payment token balance before first mint: " + ethers.utils.formatUnits(ownerBalanceBefore, paymentTokenDecimals) + " " + paymentTokenSymbol);
// Mint 10 domains
await mintContract.connect(user1).mint(
"0", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[0]]
);
await mintContract.connect(user1).mint(
"1", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[1]]
);
await mintContract.connect(user1).mint(
"2", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[2]]
);
await mintContract.connect(user1).mint(
"3", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[3]]
);
await mintContract.connect(user1).mint(
"4", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[4]]
);
await mintContract.connect(user1).mint(
"5", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[5]]
);
await mintContract.connect(user1).mint(
"6", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[6]]
);
await mintContract.connect(user1).mint(
"7", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[7]]
);
await mintContract.connect(user1).mint(
"8", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[8]]
);
await mintContract.connect(user1).mint(
"9", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
[featureIds[9]]
);
// get metadata for 5.degen
const metadata = await tldContract.tokenURI(6);
const mdJson = Buffer.from(metadata.substring(29), "base64");
const mdResult = JSON.parse(mdJson);
expect(mdResult.name).to.equal("5.degen");
expect(mdResult.paid).to.equal(price1char);
console.log(mdResult.attributes);
const pausedAfter = await mintContract.paused();
expect(pausedAfter).to.be.true;
const balanceDomainAfter = await tldContract.balanceOf(user1.address);
expect(balanceDomainAfter).to.equal(10);
// TLD contract owner's balance after minting
const ownerBalanceAfter = await paymentTokenContract.balanceOf(signer.address);
expect(ownerBalanceAfter).to.equal(maxTotalPayments); // signer gets both royalty and the rest of the domain payment
console.log("Signer's payment token balance after first mint: " + ethers.utils.formatUnits(ownerBalanceAfter, paymentTokenDecimals) + " " + paymentTokenSymbol);
// TRY ANOTHER MINT
// Give payment token allowance
await paymentTokenContract.connect(user1).approve(
mintContract.address, // spender
maxTotalPayments // amount
);
// should revert because minting is paused
await expect(mintContract.connect(user1).mint(
"hello", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
["3A1174741911F257FFCA965A000000331"]
)).to.be.revertedWith("Minting paused");
// unpause minting
await mintContract.togglePaused();
// should revert because max payment is reached
await expect(mintContract.connect(user1).mint(
"hello", // domain name (without TLD)
user1.address, // domain holder
ethers.constants.AddressZero, // no referrer in this case
["3A1174741911F257FFCA965A000000331"]
)).to.be.revertedWith("Max total payments reached");
});
it("should change domain price (only owner)", async function () {
const priceBefore = await mintContract.price5char();
expect(priceBefore).to.equal(price5char);
const newPrice = ethers.utils.parseUnits("70", paymentTokenDecimals); // domain price is in payment tokens
await mintContract.changePrice(
newPrice,
5 // chars (price for domains with 5 chars)
);
const priceAfter = await mintContract.price5char();
expect(priceAfter).to.equal(newPrice);
// cannot be zero
await expect(mintContract.changePrice(0, 5)).to.be.revertedWith('Cannot be zero');
// if user is not owner, the tx should revert
await expect(mintContract.connect(user1).changePrice(123456, 5)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should change referral fee (only owner)", async function () {
const refBefore = await mintContract.referralFee();
expect(refBefore).to.equal(1000);
const newRef = 1500;
await mintContract.changeReferralFee(newRef);
const refAfter = await mintContract.referralFee();
expect(refAfter).to.equal(newRef);
// cannot exceed 20%
await expect(mintContract.changeReferralFee(2100)).to.be.revertedWith('Cannot exceed 20%');
// if user is not owner, the tx should revert
await expect(mintContract.connect(user1).changeReferralFee(666)).to.be.revertedWith('Ownable: caller is not the owner');
});
it("should recover ERC-20 tokens mistakenly sent to contract address", async function () {
const ERC20MockToken = await ethers.getContractFactory("MockErc20Token");
const mockErc20Contract = await ERC20MockToken.deploy("Mock", "MOCK");
const signerBalance = await mockErc20Contract.balanceOf(signer.address);
expect(Number(ethers.utils.formatEther(signerBalance))).to.equal(1000); // 1000 tokens minted in the ERC20 contract constructor
const mintContractBalance = await mockErc20Contract.balanceOf(mintContract.address);
expect(mintContractBalance).to.equal(0); // should be 0
// send 200 tokens to contract
await mockErc20Contract.transfer(mintContract.address, ethers.utils.parseEther("200"));
const signerBalance2 = await mockErc20Contract.balanceOf(signer.address);
expect(Number(ethers.utils.formatEther(signerBalance2))).to.equal(800);
const mintContractBalance2 = await mockErc20Contract.balanceOf(mintContract.address);
expect(Number(ethers.utils.formatEther(mintContractBalance2))).to.equal(200);
// recover tokens from contract
await mintContract.recoverERC20(
mockErc20Contract.address, // token address
ethers.utils.parseEther("200"), // token amount
signer.address // recipient
);
const signerBalance3 = await mockErc20Contract.balanceOf(signer.address);
expect(Number(ethers.utils.formatEther(signerBalance3))).to.equal(1000); // back to 1000
const mintContractBalance3 = await mockErc20Contract.balanceOf(mintContract.address);
expect(Number(ethers.utils.formatEther(mintContractBalance3))).to.equal(0); // back to 0
});
});

@ -0,0 +1,45 @@
// npx hardhat test test/nft/angel/angelMetadata.test.js
const { expect } = require("chai");
describe("Degen Anon Metadata", function () {
let metadataContract;
let signer;
beforeEach(async function () {
[signer] = await ethers.getSigners();
const DegenAnonMetadata = await ethers.getContractFactory("DegenAnonMetadata");
metadataContract = await DegenAnonMetadata.deploy();
await metadataContract.changeMinter(signer.address);
const features1 = "3A1174741911F257FFCA965A000000231"; // bg1, bg2, hair, skin, dress, face (0-3), arms (0-3), lips (0-2)
const domainPrice = ethers.utils.parseUnits("1", "ether");
await metadataContract.setUniqueFeaturesId(1, [features1], domainPrice);
});
it("should fetch and parse metadata", async function () {
const tokenId = 1;
const domainName = "techie";
const tld = ".degen";
const metadata = await metadataContract.getMetadata(domainName, tld, tokenId);
console.log(metadata)
const mdJson = Buffer.from(metadata.substring(29), "base64");
const mdResult = JSON.parse(mdJson);
// metadata:
//console.log(mdResult);
console.log(mdResult.name);
console.log(mdResult.attributes);
expect(mdResult.name).to.equal(domainName+tld);
expect(mdResult.description).to.equal("A collection of Degen Anon NFTs created by Degen Domain Service: https://degendomains.io/#/nft/angel");
// SVG image:
console.log(mdResult.image);
});
});

@ -0,0 +1,118 @@
// npx hardhat test test/nft/angel/angelWhitelist.test.js
const { expect } = require("chai");
function calculateGasCosts(testName, receipt) {
console.log(testName + " gasUsed: " + receipt.gasUsed);
// coin prices in USD
const matic = 0.7;
const eth = 1800;
const gasCostMatic = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("35", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostEthereum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("55", "gwei")) * Number(receipt.gasUsed)), "ether");
const gasCostArbitrum = ethers.utils.formatUnits(String(Number(ethers.utils.parseUnits("1", "gwei")) * Number(receipt.gasUsed)), "ether");
console.log(testName + " gas cost (Ethereum): $" + String(Number(gasCostEthereum)*eth));
console.log(testName + " gas cost (Arbitrum): $" + String(Number(gasCostArbitrum)*eth));
console.log(testName + " gas cost (Polygon): $" + String(Number(gasCostMatic)*matic));
}
describe("Degen Anon Whitelist", function () {
let contract;
let signer;
let user1;
let user2;
beforeEach(async function () {
[signer, user1, user2] = await ethers.getSigners();
const DegenAnonWhitelist = await ethers.getContractFactory("DegenAnonWhitelist");
contract = await DegenAnonWhitelist.deploy();
});
it("should join the whitelist", async function () {
const amount = 5000;
// check if user1 is whitelisted
const isWhitelistedBefore = await contract.isWhitelisted(user1.address);
expect(isWhitelistedBefore).to.be.false;
// check total whitelisted addresses
const totalAddressesBefore = await contract.totalAddresses();
expect(totalAddressesBefore).to.equal(0);
// check total amount
const totalAmountBefore = await contract.totalAmount();
expect(totalAmountBefore).to.equal(0);
await contract.togglePaused();
// fail at whitelisting when contract is paused
await expect(contract.connect(user1).joinWhitelist(
amount
)).to.be.revertedWith('Whitelisting is paused.');
await contract.togglePaused();
// whitelisting should now succeed
const tx = await contract.connect(user1).joinWhitelist(amount);
const receipt = await tx.wait()
calculateGasCosts("Join Whitelist", receipt);
const events = [];
for (let item of receipt.events) {
events.push(item.event);
}
expect(events).to.include("UserJoinWhitelist");
// check if user1 is whitelisted
const isWhitelistedAfter = await contract.isWhitelisted(user1.address);
expect(isWhitelistedAfter).to.be.true;
// check total whitelisted addresses
const totalAddressesAfter = await contract.totalAddresses();
expect(totalAddressesAfter).to.equal(1);
// check total amount
const totalAmountAfter = await contract.totalAmount();
expect(totalAmountAfter).to.equal(amount);
// whitelist the same user again
const newAmount = 6000;
const tx2 = await contract.connect(user1).joinWhitelist(newAmount);
const receipt2 = await tx2.wait()
calculateGasCosts("Join Whitelist Again", receipt2);
const events2 = [];
for (let item of receipt2.events) {
events2.push(item.event);
}
expect(events2).to.include("UserJoinWhitelist");
// check if user1 is whitelisted
const isWhitelistedAfter2 = await contract.isWhitelisted(user1.address);
expect(isWhitelistedAfter2).to.be.true;
// check total whitelisted addresses
const totalAddressesAfter2 = await contract.totalAddresses();
expect(totalAddressesAfter2).to.equal(1);
// check total amount
const totalAmountAfter2 = await contract.totalAmount();
expect(totalAmountAfter2).to.equal(newAmount);
});
it("should fail at whitelisting if amount is too high", async function () {
await expect(contract.connect(user1).joinWhitelist(
51000
)).to.be.revertedWith('Amount is too high.');
});
});

@ -0,0 +1,484 @@
// npx hardhat test test/resolver/proxy.test.js
const { expect } = require('chai');
describe("Degen Resolver Proxy", function () {
let contract;
let forbTldsContract;
let factoryContract1;
let factoryContract2;
let tldContract1;
let tldContract2;
let tldContract3;
let signer;
let user1;
let user2;
// TLD1
const tldName1 = ".lambo";
const domainSymbol1 = ".LAMBO";
const domainPrice1 = ethers.utils.parseUnits("1", "ether");
// TLD2
const tldName2 = ".moon";
const domainSymbol2 = ".MOON";
const domainPrice2 = ethers.utils.parseUnits("2", "ether");
// TLD1
const tldName3 = ".dex";
const domainSymbol3 = ".DEX";
const domainPrice3 = ethers.utils.parseUnits("3", "ether");
beforeEach(async function () {
[signer, user1, user2] = await ethers.getSigners();
// deploy V1
const DegenResolverV1 = await ethers.getContractFactory("DegenResolverV1");
contract = await upgrades.deployProxy(DegenResolverV1); // alternative: upgrades.deployProxy(CounterV1, {initializer: 'initialize'});
// deploy Frobidden TLDs contract
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
forbTldsContract = await DegenForbiddenTlds.deploy();
// deploy multiple factory contracts
const DegenTLDFactory = await ethers.getContractFactory("DegenTLDFactory");
factoryContract1 = await DegenTLDFactory.deploy(ethers.utils.parseUnits("1", "ether"), forbTldsContract.address);
factoryContract2 = await DegenTLDFactory.deploy(ethers.utils.parseUnits("2", "ether"), forbTldsContract.address);
await forbTldsContract.addFactoryAddress(factoryContract1.address);
await forbTldsContract.addFactoryAddress(factoryContract2.address);
// create TLD no. 1
await factoryContract1.ownerCreateTld(
tldName1,
domainSymbol1,
signer.address, // TLD owner
domainPrice1,
true // buying enabled
)
// create TLD no. 2
await factoryContract1.ownerCreateTld(
tldName2,
domainSymbol2,
signer.address, // TLD owner
domainPrice2,
true // buying enabled
)
// create TLD no. 3
await factoryContract2.ownerCreateTld(
tldName3,
domainSymbol3,
signer.address, // TLD owner
domainPrice3,
true // buying enabled
)
const tldAddress1 = await factoryContract1.tldNamesAddresses(tldName1);
const tldAddress2 = await factoryContract1.tldNamesAddresses(tldName2);
const tldAddress3 = await factoryContract2.tldNamesAddresses(tldName3);
tldContract1 = await hre.ethers.getContractAt("DegenTLD", tldAddress1);
tldContract2 = await hre.ethers.getContractAt("DegenTLD", tldAddress2);
tldContract3 = await hre.ethers.getContractAt("DegenTLD", tldAddress3);
});
it('adds and removes a factory address (only owner)', async function () {
const owner = await contract.owner();
expect(owner).to.equal(signer.address);
const factoryAddresses1 = contract.getFactoriesArray();
expect(factoryAddresses1).to.be.empty;
await contract.addFactoryAddress(factoryContract1.address);
const factoryAddresses2 = await contract.getFactoriesArray();
expect(factoryAddresses2).to.have.members([factoryContract1.address]);
await expect(contract.connect(user1).addFactoryAddress(
factoryContract2.address
)).to.be.revertedWith('Ownable: caller is not the owner');
await contract.addFactoryAddress(factoryContract2.address);
const factoryAddresses3 = await contract.getFactoriesArray();
expect(factoryAddresses3).to.have.members([factoryContract1.address, factoryContract2.address]);
await contract.removeFactoryAddress(0); // remove factory contract 1
const factoryAddresses4 = await contract.getFactoriesArray();
expect(factoryAddresses4).to.have.members([factoryContract2.address]);
// fail if user is not owner
await expect(contract.connect(user1).removeFactoryAddress(
0
)).to.be.revertedWith('Ownable: caller is not the owner');
});
it('fetches a domain holder', async function () {
const domainName = "user1";
// check domain holder via TLD contract before
const domainHolderViaTldBefore = await tldContract1.getDomainHolder(domainName);
expect(domainHolderViaTldBefore).to.equal(ethers.constants.AddressZero);
// create domain name
await tldContract1.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice1 // pay for the domain
}
);
// check domain holder via TLD contract after
const domainHolderViaTldAfter = await tldContract1.getDomainHolder(domainName);
expect(domainHolderViaTldAfter).to.equal(user1.address);
// check domain holder via Resolver before
const domainHolderViaResolverBefore = await contract.getDomainHolder(domainName, tldName1);
expect(domainHolderViaResolverBefore).to.equal(ethers.constants.AddressZero);
// add factory address to the resolver contract
await contract.addFactoryAddress(factoryContract1.address);
// check domain holder via Resolver after
const domainHolderViaResolverAfter = await contract.getDomainHolder(domainName, tldName1);
expect(domainHolderViaResolverAfter).to.equal(user1.address);
// check non-existing domain name via Resolver
const domainHolderViaResolverNonExisting = await contract.getDomainHolder("nonExistingDomain", tldName1);
expect(domainHolderViaResolverNonExisting).to.equal(ethers.constants.AddressZero);
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
// should return 0x0 address because TLD is deprecated
const domainHolderViaResolverDeprecated = await contract.getDomainHolder(domainName, tldName1);
expect(domainHolderViaResolverDeprecated).to.equal(ethers.constants.AddressZero);
});
it('fetches a default domain for a user address', async function () {
// query default domain via TLD contract before
const defaultDomainViaTldBefore = await tldContract1.defaultNames(user1.address);
expect(defaultDomainViaTldBefore).to.equal("");
// create domain name
const domainName = "user1";
await tldContract1.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice1 // pay for the domain
}
);
// check default domain via TLD contract after
const defaultDomainViaTldAfter = await tldContract1.defaultNames(user1.address);
expect(defaultDomainViaTldAfter).to.equal(domainName);
// check default domain via Resolver before
const defaultDomainViaResolverBefore = await contract.getDefaultDomain(user1.address, tldName1);
expect(defaultDomainViaResolverBefore).to.equal("");
// add factory address to the resolver contract
await contract.addFactoryAddress(factoryContract1.address);
// check default domain via Resolver after
const defaultDomainViaResolverAfter = await contract.getDefaultDomain(user1.address, tldName1);
expect(defaultDomainViaResolverAfter).to.equal(domainName);
// check non-existing default domain via Resolver
const defaultDomainViaResolverNonExisting = await contract.getDefaultDomain(user2.address, tldName1);
expect(defaultDomainViaResolverNonExisting).to.equal("");
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
// should return empty string because TLD is deprecated
const domainDomainViaResolverDeprecated = await contract.getDomainData(user1.address, tldName1);
expect(domainDomainViaResolverDeprecated).to.equal("");
});
it('fetches domain data', async function () {
const domainName = "user1";
// check domain data via TLD contract before
const domainDataViaTldBefore = await tldContract1.getDomainData(domainName);
expect(domainDataViaTldBefore).to.equal("");
// create domain name
await tldContract1.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice1 // pay for the domain
}
);
const newDomainData = "new data";
await tldContract1.connect(user1).editData(domainName, newDomainData);
// check domain data via TLD contract after
const domainDataViaTldAfter = await tldContract1.getDomainData(domainName);
expect(domainDataViaTldAfter).to.equal(newDomainData);
// check domain data via Resolver before
const domainDataViaResolverBefore = await contract.getDomainData(domainName, tldName1);
expect(domainDataViaResolverBefore).to.equal("");
// add factory address to the resolver contract
await contract.addFactoryAddress(factoryContract1.address);
// check domain data via Resolver after
const domainDataViaResolverAfter = await contract.getDomainData(domainName, tldName1);
expect(domainDataViaResolverAfter).to.equal(newDomainData);
// check non-existing domain name via Resolver
const domainDataViaResolverNonExisting = await contract.getDomainData("nonExistingDomain", tldName1);
expect(domainDataViaResolverNonExisting).to.equal("");
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
// should return 0x0 address because TLD is deprecated
const domainDataViaResolverDeprecated = await contract.getDomainData(domainName, tldName1);
expect(domainDataViaResolverDeprecated).to.equal("");
});
it('fetches the address of a given TLD', async function () {
const tldAddressBefore = await contract.getTldAddress(tldName1);
expect(tldAddressBefore).to.equal(ethers.constants.AddressZero);
await contract.addFactoryAddress(factoryContract1.address);
await contract.addFactoryAddress(factoryContract2.address);
const tldAddressAfter1 = await contract.getTldAddress(tldName1);
expect(tldAddressAfter1).to.equal(tldContract1.address);
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
const tldAddressAfter2 = await contract.getTldAddress(tldName1);
expect(tldAddressAfter2).to.equal(ethers.constants.AddressZero);
});
it('fetches a stringified CSV of all active TLDs', async function () {
const tldsCsvStringBefore = await contract.getTlds();
expect(tldsCsvStringBefore).to.be.empty;
await contract.addFactoryAddress(factoryContract1.address);
await contract.addFactoryAddress(factoryContract2.address);
const tldsCsvStringAfter = await contract.getTlds();
expect(tldsCsvStringAfter).to.include(tldName1);
console.log(tldsCsvStringAfter);
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
const tldsCsvStringAfter2 = await contract.getTlds();
expect(tldsCsvStringAfter2).to.not.include(tldName1);
console.log(tldsCsvStringAfter2);
});
it('fetches a list of default domains for a user address across all TLDs', async function () {
// query default domain via TLD contract before
const defaultDomainViaTldBefore = await tldContract1.defaultNames(user1.address);
expect(defaultDomainViaTldBefore).to.equal("");
// create domain name
const domainName = "user1";
await tldContract1.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice1 // pay for the domain
}
);
await tldContract3.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice3 // pay for the domain
}
);
// check default domain via TLD contract after
const defaultDomainViaTldAfter = await tldContract1.defaultNames(user1.address);
expect(defaultDomainViaTldAfter).to.equal(domainName);
// check default domain via Resolver before
const defaultDomainViaResolverBefore = await contract.getDefaultDomains(user1.address);
expect(defaultDomainViaResolverBefore).to.equal("");
// add factory addresses to the resolver contract
await contract.addFactoryAddress(factoryContract1.address);
await contract.addFactoryAddress(factoryContract2.address);
// check default domain via Resolver after
const defaultDomainViaResolverAfter = await contract.getDefaultDomains(user1.address);
console.log(defaultDomainViaResolverAfter);
expect(defaultDomainViaResolverAfter).to.equal(domainName + tldName1 + " " + domainName + tldName3);
// check non-existing default domain via Resolver
const defaultDomainViaResolverNonExisting = await contract.getDefaultDomains(user2.address);
expect(defaultDomainViaResolverNonExisting).to.equal("");
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
// should return 1 less domain name because TLD is deprecated
const defaultDomainViaResolverAfter2 = await contract.getDefaultDomains(user1.address);
console.log(defaultDomainViaResolverAfter2);
expect(defaultDomainViaResolverAfter2).to.equal(domainName + tldName3);
});
it('fetches a single users default domain name, the first that comes', async function () {
// query default domain via TLD contract before
const defaultDomainViaTldBefore = await tldContract1.defaultNames(user1.address);
expect(defaultDomainViaTldBefore).to.equal("");
// create domain name
const domainName = "user1";
await tldContract1.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice1 // pay for the domain
}
);
await tldContract3.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice3 // pay for the domain
}
);
// check default domain via TLD contract after
const defaultDomainViaTldAfter = await tldContract1.defaultNames(user1.address);
expect(defaultDomainViaTldAfter).to.equal(domainName);
// check default domain via Resolver before
const defaultDomainViaResolverBefore = await contract.getFirstDefaultDomain(user1.address);
expect(defaultDomainViaResolverBefore).to.equal("");
// add factory addresses to the resolver contract
await contract.addFactoryAddress(factoryContract1.address);
await contract.addFactoryAddress(factoryContract2.address);
// check default domain via Resolver after
const defaultDomainViaResolverAfter = await contract.getFirstDefaultDomain(user1.address);
console.log(defaultDomainViaResolverAfter);
expect(defaultDomainViaResolverAfter).to.equal(domainName + tldName1);
// check non-existing default domain via Resolver
const defaultDomainViaResolverNonExisting = await contract.getFirstDefaultDomain(user2.address);
expect(defaultDomainViaResolverNonExisting).to.equal("");
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
// should return a different domain name because the first TLD is deprecated
const defaultDomainViaResolverAfter2 = await contract.getDefaultDomains(user1.address);
expect(defaultDomainViaResolverAfter2).to.equal(domainName + tldName3);
});
it('un/sets a TLD as deprecated (only owner)', async function () {
const isDeprecatedBefore = await contract.isTldDeprecated(tldContract2.address);
expect(isDeprecatedBefore).to.be.false;
await contract.addDeprecatedTldAddress(tldContract2.address);
const isDeprecatedAfter1 = await contract.isTldDeprecated(tldContract2.address);
expect(isDeprecatedAfter1).to.be.true;
await contract.removeDeprecatedTldAddress(tldContract2.address);
const isDeprecatedAfter2 = await contract.isTldDeprecated(tldContract2.address);
expect(isDeprecatedAfter2).to.be.false;
// should fail if user is not owner
await expect(
contract.connect(user1).addDeprecatedTldAddress(tldContract2.address)
).to.be.revertedWith('Ownable: caller is not the owner');
});
it('fetch domain metadata via tokenURI', async function () {
const domainName = "user1";
// create domain name
await tldContract1.mint(
domainName, // domain name (without TLD)
user1.address, // domain owner
ethers.constants.AddressZero, // no referrer
{
value: domainPrice1 // pay for the domain
}
);
// check domain metadata via TLD contract
const domainMetadataViaTldAfter = await tldContract1.tokenURI(0);
const mdJson = Buffer.from(domainMetadataViaTldAfter.substring(29), "base64");
const mdResult = JSON.parse(mdJson);
expect(mdResult.name).to.equal(domainName+tldName1);
// check domain metadata via Resolver contract
const domainMetadataViaTldAfter2 = await contract.getDomainTokenUri(domainName, tldName1);
expect(domainMetadataViaTldAfter2).to.be.empty;
// add factory address to the resolver contract
await contract.addFactoryAddress(factoryContract1.address);
// check domain metadata via Resolver contract
const domainMetadataViaTldAfter3 = await contract.getDomainTokenUri(domainName, tldName1);
const mdJson2 = Buffer.from(domainMetadataViaTldAfter3.substring(29), "base64");
const mdResult2 = JSON.parse(mdJson2);
expect(mdResult2.name).to.equal(domainName+tldName1);
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
// should return an empty string because the TLD is deprecated
const domainMetadataViaTldAfter4 = await contract.getDomainTokenUri(domainName, tldName1);
expect(domainMetadataViaTldAfter4).to.be.empty;
});
it('fetches the address of the factory through which a given TLD was created', async function () {
const factoryAddressBefore = await contract.getTldFactoryAddress(tldName1);
expect(factoryAddressBefore).to.equal(ethers.constants.AddressZero);
await contract.addFactoryAddress(factoryContract1.address);
await contract.addFactoryAddress(factoryContract2.address);
const factoryAddressAfter1 = await contract.getTldFactoryAddress(tldName1);
expect(factoryAddressAfter1).to.equal(factoryContract1.address);
// deprecate a TLD
await contract.addDeprecatedTldAddress(tldContract1.address);
const factoryAddressAfter2 = await contract.getTldFactoryAddress(tldName1);
expect(factoryAddressAfter2).to.equal(ethers.constants.AddressZero);
});
});

@ -0,0 +1,37 @@
// npx hardhat test test/resolver/resolver.v1.test.js
const { expect } = require('chai');
const contractName = "DegenResolverV1";
describe(contractName, function () {
let contract;
let forbTldsContract;
let factoryContract1;
let factoryContract2;
let factoryContract3;
let signer;
let user1;
let user2;
beforeEach(async function () {
[signer, user1, user2] = await ethers.getSigners();
const contractCode = await ethers.getContractFactory(contractName);
contract = await contractCode.deploy();
const DegenForbiddenTlds = await ethers.getContractFactory("DegenForbiddenTlds");
forbTldsContract = await DegenForbiddenTlds.deploy();
const DegenTLDFactory = await ethers.getContractFactory("DegenTLDFactory");
factoryContract1 = await DegenTLDFactory.deploy(ethers.utils.parseUnits("1", "ether"), forbTldsContract.address);
factoryContract2 = await DegenTLDFactory.deploy(ethers.utils.parseUnits("2", "ether"), forbTldsContract.address);
factoryContract3 = await DegenTLDFactory.deploy(ethers.utils.parseUnits("3", "ether"), forbTldsContract.address);
await forbTldsContract.addFactoryAddress(factoryContract1.address);
await forbTldsContract.addFactoryAddress(factoryContract2.address);
await forbTldsContract.addFactoryAddress(factoryContract3.address);
});
//it('', async function () {});
});

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save