diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 99c10659b..28004803a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,6 +25,7 @@ jobs: package: - solidity - cairo + - stellar runs-on: ubuntu-latest steps: diff --git a/packages/core/stellar/.gitignore b/packages/core/stellar/.gitignore new file mode 100644 index 000000000..017fefa2d --- /dev/null +++ b/packages/core/stellar/.gitignore @@ -0,0 +1,4 @@ +/cache +/artifacts +/contracts/generated +/openzeppelin-contracts.json diff --git a/packages/core/stellar/CHANGELOG.md b/packages/core/stellar/CHANGELOG.md new file mode 100644 index 000000000..d0dfa9868 --- /dev/null +++ b/packages/core/stellar/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +## 0.1.0 (2025-02-25) + +- Initial version. ([#460](https://github.com/OpenZeppelin/contracts-wizard/pull/460)) diff --git a/packages/core/stellar/LICENSE b/packages/core/stellar/LICENSE new file mode 100644 index 000000000..be3f7b28e --- /dev/null +++ b/packages/core/stellar/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/packages/core/stellar/NOTICE b/packages/core/stellar/NOTICE new file mode 100644 index 000000000..e68e93389 --- /dev/null +++ b/packages/core/stellar/NOTICE @@ -0,0 +1,8 @@ +OpenZeppelin Contracts Wizard +Copyright (C) 2021-2025 Zeppelin Group Ltd + +This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + +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 Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License along with this program. If not, see . \ No newline at end of file diff --git a/packages/core/stellar/README.md b/packages/core/stellar/README.md new file mode 100644 index 000000000..b4dc05915 --- /dev/null +++ b/packages/core/stellar/README.md @@ -0,0 +1,57 @@ +# OpenZeppelin Contracts Wizard for Stellar + +Interactively build a contract out of components from OpenZeppelin Stellar Soroban Contracts. Provide parameters and desired features for the kind of contract that you want, and the Wizard will generate all of the code necessary. The resulting code is ready to be compiled and deployed, or it can serve as a starting point and customized further with application specific logic. + +This package provides a programmatic API. For a web interface, see https://wizard.openzeppelin.com/stellar + +### Installation + +`npm install @openzeppelin/wizard-stellar` + +### Contract types + +The following contract types are supported: +- `fungible` + +Each contract type has functions/constants as defined below. + +### Functions + +#### `print` +```js +function print(opts?: FungibleOptions): string +``` +Returns a string representation of a contract generated using the provided options. If `opts` is not provided, uses [`defaults`](#defaults). + +#### `defaults` +```js +const defaults: Required +``` +The default options that are used for [`print`](#print). + +### Examples + +Import the contract type(s) (for example, `fungible`) that you want to use from the `@openzeppelin/wizard-stellar` package: + +```js +import { fungible } from '@openzeppelin/wizard-stellar'; +``` + +To generate the source code for an Fungible contract with all of the default settings: +```js +const contract = fungible.print(); +``` + +To generate the source code for an Fungible contract with some custom settings: +```js +const contract = fungible.print({ + pausable: true, +}); +``` +or +```js +const contract = fungible.print({ + ...fungible.defaults, + pausable: true, +}); +``` diff --git a/packages/core/stellar/ava.config.js b/packages/core/stellar/ava.config.js new file mode 100644 index 000000000..e39146f7a --- /dev/null +++ b/packages/core/stellar/ava.config.js @@ -0,0 +1,9 @@ +module.exports = { + extensions: ['ts'], + require: ['ts-node/register'], + watchmode: { + ignoreChanges: ['contracts', 'artifacts', 'cache'], + }, + timeout: '10m', + workerThreads: false, +}; diff --git a/packages/core/stellar/package.json b/packages/core/stellar/package.json new file mode 100644 index 000000000..0713e2d14 --- /dev/null +++ b/packages/core/stellar/package.json @@ -0,0 +1,33 @@ +{ + "name": "@openzeppelin/wizard-stellar", + "version": "0.1.0", + "description": "A boilerplate generator to get started with OpenZeppelin Stellar Soroban Contracts", + "license": "AGPL-3.0-only", + "repository": "https://github.com/OpenZeppelin/contracts-wizard", + "main": "dist/index.js", + "ts:main": "src/index.ts", + "files": [ + "LICENSE", + "NOTICE", + "/dist", + "/src", + "!**/*.test.*" + ], + "scripts": { + "prepare": "tsc", + "prepublish": "rimraf dist *.tsbuildinfo", + "test": "ava", + "test:update-snapshots": "ava --update-snapshots", + "test:watch": "ava --watch", + "version": "node ../../../scripts/bump-changelog.js" + }, + "devDependencies": { + "@types/node": "^18.0.0", + "@types/semver": "^7.5.7", + "ava": "^6.0.0", + "rimraf": "^5.0.0", + "ts-node": "^10.4.0", + "typescript": "^5.0.0", + "semver": "^7.6.0" + } +} diff --git a/packages/core/stellar/src/add-pausable.ts b/packages/core/stellar/src/add-pausable.ts new file mode 100644 index 000000000..22334de0b --- /dev/null +++ b/packages/core/stellar/src/add-pausable.ts @@ -0,0 +1,40 @@ +import { getSelfArg } from './common-options'; +import type { ContractBuilder } from './contract'; +import type { Access } from './set-access-control'; +import { requireAccessControl } from './set-access-control'; +import { defineFunctions } from './utils/define-functions'; + +export function addPausable(c: ContractBuilder, access: Access) { + c.addUseClause('openzeppelin_pausable', 'self', { alias: 'pausable' }); + c.addUseClause('openzeppelin_pausable', 'Pausable'); + + const pausableTrait = { + name: 'Pausable', + for: c.name, + tags: ['contractimpl'], + section: 'Utils', + }; + + c.addFunction(pausableTrait, functions.paused); + c.addFunction(pausableTrait, functions.pause); + c.addFunction(pausableTrait, functions.unpause); + + requireAccessControl(c, pausableTrait, functions.pause, access, 'caller'); + requireAccessControl(c, pausableTrait, functions.unpause, access, 'caller'); +} + +const functions = defineFunctions({ + paused: { + args: [getSelfArg()], + returns: 'bool', + code: ['pausable::paused(e)'], + }, + pause: { + args: [getSelfArg(), { name: 'caller', type: 'Address' }], + code: ['pausable::pause(e, &caller)'], + }, + unpause: { + args: [getSelfArg(), { name: 'caller', type: 'Address' }], + code: ['pausable::unpause(e, &caller)'], + }, +}); diff --git a/packages/core/stellar/src/api.ts b/packages/core/stellar/src/api.ts new file mode 100644 index 000000000..9e9b0e4fe --- /dev/null +++ b/packages/core/stellar/src/api.ts @@ -0,0 +1,30 @@ +import type { CommonContractOptions } from './common-options'; +import type { FungibleOptions } from './fungible'; +import { printFungible, defaults as fungibledefaults } from './fungible'; + +export interface WizardContractAPI { + /** + * Returns a string representation of a contract generated using the provided options. If opts is not provided, uses `defaults`. + */ + print: (opts?: Options) => string; + + /** + * The default options that are used for `print`. + */ + defaults: Required; +} + +export interface AccessControlAPI { + /** + * Whether any of the provided options require access control to be enabled. If this returns `true`, then calling `print` with the + * same options would cause the `access` option to default to `'ownable'` if it was `undefined` or `false`. + */ + isAccessControlRequired: (opts: Partial) => boolean; +} + +export type Fungible = WizardContractAPI; // TODO add AccessControlAPI when access control is implemented, if useful + +export const fungible: Fungible = { + print: printFungible, + defaults: fungibledefaults, +}; diff --git a/packages/core/stellar/src/build-generic.ts b/packages/core/stellar/src/build-generic.ts new file mode 100644 index 000000000..5fb8acd7c --- /dev/null +++ b/packages/core/stellar/src/build-generic.ts @@ -0,0 +1,19 @@ +import type { FungibleOptions } from './fungible'; +import { buildFungible } from './fungible'; + +export interface KindedOptions { + Fungible: { kind: 'Fungible' } & FungibleOptions; +} + +export type GenericOptions = KindedOptions[keyof KindedOptions]; + +export function buildGeneric(opts: GenericOptions) { + switch (opts.kind) { + case 'Fungible': + return buildFungible(opts); + default: { + const _: never = opts.kind; // TODO: When there are additional kinds above, change this assignment to just `opts` instead of `opts.kind` + throw new Error('Unknown ERC'); + } + } +} diff --git a/packages/core/stellar/src/common-options.ts b/packages/core/stellar/src/common-options.ts new file mode 100644 index 000000000..f342cef7d --- /dev/null +++ b/packages/core/stellar/src/common-options.ts @@ -0,0 +1,38 @@ +import type { Argument } from './contract'; +import type { Access } from './set-access-control'; +import type { Info } from './set-info'; +import { defaults as infoDefaults } from './set-info'; + +export const defaults: Required = { + info: infoDefaults, +} as const; + +export const contractDefaults: Required = { + ...defaults, + access: false, +} as const; + +export interface CommonOptions { + info?: Info; +} + +export interface CommonContractOptions extends CommonOptions { + access?: Access; +} + +export function withCommonDefaults(opts: CommonOptions): Required { + return { + info: opts.info ?? defaults.info, + }; +} + +export function withCommonContractDefaults(opts: CommonContractOptions): Required { + return { + ...withCommonDefaults(opts), + access: opts.access ?? contractDefaults.access, + }; +} + +export function getSelfArg(): Argument { + return { name: 'e', type: '&Env' }; +} diff --git a/packages/core/stellar/src/contract.test.ts b/packages/core/stellar/src/contract.test.ts new file mode 100644 index 000000000..ad825a20c --- /dev/null +++ b/packages/core/stellar/src/contract.test.ts @@ -0,0 +1,82 @@ +import test from 'ava'; + +import type { BaseFunction, BaseImplementedTrait } from './contract'; +import { ContractBuilder } from './contract'; +import { printContract } from './print'; + +test('contract basics', t => { + const Foo = new ContractBuilder('Foo'); + t.snapshot(printContract(Foo)); +}); + +test('contract with constructor code', t => { + const Foo = new ContractBuilder('Foo'); + Foo.addConstructorCode('someFunction()'); + t.snapshot(printContract(Foo)); +}); + +test('contract with constructor code with semicolon', t => { + const Foo = new ContractBuilder('Foo'); + Foo.addConstructorCode('someFunction();'); + t.snapshot(printContract(Foo)); +}); + +test('contract with function code before', t => { + const Foo = new ContractBuilder('Foo'); + const trait: BaseImplementedTrait = { + name: 'External', + for: 'ExternalTrait', + tags: ['othertag', 'contractimpl'], + }; + Foo.addImplementedTrait(trait); + const fn: BaseFunction = { + name: 'someFunction', + args: [], + code: ['someFunction()'], + }; + Foo.addFunction(trait, fn); + Foo.addFunctionTag(trait, fn, 'functiontag'); + Foo.addFunctionCodeBefore(trait, fn, ['before()']); + t.snapshot(printContract(Foo)); +}); + +test('contract with function code before with semicolons', t => { + const Foo = new ContractBuilder('Foo'); + const trait: BaseImplementedTrait = { + name: 'External', + for: 'ExternalTrait', + tags: ['othertag', 'contractimpl'], + }; + Foo.addImplementedTrait(trait); + const fn: BaseFunction = { + name: 'someFunction', + args: [], + code: ['someFunction();'], + }; + Foo.addFunction(trait, fn); + Foo.addFunctionTag(trait, fn, 'functiontag'); + Foo.addFunctionCodeBefore(trait, fn, ['before();']); + t.snapshot(printContract(Foo)); +}); + +test('contract with standalone import', t => { + const Foo = new ContractBuilder('Foo'); + Foo.addUseClause('some::library', 'SomeLibrary'); + t.snapshot(printContract(Foo)); +}); + +test('contract with grouped imports', t => { + const Foo = new ContractBuilder('Foo'); + Foo.addUseClause('some::library', 'SomeLibrary'); + Foo.addUseClause('some::library', 'Misc'); + t.snapshot(printContract(Foo)); +}); + +test('contract with sorted use clauses', t => { + const Foo = new ContractBuilder('Foo'); + Foo.addUseClause('some::library', 'SomeLibrary'); + Foo.addUseClause('another::library', 'AnotherLibrary'); + Foo.addUseClause('another::library', 'self', { alias: 'custom2' }); + Foo.addUseClause('another::library', 'self', { alias: 'custom1' }); + t.snapshot(printContract(Foo)); +}); diff --git a/packages/core/stellar/src/contract.test.ts.md b/packages/core/stellar/src/contract.test.ts.md new file mode 100644 index 000000000..a58d43d9f --- /dev/null +++ b/packages/core/stellar/src/contract.test.ts.md @@ -0,0 +1,158 @@ +# Snapshot report for `src/contract.test.ts` + +The actual snapshot is saved in `contract.test.ts.snap`. + +Generated by [AVA](https://avajs.dev). + +## contract basics + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + }␊ + ` + +## contract with constructor code + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + pub fn __constructor(e: &Env) {␊ + someFunction();␊ + }␊ + }␊ + ` + +## contract with constructor code with semicolon + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + pub fn __constructor(e: &Env) {␊ + someFunction();␊ + }␊ + }␊ + ` + +## contract with function code before + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + }␊ + ␊ + #[othertag]␊ + #[contractimpl]␊ + impl External for ExternalTrait {␊ + #[functiontag]␊ + fn someFunction() {␊ + before();␊ + someFunction();␊ + }␊ + }␊ + ` + +## contract with function code before with semicolons + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + }␊ + ␊ + #[othertag]␊ + #[contractimpl]␊ + impl External for ExternalTrait {␊ + #[functiontag]␊ + fn someFunction() {␊ + before();␊ + someFunction();␊ + }␊ + }␊ + ` + +## contract with standalone import + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use some::library::SomeLibrary;␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + }␊ + ` + +## contract with grouped imports + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use some::library::{Misc, SomeLibrary};␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + }␊ + ` + +## contract with sorted use clauses + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use another::library::{self as custom1, self as custom2, AnotherLibrary};␊ + use some::library::SomeLibrary;␊ + ␊ + #[contract]␊ + pub struct Foo;␊ + ␊ + #[contractimpl]␊ + impl Foo {␊ + }␊ + ` diff --git a/packages/core/stellar/src/contract.test.ts.snap b/packages/core/stellar/src/contract.test.ts.snap new file mode 100644 index 000000000..b8896e034 Binary files /dev/null and b/packages/core/stellar/src/contract.test.ts.snap differ diff --git a/packages/core/stellar/src/contract.ts b/packages/core/stellar/src/contract.ts new file mode 100644 index 000000000..069cef822 --- /dev/null +++ b/packages/core/stellar/src/contract.ts @@ -0,0 +1,201 @@ +import { toIdentifier } from './utils/convert-strings'; + +export interface Contract { + license: string; + name: string; + useClauses: UseClause[]; + constructorCode: string[]; + constructorArgs: Argument[]; + implementedTraits: ImplementedTrait[]; + variables: Variable[]; + errors: Error[]; + ownable: boolean; +} + +export interface Error { + name: string; + num: number; +} + +export type Value = string | number | bigint | { lit: string } | { note: string; value: Value }; + +export interface UseClause { + containerPath: string; + name: string; + groupable?: boolean; + alias?: string; +} + +export interface BaseImplementedTrait { + name: string; + for: string; + tags: string[]; + section?: string; + /** + * Priority for which trait to print first. + * Lower numbers are higher priority, undefined is lowest priority. + */ + priority?: number; +} + +export interface ImplementedTrait extends BaseImplementedTrait { + functions: ContractFunction[]; + section?: string; +} + +export interface BaseFunction { + name: string; + args: Argument[]; + code: string[]; + returns?: string; +} + +export interface ContractFunction extends BaseFunction { + codeBefore?: string[]; + tag?: string; +} + +export interface Variable { + name: string; + type: string; + value: string; +} + +export interface Argument { + name: string; + type?: string; +} + +export class ContractBuilder implements Contract { + readonly name: string; + license = 'MIT'; + ownable = false; + + readonly constructorArgs: Argument[] = []; + readonly constructorCode: string[] = []; + + private implementedTraitsMap: Map = new Map(); + private variablesMap: Map = new Map(); + private useClausesMap: Map = new Map(); + private errorsMap: Map = new Map(); + + constructor(name: string) { + this.name = toIdentifier(name, true); + } + + get implementedTraits(): ImplementedTrait[] { + return [...this.implementedTraitsMap.values()]; + } + + get variables(): Variable[] { + return [...this.variablesMap.values()]; + } + + get useClauses(): UseClause[] { + return [...this.useClausesMap.values()]; + } + + get errors(): Error[] { + return [...this.errorsMap.values()]; + } + + addError(name: string, num: number): boolean { + if (this.errorsMap.has(name)) { + return false; + } else { + this.addUseClause('soroban_sdk', 'contracterror'); + this.errorsMap.set(name, { name, num }); + return true; + } + } + + addUseClause(containerPath: string, name: string, options?: { groupable?: boolean; alias?: string }): void { + // groupable defaults to true + const groupable = options?.groupable ?? true; + const alias = options?.alias ?? ''; + const uniqueName = alias.length > 0 ? alias : name; + const present = this.useClausesMap.has(uniqueName); + if (!present) { + this.useClausesMap.set(uniqueName, { containerPath, name, groupable, alias }); + } + } + + addVariable(variable: Variable): boolean { + if (this.variablesMap.has(variable.name)) { + return false; + } else { + this.variablesMap.set(variable.name, variable); + return true; + } + } + + addImplementedTrait(baseTrait: BaseImplementedTrait): ImplementedTrait { + const key = baseTrait.name; + const existingTrait = this.implementedTraitsMap.get(key); + if (existingTrait !== undefined) { + return existingTrait; + } else { + const t: ImplementedTrait = { + name: baseTrait.name, + for: baseTrait.for, + tags: [...baseTrait.tags], + functions: [], + section: baseTrait.section, + priority: baseTrait.priority, + }; + this.implementedTraitsMap.set(key, t); + return t; + } + } + + addFunction(baseTrait: BaseImplementedTrait, fn: BaseFunction): ContractFunction { + const t = this.addImplementedTrait(baseTrait); + + const signature = this.getFunctionSignature(fn); + + // Look for the existing function with the same signature and return it if found + for (let i = 0; i < t.functions.length; i++) { + const existingFn = t.functions[i]; + if (existingFn !== undefined && this.getFunctionSignature(existingFn) === signature) { + return existingFn; + } + } + + // Otherwise, add the function + const contractFn: ContractFunction = { + ...fn, + codeBefore: [], + }; + t.functions.push(contractFn); + return contractFn; + } + + private getFunctionSignature(fn: BaseFunction): string { + return [fn.name, '(', ...fn.args.map(a => a.name), ')'].join(''); + } + + addFunctionCodeBefore(baseTrait: BaseImplementedTrait, fn: BaseFunction, codeBefore: string[]): void { + this.addImplementedTrait(baseTrait); + const existingFn = this.addFunction(baseTrait, fn); + existingFn.codeBefore = [...(existingFn.codeBefore ?? []), ...codeBefore]; + } + + addFunctionTag(baseTrait: BaseImplementedTrait, fn: BaseFunction, tag: string): void { + this.addImplementedTrait(baseTrait); + const existingFn = this.addFunction(baseTrait, fn); + existingFn.tag = tag; + } + + addConstructorArgument(arg: Argument): void { + for (const existingArg of this.constructorArgs) { + if (existingArg.name == arg.name) { + return; + } + } + this.constructorArgs.push(arg); + } + + addConstructorCode(code: string): void { + this.constructorCode.push(code); + } +} diff --git a/packages/core/stellar/src/error.ts b/packages/core/stellar/src/error.ts new file mode 100644 index 000000000..a26433319 --- /dev/null +++ b/packages/core/stellar/src/error.ts @@ -0,0 +1,7 @@ +export type OptionsErrorMessages = { [prop in string]?: string }; + +export class OptionsError extends Error { + constructor(readonly messages: OptionsErrorMessages) { + super('Invalid options'); + } +} diff --git a/packages/core/stellar/src/fungible.test.ts b/packages/core/stellar/src/fungible.test.ts new file mode 100644 index 000000000..251efd2fc --- /dev/null +++ b/packages/core/stellar/src/fungible.test.ts @@ -0,0 +1,117 @@ +import test from 'ava'; + +import type { FungibleOptions } from './fungible'; +import { buildFungible, getInitialSupply } from './fungible'; +import { printContract } from './print'; + +import type { OptionsError } from '.'; +import { fungible } from '.'; + +function testFungible(title: string, opts: Partial) { + test(title, t => { + const c = buildFungible({ + name: 'MyToken', + symbol: 'MTK', + ...opts, + }); + t.snapshot(printContract(c)); + }); +} + +/** + * Tests external API for equivalence with internal API + */ +function testAPIEquivalence(title: string, opts?: FungibleOptions) { + test(title, t => { + t.is( + fungible.print(opts), + printContract( + buildFungible({ + name: 'MyToken', + symbol: 'MTK', + ...opts, + }), + ), + ); + }); +} + +testFungible('basic fungible', {}); + +testFungible('fungible burnable', { + burnable: true, +}); + +testFungible('fungible pausable', { + pausable: true, +}); + +testFungible('fungible burnable pausable', { + burnable: true, + pausable: true, +}); + +testFungible('fungible preminted', { + premint: '1000', +}); + +testFungible('fungible premint of 0', { + premint: '0', +}); + +testFungible('fungible mintable', { + mintable: true, +}); + +testFungible('fungible ownable', { + access: 'ownable', +}); + +testFungible('fungible full', { + premint: '2000', + access: 'ownable', + burnable: true, + mintable: true, + pausable: true, +}); + +testFungible('fungible full - complex name', { + name: 'Custom $ Token', + premint: '2000', + access: 'ownable', + burnable: true, + mintable: true, + pausable: true, +}); + +testAPIEquivalence('fungible API default'); + +testAPIEquivalence('fungible API basic', { name: 'CustomToken', symbol: 'CTK' }); + +testAPIEquivalence('fungible API full', { + name: 'CustomToken', + symbol: 'CTK', + premint: '2000', + burnable: true, + mintable: true, + pausable: true, +}); + +test('fungible API assert defaults', async t => { + t.is(fungible.print(fungible.defaults), fungible.print()); +}); + +test('fungible getInitialSupply', async t => { + t.is(getInitialSupply('1000', 18), '1000000000000000000000'); + t.is(getInitialSupply('1000.1', 18), '1000100000000000000000'); + t.is(getInitialSupply('.1', 18), '100000000000000000'); + t.is(getInitialSupply('.01', 2), '1'); + + let error = t.throws(() => getInitialSupply('.01', 1)); + t.not(error, undefined); + t.is((error as OptionsError).messages.premint, 'Too many decimals'); + + error = t.throws(() => getInitialSupply('1.1.1', 18)); + t.not(error, undefined); + t.is((error as OptionsError).messages.premint, 'Not a valid number'); +}); diff --git a/packages/core/stellar/src/fungible.test.ts.md b/packages/core/stellar/src/fungible.test.ts.md new file mode 100644 index 000000000..297bc2593 --- /dev/null +++ b/packages/core/stellar/src/fungible.test.ts.md @@ -0,0 +1,901 @@ +# Snapshot report for `src/fungible.test.ts` + +The actual snapshot is saved in `fungible.test.ts.snap`. + +Generated by [AVA](https://avajs.dev). + +## basic fungible + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{self as fungible, FungibleToken};␊ + use soroban_sdk::{Address, contract, contractimpl, Env, String, Symbol};␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ` + +## fungible burnable + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{␊ + self as fungible, burnable::FungibleBurnable, FungibleToken␊ + };␊ + use soroban_sdk::{Address, contract, contractimpl, Env, String, Symbol};␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ␊ + //␊ + // Extensions␊ + //␊ + ␊ + #[contractimpl]␊ + impl FungibleBurnable for MyToken {␊ + fn burn(e: &Env, from: Address, amount: i128) {␊ + fungible::burnable::burn(e, &from, amount);␊ + }␊ + ␊ + fn burn_from(e: &Env, spender: Address, from: Address, amount: i128) {␊ + fungible::burnable::burn_from(e, &spender, &from, amount);␊ + }␊ + }␊ + ` + +## fungible pausable + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{self as fungible, FungibleToken};␊ + use openzeppelin_pausable::{self as pausable, Pausable};␊ + use openzeppelin_pausable_macros::when_not_paused;␊ + use soroban_sdk::{␊ + Address, contract, contracterror, contractimpl, Env, panic_with_error, String, Symbol,␊ + symbol_short␊ + };␊ + ␊ + const OWNER: Symbol = symbol_short!("OWNER");␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contracterror]␊ + #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]␊ + #[repr(u32)]␊ + pub enum MyTokenError {␊ + Unauthorized = 1,␊ + }␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env, owner: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + e.storage().instance().set(&OWNER, &owner);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ␊ + //␊ + // Utils␊ + //␊ + ␊ + #[contractimpl]␊ + impl Pausable for MyToken {␊ + fn paused(e: &Env) -> bool {␊ + pausable::paused(e)␊ + }␊ + ␊ + fn pause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, MyTokenError::Unauthorized);␊ + }␊ + pausable::pause(e, &caller);␊ + }␊ + ␊ + fn unpause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, MyTokenError::Unauthorized);␊ + }␊ + pausable::unpause(e, &caller);␊ + }␊ + }␊ + ` + +## fungible burnable pausable + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{␊ + self as fungible, burnable::FungibleBurnable, FungibleToken␊ + };␊ + use openzeppelin_pausable::{self as pausable, Pausable};␊ + use openzeppelin_pausable_macros::when_not_paused;␊ + use soroban_sdk::{␊ + Address, contract, contracterror, contractimpl, Env, panic_with_error, String, Symbol,␊ + symbol_short␊ + };␊ + ␊ + const OWNER: Symbol = symbol_short!("OWNER");␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contracterror]␊ + #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]␊ + #[repr(u32)]␊ + pub enum MyTokenError {␊ + Unauthorized = 1,␊ + }␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env, owner: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + e.storage().instance().set(&OWNER, &owner);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ␊ + //␊ + // Extensions␊ + //␊ + ␊ + #[contractimpl]␊ + impl FungibleBurnable for MyToken {␊ + #[when_not_paused]␊ + fn burn(e: &Env, from: Address, amount: i128) {␊ + fungible::burnable::burn(e, &from, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn burn_from(e: &Env, spender: Address, from: Address, amount: i128) {␊ + fungible::burnable::burn_from(e, &spender, &from, amount);␊ + }␊ + }␊ + ␊ + //␊ + // Utils␊ + //␊ + ␊ + #[contractimpl]␊ + impl Pausable for MyToken {␊ + fn paused(e: &Env) -> bool {␊ + pausable::paused(e)␊ + }␊ + ␊ + fn pause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, MyTokenError::Unauthorized);␊ + }␊ + pausable::pause(e, &caller);␊ + }␊ + ␊ + fn unpause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, MyTokenError::Unauthorized);␊ + }␊ + pausable::unpause(e, &caller);␊ + }␊ + }␊ + ` + +## fungible preminted + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{␊ + self as fungible, FungibleToken, mintable::FungibleMintable␊ + };␊ + use soroban_sdk::{Address, contract, contractimpl, Env, String, Symbol};␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env, recipient: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + fungible::mintable::mint(e, &recipient, 1000000000000000000000);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ` + +## fungible premint of 0 + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{self as fungible, FungibleToken};␊ + use soroban_sdk::{Address, contract, contractimpl, Env, String, Symbol};␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ` + +## fungible mintable + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{␊ + self as fungible, FungibleToken, mintable::FungibleMintable␊ + };␊ + use soroban_sdk::{Address, contract, contractimpl, Env, String, Symbol, symbol_short};␊ + ␊ + const OWNER: Symbol = symbol_short!("OWNER");␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env, owner: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + e.storage().instance().set(&OWNER, &owner);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ␊ + //␊ + // Extensions␊ + //␊ + ␊ + #[contractimpl]␊ + impl FungibleMintable for MyToken {␊ + fn mint(e: &Env, account: Address, amount: i128) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + owner.require_auth();␊ + fungible::mintable::mint(e, &account, amount);␊ + }␊ + }␊ + ` + +## fungible ownable + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{self as fungible, FungibleToken};␊ + use soroban_sdk::{Address, contract, contractimpl, Env, String, Symbol, symbol_short};␊ + ␊ + const OWNER: Symbol = symbol_short!("OWNER");␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env, owner: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + e.storage().instance().set(&OWNER, &owner);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ` + +## fungible full + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{␊ + self as fungible, burnable::FungibleBurnable, FungibleToken, mintable::FungibleMintable␊ + };␊ + use openzeppelin_pausable::{self as pausable, Pausable};␊ + use openzeppelin_pausable_macros::when_not_paused;␊ + use soroban_sdk::{␊ + Address, contract, contracterror, contractimpl, Env, panic_with_error, String, Symbol,␊ + symbol_short␊ + };␊ + ␊ + const OWNER: Symbol = symbol_short!("OWNER");␊ + ␊ + #[contract]␊ + pub struct MyToken;␊ + ␊ + #[contracterror]␊ + #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]␊ + #[repr(u32)]␊ + pub enum MyTokenError {␊ + Unauthorized = 1,␊ + }␊ + ␊ + #[contractimpl]␊ + impl MyToken {␊ + pub fn __constructor(e: &Env, recipient: Address, owner: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "MyToken"), String::from_str(e, "MTK"));␊ + fungible::mintable::mint(e, &recipient, 2000000000000000000000);␊ + e.storage().instance().set(&OWNER, &owner);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for MyToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ␊ + //␊ + // Extensions␊ + //␊ + ␊ + #[contractimpl]␊ + impl FungibleBurnable for MyToken {␊ + #[when_not_paused]␊ + fn burn(e: &Env, from: Address, amount: i128) {␊ + fungible::burnable::burn(e, &from, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn burn_from(e: &Env, spender: Address, from: Address, amount: i128) {␊ + fungible::burnable::burn_from(e, &spender, &from, amount);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleMintable for MyToken {␊ + #[when_not_paused]␊ + fn mint(e: &Env, account: Address, amount: i128) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + owner.require_auth();␊ + fungible::mintable::mint(e, &account, amount);␊ + }␊ + }␊ + ␊ + //␊ + // Utils␊ + //␊ + ␊ + #[contractimpl]␊ + impl Pausable for MyToken {␊ + fn paused(e: &Env) -> bool {␊ + pausable::paused(e)␊ + }␊ + ␊ + fn pause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, MyTokenError::Unauthorized);␊ + }␊ + pausable::pause(e, &caller);␊ + }␊ + ␊ + fn unpause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, MyTokenError::Unauthorized);␊ + }␊ + pausable::unpause(e, &caller);␊ + }␊ + }␊ + ` + +## fungible full - complex name + +> Snapshot 1 + + `// SPDX-License-Identifier: MIT␊ + // Compatible with OpenZeppelin Stellar Soroban Contracts ^0.1.0␊ + ␊ + use openzeppelin_fungible_token::{␊ + self as fungible, burnable::FungibleBurnable, FungibleToken, mintable::FungibleMintable␊ + };␊ + use openzeppelin_pausable::{self as pausable, Pausable};␊ + use openzeppelin_pausable_macros::when_not_paused;␊ + use soroban_sdk::{␊ + Address, contract, contracterror, contractimpl, Env, panic_with_error, String, Symbol,␊ + symbol_short␊ + };␊ + ␊ + const OWNER: Symbol = symbol_short!("OWNER");␊ + ␊ + #[contract]␊ + pub struct CustomToken;␊ + ␊ + #[contracterror]␊ + #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]␊ + #[repr(u32)]␊ + pub enum CustomTokenError {␊ + Unauthorized = 1,␊ + }␊ + ␊ + #[contractimpl]␊ + impl CustomToken {␊ + pub fn __constructor(e: &Env, recipient: Address, owner: Address) {␊ + fungible::metadata::set_metadata(e, 18, String::from_str(e, "Custom $ Token"), String::from_str(e, "MTK"));␊ + fungible::mintable::mint(e, &recipient, 2000000000000000000000);␊ + e.storage().instance().set(&OWNER, &owner);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleToken for CustomToken {␊ + fn total_supply(e: &Env) -> i128 {␊ + fungible::total_supply(e)␊ + }␊ + ␊ + fn balance(e: &Env, account: Address) -> i128 {␊ + fungible::balance(e, &account)␊ + }␊ + ␊ + fn allowance(e: &Env, owner: Address, spender: Address) -> i128 {␊ + fungible::allowance(e, &owner, &spender)␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer(e: &Env, from: Address, to: Address, amount: i128) {␊ + fungible::transfer(e, &from, &to, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn transfer_from(e: &Env, spender: Address, from: Address, to: Address, amount: i128) {␊ + fungible::transfer_from(e, &spender, &from, &to, amount);␊ + }␊ + ␊ + fn approve(e: &Env, owner: Address, spender: Address, amount: i128, live_until_ledger: u32) {␊ + fungible::approve(e, &owner, &spender, amount, live_until_ledger);␊ + }␊ + ␊ + fn decimals(e: &Env) -> u32 {␊ + fungible::metadata::decimals(e)␊ + }␊ + ␊ + fn name(e: &Env) -> String {␊ + fungible::metadata::name(e)␊ + }␊ + ␊ + fn symbol(e: &Env) -> String {␊ + fungible::metadata::symbol(e)␊ + }␊ + }␊ + ␊ + //␊ + // Extensions␊ + //␊ + ␊ + #[contractimpl]␊ + impl FungibleBurnable for CustomToken {␊ + #[when_not_paused]␊ + fn burn(e: &Env, from: Address, amount: i128) {␊ + fungible::burnable::burn(e, &from, amount);␊ + }␊ + ␊ + #[when_not_paused]␊ + fn burn_from(e: &Env, spender: Address, from: Address, amount: i128) {␊ + fungible::burnable::burn_from(e, &spender, &from, amount);␊ + }␊ + }␊ + ␊ + #[contractimpl]␊ + impl FungibleMintable for CustomToken {␊ + #[when_not_paused]␊ + fn mint(e: &Env, account: Address, amount: i128) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + owner.require_auth();␊ + fungible::mintable::mint(e, &account, amount);␊ + }␊ + }␊ + ␊ + //␊ + // Utils␊ + //␊ + ␊ + #[contractimpl]␊ + impl Pausable for CustomToken {␊ + fn paused(e: &Env) -> bool {␊ + pausable::paused(e)␊ + }␊ + ␊ + fn pause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, CustomTokenError::Unauthorized);␊ + }␊ + pausable::pause(e, &caller);␊ + }␊ + ␊ + fn unpause(e: &Env, caller: Address) {␊ + let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");␊ + if owner != caller {␊ + panic_with_error!(e, CustomTokenError::Unauthorized);␊ + }␊ + pausable::unpause(e, &caller);␊ + }␊ + }␊ + ` diff --git a/packages/core/stellar/src/fungible.test.ts.snap b/packages/core/stellar/src/fungible.test.ts.snap new file mode 100644 index 000000000..437da73ab Binary files /dev/null and b/packages/core/stellar/src/fungible.test.ts.snap differ diff --git a/packages/core/stellar/src/fungible.ts b/packages/core/stellar/src/fungible.ts new file mode 100644 index 000000000..d5c5e0603 --- /dev/null +++ b/packages/core/stellar/src/fungible.ts @@ -0,0 +1,300 @@ +import type { Contract } from './contract'; +import { ContractBuilder } from './contract'; +import type { Access } from './set-access-control'; +import { requireAccessControl, setAccessControl } from './set-access-control'; +import { addPausable } from './add-pausable'; +import { defineFunctions } from './utils/define-functions'; +import type { CommonContractOptions } from './common-options'; +import { withCommonContractDefaults, getSelfArg } from './common-options'; +import { setInfo } from './set-info'; +import { OptionsError } from './error'; +import { contractDefaults as commonDefaults } from './common-options'; +import { printContract } from './print'; +import { toByteArray, toUint } from './utils/convert-strings'; + +export const defaults: Required = { + name: 'MyToken', + symbol: 'MTK', + burnable: false, + pausable: false, + premint: '0', + mintable: false, + access: commonDefaults.access, // TODO: Determine whether Access Control options should be visible in the UI before they are implemented as modules + info: commonDefaults.info, +} as const; + +export function printFungible(opts: FungibleOptions = defaults): string { + return printContract(buildFungible(opts)); +} + +export interface FungibleOptions extends CommonContractOptions { + name: string; + symbol: string; + burnable?: boolean; + pausable?: boolean; + premint?: string; + mintable?: boolean; +} + +function withDefaults(opts: FungibleOptions): Required { + return { + ...opts, + ...withCommonContractDefaults(opts), + burnable: opts.burnable ?? defaults.burnable, + pausable: opts.pausable ?? defaults.pausable, + premint: opts.premint || defaults.premint, + mintable: opts.mintable ?? defaults.mintable, + }; +} + +export function buildFungible(opts: FungibleOptions): Contract { + const c = new ContractBuilder(opts.name); + + const allOpts = withDefaults(opts); + + addBase(c, toByteArray(allOpts.name), toByteArray(allOpts.symbol), allOpts.pausable); + + if (allOpts.premint) { + addPremint(c, allOpts.premint); + } + + if (allOpts.pausable) { + addPausable(c, allOpts.access); + } + + if (allOpts.burnable) { + addBurnable(c, allOpts.pausable); + } + + if (allOpts.mintable) { + addMintable(c, allOpts.access, allOpts.pausable); + } + + setAccessControl(c, allOpts.access); + setInfo(c, allOpts.info); + + return c; +} + +function addBase(c: ContractBuilder, name: string, symbol: string, pausable: boolean) { + // Set metadata + c.addConstructorCode( + `fungible::metadata::set_metadata(e, 18, String::from_str(e, "${name}"), String::from_str(e, "${symbol}"));`, + ); + + // Set token functions + c.addUseClause('openzeppelin_fungible_token', 'self', { alias: 'fungible' }); + c.addUseClause('openzeppelin_fungible_token', 'FungibleToken'); + c.addUseClause('soroban_sdk', 'contract'); + c.addUseClause('soroban_sdk', 'contractimpl'); + c.addUseClause('soroban_sdk', 'Address'); + c.addUseClause('soroban_sdk', 'String'); + c.addUseClause('soroban_sdk', 'Env'); + c.addUseClause('soroban_sdk', 'Symbol'); + + const fungibleTokenTrait = { + name: 'FungibleToken', + for: c.name, + tags: ['contractimpl'], + }; + + c.addFunction(fungibleTokenTrait, functions.total_supply); + c.addFunction(fungibleTokenTrait, functions.balance); + c.addFunction(fungibleTokenTrait, functions.allowance); + c.addFunction(fungibleTokenTrait, functions.transfer); + c.addFunction(fungibleTokenTrait, functions.transfer_from); + c.addFunction(fungibleTokenTrait, functions.approve); + c.addFunction(fungibleTokenTrait, functions.decimals); + c.addFunction(fungibleTokenTrait, functions.name); + c.addFunction(fungibleTokenTrait, functions.symbol); + + if (pausable) { + c.addUseClause('openzeppelin_pausable_macros', 'when_not_paused'); + c.addFunctionTag(fungibleTokenTrait, functions.transfer, 'when_not_paused'); + c.addFunctionTag(fungibleTokenTrait, functions.transfer_from, 'when_not_paused'); + } +} + +function addBurnable(c: ContractBuilder, pausable: boolean) { + c.addUseClause('openzeppelin_fungible_token', 'burnable::FungibleBurnable'); + c.addUseClause('soroban_sdk', 'Address'); + + const fungibleBurnableTrait = { + name: 'FungibleBurnable', + for: c.name, + tags: ['contractimpl'], + section: 'Extensions', + }; + + c.addFunction(fungibleBurnableTrait, functions.burn); + c.addFunction(fungibleBurnableTrait, functions.burn_from); + + if (pausable) { + c.addUseClause('openzeppelin_pausable_macros', 'when_not_paused'); + c.addFunctionTag(fungibleBurnableTrait, functions.burn, 'when_not_paused'); + c.addFunctionTag(fungibleBurnableTrait, functions.burn_from, 'when_not_paused'); + } +} + +export const premintPattern = /^(\d*\.?\d*)$/; + +function addPremint(c: ContractBuilder, amount: string) { + if (amount !== undefined && amount !== '0') { + if (!premintPattern.test(amount)) { + throw new OptionsError({ + premint: 'Not a valid number', + }); + } + + // TODO: handle signed int? + const premintAbsolute = toUint(getInitialSupply(amount, 18), 'premint', 'u128'); + + c.addUseClause('openzeppelin_fungible_token', 'mintable::FungibleMintable'); + c.addUseClause('soroban_sdk', 'Address'); + + c.addConstructorArgument({ name: 'recipient', type: 'Address' }); + c.addConstructorCode(`fungible::mintable::mint(e, &recipient, ${premintAbsolute});`); + } +} + +/** + * Calculates the initial supply that would be used in an Fungible contract based on a given premint amount and number of decimals. + * + * @param premint Premint amount in token units, may be fractional + * @param decimals The number of decimals in the token + * @returns `premint` with zeros padded or removed based on `decimals`. + * @throws OptionsError if `premint` has more than one decimal character or is more precise than allowed by the `decimals` argument. + */ +export function getInitialSupply(premint: string, decimals: number): string { + let result; + const premintSegments = premint.split('.'); + if (premintSegments.length > 2) { + throw new OptionsError({ + premint: 'Not a valid number', + }); + } else { + const firstSegment = premintSegments[0] ?? ''; + let lastSegment = premintSegments[1] ?? ''; + if (decimals > lastSegment.length) { + try { + lastSegment += '0'.repeat(decimals - lastSegment.length); + } catch { + // .repeat gives an error if decimals number is too large + throw new OptionsError({ + premint: 'Decimals number too large', + }); + } + } else if (decimals < lastSegment.length) { + throw new OptionsError({ + premint: 'Too many decimals', + }); + } + // concat segments without leading zeros + result = firstSegment.concat(lastSegment).replace(/^0+/, ''); + } + if (result.length === 0) { + result = '0'; + } + return result; +} + +function addMintable(c: ContractBuilder, access: Access, pausable: boolean) { + c.addUseClause('openzeppelin_fungible_token', 'mintable::FungibleMintable'); + + const fungibleMintableTrait = { + name: 'FungibleMintable', + for: c.name, + tags: ['contractimpl'], + section: 'Extensions', + }; + + c.addFunction(fungibleMintableTrait, functions.mint); + + requireAccessControl(c, fungibleMintableTrait, functions.mint, access); + + if (pausable) { + c.addFunctionTag(fungibleMintableTrait, functions.mint, 'when_not_paused'); + } +} + +const functions = defineFunctions({ + // Token Functions + total_supply: { + args: [getSelfArg()], + returns: 'i128', + code: ['fungible::total_supply(e)'], + }, + balance: { + args: [getSelfArg(), { name: 'account', type: 'Address' }], + returns: 'i128', + code: ['fungible::balance(e, &account)'], + }, + allowance: { + args: [getSelfArg(), { name: 'owner', type: 'Address' }, { name: 'spender', type: 'Address' }], + returns: 'i128', + code: ['fungible::allowance(e, &owner, &spender)'], + }, + transfer: { + args: [ + getSelfArg(), + { name: 'from', type: 'Address' }, + { name: 'to', type: 'Address' }, + { name: 'amount', type: 'i128' }, + ], + code: ['fungible::transfer(e, &from, &to, amount)'], + }, + transfer_from: { + args: [ + getSelfArg(), + { name: 'spender', type: 'Address' }, + { name: 'from', type: 'Address' }, + { name: 'to', type: 'Address' }, + { name: 'amount', type: 'i128' }, + ], + code: ['fungible::transfer_from(e, &spender, &from, &to, amount)'], + }, + approve: { + args: [ + getSelfArg(), + { name: 'owner', type: 'Address' }, + { name: 'spender', type: 'Address' }, + { name: 'amount', type: 'i128' }, + { name: 'live_until_ledger', type: 'u32' }, + ], + code: ['fungible::approve(e, &owner, &spender, amount, live_until_ledger)'], + }, + decimals: { + args: [getSelfArg()], + returns: 'u32', + code: ['fungible::metadata::decimals(e)'], + }, + name: { + args: [getSelfArg()], + returns: 'String', + code: ['fungible::metadata::name(e)'], + }, + symbol: { + args: [getSelfArg()], + returns: 'String', + code: ['fungible::metadata::symbol(e)'], + }, + + // Extensions + burn: { + args: [getSelfArg(), { name: 'from', type: 'Address' }, { name: 'amount', type: 'i128' }], + code: ['fungible::burnable::burn(e, &from, amount)'], + }, + burn_from: { + args: [ + getSelfArg(), + { name: 'spender', type: 'Address' }, + { name: 'from', type: 'Address' }, + { name: 'amount', type: 'i128' }, + ], + code: ['fungible::burnable::burn_from(e, &spender, &from, amount)'], + }, + mint: { + args: [getSelfArg(), { name: 'account', type: 'Address' }, { name: 'amount', type: 'i128' }], + code: ['fungible::mintable::mint(e, &account, amount);'], + }, +}); diff --git a/packages/core/stellar/src/generate/alternatives.ts b/packages/core/stellar/src/generate/alternatives.ts new file mode 100644 index 000000000..b66e733cf --- /dev/null +++ b/packages/core/stellar/src/generate/alternatives.ts @@ -0,0 +1,32 @@ +type Blueprint = Record; + +type Alternatives = { + [k in keyof B]: B[k][number]; +}; + +export function* generateAlternatives(blueprint: B): Generator> { + const entries = Object.entries(blueprint).map(([key, values]) => ({ + key, + values, + current: 0, + limit: values.length, + })); + + for (; !done(); advance()) { + yield Object.fromEntries(entries.map(e => [e.key, e.values[e.current % e.limit]])) as Alternatives; + } + + function done() { + const last = entries[entries.length - 1]; + return last?.current === last?.limit; + } + + function advance() { + for (const e of entries) { + e.current = (e.current % e.limit) + 1; + if (e.current < e.limit) { + break; + } + } + } +} diff --git a/packages/core/stellar/src/generate/fungible.ts b/packages/core/stellar/src/generate/fungible.ts new file mode 100644 index 000000000..4aa2b4d24 --- /dev/null +++ b/packages/core/stellar/src/generate/fungible.ts @@ -0,0 +1,21 @@ +import type { FungibleOptions } from '../fungible'; +import { accessOptions } from '../set-access-control'; +import { infoOptions } from '../set-info'; +import { generateAlternatives } from './alternatives'; + +const booleans = [true, false]; + +const blueprint = { + name: ['MyToken'], + symbol: ['MTK'], + burnable: booleans, + pausable: booleans, + mintable: booleans, + premint: ['1'], + access: accessOptions, + info: infoOptions, +}; + +export function* generateFungibleOptions(): Generator> { + yield* generateAlternatives(blueprint); +} diff --git a/packages/core/stellar/src/generate/sources.ts b/packages/core/stellar/src/generate/sources.ts new file mode 100644 index 000000000..0b0e24a3e --- /dev/null +++ b/packages/core/stellar/src/generate/sources.ts @@ -0,0 +1,75 @@ +import { promises as fs } from 'fs'; +import path from 'path'; +import crypto from 'crypto'; + +import { generateFungibleOptions } from './fungible'; +import type { GenericOptions, KindedOptions } from '../build-generic'; +import { buildGeneric } from '../build-generic'; +import { printContract } from '../print'; +import { OptionsError } from '../error'; +import type { Contract } from '../contract'; + +type Kind = keyof KindedOptions; + +export function* generateOptions(kind?: Kind): Generator { + if (!kind || kind === 'Fungible') { + for (const kindOpts of generateFungibleOptions()) { + yield { kind: 'Fungible', ...kindOpts }; + } + } +} + +interface GeneratedContract { + id: string; + options: GenericOptions; + contract: Contract; +} + +interface GeneratedSource extends GeneratedContract { + source: string; +} + +function generateContractSubset(kind?: Kind): GeneratedContract[] { + const contracts = []; + + for (const options of generateOptions(kind)) { + const id = crypto.createHash('sha1').update(JSON.stringify(options)).digest().toString('hex'); + + try { + const contract = buildGeneric(options); + contracts.push({ id, options, contract }); + } catch (e: unknown) { + if (e instanceof OptionsError) { + continue; + } else { + throw e; + } + } + } + + return contracts; +} + +export function* generateSources(uniqueName?: boolean, kind?: Kind): Generator { + let counter = 1; + for (const c of generateContractSubset(kind)) { + if (uniqueName) { + c.contract.name = `Contract${counter++}`; + } + const source = printContract(c.contract); + yield { ...c, source }; + } +} + +export async function writeGeneratedSources(dir: string, uniqueName?: boolean, kind?: Kind): Promise { + await fs.mkdir(dir, { recursive: true }); + const contractNames = []; + + for (const { id, contract, source } of generateSources(uniqueName, kind)) { + const name = uniqueName ? contract.name : id; + await fs.writeFile(path.format({ dir, name, ext: '.rs' }), source); + contractNames.push(name); + } + + return contractNames; +} diff --git a/packages/core/stellar/src/index.ts b/packages/core/stellar/src/index.ts new file mode 100644 index 000000000..017fee450 --- /dev/null +++ b/packages/core/stellar/src/index.ts @@ -0,0 +1,24 @@ +export type { GenericOptions, KindedOptions } from './build-generic'; +export { buildGeneric } from './build-generic'; + +export type { Contract } from './contract'; +export { ContractBuilder } from './contract'; + +export { printContract } from './print'; + +export type { Access } from './set-access-control'; +export type { Info } from './set-info'; + +export { premintPattern } from './fungible'; + +export { defaults as infoDefaults } from './set-info'; + +export type { OptionsErrorMessages } from './error'; +export { OptionsError } from './error'; + +export type { Kind } from './kind'; +export { sanitizeKind } from './kind'; + +export { contractsVersion, contractsVersionTag, compatibleContractsSemver } from './utils/version'; + +export { fungible } from './api'; diff --git a/packages/core/stellar/src/kind.ts b/packages/core/stellar/src/kind.ts new file mode 100644 index 000000000..0418f12b6 --- /dev/null +++ b/packages/core/stellar/src/kind.ts @@ -0,0 +1,26 @@ +import type { GenericOptions } from './build-generic'; + +export type Kind = GenericOptions['kind']; + +export function sanitizeKind(kind: unknown): Kind { + if (typeof kind === 'string') { + const sanitized = kind.replace(/^(ERC|.)/i, c => c.toUpperCase()); + if (isKind(sanitized)) { + return sanitized; + } + } + return 'Fungible'; +} + +function isKind(value: Kind | T): value is Kind { + switch (value) { + case 'Fungible': + return true; + + default: { + // Static assert that we've checked all kinds. + const _: T = value; + return false; + } + } +} diff --git a/packages/core/stellar/src/print.ts b/packages/core/stellar/src/print.ts new file mode 100644 index 000000000..1087b3fa3 --- /dev/null +++ b/packages/core/stellar/src/print.ts @@ -0,0 +1,305 @@ +import type { Contract, Argument, ContractFunction, ImplementedTrait, UseClause } from './contract'; + +import type { Lines } from './utils/format-lines'; +import { formatLines, spaceBetween } from './utils/format-lines'; +import { getSelfArg } from './common-options'; +import { compatibleContractsSemver } from './utils/version'; + +const DEFAULT_SECTION = '1. with no section'; +const STANDALONE_IMPORTS_GROUP = 'Standalone Imports'; +const MAX_USE_CLAUSE_LINE_LENGTH = 90; +const TAB = ' '; + +export function printContract(contract: Contract): string { + return formatLines( + ...spaceBetween( + [ + `// SPDX-License-Identifier: ${contract.license}`, + `// Compatible with OpenZeppelin Stellar Soroban Contracts ${compatibleContractsSemver}`, + ], + spaceBetween( + printUseClauses(contract), + printVariables(contract), + printContractStruct(contract), + printContractErrors(contract), + printContractFunctions(contract), + printImplementedTraits(contract), + ), + ), + ); +} + +function printContractStruct(contract: Contract): Lines[] { + return ['#[contract]', `pub struct ${contract.name};`]; +} + +function printContractErrors(contract: Contract): Lines[] { + if (contract.errors.length === 0) { + return []; + } + return [ + '#[contracterror]', + '#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]', + '#[repr(u32)]', + `pub enum ${contract.name}Error {`, + contract.errors.map(e => `${e.name} = ${e.num},`), + `}`, + ]; +} + +function withSemicolons(lines: string[]): string[] { + return lines.map(line => (line.endsWith(';') ? line : line + ';')); +} + +function printVariables(contract: Contract): string[] { + return withSemicolons(contract.variables.map(v => `const ${v.name}: ${v.type} = ${v.value}`)); +} + +function printUseClauses(contract: Contract): Lines[] { + const useClauses = sortUseClauses(contract); + + // group by containerPath + const grouped = useClauses.reduce((result: { [containerPath: string]: UseClause[] }, useClause: UseClause) => { + if (useClause.groupable) { + (result[useClause.containerPath] = result[useClause.containerPath] || []).push(useClause); + } else { + (result[STANDALONE_IMPORTS_GROUP] = result[STANDALONE_IMPORTS_GROUP] || []).push(useClause); + } + return result; + }, {}); + + const lines = Object.entries(grouped).flatMap(([groupName, group]) => getLinesFromUseClausesGroup(group, groupName)); + return lines.flatMap(line => splitLongUseClauseLine(line.toString())); +} + +function getLinesFromUseClausesGroup(group: UseClause[], groupName: string): Lines[] { + const lines = []; + if (groupName === STANDALONE_IMPORTS_GROUP) { + for (const useClause of group) { + lines.push(`use ${useClause.containerPath}::${nameWithAlias(useClause)};`); + } + } else { + if (group.length == 1) { + lines.push(`use ${groupName}::${nameWithAlias(group[0]!)};`); + } else if (group.length > 1) { + const names = group.map(useClause => nameWithAlias(useClause)).join(', '); + lines.push(`use ${groupName}::{${names}};`); + } + } + return lines; +} + +function nameWithAlias(useClause: UseClause): string { + return useClause.alias ? `${useClause.name} as ${useClause.alias}` : useClause.name; +} + +// TODO: remove this when we can use a formatting js library +function splitLongUseClauseLine(line: string): Lines[] { + const lines = []; + + const containsBraces = line.indexOf('{') !== -1; + if (containsBraces && line.length > MAX_USE_CLAUSE_LINE_LENGTH) { + // split at the first brace + lines.push(line.slice(0, line.indexOf('{') + 1)); + lines.push(...splitLongLineInner(line.slice(line.indexOf('{') + 1, -2))); + lines.push('};'); + } else { + lines.push(line); + } + return lines; +} + +function splitLongLineInner(line: string): Lines[] { + const lines = []; + if (line.length > MAX_USE_CLAUSE_LINE_LENGTH) { + const max_accessible_string = line.slice(0, MAX_USE_CLAUSE_LINE_LENGTH); + const lastCommaIndex = max_accessible_string.lastIndexOf(','); + if (lastCommaIndex !== -1) { + lines.push(TAB + max_accessible_string.slice(0, lastCommaIndex + 1)); + lines.push(...splitLongLineInner(line.slice(lastCommaIndex + 2))); + } else { + lines.push(TAB + max_accessible_string); + } + } else { + lines.push(TAB + line); + } + return lines; +} + +function sortUseClauses(contract: Contract): UseClause[] { + return contract.useClauses.sort((a, b) => { + if (a.containerPath === b.containerPath) { + if (a.name === 'self' && b.name !== 'self') { + return -1; + } else if (a.name !== 'self' && b.name === 'self') { + return 1; + } + return nameWithAlias(a).localeCompare(nameWithAlias(b)); + } else { + return a.containerPath.localeCompare(b.containerPath); + } + }); +} + +function printImplementedTraits(contract: Contract): Lines[] { + // sort first by priority, then number of tags, then name + const sortedTraits = contract.implementedTraits.sort((a, b) => { + if (a.priority !== b.priority) { + return (a.priority ?? Infinity) - (b.priority ?? Infinity); + } + if (a.tags.length !== b.tags.length) { + return a.tags.length - b.tags.length; + } + return a.name.localeCompare(b.name); + }); + + // group by section + const grouped = sortedTraits.reduce( + (result: { [section: string]: ImplementedTrait[] }, current: ImplementedTrait) => { + // default to no section + const section = current.section ?? DEFAULT_SECTION; + (result[section] = result[section] || []).push(current); + return result; + }, + {}, + ); + + const sections = Object.entries(grouped) + .sort((a, b) => a[0].localeCompare(b[0])) + .map(([section, impls]) => printImplementedTraitsSection(section, impls as ImplementedTrait[])); + + return spaceBetween(...sections); +} + +function printImplementedTraitsSection(section: string, impls: ImplementedTrait[]): Lines[] { + const lines = []; + const isDefaultSection = section === DEFAULT_SECTION; + if (!isDefaultSection) { + lines.push('//'); + lines.push(`// ${section}`); + lines.push('//'); + } + impls.forEach((trait, index) => { + if (index > 0 || !isDefaultSection) { + lines.push(''); + } + lines.push(...printImplementedTrait(trait)); + }); + return lines; +} + +function printImplementedTrait(trait: ImplementedTrait): Lines[] { + const implLines = []; + implLines.push(...trait.tags.map(t => `#[${t}]`)); + implLines.push(`impl ${trait.name} for ${trait.for} {`); + const fns = trait.functions.map(fn => printFunction(fn)); + implLines.push(spaceBetween(...fns)); + implLines.push('}'); + return implLines; +} + +function printFunction(fn: ContractFunction): Lines[] { + const head = `fn ${fn.name}`; + const args = fn.args.map(a => printArgument(a)); + + const codeLines = fn.codeBefore?.concat(fn.code) ?? fn.code; + for (let i = 0; i < codeLines.length; i++) { + const line = codeLines[i]; + const shouldEndWithSemicolon = i < codeLines.length - 1 || fn.returns === undefined; + if (line !== undefined && line.length > 0) { + if (shouldEndWithSemicolon && !['{', '}', ';'].includes(line.charAt(line.length - 1))) { + codeLines[i] += ';'; + } else if (!shouldEndWithSemicolon && line.endsWith(';')) { + codeLines[i] = line.slice(0, line.length - 1); + } + } + } + + return printFunction2(head, args, fn.tag, fn.returns, undefined, codeLines); +} + +function printContractFunctions(contract: Contract): Lines[] { + const implLines = []; + implLines.push('#[contractimpl]'); + implLines.push(`impl ${contract.name} {`); + implLines.push(printConstructor(contract)); + implLines.push('}'); + return implLines; +} + +function printConstructor(contract: Contract): Lines[] { + if (contract.constructorCode.length > 0) { + const head = 'pub fn __constructor'; + const args = [getSelfArg(), ...contract.constructorArgs]; + + const body = spaceBetween(withSemicolons(contract.constructorCode)); + + const constructor = printFunction2( + head, + args.map(a => printArgument(a)), + undefined, + undefined, + undefined, + body, + ); + return constructor; + } else { + return []; + } +} + +// generic for functions and constructors +// kindedName = 'fn foo' +function printFunction2( + kindedName: string, + args: string[], + tag: string | undefined, + returns: string | undefined, + returnLine: string | undefined, + code: Lines[], +): Lines[] { + const fn = []; + + if (tag !== undefined) { + fn.push(`#[${tag}]`); + } + + let accum = `${kindedName}(`; + + if (args.length > 0) { + const formattedArgs = args.join(', '); + if (formattedArgs.length > 80) { + fn.push(accum); + accum = ''; + // print each arg in a separate line + fn.push(args.map(arg => `${arg},`)); + } else { + accum += `${formattedArgs}`; + } + } + accum += ')'; + + if (returns === undefined) { + accum += ' {'; + } else { + accum += ` -> ${returns} {`; + } + + fn.push(accum); + fn.push(code); + if (returnLine !== undefined) { + fn.push([returnLine]); + } + fn.push('}'); + + return fn; +} + +function printArgument(arg: Argument): string { + if (arg.type !== undefined) { + const type = arg.type; + return `${arg.name}: ${type}`; + } else { + return `${arg.name}`; + } +} diff --git a/packages/core/stellar/src/set-access-control.ts b/packages/core/stellar/src/set-access-control.ts new file mode 100644 index 000000000..4f5e998c3 --- /dev/null +++ b/packages/core/stellar/src/set-access-control.ts @@ -0,0 +1,73 @@ +import type { BaseFunction, BaseImplementedTrait, ContractBuilder } from './contract'; + +export const accessOptions = [false, 'ownable'] as const; +export const DEFAULT_ACCESS_CONTROL = 'ownable'; + +export type Access = (typeof accessOptions)[number]; + +/** + * Sets access control for the contract via constructor args. + */ +export function setAccessControl(c: ContractBuilder, access: Access): void { + switch (access) { + case false: + break; + case 'ownable': { + if (!c.ownable) { + c.ownable = true; + c.addUseClause('soroban_sdk', 'symbol_short'); + c.addUseClause('soroban_sdk', 'Symbol'); + c.addVariable({ name: 'OWNER', type: 'Symbol', value: `symbol_short!("OWNER")` }); + c.addConstructorArgument({ name: 'owner', type: 'Address' }); + c.addConstructorCode('e.storage().instance().set(&OWNER, &owner);'); + } + break; + } + default: { + const _: never = access; + throw new Error('Unknown value for `access`'); + } + } +} + +/** + * Enables access control for the contract and restricts the given function with access control. + * + * If `caller` is provided, requires that the caller is the owner. Otherwise, requires that the owner is authorized. + */ +export function requireAccessControl( + c: ContractBuilder, + trait: BaseImplementedTrait, + fn: BaseFunction, + access: Access, + caller?: string, +): void { + if (access === false) { + access = DEFAULT_ACCESS_CONTROL; + } + setAccessControl(c, access); + + switch (access) { + case 'ownable': { + c.addUseClause('soroban_sdk', 'Address'); + const getOwner = 'let owner: Address = e.storage().instance().get(&OWNER).expect("owner should be set");'; + if (caller) { + c.addUseClause('soroban_sdk', 'panic_with_error'); + c.addError('Unauthorized', 1); // TODO: Ensure there are no conflicts in error codes + c.addFunctionCodeBefore(trait, fn, [ + getOwner, + 'if owner != caller {', + ` panic_with_error!(e, ${c.name}Error::Unauthorized)`, + '}', + ]); + } else { + c.addFunctionCodeBefore(trait, fn, [getOwner, 'owner.require_auth();']); + } + break; + } + default: { + const _: never = access; + throw new Error('Unknown value for `access`'); + } + } +} diff --git a/packages/core/stellar/src/set-info.ts b/packages/core/stellar/src/set-info.ts new file mode 100644 index 000000000..232662ae8 --- /dev/null +++ b/packages/core/stellar/src/set-info.ts @@ -0,0 +1,17 @@ +import type { ContractBuilder } from './contract'; + +export const infoOptions = [{}, { license: 'WTFPL' }] as const; + +export const defaults: Info = { license: 'MIT' }; + +export type Info = { + license?: string; +}; + +export function setInfo(c: ContractBuilder, info: Info): void { + const { license } = info; + + if (license) { + c.license = license; + } +} diff --git a/packages/core/stellar/src/test.ts b/packages/core/stellar/src/test.ts new file mode 100644 index 000000000..9a05e5450 --- /dev/null +++ b/packages/core/stellar/src/test.ts @@ -0,0 +1,26 @@ +import { promises as fs } from 'fs'; +import os from 'os'; +import type { TestFn, ExecutionContext } from 'ava'; +import _test from 'ava'; +import path from 'path'; + +import { writeGeneratedSources } from './generate/sources'; +import type { KindedOptions } from './build-generic'; + +interface Context { + generatedSourcesPath: string; +} + +const test = _test as TestFn; + +test.serial('fungible result generated', async t => { + await testGenerate(t, 'Fungible'); +}); + +async function testGenerate(t: ExecutionContext, kind: keyof KindedOptions) { + const generatedSourcesPath = path.join(os.tmpdir(), 'oz-wizard-stellar'); + await fs.rm(generatedSourcesPath, { force: true, recursive: true }); + await writeGeneratedSources(generatedSourcesPath, true, kind); + + t.pass(); +} diff --git a/packages/core/stellar/src/utils/convert-strings.test.ts b/packages/core/stellar/src/utils/convert-strings.test.ts new file mode 100644 index 000000000..1e3180a71 --- /dev/null +++ b/packages/core/stellar/src/utils/convert-strings.test.ts @@ -0,0 +1,72 @@ +import test from 'ava'; + +import { toIdentifier, toByteArray } from './convert-strings'; +import { OptionsError } from '../error'; + +test('identifier - unmodified', t => { + t.is(toIdentifier('abc'), 'abc'); +}); + +test('identifier - remove leading specials', t => { + t.is(toIdentifier('--abc'), 'abc'); +}); + +test('identifier - remove specials and upcase next char', t => { + t.is(toIdentifier('abc-def'), 'abcDef'); + t.is(toIdentifier('abc--def'), 'abcDef'); +}); + +test('identifier - capitalize', t => { + t.is(toIdentifier('abc', true), 'Abc'); +}); + +test('identifier - remove accents', t => { + t.is(toIdentifier('ábc'), 'abc'); +}); + +test('identifier - underscores', t => { + t.is(toIdentifier('_abc_'), '_abc_'); +}); + +test('identifier - remove starting numbers', t => { + t.is(toIdentifier('123abc456'), 'abc456'); +}); + +test('identifier - empty string', t => { + const error = t.throws(() => toIdentifier(''), { instanceOf: OptionsError }); + t.is(error.messages.name, 'Identifier is empty or does not have valid characters'); +}); + +test('identifier - no valid chars', t => { + const error = t.throws(() => toIdentifier('123'), { instanceOf: OptionsError }); + t.is(error.messages.name, 'Identifier is empty or does not have valid characters'); +}); + +test('toByteArray - unmodified', t => { + t.is(toByteArray('abc'), 'abc'); +}); + +test('toByteArray - remove accents', t => { + t.is(toByteArray('ábc'), 'abc'); +}); + +test('toByteArray - remove non-ascii-printable characters', t => { + t.is(toByteArray('abc😀'), 'abc'); +}); + +test('toByteArray - escape double quote', t => { + t.is(toByteArray('abc"def'), 'abc\\"def'); +}); + +test('toByteArray - does not escape single quote', t => { + t.is(toByteArray("abc'def"), "abc'def"); +}); + +test('toByteArray - escape backslash', t => { + t.is(toByteArray('abc\\def'), 'abc\\\\def'); +}); + +test('more than 31 characters', t => { + t.is(toByteArray('A234567890123456789012345678901'), 'A234567890123456789012345678901'); + t.is(toByteArray('A2345678901234567890123456789012'), 'A2345678901234567890123456789012'); +}); diff --git a/packages/core/stellar/src/utils/convert-strings.ts b/packages/core/stellar/src/utils/convert-strings.ts new file mode 100644 index 000000000..b0a3203af --- /dev/null +++ b/packages/core/stellar/src/utils/convert-strings.ts @@ -0,0 +1,83 @@ +import { OptionsError } from '../error'; + +// TODO: Review and convert these to properly handle language restrictions for Stellar + +/** + * Converts to an identifier according to the rules in https://docs.cairo-lang.org/language_constructs/identifiers.html + */ +export function toIdentifier(str: string, capitalize = false): string { + const result = str + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') // remove accents + .replace(/^[^a-zA-Z_]+/, '') + .replace(/^(.)/, c => (capitalize ? c.toUpperCase() : c)) + .replace(/[^\w]+(.?)/g, (_, c) => c.toUpperCase()); + + if (result.length === 0) { + throw new OptionsError({ + name: 'Identifier is empty or does not have valid characters', + }); + } else { + return result; + } +} + +/** + * Converts to a ByteArray compatible string literal + */ +export function toByteArray(str: string): string { + return str + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') // remove accents + .replace(/[^\x20-\x7E]+/g, '') // remove non-ascii-printable characters + .replace(/(\\|")/g, (_, c) => '\\' + c); // escape backslash or double quotes +} + +function maxValueOfUint(bits: number): bigint { + if (bits <= 0) { + throw new Error(`Number of bits must be positive (actual '${bits}').`); + } + if (bits % 8 !== 0) { + throw new Error(`The number of bits must be a multiple of 8 (actual '${bits}').`); + } + const bytes = bits / 8; + return BigInt('0x' + 'ff'.repeat(bytes)); +} + +const UINT_MAX_VALUES = { + u8: maxValueOfUint(8), + u16: maxValueOfUint(16), + u32: maxValueOfUint(32), + u64: maxValueOfUint(64), + u128: maxValueOfUint(128), + u256: maxValueOfUint(256), +} as const; + +export type UintType = keyof typeof UINT_MAX_VALUES; + +/** + * Checks that a string/number value is a valid `uint` value and converts it to bigint + */ +export function toUint(value: number | string, field: string, type: UintType): bigint { + const valueAsStr = value.toString(); + const isValidNumber = /^\d+$/.test(valueAsStr); + if (!isValidNumber) { + throw new OptionsError({ + [field]: 'Not a valid number', + }); + } + const numValue = BigInt(valueAsStr); + if (numValue > UINT_MAX_VALUES[type]) { + throw new OptionsError({ + [field]: `Value is greater than ${type} max value`, + }); + } + return numValue; +} + +/** + * Checks that a string/number value is a valid `uint` value + */ +export function validateUint(value: number | string, field: string, type: UintType): void { + const _ = toUint(value, field, type); +} diff --git a/packages/core/stellar/src/utils/define-functions.ts b/packages/core/stellar/src/utils/define-functions.ts new file mode 100644 index 000000000..3c89e6c76 --- /dev/null +++ b/packages/core/stellar/src/utils/define-functions.ts @@ -0,0 +1,9 @@ +import type { BaseFunction } from '../contract'; + +type ImplicitNameFunction = Omit; + +export function defineFunctions(fns: Record): Record; + +export function defineFunctions(fns: Record): Record { + return Object.fromEntries(Object.entries(fns).map(([name, fn]) => [name, Object.assign({ name }, fn)])); +} diff --git a/packages/core/stellar/src/utils/format-lines.ts b/packages/core/stellar/src/utils/format-lines.ts new file mode 100644 index 000000000..52af7ab52 --- /dev/null +++ b/packages/core/stellar/src/utils/format-lines.ts @@ -0,0 +1,26 @@ +export type Lines = string | typeof whitespace | Lines[]; + +const whitespace = Symbol('whitespace'); + +export function formatLines(...lines: Lines[]): string { + return [...indentEach(0, lines)].join('\n') + '\n'; +} + +function* indentEach(indent: number, lines: Lines[]): Generator { + for (const line of lines) { + if (line === whitespace) { + yield ''; + } else if (Array.isArray(line)) { + yield* indentEach(indent + 1, line); + } else { + yield ' '.repeat(indent) + line; + } + } +} + +export function spaceBetween(...lines: Lines[][]): Lines[] { + return lines + .filter(l => l.length > 0) + .flatMap(l => [whitespace, ...l]) + .slice(1); +} diff --git a/packages/core/stellar/src/utils/sorted-by.ts b/packages/core/stellar/src/utils/sorted-by.ts new file mode 100644 index 000000000..c865494bb --- /dev/null +++ b/packages/core/stellar/src/utils/sorted-by.ts @@ -0,0 +1,3 @@ +export function sortedBy(xs: Iterable, fn: (x: T) => number): T[] { + return Array.from(xs).sort((a, b) => fn(a) - fn(b)); +} diff --git a/packages/core/stellar/src/utils/version.test.ts b/packages/core/stellar/src/utils/version.test.ts new file mode 100644 index 000000000..735d62527 --- /dev/null +++ b/packages/core/stellar/src/utils/version.test.ts @@ -0,0 +1,13 @@ +import test from 'ava'; + +import semver from 'semver'; + +import { contractsVersion, compatibleContractsSemver } from './version'; + +test('latest target contracts satisfies compatible range', t => { + t.true( + semver.satisfies(contractsVersion, compatibleContractsSemver), + `Latest target contracts version ${contractsVersion} does not satisfy compatible range ${compatibleContractsSemver}. +Check whether the compatible range is up to date.`, + ); +}); diff --git a/packages/core/stellar/src/utils/version.ts b/packages/core/stellar/src/utils/version.ts new file mode 100644 index 000000000..1ec569bd7 --- /dev/null +++ b/packages/core/stellar/src/utils/version.ts @@ -0,0 +1,10 @@ +/** + * The actual latest version to use in links. + */ +export const contractsVersion = '0.1.0'; +export const contractsVersionTag = `v${contractsVersion}`; + +/** + * Semantic version string representing of the minimum compatible version of Contracts to display in output. + */ +export const compatibleContractsSemver = '^0.1.0'; diff --git a/packages/core/stellar/tsconfig.json b/packages/core/stellar/tsconfig.json new file mode 100644 index 000000000..e51988c6e --- /dev/null +++ b/packages/core/stellar/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "incremental": true, + "module": "commonjs", + "sourceMap": true, + "declaration": true, + "declarationMap": true, + "skipLibCheck": true, + "rootDir": "src", + "outDir": "dist" + }, + "include": [ + "src/**/*" + ] +} diff --git a/packages/ui/public/cairo.html b/packages/ui/public/cairo.html index 0b76749ca..3764e98d1 100644 --- a/packages/ui/public/cairo.html +++ b/packages/ui/public/cairo.html @@ -52,6 +52,7 @@
diff --git a/packages/ui/public/index.html b/packages/ui/public/index.html index e8b5961a9..b4d284516 100644 --- a/packages/ui/public/index.html +++ b/packages/ui/public/index.html @@ -84,6 +84,7 @@
diff --git a/packages/ui/public/stellar.html b/packages/ui/public/stellar.html new file mode 100644 index 000000000..991715357 --- /dev/null +++ b/packages/ui/public/stellar.html @@ -0,0 +1,81 @@ + + + + + + OpenZeppelin Contracts Wizard + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+ Forum + Docs + GitHub OpenZeppelin + Twitter/X +
+
+ +
+ + +
+ + + + + + + + + + diff --git a/packages/ui/src/cairo/inject-hyperlinks.ts b/packages/ui/src/cairo/inject-hyperlinks.ts index a83929d2e..99bfa0d1f 100644 --- a/packages/ui/src/cairo/inject-hyperlinks.ts +++ b/packages/ui/src/cairo/inject-hyperlinks.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-useless-escape */ import { contractsVersionTag } from '@openzeppelin/wizard-cairo/src'; export function injectHyperlinks(code: string) { @@ -17,7 +16,7 @@ export function injectHyperlinks(code: string) { let replacement; if (suffix === '::{') { // Multiple components are imported, so remove components and link to the parent .cairo file - replacement = `use<\/span> ${libraryPrefix}::${libraryPath}${suffix}`; // Exclude suffix from link } else { @@ -26,7 +25,7 @@ export function injectHyperlinks(code: string) { const componentName = suffix.substring(2, suffix.length); const mapping = componentMappings[componentName]; const urlSuffix = mapping ? `/${mapping}.cairo` : '.cairo'; - replacement = `use<\/span> ${libraryPrefix}::${libraryPath}${suffix}`; // Include suffix (component) in link } diff --git a/packages/ui/src/common/post-config.ts b/packages/ui/src/common/post-config.ts index b917f6d40..156ca5844 100644 --- a/packages/ui/src/common/post-config.ts +++ b/packages/ui/src/common/post-config.ts @@ -1,5 +1,6 @@ import type { GenericOptions as SolidityOptions } from '@openzeppelin/wizard'; import type { GenericOptions as CairoOptions } from '@openzeppelin/wizard-cairo'; +import type { GenericOptions as StellarOptions } from '@openzeppelin/wizard-stellar'; declare global { interface Window { @@ -11,13 +12,9 @@ export type Action = 'copy' | 'remix' | 'download-file' | 'download-hardhat' | ' export type Language = 'solidity' | 'cairo' | 'stylus' | 'stellar'; export async function postConfig( - opts: Required | Required, + opts: Required | Required | Required, action: Action, language: Language, ) { - window.gtag?.('event', 'wizard_action', { - ...opts, - action, - wizard_lang: language, - }); + window.gtag?.('event', 'wizard_action', { ...opts, action, wizard_lang: language }); } diff --git a/packages/ui/src/main.ts b/packages/ui/src/main.ts index 346c3d8ea..29d9e9497 100644 --- a/packages/ui/src/main.ts +++ b/packages/ui/src/main.ts @@ -3,6 +3,7 @@ import './common/styles/global.css'; import type {} from 'svelte'; import SolidityApp from './solidity/App.svelte'; import CairoApp from './cairo/App.svelte'; +import StellarApp from './stellar/App.svelte'; import { postMessage } from './common/post-message'; import UnsupportedVersion from './common/UnsupportedVersion.svelte'; import semver from 'semver'; @@ -49,6 +50,9 @@ if (requestedVersion && !semver.satisfies(requestedVersion, compatibleVersionSem props: { initialTab, initialOpts }, }); break; + case 'stellar': + app = new StellarApp({ target: document.body, props: { initialTab, initialOpts } }); + break; case 'solidity': default: app = new SolidityApp({ diff --git a/packages/ui/src/stellar/App.svelte b/packages/ui/src/stellar/App.svelte new file mode 100644 index 000000000..8271b93fe --- /dev/null +++ b/packages/ui/src/stellar/App.svelte @@ -0,0 +1,283 @@ + + +
+
+
+ + + +
+ +
+ + + + + + + +
+
+ +
+
+
+ +
+
+
+
{@html highlightedCode}
+
+
+
+ + diff --git a/packages/ui/src/stellar/FungibleControls.svelte b/packages/ui/src/stellar/FungibleControls.svelte new file mode 100644 index 000000000..e610ee41c --- /dev/null +++ b/packages/ui/src/stellar/FungibleControls.svelte @@ -0,0 +1,75 @@ + + +
+

Settings

+ +
+ + + +
+ + +
+ +
+

Features

+ +
+ + + + + +
+
+ + diff --git a/packages/ui/src/stellar/InfoSection.svelte b/packages/ui/src/stellar/InfoSection.svelte new file mode 100644 index 000000000..497cd85e4 --- /dev/null +++ b/packages/ui/src/stellar/InfoSection.svelte @@ -0,0 +1,21 @@ + + +
+

+ + +

+ + +
+ diff --git a/packages/ui/src/stellar/highlightjs.ts b/packages/ui/src/stellar/highlightjs.ts new file mode 100644 index 000000000..85d7b7166 --- /dev/null +++ b/packages/ui/src/stellar/highlightjs.ts @@ -0,0 +1,5 @@ +import hljs from 'highlight.js/lib/core'; +import rust from 'highlight.js/lib/languages/rust'; +hljs.registerLanguage('rust', rust); + +export default hljs; diff --git a/packages/ui/src/stellar/inject-hyperlinks.ts b/packages/ui/src/stellar/inject-hyperlinks.ts new file mode 100644 index 000000000..1f98ea6d3 --- /dev/null +++ b/packages/ui/src/stellar/inject-hyperlinks.ts @@ -0,0 +1,27 @@ +import { contractsVersionTag } from '@openzeppelin/wizard-stellar/src'; + +export function injectHyperlinks(code: string) { + const importRegex = /use<\/span> (openzeppelin_[a-zA-Z0-9_]*)/g; + let result = code; + let match = importRegex.exec(code); + while (match != null) { + const [line, libraryPrefix] = match; + if (line !== undefined && libraryPrefix !== undefined) { + const githubPrefix = `https://github.com/OpenZeppelin/stellar-contracts/blob/${contractsVersionTag}/contracts/`; + + const mapping = importSourceMappings[libraryPrefix]; + if (mapping !== undefined) { + const replacement = `use ${libraryPrefix}`; + result = result.replace(line, replacement); + } + } + match = importRegex.exec(code); + } + return result; +} + +const importSourceMappings: { [key: string]: string } = { + openzeppelin_fungible_token: 'token/fungible/src', + openzeppelin_pausable: 'utils/pausable/src', + openzeppelin_pausable_macros: 'utils/pausable-macros/src', +} as const;