From 3dc0a4699f06b39bae6361dac7d894c5829c2ba7 Mon Sep 17 00:00:00 2001 From: gianfra-t <96739519+gianfra-t@users.noreply.github.com> Date: Tue, 28 Nov 2023 10:44:51 -0300 Subject: [PATCH 01/11] Update LICENSE (#354) --- LICENSE | 250 ++++++++++++++++-- .../amplitude/src/custom_fungibles_adapter.rs | 114 ++++++++ runtime/foucoco/Cargo.toml | 2 +- runtime/foucoco/src/lib.rs | 2 +- 4 files changed, 342 insertions(+), 26 deletions(-) create mode 100644 runtime/amplitude/src/custom_fungibles_adapter.rs diff --git a/LICENSE b/LICENSE index cf1ab25da..36caec951 100644 --- a/LICENSE +++ b/LICENSE @@ -1,24 +1,226 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to + +GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright © 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 General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. +TERMS AND CONDITIONS +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. +1. Source Code. + +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. +2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. +7. Additional Terms. + +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. +11. Patents. + +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/runtime/amplitude/src/custom_fungibles_adapter.rs b/runtime/amplitude/src/custom_fungibles_adapter.rs new file mode 100644 index 000000000..4cfdc66f6 --- /dev/null +++ b/runtime/amplitude/src/custom_fungibles_adapter.rs @@ -0,0 +1,114 @@ +use xcm_builder::{FungiblesAdapter, FungiblesMutateAdapter, FungiblesTransferAdapter, AssetChecking}; +use frame_support::traits::{tokens::fungibles, Contains, Get}; +use sp_std::{marker::PhantomData, prelude::*, result}; +use xcm::latest::prelude::*; +use xcm_executor::traits::{Convert, Error as MatchError, MatchesFungibles, TransactAsset}; + + +pub struct CustomFungiblesAdapter< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + DefinedDoStuff +>(PhantomData<(Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount, DefinedDoStuff)>); +impl< + Assets: fungibles::Mutate + fungibles::Transfer, + Matcher: MatchesFungibles, + AccountIdConverter: Convert, + AccountId: Clone, // can't get away without it since Currency is generic over it. + CheckAsset: AssetChecking, + CheckingAccount: Get, + DefinedDoStuff: HandleSpecialLocation, + > TransactAsset + for CustomFungiblesAdapter +{ + fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + FungiblesMutateAdapter::< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + >::can_check_in(origin, what, context) + } + + fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + FungiblesMutateAdapter::< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + >::check_in(origin, what, context) + } + + fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + FungiblesMutateAdapter::< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + >::can_check_out(dest, what, context) + } + + fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + FungiblesMutateAdapter::< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + >::check_out(dest, what, context) + } + + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: &XcmContext) -> XcmResult { + DefinedDoStuff::do_stuff(); + FungiblesMutateAdapter::< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + >::deposit_asset(what, who, context) + } + + fn withdraw_asset( + what: &MultiAsset, + who: &MultiLocation, + maybe_context: Option<&XcmContext>, + ) -> result::Result { + FungiblesMutateAdapter::< + Assets, + Matcher, + AccountIdConverter, + AccountId, + CheckAsset, + CheckingAccount, + >::withdraw_asset(what, who, maybe_context) + } + + fn internal_transfer_asset( + what: &MultiAsset, + from: &MultiLocation, + to: &MultiLocation, + context: &XcmContext, + ) -> result::Result { + FungiblesTransferAdapter::::internal_transfer_asset( + what, from, to, context + ) + } +} + +pub trait HandleSpecialLocation{ + + fn handle(what: &MultiAsset, context: Option<&XcmContext> ) -> Result<(),()>; +} \ No newline at end of file diff --git a/runtime/foucoco/Cargo.toml b/runtime/foucoco/Cargo.toml index eebf50853..ee0804cfc 100644 --- a/runtime/foucoco/Cargo.toml +++ b/runtime/foucoco/Cargo.toml @@ -262,7 +262,7 @@ runtime-benchmarks = [ "replace/runtime-benchmarks", "stellar-relay/runtime-benchmarks", "vault-registry/runtime-benchmarks", - + "oracle/testing-utils", "runtime-common/runtime-benchmarks", "orml-currencies-allowance-extension/runtime-benchmarks" ] diff --git a/runtime/foucoco/src/lib.rs b/runtime/foucoco/src/lib.rs index dc67a6ed9..57f7f65a8 100644 --- a/runtime/foucoco/src/lib.rs +++ b/runtime/foucoco/src/lib.rs @@ -1577,7 +1577,7 @@ impl oracle::Config for Runtime { type WeightInfo = oracle::SubstrateWeight; type DataProvider = DataProviderImpl; #[cfg(feature = "runtime-benchmarks")] - type DataFeedProvider = DataFeederBenchmark< + type DataFeeder = DataFeederBenchmark< oracle::OracleKey, oracle::TimestampedValue, Self::AccountId, From f8cfcad5e301edecf1380e05ea1622ff3cf323f8 Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Tue, 5 Dec 2023 18:26:22 -0300 Subject: [PATCH 02/11] second iteration on xcm intercept --- Cargo.lock | 1 + runtime/amplitude/src/assets.rs | 20 +-- runtime/amplitude/src/custom_barrier.rs | 82 ----------- .../amplitude/src/custom_fungibles_adapter.rs | 120 --------------- runtime/amplitude/src/lib.rs | 2 - runtime/amplitude/src/xcm_config.rs | 106 ++++++++++---- runtime/common/Cargo.toml | 3 +- runtime/common/src/custom_xcm_barrier.rs | 115 +++++++++++++++ runtime/common/src/lib.rs | 1 + .../integration-tests/src/amplitude_tests.rs | 138 +++++++++--------- .../integration-tests/src/pendulum_tests.rs | 94 ++++++------ runtime/integration-tests/src/sibling.rs | 3 + runtime/integration-tests/src/test_macros.rs | 67 +++------ 13 files changed, 330 insertions(+), 422 deletions(-) delete mode 100644 runtime/amplitude/src/custom_barrier.rs delete mode 100644 runtime/amplitude/src/custom_fungibles_adapter.rs create mode 100644 runtime/common/src/custom_xcm_barrier.rs diff --git a/Cargo.lock b/Cargo.lock index fb37ec98f..3972e2148 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10051,6 +10051,7 @@ dependencies = [ "sp-std", "spacewalk-primitives 1.0.0", "xcm", + "xcm-executor", "zenlink-protocol", ] diff --git a/runtime/amplitude/src/assets.rs b/runtime/amplitude/src/assets.rs index 398fa0c69..e72a5a2fa 100644 --- a/runtime/amplitude/src/assets.rs +++ b/runtime/amplitude/src/assets.rs @@ -36,22 +36,4 @@ pub mod native_locations { ), } } -} -pub mod intercept_multilocation { - use xcm::latest::{ - Junction::{PalletInstance, Parachain, GeneralKey}, - Junctions::{X2,X3}, - MultiLocation, - }; - pub fn matches_general_structure(location: &MultiLocation) -> Option<(u8, [u8; 32])> { - if let MultiLocation { - parents: 0, - interior: X2(PalletInstance(99), GeneralKey { length, data }) - } = location { - Some((*length, *data)) - } else { - None - } - } - -} +} \ No newline at end of file diff --git a/runtime/amplitude/src/custom_barrier.rs b/runtime/amplitude/src/custom_barrier.rs deleted file mode 100644 index 9724f91ed..000000000 --- a/runtime/amplitude/src/custom_barrier.rs +++ /dev/null @@ -1,82 +0,0 @@ -use super::{ - AccountId, Balance, Balances, CurrencyId, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, WeightToFee, XcmpQueue, System -}; -use crate::{ - assets::{ - native_locations::{native_location_external_pov, native_location_local_pov}, - xcm_assets, - intercept_multilocation - }, - ConstU32, -}; -use core::marker::PhantomData; -use frame_support::{ - log, match_types, parameter_types,ensure, - traits::{Contains,ContainsPair, Everything, Nothing}, -}; -use orml_traits::{ - location::{RelativeReserveProvider, Reserve}, - parameter_type_with_key, -}; -use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; -use polkadot_runtime_common::impls::ToAuthor; -use runtime_common::parachains::kusama::asset_hub; -use sp_runtime::traits::Convert; -use xcm::latest::{Instruction::{self, *},prelude::*, Weight as XCMWeight}; - -use xcm_executor::{ - traits::{JustTry, ShouldExecute}, - XcmExecutor, -}; - - -pub struct AllowUnpaidExecutionFromCustom(PhantomData); -impl> ShouldExecute for AllowUnpaidExecutionFromCustom { - fn should_execute( - origin: &MultiLocation, - instructions: &mut [Instruction], - _max_weight: XCMWeight, - _weight_credit: &mut XCMWeight, - ) -> Result<(), ()> { - log::info!( - target: "xcm::barriers", - "AllowUnpaidExecutionFromCustom origin: {:?}, instructions: {:?}, max_weight: {:?}, weight_credit: {:?}", - origin, instructions, _max_weight, _weight_credit, - ); - log::info!("origin {:?}",origin); - // Check if the origin is the specific parachain - if let MultiLocation { - parents: 1, - interior: X1(Parachain(parachain_id)) - } = origin { - log::info!("paraid {:?}",*parachain_id); - if *parachain_id == 9999 { - log::info!("parachain match"); - // Iterate through the instructions - for instruction in instructions.iter() { - match instruction { - Instruction::DepositAsset { assets, beneficiary } => { - match (assets, beneficiary) { - (Wild(AllCounted(1)), MultiLocation { - parents: 0, - interior: X2(PalletInstance(99), GeneralKey { length, data }) - }) if *length == 32 => { - // Execute custom function from automation pallet (here just a remark) - System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0u8;32])), data.to_vec()); - return Err(()); - }, - _ => continue, - } - }, - _ => continue, - } - } - } - } - - ensure!(T::contains(origin), ()); - Ok(()) - } -} \ No newline at end of file diff --git a/runtime/amplitude/src/custom_fungibles_adapter.rs b/runtime/amplitude/src/custom_fungibles_adapter.rs deleted file mode 100644 index eca1a5855..000000000 --- a/runtime/amplitude/src/custom_fungibles_adapter.rs +++ /dev/null @@ -1,120 +0,0 @@ -use xcm_builder::{FungiblesAdapter, FungiblesMutateAdapter, FungiblesTransferAdapter, AssetChecking}; -use frame_support::traits::{tokens::fungibles, Contains, Get}; -use sp_std::{marker::PhantomData, prelude::*, result}; -use xcm::latest::prelude::*; -use xcm_executor::traits::{Convert, Error as MatchError, MatchesFungibles, TransactAsset}; - - -pub struct CustomFungiblesAdapter< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - Handle ->(PhantomData<(Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount, Handle)>); -impl< - Assets: fungibles::Mutate + fungibles::Transfer, - Matcher: MatchesFungibles, - AccountIdConverter: Convert, - AccountId: Clone, // can't get away without it since Currency is generic over it. - CheckAsset: AssetChecking, - CheckingAccount: Get, - Handle: HandleSpecialLocation, - > TransactAsset - for CustomFungiblesAdapter -{ - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { - FungiblesMutateAdapter::< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - >::can_check_in(origin, what, context) - } - - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { - FungiblesMutateAdapter::< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - >::check_in(origin, what, context) - } - - fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { - FungiblesMutateAdapter::< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - >::can_check_out(dest, what, context) - } - - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { - FungiblesMutateAdapter::< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - >::check_out(dest, what, context) - } - - fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: &XcmContext) -> XcmResult { - if !Handle::handle(who, context){ - - return FungiblesMutateAdapter::< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - >::deposit_asset(what, who, context) - }; - return Ok(()); - - } - - fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, - maybe_context: Option<&XcmContext>, - ) -> result::Result { - FungiblesMutateAdapter::< - Assets, - Matcher, - AccountIdConverter, - AccountId, - CheckAsset, - CheckingAccount, - >::withdraw_asset(what, who, maybe_context) - } - - fn internal_transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, - context: &XcmContext, - ) -> result::Result { - FungiblesTransferAdapter::::internal_transfer_asset( - what, from, to, context - ) - } -} - -pub trait HandleSpecialLocation{ - - fn handle(what: &MultiLocation, context: &XcmContext ) -> bool; -} - - diff --git a/runtime/amplitude/src/lib.rs b/runtime/amplitude/src/lib.rs index 26118ffa6..072f2e0ac 100644 --- a/runtime/amplitude/src/lib.rs +++ b/runtime/amplitude/src/lib.rs @@ -10,8 +10,6 @@ mod assets; mod weights; pub mod xcm_config; pub mod zenlink; -pub mod custom_fungibles_adapter; -pub mod custom_barrier; use crate::zenlink::*; use bifrost_farming as farming; diff --git a/runtime/amplitude/src/xcm_config.rs b/runtime/amplitude/src/xcm_config.rs index eccf4bf30..cc8ad5148 100644 --- a/runtime/amplitude/src/xcm_config.rs +++ b/runtime/amplitude/src/xcm_config.rs @@ -6,10 +6,10 @@ use crate::{ assets::{ native_locations::{native_location_external_pov, native_location_local_pov}, xcm_assets, - intercept_multilocation }, ConstU32, }; + use core::marker::PhantomData; use frame_support::{ log, match_types, parameter_types, @@ -26,7 +26,7 @@ use runtime_common::parachains::kusama::asset_hub; use sp_runtime::traits::Convert; use xcm::latest::{Instruction::{self, *},prelude::*, Weight as XCMWeight}; use xcm_builder::{ - AccountId32Aliases, AllowUnpaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, + AccountId32Aliases, ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, NoChecking, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, UsingComponents, @@ -36,14 +36,13 @@ use xcm_executor::{ XcmExecutor, }; -use frame_support::{ - ensure, - traits::{Contains, Get}, -}; - +use scale_info::prelude::boxed::Box; use cumulus_primitives_core::XcmContext; -use crate::custom_fungibles_adapter::{CustomFungiblesAdapter, HandleSpecialLocation}; -use crate::custom_barrier::AllowUnpaidExecutionFromCustom; +use runtime_common::custom_xcm_barrier::{MatcherConfig,AllowUnpaidExecutionFromCustom,WithdrawAssetMatcher, DepositAssetMatcher, MatcherPair }; +use xcm::latest::{ + Junction::{Parachain, PalletInstance,GeneralKey}, Junctions::{X2,X3}, MultiLocation, +}; +use sp_std::{vec,vec::Vec}; parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayNetwork: NetworkId = NetworkId::Kusama; @@ -138,28 +137,9 @@ where false } } -use xcm::latest::{ - Junction, Junction::{Parachain, PalletInstance,GeneralKey}, Junctions::{X2,X3}, MultiLocation, -}; -use frame_support::{ - log::{error, info}}; -pub struct MultiLocationFilter; - -impl HandleSpecialLocation for MultiLocationFilter{ - fn handle(who: &MultiLocation, _ctx: &XcmContext) -> bool { - info!("from {:?}", _ctx.origin); - info!("Handling deposit multiloc {:?}", &who); - if let Some((len, data)) = intercept_multilocation::matches_general_structure(who) { - System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0u8;32])), data.to_vec()); - return true - } - return false - } - -} -pub type FungiblesTransactor = CustomFungiblesAdapter< +pub type FungiblesTransactor = FungiblesAdapter< // Use this fungibles implementation Tokens, // This means that this adapter should handle any token that `CurrencyIdConvert` can convert @@ -172,8 +152,7 @@ AccountId, // We dont allow teleports. NoChecking, // The account to use for tracking teleports. -CheckingAccount, -MultiLocationFilter +CheckingAccount >; /// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, @@ -278,8 +257,71 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { -pub type Barrier = AllowUnpaidExecutionFromCustom; +// This one allows to test it with the current configuration in amplitude integration tests +struct WithdrawAssetMatcher1; +impl WithdrawAssetMatcher for WithdrawAssetMatcher1 { + fn matches(&self, multi_asset: &MultiAsset) -> bool { + if let MultiAsset { id: Concrete(MultiLocation { parents: 0, interior: X1(PalletInstance(2)) }),.. } = multi_asset { + true + } else { + false + } + } +} + +//For moonbeam asset like BRZ we expect to use +// impl DepositAssetMatcher for MyDepositAssetMatcher { +// fn matches(&self, multi_asset: &MultiAsset) -> bool { +// if let MultiLocation { +// parents: 1, +// interior: X3(Parachain(2004), PalletInstance(110), AccountKey20 { key }) +// } = beneficiary { +// if key == b"INSERT_ERC20_ADDRESS" { +// // Return some relevant data if needed, otherwise just return Some(()) or similar +// return true; +// } +// } +// false +// } +// } + +struct DepositAssetMatcher1; +impl DepositAssetMatcher for DepositAssetMatcher1 { + fn matches<'a>(&self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])> { + if let (Wild(AllCounted(1)), MultiLocation { parents: 0, interior: X2(PalletInstance(99), GeneralKey { length, data }) }) = (assets, beneficiary) { + Some((*length, &*data)) + } else { + None + } + } +} + +pub struct MatcherConfigAmplitude; + +impl MatcherConfig for MatcherConfigAmplitude { + fn get_matcher_pairs() -> Vec { + vec![ + MatcherPair::new( + Box::new(WithdrawAssetMatcher1), + Box::new(DepositAssetMatcher1), + ), + // Additional matcher pairs to be defined in the future + ] + } + fn get_incoming_parachain_id() -> u32{ + // TODO change to moonbeam or moonbase id + 9999u32 + } + + fn callback()-> Result<(),()>{ + // TODO change to call the actual automation pallet, with data and length + System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0;32])), [0;1].to_vec()); + Ok(()) + } +} + +pub type Barrier = AllowUnpaidExecutionFromCustom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index ff0d48d7b..42dfbb844 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -24,6 +24,7 @@ sp-consensus-aura = { git = "https://github.com/paritytech/substrate", default-f sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.40" } xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.40" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.40" } orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.40" } orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.40" } @@ -32,7 +33,6 @@ dia-oracle = { git = "https://github.com/pendulum-chain/oracle-pallet", default- zenlink-protocol = { git = "https://github.com/pendulum-chain/Zenlink-DEX-Module", default-features = false, branch = "polkadot-v0.9.40-protocol" } spacewalk-primitives = { git = "https://github.com/pendulum-chain/spacewalk", default-features = false, rev = "d05b0015d15ca39cc780889bcc095335e9862a36" } - [features] default = [ "std", @@ -49,6 +49,7 @@ std = [ "sp-consensus-aura/std", "sp-core/std", "xcm/std", + "xcm-executor/std", "orml-traits/std", "dia-oracle/std", "orml-asset-registry/std", diff --git a/runtime/common/src/custom_xcm_barrier.rs b/runtime/common/src/custom_xcm_barrier.rs new file mode 100644 index 000000000..30fc4bf61 --- /dev/null +++ b/runtime/common/src/custom_xcm_barrier.rs @@ -0,0 +1,115 @@ + +use core::marker::PhantomData; +use frame_support::{ + log,ensure, + traits::Contains, +}; + +use xcm::latest::{Instruction::self,prelude::*, Weight as XCMWeight}; + +use xcm_executor::{ + traits::ShouldExecute, +}; + +use scale_info::prelude::boxed::Box; +use sp_std::vec::Vec; + +pub trait WithdrawAssetMatcher: Sync { + fn matches(&self, multi_asset: &MultiAsset) -> bool; +} + +pub trait DepositAssetMatcher { + fn matches<'a>(&self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])>; +} +pub struct MatcherPair { + withdraw_asset_matcher: Box, + deposit_asset_matcher: Box, +} + +impl MatcherPair { + pub fn new(withdraw_asset_matcher: Box, deposit_asset_matcher: Box) -> Self { + MatcherPair { + withdraw_asset_matcher, + deposit_asset_matcher, + } + } + + fn matches_withdraw_asset(&self, multi_asset: &MultiAsset) -> bool { + self.withdraw_asset_matcher.matches(multi_asset) + } + + fn matches_deposit_asset<'a>(&'a self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])> { + self.deposit_asset_matcher.matches(assets, beneficiary) + } +} + +pub trait MatcherConfig { + fn get_matcher_pairs() -> Vec; + fn callback() -> Result<(),()>; + fn get_incoming_parachain_id() -> u32; +} + + +pub struct AllowUnpaidExecutionFromCustom { + _phantom: PhantomData<(T, V)>, +} +impl, V: MatcherConfig> ShouldExecute for AllowUnpaidExecutionFromCustom { + fn should_execute( + origin: &MultiLocation, + instructions: &mut [Instruction], + _max_weight: XCMWeight, + _weight_credit: &mut XCMWeight, + ) -> Result<(), ()> { + log::info!( + target: "xcm::barriers", + "AllowUnpaidExecutionFromCustom origin: {:?}, instructions: {:?}, max_weight: {:?}, weight_credit: {:?}", + origin, instructions, _max_weight, _weight_credit, + ); + log::info!("origin {:?}",origin); + let incoming_parachain_id = V::get_incoming_parachain_id(); + // Check if the origin is the specific parachain + if let MultiLocation { + parents: 1, + interior: X1(Parachain(parachain_id)) + } = origin { + log::info!("paraid {:?}",*parachain_id); + if *parachain_id == incoming_parachain_id { + log::info!("parachain match"); + + let matcher_pairs = V::get_matcher_pairs(); + // Iterate through the instructions, for + // each match pair we allow + for matcher_pair in matcher_pairs { + let mut withdraw_asset_matched = false; + + // Check for WithdrawAsset + for instruction in instructions.iter() { + if let Instruction::WithdrawAsset(assets) = instruction { + if assets.clone().into_inner().iter().any(|asset| matcher_pair.matches_withdraw_asset(asset)) { + withdraw_asset_matched = true; + break; + } + } + } + + // If WithdrawAsset matches, then check for DepositAsset with the same matcher pair + // and execute the callback + if withdraw_asset_matched { + for instruction in instructions.iter() { + if let Instruction::DepositAsset { assets, beneficiary } = instruction { + if let Some((length, data)) = matcher_pair.matches_deposit_asset(assets, beneficiary) { + V::callback(); + return Err(()); + } + } + } + } + } + } + } + + ensure!(T::contains(origin), ()); + Ok(()) + } +} + diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 4eea326c4..51720b1a5 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -11,6 +11,7 @@ pub mod chain_ext; mod proxy_type; pub mod stellar; pub mod zenlink; +pub mod custom_xcm_barrier; #[cfg(feature = "runtime-benchmarks")] pub mod benchmarking; diff --git a/runtime/integration-tests/src/amplitude_tests.rs b/runtime/integration-tests/src/amplitude_tests.rs index 374f2bcfb..e3d81a549 100644 --- a/runtime/integration-tests/src/amplitude_tests.rs +++ b/runtime/integration-tests/src/amplitude_tests.rs @@ -69,81 +69,81 @@ decl_test_network! { } } -// #[test] -// fn transfer_ksm_from_kusama_to_amplitude() { -// transfer_20_relay_token_from_relay_chain_to_parachain!( -// KusamaMockNet, -// kusama_runtime, -// KusamaRelay, -// amplitude_runtime, -// AmplitudeParachain, -// AMPLITUDE_ID, -// KSM_FEE_WHEN_TRANSFER_TO_PARACHAIN -// ); -// } +#[test] +fn transfer_ksm_from_kusama_to_amplitude() { + transfer_20_relay_token_from_relay_chain_to_parachain!( + KusamaMockNet, + kusama_runtime, + KusamaRelay, + amplitude_runtime, + AmplitudeParachain, + AMPLITUDE_ID, + KSM_FEE_WHEN_TRANSFER_TO_PARACHAIN + ); +} -// #[test] -// fn transfer_ksm_from_amplitude_to_kusama() { -// transfer_10_relay_token_from_parachain_to_relay_chain!( -// KusamaMockNet, -// kusama_runtime, -// KusamaRelay, -// amplitude_runtime, -// AmplitudeParachain -// ); -// } +#[test] +fn transfer_ksm_from_amplitude_to_kusama() { + transfer_10_relay_token_from_parachain_to_relay_chain!( + KusamaMockNet, + kusama_runtime, + KusamaRelay, + amplitude_runtime, + AmplitudeParachain + ); +} -// #[test] -// fn assethub_transfer_incorrect_asset_to_amplitude_should_fail() { -// parachain1_transfer_incorrect_asset_to_parachain2_should_fail!( -// kusama_asset_hub_runtime, -// AssetHubParachain, -// amplitude_runtime, -// AmplitudeParachain, -// AMPLITUDE_ID -// ); -// } +#[test] +fn assethub_transfer_incorrect_asset_to_amplitude_should_fail() { + parachain1_transfer_incorrect_asset_to_parachain2_should_fail!( + kusama_asset_hub_runtime, + AssetHubParachain, + amplitude_runtime, + AmplitudeParachain, + AMPLITUDE_ID + ); +} -// #[test] -// fn assethub_transfer_asset_to_amplitude() { -// parachain1_transfer_asset_to_parachain2!( -// kusama_asset_hub_runtime, -// AssetHubParachain, -// USDT_ASSET_ID, -// amplitude_runtime, -// AmplitudeParachain, -// AMPLITUDE_ID -// ); -// } +#[test] +fn assethub_transfer_asset_to_amplitude() { + parachain1_transfer_asset_to_parachain2!( + kusama_asset_hub_runtime, + AssetHubParachain, + USDT_ASSET_ID, + amplitude_runtime, + AmplitudeParachain, + AMPLITUDE_ID + ); +} -// #[test] -// fn assethub_transfer_asset_to_amplitude_and_back() { -// let network_id = NetworkId::Kusama; +#[test] +fn assethub_transfer_asset_to_amplitude_and_back() { + let network_id = NetworkId::Kusama; -// parachain1_transfer_asset_to_parachain2_and_back!( -// kusama_asset_hub_runtime, -// AssetHubParachain, -// ASSETHUB_ID, -// USDT_ASSET_ID, -// amplitude_runtime, -// AmplitudeParachain, -// AMPLITUDE_ID, -// network_id -// ); -// } + parachain1_transfer_asset_to_parachain2_and_back!( + kusama_asset_hub_runtime, + AssetHubParachain, + ASSETHUB_ID, + USDT_ASSET_ID, + amplitude_runtime, + AmplitudeParachain, + AMPLITUDE_ID, + network_id + ); +} -// #[test] -// fn transfer_native_token_from_amplitude_to_sibling_parachain_and_back() { -// transfer_native_token_from_parachain1_to_parachain2_and_back!( -// KusamaMockNet, -// amplitude_runtime, -// AmplitudeParachain, -// sibling, -// SiblingParachain, -// AMPLITUDE_ID, -// SIBLING_ID -// ); -// } +#[test] +fn transfer_native_token_from_amplitude_to_sibling_parachain_and_back() { + transfer_native_token_from_parachain1_to_parachain2_and_back!( + KusamaMockNet, + amplitude_runtime, + AmplitudeParachain, + sibling, + SiblingParachain, + AMPLITUDE_ID, + SIBLING_ID + ); +} #[test] fn moonbeam_transfers_token_and_handle_automation() { diff --git a/runtime/integration-tests/src/pendulum_tests.rs b/runtime/integration-tests/src/pendulum_tests.rs index 79caa871c..13038d66b 100644 --- a/runtime/integration-tests/src/pendulum_tests.rs +++ b/runtime/integration-tests/src/pendulum_tests.rs @@ -91,54 +91,54 @@ fn transfer_dot_from_pendulum_to_polkadot() { ); } -#[test] -fn assethub_transfer_incorrect_asset_to_pendulum_should_fail() { - parachain1_transfer_incorrect_asset_to_parachain2_should_fail!( - polkadot_asset_hub_runtime, - AssetHubParachain, - pendulum_runtime, - PendulumParachain, - PENDULUM_ID - ); -} +// #[test] +// fn assethub_transfer_incorrect_asset_to_pendulum_should_fail() { +// parachain1_transfer_incorrect_asset_to_parachain2_should_fail!( +// polkadot_asset_hub_runtime, +// AssetHubParachain, +// pendulum_runtime, +// PendulumParachain, +// PENDULUM_ID +// ); +// } -#[test] -fn assethub_transfer_asset_to_pendulum() { - parachain1_transfer_asset_to_parachain2!( - polkadot_asset_hub_runtime, - AssetHubParachain, - USDT_ASSET_ID, - pendulum_runtime, - PendulumParachain, - PENDULUM_ID - ); -} +// #[test] +// fn assethub_transfer_asset_to_pendulum() { +// parachain1_transfer_asset_to_parachain2!( +// polkadot_asset_hub_runtime, +// AssetHubParachain, +// USDT_ASSET_ID, +// pendulum_runtime, +// PendulumParachain, +// PENDULUM_ID +// ); +// } -#[test] -fn assethub_transfer_asset_to_pendulum_and_back() { - let network_id = NetworkId::Polkadot; +// #[test] +// fn assethub_transfer_asset_to_pendulum_and_back() { +// let network_id = NetworkId::Polkadot; - parachain1_transfer_asset_to_parachain2_and_back!( - polkadot_asset_hub_runtime, - AssetHubParachain, - ASSETHUB_ID, - USDT_ASSET_ID, - pendulum_runtime, - PendulumParachain, - PENDULUM_ID, - network_id - ); -} +// parachain1_transfer_asset_to_parachain2_and_back!( +// polkadot_asset_hub_runtime, +// AssetHubParachain, +// ASSETHUB_ID, +// USDT_ASSET_ID, +// pendulum_runtime, +// PendulumParachain, +// PENDULUM_ID, +// network_id +// ); +// } -#[test] -fn transfer_native_token_from_pendulum_to_sibling_parachain_and_back() { - transfer_native_token_from_parachain1_to_parachain2_and_back!( - PolkadotMockNet, - pendulum_runtime, - PendulumParachain, - sibling, - SiblingParachain, - PENDULUM_ID, - SIBLING_ID - ); -} +// #[test] +// fn transfer_native_token_from_pendulum_to_sibling_parachain_and_back() { +// transfer_native_token_from_parachain1_to_parachain2_and_back!( +// PolkadotMockNet, +// pendulum_runtime, +// PendulumParachain, +// sibling, +// SiblingParachain, +// PENDULUM_ID, +// SIBLING_ID +// ); +// } diff --git a/runtime/integration-tests/src/sibling.rs b/runtime/integration-tests/src/sibling.rs index 5ac86b728..7887da235 100644 --- a/runtime/integration-tests/src/sibling.rs +++ b/runtime/integration-tests/src/sibling.rs @@ -92,6 +92,7 @@ pub enum CurrencyId { Amplitude, Native, XCM(u8), + Token } // Convert from u32 parachain id to CurrencyId @@ -127,6 +128,7 @@ impl Convert> for CurrencyIdConvert { Some(MultiLocation::new(1, X2(Parachain(PENDULUM_ID), PalletInstance(10)))), CurrencyId::Amplitude => Some(MultiLocation::new(1, X2(Parachain(AMPLITUDE_ID), PalletInstance(10)))), + CurrencyId::Token => Some(MultiLocation { parents: 1, interior: X2(Parachain(AMPLITUDE_ID), PalletInstance(2)) }), CurrencyId::XCM(f) => match f { XCM_ASSET_RELAY_DOT => Some(MultiLocation::parent()), // Handles both Kusama and Polkadot asset hub @@ -155,6 +157,7 @@ impl Convert> for CurrencyIdConvert { Some(CurrencyId::XCM(XCM_ASSET_ASSETHUB_USDT)), MultiLocation { parents: 1, interior: Here } => Some(CurrencyId::XCM(XCM_ASSET_RELAY_DOT)), + MultiLocation { parents: 1, interior: X2(Parachain(AMPLITUDE_ID), PalletInstance(2)) } => Some(CurrencyId::Token), _ => None, } } diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index 36cae0821..fd7b1f0ef 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -562,7 +562,7 @@ macro_rules! transfer_native_token_from_parachain1_to_parachain2_and_back { // Verify ALICE's balance on parachain1 after receiving // Should become the same amount as initial balance before both transfers $parachain1::execute_with(|| { - use $parachain1_runtime::{RuntimeEvent, System, XTokens}; + use $parachain1_runtime::System; for i in System::events().iter() { println!("para 1 events {}: {:?}\n", stringify!($para2_runtime), i); } @@ -585,13 +585,11 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { $parachain1_id:ident, $parachain2_id:ident ) => {{ - use crate::mock::{units, ALICE, BOB}; - use frame_support::traits::fungibles::Inspect; + use crate::mock::{units, ALICE}; use polkadot_core_primitives::Balance; use xcm::latest::{ - Junction, Junction::{AccountId32, GeneralKey, PalletInstance}, Junctions::{X2, X3}, MultiLocation, WeightLimit, + Junction, Junction::{ GeneralKey, PalletInstance}, Junctions::{X1,X2, X3}, MultiLocation, WeightLimit, }; - use $parachain1_runtime::CurrencyId as Parachain1CurrencyId; use $parachain2_runtime::CurrencyId as Parachain2CurrencyId; @@ -599,54 +597,22 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { // Asset Location and amount are not important for this test let transfer_amount: Balance = units(10); - let asset_location = MultiLocation::new( - 1, - X2(Junction::Parachain($parachain1_id), Junction::PalletInstance(10)), - ); - - let para1_native_currency_on_para2 = Parachain2CurrencyId::from($parachain1_id); - - // We transfer to parachain 2 (sibling) so that it is able to transfer back - $parachain1::execute_with(|| { - use $parachain1_runtime::{RuntimeEvent, System, XTokens}; - - - assert_ok!(XTokens::transfer_multiasset( - $parachain1_runtime::RuntimeOrigin::signed(ALICE.into()), - Box::new((asset_location.clone(), transfer_amount).into()), - Box::new( - MultiLocation { - parents: 1, - interior: X2( - Junction::Parachain($parachain2_id), - AccountId32 { network: None, id: BOB } - ) - } - .into() - ), - WeightLimit::Unlimited - )); - - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::XTokens(orml_xtokens::Event::TransferredMultiAssets { .. }) - ))); - }); - // Here we use the same asset, but the important bit is the multilocation // This emulates the special multilocation that triggers the automation pallet $parachain2::execute_with(|| { - use $parachain2_runtime::{RuntimeEvent, System, XTokens}; + use $parachain2_runtime::{XTokens, Tokens,RuntimeOrigin}; - assert_ok!(XTokens::transfer_multiasset( - $parachain2_runtime::RuntimeOrigin::signed(BOB.into()), - Box::new((asset_location.clone(), transfer_amount).into()), + assert_ok!(Tokens::set_balance(RuntimeOrigin::root().into(), ALICE.clone().into(), Parachain2CurrencyId::Token,transfer_amount, 0)); + assert_ok!(XTokens::transfer( + $parachain2_runtime::RuntimeOrigin::signed(ALICE.into()), + Parachain2CurrencyId::Token, + transfer_amount, Box::new( MultiLocation::new( 1, X3( - Junction::Parachain(2124), + Junction::Parachain($parachain1_id), PalletInstance(99), GeneralKey {length:32 , data:[1u8;32]} ) @@ -655,18 +621,19 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { ), WeightLimit::Unlimited )); - - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::XTokens(orml_xtokens::Event::TransferredMultiAssets { .. }) - ))); }); $parachain1::execute_with(|| { - use $parachain1_runtime::{RuntimeEvent, System, XTokens}; + use $parachain1_runtime::{RuntimeEvent, System}; for i in System::events().iter() { println!("para 1 events {}: {:?}\n", stringify!($para2_runtime), i); } + // given the configuration in amplitude's xcm_config, we expect the callback (in this case a Remark) + // to be executed + assert!(System::events().iter().any(|r| matches!( + r.event, + RuntimeEvent::System(frame_system::Event::Remarked { .. }) + ))); }); }}; From b68785986050bc68c12ca7c101ea3ba8d7be942c Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Wed, 6 Dec 2023 16:07:05 -0300 Subject: [PATCH 03/11] listen to ReserveAssetDeposited instruction instead of WithdrawAsset. Mock Moonbeam transfer of asset. Implement custom barrier for other runtimes --- runtime/amplitude/src/xcm_config.rs | 57 ++++++----- runtime/common/src/custom_xcm_barrier.rs | 30 +++--- runtime/common/src/lib.rs | 56 +++++++++++ runtime/foucoco/src/xcm_config.rs | 54 ++++++++++- .../integration-tests/src/amplitude_tests.rs | 17 +++- runtime/integration-tests/src/mock.rs | 20 ++++ .../integration-tests/src/pendulum_tests.rs | 94 +++++++++---------- runtime/integration-tests/src/sibling.rs | 5 +- runtime/integration-tests/src/test_macros.rs | 20 ++-- runtime/pendulum/src/xcm_config.rs | 57 ++++++++++- 10 files changed, 301 insertions(+), 109 deletions(-) diff --git a/runtime/amplitude/src/xcm_config.rs b/runtime/amplitude/src/xcm_config.rs index cc8ad5148..8ec230dbf 100644 --- a/runtime/amplitude/src/xcm_config.rs +++ b/runtime/amplitude/src/xcm_config.rs @@ -23,6 +23,8 @@ use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; use runtime_common::parachains::kusama::asset_hub; +use runtime_common::parachains::kusama::moonriver::{PARA_ID as MOONRIVER_PARA_ID, BRZ_location}; + use sp_runtime::traits::Convert; use xcm::latest::{Instruction::{self, *},prelude::*, Weight as XCMWeight}; use xcm_builder::{ @@ -38,7 +40,7 @@ use xcm_executor::{ use scale_info::prelude::boxed::Box; use cumulus_primitives_core::XcmContext; -use runtime_common::custom_xcm_barrier::{MatcherConfig,AllowUnpaidExecutionFromCustom,WithdrawAssetMatcher, DepositAssetMatcher, MatcherPair }; +use runtime_common::custom_xcm_barrier::{MatcherConfig,AllowUnpaidExecutionFromCustom,ReserveAssetDepositedMatcher, DepositAssetMatcher, MatcherPair }; use xcm::latest::{ Junction::{Parachain, PalletInstance,GeneralKey}, Junctions::{X2,X3}, MultiLocation, }; @@ -257,34 +259,30 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { -// This one allows to test it with the current configuration in amplitude integration tests -struct WithdrawAssetMatcher1; -impl WithdrawAssetMatcher for WithdrawAssetMatcher1 { +// We will allow for BRZ location from moonriver +struct ReserveAssetDepositedMatcher1; +impl ReserveAssetDepositedMatcher for ReserveAssetDepositedMatcher1 { fn matches(&self, multi_asset: &MultiAsset) -> bool { - if let MultiAsset { id: Concrete(MultiLocation { parents: 0, interior: X1(PalletInstance(2)) }),.. } = multi_asset { - true - } else { - false - } - } -} + let expected_multiloc = BRZ_location(); -//For moonbeam asset like BRZ we expect to use -// impl DepositAssetMatcher for MyDepositAssetMatcher { -// fn matches(&self, multi_asset: &MultiAsset) -> bool { -// if let MultiLocation { -// parents: 1, -// interior: X3(Parachain(2004), PalletInstance(110), AccountKey20 { key }) -// } = beneficiary { -// if key == b"INSERT_ERC20_ADDRESS" { -// // Return some relevant data if needed, otherwise just return Some(()) or similar -// return true; -// } -// } -// false -// } -// } + match multi_asset { + MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => return true, + _ => return false, + } + } +} +// The beneficiary. We will always expect a location of the form +// MultiLocation: { +// parents: 1, +// interior: { X3: { +// Parachain(SenderParachainId), +// PalletInstance(xx), // will point to the automation pallet +// GeneralKey{ length: xx, data: [] }, // this will hold the reference number for Mykobo +// }, +// Keep in mind that this location will be re-anchored + +// TODO modify with automation's pallet instance struct DepositAssetMatcher1; impl DepositAssetMatcher for DepositAssetMatcher1 { fn matches<'a>(&self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])> { @@ -302,18 +300,17 @@ impl MatcherConfig for MatcherConfigAmplitude { fn get_matcher_pairs() -> Vec { vec![ MatcherPair::new( - Box::new(WithdrawAssetMatcher1), + Box::new(ReserveAssetDepositedMatcher1), Box::new(DepositAssetMatcher1), ), // Additional matcher pairs to be defined in the future ] } fn get_incoming_parachain_id() -> u32{ - // TODO change to moonbeam or moonbase id - 9999u32 + MOONRIVER_PARA_ID } - fn callback()-> Result<(),()>{ + fn callback(_length: u8, _data: &[u8])-> Result<(),()>{ // TODO change to call the actual automation pallet, with data and length System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0;32])), [0;1].to_vec()); Ok(()) diff --git a/runtime/common/src/custom_xcm_barrier.rs b/runtime/common/src/custom_xcm_barrier.rs index 30fc4bf61..28dfa6b1b 100644 --- a/runtime/common/src/custom_xcm_barrier.rs +++ b/runtime/common/src/custom_xcm_barrier.rs @@ -14,7 +14,7 @@ use xcm_executor::{ use scale_info::prelude::boxed::Box; use sp_std::vec::Vec; -pub trait WithdrawAssetMatcher: Sync { +pub trait ReserveAssetDepositedMatcher: Sync { fn matches(&self, multi_asset: &MultiAsset) -> bool; } @@ -22,20 +22,20 @@ pub trait DepositAssetMatcher { fn matches<'a>(&self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])>; } pub struct MatcherPair { - withdraw_asset_matcher: Box, + reserve_deposited_asset_matcher: Box, deposit_asset_matcher: Box, } impl MatcherPair { - pub fn new(withdraw_asset_matcher: Box, deposit_asset_matcher: Box) -> Self { + pub fn new(reserve_deposited_asset_matcher: Box, deposit_asset_matcher: Box) -> Self { MatcherPair { - withdraw_asset_matcher, + reserve_deposited_asset_matcher, deposit_asset_matcher, } } - fn matches_withdraw_asset(&self, multi_asset: &MultiAsset) -> bool { - self.withdraw_asset_matcher.matches(multi_asset) + fn matches_reserve_deposited(&self, multi_asset: &MultiAsset) -> bool { + self.reserve_deposited_asset_matcher.matches(multi_asset) } fn matches_deposit_asset<'a>(&'a self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])> { @@ -45,7 +45,7 @@ impl MatcherPair { pub trait MatcherConfig { fn get_matcher_pairs() -> Vec; - fn callback() -> Result<(),()>; + fn callback(length: u8, data: &[u8]) -> Result<(),()>; fn get_incoming_parachain_id() -> u32; } @@ -80,25 +80,25 @@ impl, V: MatcherConfig> ShouldExecute for AllowUnpaid // Iterate through the instructions, for // each match pair we allow for matcher_pair in matcher_pairs { - let mut withdraw_asset_matched = false; + let mut reserve_deposited_matched = false; - // Check for WithdrawAsset + // Check for ReserveAssetDeposited instruction for instruction in instructions.iter() { - if let Instruction::WithdrawAsset(assets) = instruction { - if assets.clone().into_inner().iter().any(|asset| matcher_pair.matches_withdraw_asset(asset)) { - withdraw_asset_matched = true; + if let Instruction::ReserveAssetDeposited(assets) = instruction { + if assets.clone().into_inner().iter().any(|asset| matcher_pair.matches_reserve_deposited(asset)) { + reserve_deposited_matched = true; break; } } } - // If WithdrawAsset matches, then check for DepositAsset with the same matcher pair + // If ReserveAssetDeposited matches, then check for DepositAsset with the same matcher pair // and execute the callback - if withdraw_asset_matched { + if reserve_deposited_matched { for instruction in instructions.iter() { if let Instruction::DepositAsset { assets, beneficiary } = instruction { if let Some((length, data)) = matcher_pair.matches_deposit_asset(assets, beneficiary) { - V::callback(); + V::callback(length, data); return Err(()); } } diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 51720b1a5..938193265 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -193,6 +193,62 @@ pub mod parachains { pub mod asset_hub { pub use super::super::polkadot::asset_hub::*; } + + pub mod moonriver { + use xcm::latest::{ + Junction::{AccountKey20, PalletInstance, Parachain}, + Junctions::X3, + }; + + // see https://docs.moonbeam.network/builders/interoperability/xcm/xc-registration/assets/ + pub const PARA_ID: u32 = 2023; + pub const ASSET_PALLET_INDEX: u8 = 10; + + // TODO use the REAL BRZ asset on moonriver + // 0xD65A1872f2E2E26092A443CB86bb5d8572027E6E + // extracted using `H160::from_str("...")` then `as_bytes()` + pub const BRZ_ASSET_ACCOUNT_IN_BYTES: [u8; 20] = [ + 214, 90, 24, 114, 242, 226, 226, 96, 146, 164, 67, 203, 134, 187, 93, 133, 114, 2, + 126, 110, + ]; + + parachain_asset_location!( + BRZ, + X3( + Parachain(PARA_ID), + PalletInstance(ASSET_PALLET_INDEX), + AccountKey20 { network: None, key: BRZ_ASSET_ACCOUNT_IN_BYTES } + ) + ); + } + } + + pub mod moonbase_alpha{ + use xcm::latest::{ + Junction::{AccountKey20, PalletInstance, Parachain}, + Junctions::X3, + }; + + // see https://docs.moonbeam.network/builders/interoperability/xcm/xc-registration/assets/ + pub const PARA_ID: u32 = 1000; + pub const ASSET_PALLET_INDEX: u8 = 3; + + // TODO use the REAL BRZ asset on moonbase alpha + // 0xD65A1872f2E2E26092A443CB86bb5d8572027E6E + // extracted using `H160::from_str("...")` then `as_bytes()` + pub const BRZ_ASSET_ACCOUNT_IN_BYTES: [u8; 20] = [ + 214, 90, 24, 114, 242, 226, 226, 96, 146, 164, 67, 203, 134, 187, 93, 133, 114, 2, + 126, 110, + ]; + + parachain_asset_location!( + BRZ, + X3( + Parachain(PARA_ID), + PalletInstance(ASSET_PALLET_INDEX), + AccountKey20 { network: None, key: BRZ_ASSET_ACCOUNT_IN_BYTES } + ) + ); } } diff --git a/runtime/foucoco/src/xcm_config.rs b/runtime/foucoco/src/xcm_config.rs index 16c540cea..1d0428f57 100644 --- a/runtime/foucoco/src/xcm_config.rs +++ b/runtime/foucoco/src/xcm_config.rs @@ -31,6 +31,10 @@ use xcm_executor::{ XcmExecutor, }; +use runtime_common::parachains::moonbase_alpha::{PARA_ID as MOONBASE_PARA_ID, BRZ_location}; +use sp_std::{vec,vec::Vec}; +use runtime_common::custom_xcm_barrier::{MatcherConfig,AllowUnpaidExecutionFromCustom,ReserveAssetDepositedMatcher, DepositAssetMatcher, MatcherPair }; + parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayNetwork: NetworkId = NetworkId::Rococo; @@ -256,7 +260,55 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } } -pub type Barrier = AllowUnpaidExecutionFrom; + +struct ReserveAssetDepositedMatcher1; +impl ReserveAssetDepositedMatcher for ReserveAssetDepositedMatcher1 { + fn matches(&self, multi_asset: &MultiAsset) -> bool { + let expected_multiloc = BRZ_location(); + + match multi_asset { + MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => return true, + _ => return false, + } + } +} +// TODO modify with automation's pallet instance +struct DepositAssetMatcher1; +impl DepositAssetMatcher for DepositAssetMatcher1 { + fn matches<'a>(&self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])> { + if let (Wild(AllCounted(1)), MultiLocation { parents: 0, interior: X2(PalletInstance(99), GeneralKey { length, data }) }) = (assets, beneficiary) { + Some((*length, &*data)) + } else { + None + } + } +} + +pub struct MatcherConfigFoucoco; + +impl MatcherConfig for MatcherConfigFoucoco { + fn get_matcher_pairs() -> Vec { + vec![ + MatcherPair::new( + Box::new(ReserveAssetDepositedMatcher1), + Box::new(DepositAssetMatcher1), + ), + // Additional matcher pairs to be defined in the future + ] + } + fn get_incoming_parachain_id() -> u32{ + MOONRIVER_PARA_ID + } + + fn callback(_length: u8, _data: &[u8])-> Result<(),()>{ + // TODO change to call the actual automation pallet, with data and length + System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0;32])), [0;1].to_vec()); + Ok(()) + } +} + + +pub type Barrier = MatcherConfigFoucoco; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { diff --git a/runtime/integration-tests/src/amplitude_tests.rs b/runtime/integration-tests/src/amplitude_tests.rs index e3d81a549..37ffe81cc 100644 --- a/runtime/integration-tests/src/amplitude_tests.rs +++ b/runtime/integration-tests/src/amplitude_tests.rs @@ -13,6 +13,8 @@ use crate::{ AMPLITUDE_ID, ASSETHUB_ID, SIBLING_ID, }; +use runtime_common::parachains::kusama::moonriver::{PARA_ID as MOONRIVER_PARA_ID}; + use frame_support::assert_ok; use statemine_runtime as kusama_asset_hub_runtime; use xcm::latest::NetworkId; @@ -48,6 +50,16 @@ decl_test_parachain! { } } +decl_test_parachain! { + pub struct MoonriverParachain { + Runtime = sibling::Runtime, + RuntimeOrigin = sibling::RuntimeOrigin, + XcmpMessageHandler = sibling::XcmpQueue, + DmpMessageHandler = sibling::DmpQueue, + new_ext = para_ext(ParachainType::Moonriver), + } +} + decl_test_parachain! { pub struct AssetHubParachain { Runtime = kusama_asset_hub_runtime::Runtime, @@ -65,6 +77,7 @@ decl_test_network! { (1000, AssetHubParachain), (2124, AmplitudeParachain), (9999, SiblingParachain), + (2023, MoonriverParachain), ], } } @@ -152,9 +165,9 @@ fn moonbeam_transfers_token_and_handle_automation() { amplitude_runtime, AmplitudeParachain, sibling, - SiblingParachain, + MoonriverParachain, AMPLITUDE_ID, - SIBLING_ID + MOONRIVER_PARA_ID ); } diff --git a/runtime/integration-tests/src/mock.rs b/runtime/integration-tests/src/mock.rs index 75e1a39a5..11bdb9074 100644 --- a/runtime/integration-tests/src/mock.rs +++ b/runtime/integration-tests/src/mock.rs @@ -12,6 +12,7 @@ use xcm_emulator::Weight; use statemine_runtime as kusama_asset_hub_runtime; use statemint_runtime as polkadot_asset_hub_runtime; +use runtime_common::parachains::kusama::moonriver::{PARA_ID as MOONRIVER_PARA_ID}; pub const ALICE: [u8; 32] = [4u8; 32]; pub const BOB: [u8; 32] = [5u8; 32]; @@ -118,6 +119,7 @@ pub enum ParachainType { Pendulum, Amplitude, Sibling, + Moonriver } pub struct ExtBuilderParachain { @@ -191,6 +193,7 @@ pub fn para_ext(chain: ParachainType) -> sp_io::TestExternalities { ParachainType::Amplitude => ExtBuilderParachain::amplitude_default().balances(vec![]).build(), ParachainType::Sibling => ExtBuilderParachain::sibling_default().balances(vec![]).build(), + ParachainType::Moonriver => ExtBuilderParachain::moonriver_default().balances(vec![]).build(), } } @@ -202,6 +205,7 @@ impl ExtBuilderParachain { ParachainType::Pendulum => PENDULUM_ID, ParachainType::Sibling => SIBLING_ID, ParachainType::Amplitude => AMPLITUDE_ID, + ParachainType::Moonriver => MOONRIVER_PARA_ID, } } } @@ -257,6 +261,10 @@ impl ExtBuilderParachain { pub fn sibling_default() -> Self { Self { balances: vec![], chain: ParachainType::Sibling } } + + pub fn moonriver_default() -> Self { + Self { balances: vec![], chain: ParachainType::Moonriver } + } } impl Builder for ExtBuilderParachain { @@ -278,11 +286,23 @@ impl Builder for ExtBuilderParachain { SiblingCurrencyId ) }, + ParachainType::Moonriver => { + use sibling::{Runtime, System}; + build_parachain_with_orml!( + self, + Runtime, + System, + INITIAL_BALANCE, + ORML_INITIAL_BALANCE, + SiblingCurrencyId + ) + }, _ => panic!("cannot use this chain to build"), } } } + // ------------------- for Statemint and Statemine ------------------- impl ExtBuilderParachain { pub fn polkadot_asset_hub_default() -> Self { diff --git a/runtime/integration-tests/src/pendulum_tests.rs b/runtime/integration-tests/src/pendulum_tests.rs index 13038d66b..79caa871c 100644 --- a/runtime/integration-tests/src/pendulum_tests.rs +++ b/runtime/integration-tests/src/pendulum_tests.rs @@ -91,54 +91,54 @@ fn transfer_dot_from_pendulum_to_polkadot() { ); } -// #[test] -// fn assethub_transfer_incorrect_asset_to_pendulum_should_fail() { -// parachain1_transfer_incorrect_asset_to_parachain2_should_fail!( -// polkadot_asset_hub_runtime, -// AssetHubParachain, -// pendulum_runtime, -// PendulumParachain, -// PENDULUM_ID -// ); -// } +#[test] +fn assethub_transfer_incorrect_asset_to_pendulum_should_fail() { + parachain1_transfer_incorrect_asset_to_parachain2_should_fail!( + polkadot_asset_hub_runtime, + AssetHubParachain, + pendulum_runtime, + PendulumParachain, + PENDULUM_ID + ); +} -// #[test] -// fn assethub_transfer_asset_to_pendulum() { -// parachain1_transfer_asset_to_parachain2!( -// polkadot_asset_hub_runtime, -// AssetHubParachain, -// USDT_ASSET_ID, -// pendulum_runtime, -// PendulumParachain, -// PENDULUM_ID -// ); -// } +#[test] +fn assethub_transfer_asset_to_pendulum() { + parachain1_transfer_asset_to_parachain2!( + polkadot_asset_hub_runtime, + AssetHubParachain, + USDT_ASSET_ID, + pendulum_runtime, + PendulumParachain, + PENDULUM_ID + ); +} -// #[test] -// fn assethub_transfer_asset_to_pendulum_and_back() { -// let network_id = NetworkId::Polkadot; +#[test] +fn assethub_transfer_asset_to_pendulum_and_back() { + let network_id = NetworkId::Polkadot; -// parachain1_transfer_asset_to_parachain2_and_back!( -// polkadot_asset_hub_runtime, -// AssetHubParachain, -// ASSETHUB_ID, -// USDT_ASSET_ID, -// pendulum_runtime, -// PendulumParachain, -// PENDULUM_ID, -// network_id -// ); -// } + parachain1_transfer_asset_to_parachain2_and_back!( + polkadot_asset_hub_runtime, + AssetHubParachain, + ASSETHUB_ID, + USDT_ASSET_ID, + pendulum_runtime, + PendulumParachain, + PENDULUM_ID, + network_id + ); +} -// #[test] -// fn transfer_native_token_from_pendulum_to_sibling_parachain_and_back() { -// transfer_native_token_from_parachain1_to_parachain2_and_back!( -// PolkadotMockNet, -// pendulum_runtime, -// PendulumParachain, -// sibling, -// SiblingParachain, -// PENDULUM_ID, -// SIBLING_ID -// ); -// } +#[test] +fn transfer_native_token_from_pendulum_to_sibling_parachain_and_back() { + transfer_native_token_from_parachain1_to_parachain2_and_back!( + PolkadotMockNet, + pendulum_runtime, + PendulumParachain, + sibling, + SiblingParachain, + PENDULUM_ID, + SIBLING_ID + ); +} diff --git a/runtime/integration-tests/src/sibling.rs b/runtime/integration-tests/src/sibling.rs index 7887da235..953e7a1dd 100644 --- a/runtime/integration-tests/src/sibling.rs +++ b/runtime/integration-tests/src/sibling.rs @@ -43,6 +43,7 @@ use xcm_builder::{ SignedToAccountId32, SovereignSignedViaLocation, }; +use runtime_common::parachains::kusama::moonriver::{BRZ_location}; use crate::{AMPLITUDE_ID, ASSETHUB_ID, PENDULUM_ID}; const XCM_ASSET_RELAY_DOT: u8 = 0; @@ -128,7 +129,7 @@ impl Convert> for CurrencyIdConvert { Some(MultiLocation::new(1, X2(Parachain(PENDULUM_ID), PalletInstance(10)))), CurrencyId::Amplitude => Some(MultiLocation::new(1, X2(Parachain(AMPLITUDE_ID), PalletInstance(10)))), - CurrencyId::Token => Some(MultiLocation { parents: 1, interior: X2(Parachain(AMPLITUDE_ID), PalletInstance(2)) }), + CurrencyId::Token => Some(BRZ_location()), CurrencyId::XCM(f) => match f { XCM_ASSET_RELAY_DOT => Some(MultiLocation::parent()), // Handles both Kusama and Polkadot asset hub @@ -157,7 +158,7 @@ impl Convert> for CurrencyIdConvert { Some(CurrencyId::XCM(XCM_ASSET_ASSETHUB_USDT)), MultiLocation { parents: 1, interior: Here } => Some(CurrencyId::XCM(XCM_ASSET_RELAY_DOT)), - MultiLocation { parents: 1, interior: X2(Parachain(AMPLITUDE_ID), PalletInstance(2)) } => Some(CurrencyId::Token), + loc if loc == BRZ_location() => Some(CurrencyId::Token), _ => None, } } diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index fd7b1f0ef..b653fcadc 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -591,19 +591,22 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { Junction, Junction::{ GeneralKey, PalletInstance}, Junctions::{X1,X2, X3}, MultiLocation, WeightLimit, }; use $parachain2_runtime::CurrencyId as Parachain2CurrencyId; - - + use runtime_common::parachains::kusama::moonriver::{BRZ_location}; $mocknet::reset(); - // Asset Location and amount are not important for this test let transfer_amount: Balance = units(10); - - // Here we use the same asset, but the important bit is the multilocation - // This emulates the special multilocation that triggers the automation pallet + // We mock parachain 2 as beeing moonriver in this case. + // Sending "Token" variant which is equivalent to BRZ mock token Multilocation + // in the sibling definition $parachain2::execute_with(|| { - use $parachain2_runtime::{XTokens, Tokens,RuntimeOrigin}; + use $parachain2_runtime::{XTokens, Tokens,RuntimeOrigin, System}; assert_ok!(Tokens::set_balance(RuntimeOrigin::root().into(), ALICE.clone().into(), Parachain2CurrencyId::Token,transfer_amount, 0)); + + // We must ensure that the destination Multilocation is of the structure + // the intercept excepts so it calls automation pallet + + // TODO replace instance 99 with automation pallet index when added assert_ok!(XTokens::transfer( $parachain2_runtime::RuntimeOrigin::signed(ALICE.into()), Parachain2CurrencyId::Token, @@ -625,9 +628,6 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { $parachain1::execute_with(|| { use $parachain1_runtime::{RuntimeEvent, System}; - for i in System::events().iter() { - println!("para 1 events {}: {:?}\n", stringify!($para2_runtime), i); - } // given the configuration in amplitude's xcm_config, we expect the callback (in this case a Remark) // to be executed assert!(System::events().iter().any(|r| matches!( diff --git a/runtime/pendulum/src/xcm_config.rs b/runtime/pendulum/src/xcm_config.rs index 02de2a822..769758357 100644 --- a/runtime/pendulum/src/xcm_config.rs +++ b/runtime/pendulum/src/xcm_config.rs @@ -1,6 +1,6 @@ use super::{ AccountId, Balance, Balances, CurrencyId, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, WeightToFee, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, WeightToFee, XcmpQueue, System }; use crate::{ assets::{ @@ -26,6 +26,7 @@ use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; use runtime_common::parachains::polkadot::{asset_hub, equilibrium, moonbeam, polkadex}; +use runtime_common::custom_xcm_barrier::{MatcherConfig,AllowUnpaidExecutionFromCustom,ReserveAssetDepositedMatcher, DepositAssetMatcher, MatcherPair }; use sp_runtime::traits::Convert; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ @@ -38,6 +39,8 @@ use xcm_executor::{ traits::{JustTry, ShouldExecute}, XcmExecutor, }; +use sp_std::{vec,vec::Vec}; +use scale_info::prelude::boxed::Box; parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); @@ -263,7 +266,57 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } } -pub type Barrier = AllowUnpaidExecutionFrom; + +// We will allow for BRZ location from moonbeam +struct ReserveAssetDepositedMatcher1; +impl ReserveAssetDepositedMatcher for ReserveAssetDepositedMatcher1 { + fn matches(&self, multi_asset: &MultiAsset) -> bool { + let expected_multiloc = moonbeam::BRZ_location(); + + match multi_asset { + MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => return true, + _ => return false, + } + } +} + +// TODO modify with automation's pallet instance +struct DepositAssetMatcher1; +impl DepositAssetMatcher for DepositAssetMatcher1 { + fn matches<'a>(&self, assets: &'a MultiAssetFilter, beneficiary: &'a MultiLocation) -> Option<(u8, &'a [u8])> { + if let (Wild(AllCounted(1)), MultiLocation { parents: 0, interior: X2(PalletInstance(99), GeneralKey { length, data }) }) = (assets, beneficiary) { + Some((*length, &*data)) + } else { + None + } + } +} + +pub struct MatcherConfigPendulum; + +impl MatcherConfig for MatcherConfigPendulum { + fn get_matcher_pairs() -> Vec { + vec![ + MatcherPair::new( + Box::new(ReserveAssetDepositedMatcher1), + Box::new(DepositAssetMatcher1), + ), + // Additional matcher pairs to be defined in the future + ] + } + fn get_incoming_parachain_id() -> u32{ + moonbeam::PARA_ID + } + + fn callback(_length: u8, _data: &[u8])-> Result<(),()>{ + // TODO change to call the actual automation pallet, with data and length + System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0;32])), [0;1].to_vec()); + Ok(()) + } +} + + +pub type Barrier = AllowUnpaidExecutionFromCustom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { From d335032e3b35760f7375a17d1808b85cba06e4d4 Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Wed, 6 Dec 2023 18:22:59 -0300 Subject: [PATCH 04/11] fixes, format --- runtime/foucoco/src/xcm_config.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/runtime/foucoco/src/xcm_config.rs b/runtime/foucoco/src/xcm_config.rs index 25d6b4acb..be0168924 100644 --- a/runtime/foucoco/src/xcm_config.rs +++ b/runtime/foucoco/src/xcm_config.rs @@ -1,6 +1,6 @@ use super::{ AccountId, Balance, Balances, CurrencyId, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, WeightToFee, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, System, Tokens, WeightToFee, XcmpQueue, }; use crate::assets::{ native_locations::{native_location_external_pov, native_location_local_pov}, @@ -39,7 +39,7 @@ use runtime_common::{ }, parachains::moonbase_alpha::{BRZ_location, PARA_ID as MOONBASE_PARA_ID}, }; -use sp_std::{vec, vec::Vec}; +use sp_std::{boxed::Box, vec, vec::Vec}; parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); @@ -318,7 +318,7 @@ impl MatcherConfig for MatcherConfigFoucoco { ] } fn get_incoming_parachain_id() -> u32 { - MOONRIVER_PARA_ID + MOONBASE_PARA_ID } fn callback(_length: u8, _data: &[u8]) -> Result<(), ()> { @@ -328,7 +328,7 @@ impl MatcherConfig for MatcherConfigFoucoco { } } -pub type Barrier = MatcherConfigFoucoco; +pub type Barrier = AllowUnpaidExecutionFromCustom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { From 541231578c36c05650f8440c5208995afc46b30d Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Wed, 13 Dec 2023 14:33:36 -0300 Subject: [PATCH 05/11] move integration test BRZ from moonbeam into pendulum --- README.md | 2 +- runtime/amplitude/src/xcm_config.rs | 109 ++---------------- runtime/common/src/custom_xcm_barrier.rs | 5 +- runtime/foucoco/src/xcm_config.rs | 73 +----------- .../integration-tests/src/amplitude_tests.rs | 13 --- runtime/integration-tests/src/mock.rs | 20 ++++ .../integration-tests/src/pendulum_tests.rs | 26 +++++ runtime/integration-tests/src/sibling.rs | 3 +- runtime/integration-tests/src/test_macros.rs | 4 +- 9 files changed, 68 insertions(+), 187 deletions(-) diff --git a/README.md b/README.md index fefb28c3c..49a0b791c 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ runtimes `lib.rs` file. ```shell ./target/production/pendulum-node benchmark pallet \ - --cha foucoco \ + --chain foucoco \ --execution=wasm \ --wasm-execution=compiled \ --pallet "*" \ diff --git a/runtime/amplitude/src/xcm_config.rs b/runtime/amplitude/src/xcm_config.rs index 399332b43..2a4451d9d 100644 --- a/runtime/amplitude/src/xcm_config.rs +++ b/runtime/amplitude/src/xcm_config.rs @@ -1,6 +1,6 @@ use super::{ AccountId, Balance, Balances, CurrencyId, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, System, Tokens, WeightToFee, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, WeightToFee, XcmpQueue, }; use crate::{ assets::{ @@ -9,7 +9,6 @@ use crate::{ }, ConstU32, }; - use core::marker::PhantomData; use frame_support::{ log, match_types, parameter_types, @@ -22,40 +21,20 @@ use orml_traits::{ use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; -use runtime_common::parachains::kusama::{ - asset_hub, - moonriver::{BRZ_location, PARA_ID as MOONRIVER_PARA_ID}, -}; - +use runtime_common::parachains::kusama::asset_hub; use sp_runtime::traits::Convert; -use xcm::latest::{ - prelude::*, - Instruction::{self, *}, - Weight as XCMWeight, -}; +use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ - AccountId32Aliases, ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, - NoChecking, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, UsingComponents, + AccountId32Aliases, AllowUnpaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, + FixedWeightBounds, FungiblesAdapter, NoChecking, ParentIsPreset, RelayChainAsNative, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, UsingComponents, }; use xcm_executor::{ traits::{JustTry, ShouldExecute}, XcmExecutor, }; -use cumulus_primitives_core::XcmContext; -use runtime_common::custom_xcm_barrier::{ - AllowUnpaidExecutionFromCustom, DepositAssetMatcher, MatcherConfig, MatcherPair, - ReserveAssetDepositedMatcher, -}; -use scale_info::prelude::boxed::Box; -use sp_std::{vec, vec::Vec}; -use xcm::latest::{ - Junction::{GeneralKey, PalletInstance, Parachain}, - Junctions::{X2, X3}, - MultiLocation, -}; parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayNetwork: NetworkId = NetworkId::Kusama; @@ -150,6 +129,7 @@ where } } +/// Means for transacting the fungibles assets of ths parachain. pub type FungiblesTransactor = FungiblesAdapter< // Use this fungibles implementation Tokens, @@ -266,77 +246,8 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } } -// We will allow for BRZ location from moonriver -struct ReserveAssetDepositedMatcher1; -impl ReserveAssetDepositedMatcher for ReserveAssetDepositedMatcher1 { - fn matches(&self, multi_asset: &MultiAsset) -> bool { - let expected_multiloc = BRZ_location(); - - match multi_asset { - MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => - return true, - _ => return false, - } - } -} - -// The beneficiary. We will always expect a location of the form -// MultiLocation: { -// parents: 1, -// interior: { X3: { -// Parachain(SenderParachainId), -// PalletInstance(xx), // will point to the automation pallet -// GeneralKey{ length: xx, data: [] }, // this will hold the reference number for Mykobo -// }, -// Keep in mind that this location will be re-anchored - -// TODO modify with automation's pallet instance -struct DepositAssetMatcher1; -impl DepositAssetMatcher for DepositAssetMatcher1 { - fn matches<'a>( - &self, - assets: &'a MultiAssetFilter, - beneficiary: &'a MultiLocation, - ) -> Option<(u8, &'a [u8])> { - if let ( - Wild(AllCounted(1)), - MultiLocation { - parents: 0, - interior: X2(PalletInstance(99), GeneralKey { length, data }), - }, - ) = (assets, beneficiary) - { - Some((*length, &*data)) - } else { - None - } - } -} - -pub struct MatcherConfigAmplitude; - -impl MatcherConfig for MatcherConfigAmplitude { - fn get_matcher_pairs() -> Vec { - vec![ - MatcherPair::new( - Box::new(ReserveAssetDepositedMatcher1), - Box::new(DepositAssetMatcher1), - ), - // Additional matcher pairs to be defined in the future - ] - } - fn get_incoming_parachain_id() -> u32 { - MOONRIVER_PARA_ID - } +pub type Barrier = AllowUnpaidExecutionFrom; - fn callback(_length: u8, _data: &[u8]) -> Result<(), ()> { - // TODO change to call the actual automation pallet, with data and length - System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0; 32])), [0; 1].to_vec()); - Ok(()) - } -} - -pub type Barrier = AllowUnpaidExecutionFromCustom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; @@ -449,4 +360,4 @@ impl Convert for AccountIdToMultiLocation { impl cumulus_pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; -} +} \ No newline at end of file diff --git a/runtime/common/src/custom_xcm_barrier.rs b/runtime/common/src/custom_xcm_barrier.rs index a4eb899da..4402f2ef9 100644 --- a/runtime/common/src/custom_xcm_barrier.rs +++ b/runtime/common/src/custom_xcm_barrier.rs @@ -70,6 +70,9 @@ impl, V: MatcherConfig> ShouldExecute ); log::info!("origin {:?}", origin); let incoming_parachain_id = V::get_incoming_parachain_id(); + + ensure!(T::contains(origin), ()); + // Check if the origin is the specific parachain if let MultiLocation { parents: 1, interior: X1(Parachain(parachain_id)) } = origin { log::info!("paraid {:?}", *parachain_id); @@ -115,7 +118,7 @@ impl, V: MatcherConfig> ShouldExecute } } - ensure!(T::contains(origin), ()); + Ok(()) } } diff --git a/runtime/foucoco/src/xcm_config.rs b/runtime/foucoco/src/xcm_config.rs index be0168924..5dc110753 100644 --- a/runtime/foucoco/src/xcm_config.rs +++ b/runtime/foucoco/src/xcm_config.rs @@ -1,6 +1,6 @@ use super::{ AccountId, Balance, Balances, CurrencyId, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, System, Tokens, WeightToFee, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, WeightToFee, XcmpQueue, }; use crate::assets::{ native_locations::{native_location_external_pov, native_location_local_pov}, @@ -32,15 +32,6 @@ use xcm_executor::{ XcmExecutor, }; -use runtime_common::{ - custom_xcm_barrier::{ - AllowUnpaidExecutionFromCustom, DepositAssetMatcher, MatcherConfig, MatcherPair, - ReserveAssetDepositedMatcher, - }, - parachains::moonbase_alpha::{BRZ_location, PARA_ID as MOONBASE_PARA_ID}, -}; -use sp_std::{boxed::Box, vec, vec::Vec}; - parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayNetwork: NetworkId = NetworkId::Rococo; @@ -270,65 +261,7 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } } -struct ReserveAssetDepositedMatcher1; -impl ReserveAssetDepositedMatcher for ReserveAssetDepositedMatcher1 { - fn matches(&self, multi_asset: &MultiAsset) -> bool { - let expected_multiloc = BRZ_location(); - - match multi_asset { - MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => - return true, - _ => return false, - } - } -} -// TODO modify with automation's pallet instance -struct DepositAssetMatcher1; -impl DepositAssetMatcher for DepositAssetMatcher1 { - fn matches<'a>( - &self, - assets: &'a MultiAssetFilter, - beneficiary: &'a MultiLocation, - ) -> Option<(u8, &'a [u8])> { - if let ( - Wild(AllCounted(1)), - MultiLocation { - parents: 0, - interior: X2(PalletInstance(99), GeneralKey { length, data }), - }, - ) = (assets, beneficiary) - { - Some((*length, &*data)) - } else { - None - } - } -} - -pub struct MatcherConfigFoucoco; - -impl MatcherConfig for MatcherConfigFoucoco { - fn get_matcher_pairs() -> Vec { - vec![ - MatcherPair::new( - Box::new(ReserveAssetDepositedMatcher1), - Box::new(DepositAssetMatcher1), - ), - // Additional matcher pairs to be defined in the future - ] - } - fn get_incoming_parachain_id() -> u32 { - MOONBASE_PARA_ID - } - - fn callback(_length: u8, _data: &[u8]) -> Result<(), ()> { - // TODO change to call the actual automation pallet, with data and length - System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0; 32])), [0; 1].to_vec()); - Ok(()) - } -} - -pub type Barrier = AllowUnpaidExecutionFromCustom; +pub type Barrier = AllowUnpaidExecutionFrom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -443,4 +376,4 @@ impl Convert for AccountIdToMultiLocation { impl cumulus_pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; -} +} \ No newline at end of file diff --git a/runtime/integration-tests/src/amplitude_tests.rs b/runtime/integration-tests/src/amplitude_tests.rs index 700f98fa5..7d07f8f1e 100644 --- a/runtime/integration-tests/src/amplitude_tests.rs +++ b/runtime/integration-tests/src/amplitude_tests.rs @@ -156,16 +156,3 @@ fn transfer_native_token_from_amplitude_to_sibling_parachain_and_back() { SIBLING_ID ); } - -#[test] -fn moonbeam_transfers_token_and_handle_automation() { - moonbeam_transfers_token_and_handle_automation!( - KusamaMockNet, - amplitude_runtime, - AmplitudeParachain, - sibling, - MoonriverParachain, - AMPLITUDE_ID, - MOONRIVER_PARA_ID - ); -} diff --git a/runtime/integration-tests/src/mock.rs b/runtime/integration-tests/src/mock.rs index 42d6a1467..0e894ca02 100644 --- a/runtime/integration-tests/src/mock.rs +++ b/runtime/integration-tests/src/mock.rs @@ -11,6 +11,7 @@ use sp_runtime::traits::AccountIdConversion; use xcm_emulator::Weight; use runtime_common::parachains::kusama::moonriver::PARA_ID as MOONRIVER_PARA_ID; +use runtime_common::parachains::polkadot::moonbeam::PARA_ID as MOONBEAM_PARA_ID; use statemine_runtime as kusama_asset_hub_runtime; use statemint_runtime as polkadot_asset_hub_runtime; @@ -120,6 +121,7 @@ pub enum ParachainType { Amplitude, Sibling, Moonriver, + Moonbeam } pub struct ExtBuilderParachain { @@ -195,6 +197,8 @@ pub fn para_ext(chain: ParachainType) -> sp_io::TestExternalities { ParachainType::Sibling => ExtBuilderParachain::sibling_default().balances(vec![]).build(), ParachainType::Moonriver => ExtBuilderParachain::moonriver_default().balances(vec![]).build(), + ParachainType::Moonbeam => + ExtBuilderParachain::moonbeam_default().balances(vec![]).build(), } } @@ -207,6 +211,7 @@ impl ExtBuilderParachain { ParachainType::Sibling => SIBLING_ID, ParachainType::Amplitude => AMPLITUDE_ID, ParachainType::Moonriver => MOONRIVER_PARA_ID, + ParachainType::Moonbeam => MOONBEAM_PARA_ID, } } } @@ -266,6 +271,10 @@ impl ExtBuilderParachain { pub fn moonriver_default() -> Self { Self { balances: vec![], chain: ParachainType::Moonriver } } + + pub fn moonbeam_default() -> Self { + Self { balances: vec![], chain: ParachainType::Moonbeam } + } } impl Builder for ExtBuilderParachain { @@ -298,6 +307,17 @@ impl Builder for ExtBuilderParachain { SiblingCurrencyId ) }, + ParachainType::Moonbeam => { + use sibling::{Runtime, System}; + build_parachain_with_orml!( + self, + Runtime, + System, + INITIAL_BALANCE, + ORML_INITIAL_BALANCE, + SiblingCurrencyId + ) + }, _ => panic!("cannot use this chain to build"), } } diff --git a/runtime/integration-tests/src/pendulum_tests.rs b/runtime/integration-tests/src/pendulum_tests.rs index 79caa871c..0f4118e29 100644 --- a/runtime/integration-tests/src/pendulum_tests.rs +++ b/runtime/integration-tests/src/pendulum_tests.rs @@ -7,6 +7,7 @@ use crate::{ transfer_10_relay_token_from_parachain_to_relay_chain, transfer_20_relay_token_from_relay_chain_to_parachain, transfer_native_token_from_parachain1_to_parachain2_and_back, + moonbeam_transfers_token_and_handle_automation }, ASSETHUB_ID, PENDULUM_ID, SIBLING_ID, }; @@ -15,6 +16,7 @@ use frame_support::assert_ok; use statemint_runtime as polkadot_asset_hub_runtime; use xcm::latest::NetworkId; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; +use runtime_common::parachains::polkadot::moonbeam::PARA_ID as MOONBEAM_PARA_ID; const DOT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 3200000000; //The fees that relay chain will charge when transfer DOT to parachain. sovereign account of some parachain will receive transfer_amount - DOT_FEE @@ -56,12 +58,23 @@ decl_test_parachain! { } } +decl_test_parachain! { + pub struct MoonbeamParachain { + Runtime = sibling::Runtime, + RuntimeOrigin = sibling::RuntimeOrigin, + XcmpMessageHandler = sibling::XcmpQueue, + DmpMessageHandler = sibling::DmpQueue, + new_ext = para_ext(ParachainType::Moonbeam), + } +} + decl_test_network! { pub struct PolkadotMockNet { relay_chain = PolkadotRelay, parachains = vec![ (1000, AssetHubParachain), (2094, PendulumParachain), + (2004, MoonbeamParachain), (9999, SiblingParachain), ], } @@ -142,3 +155,16 @@ fn transfer_native_token_from_pendulum_to_sibling_parachain_and_back() { SIBLING_ID ); } + +#[test] +fn moonbeam_transfers_token_and_handle_automation() { + moonbeam_transfers_token_and_handle_automation!( + PolkadotMockNet, + pendulum_runtime, + PendulumParachain, + sibling, + MoonbeamParachain, + PENDULUM_ID, + MOONBEAM_PARA_ID + ); +} diff --git a/runtime/integration-tests/src/sibling.rs b/runtime/integration-tests/src/sibling.rs index 9cb7609b0..30f05b4fb 100644 --- a/runtime/integration-tests/src/sibling.rs +++ b/runtime/integration-tests/src/sibling.rs @@ -44,7 +44,8 @@ use xcm_builder::{ }; use crate::{AMPLITUDE_ID, ASSETHUB_ID, PENDULUM_ID}; -use runtime_common::parachains::kusama::moonriver::BRZ_location; + +use runtime_common::parachains::polkadot::moonbeam::BRZ_location; const XCM_ASSET_RELAY_DOT: u8 = 0; const XCM_ASSET_ASSETHUB_USDT: u8 = 1; diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index 92145b8ca..c1e73fd50 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -588,7 +588,7 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { Junction, Junction::{ GeneralKey, PalletInstance}, Junctions::{X1,X2, X3}, MultiLocation, WeightLimit, }; use $parachain2_runtime::CurrencyId as Parachain2CurrencyId; - use runtime_common::parachains::kusama::moonriver::{BRZ_location}; + $mocknet::reset(); let transfer_amount: Balance = units(10); @@ -625,7 +625,7 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { $parachain1::execute_with(|| { use $parachain1_runtime::{RuntimeEvent, System}; - // given the configuration in amplitude's xcm_config, we expect the callback (in this case a Remark) + // given the configuration in pendulum's xcm_config, we expect the callback (in this case a Remark) // to be executed assert!(System::events().iter().any(|r| matches!( r.event, From 1152ff805282de6e03912c8978d320fde1f05a7a Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Wed, 13 Dec 2023 14:39:00 -0300 Subject: [PATCH 06/11] remove mock BRZ asset moonriver, moonbase --- runtime/common/src/lib.rs | 56 ------------------- .../integration-tests/src/amplitude_tests.rs | 13 ----- runtime/integration-tests/src/mock.rs | 20 ------- 3 files changed, 89 deletions(-) diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index ce965e339..5e8db8de3 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -193,62 +193,6 @@ pub mod parachains { pub mod asset_hub { pub use super::super::polkadot::asset_hub::*; } - - pub mod moonriver { - use xcm::latest::{ - Junction::{AccountKey20, PalletInstance, Parachain}, - Junctions::X3, - }; - - // see https://docs.moonbeam.network/builders/interoperability/xcm/xc-registration/assets/ - pub const PARA_ID: u32 = 2023; - pub const ASSET_PALLET_INDEX: u8 = 10; - - // TODO use the REAL BRZ asset on moonriver - // 0xD65A1872f2E2E26092A443CB86bb5d8572027E6E - // extracted using `H160::from_str("...")` then `as_bytes()` - pub const BRZ_ASSET_ACCOUNT_IN_BYTES: [u8; 20] = [ - 214, 90, 24, 114, 242, 226, 226, 96, 146, 164, 67, 203, 134, 187, 93, 133, 114, 2, - 126, 110, - ]; - - parachain_asset_location!( - BRZ, - X3( - Parachain(PARA_ID), - PalletInstance(ASSET_PALLET_INDEX), - AccountKey20 { network: None, key: BRZ_ASSET_ACCOUNT_IN_BYTES } - ) - ); - } - } - - pub mod moonbase_alpha { - use xcm::latest::{ - Junction::{AccountKey20, PalletInstance, Parachain}, - Junctions::X3, - }; - - // see https://docs.moonbeam.network/builders/interoperability/xcm/xc-registration/assets/ - pub const PARA_ID: u32 = 1000; - pub const ASSET_PALLET_INDEX: u8 = 3; - - // TODO use the REAL BRZ asset on moonbase alpha - // 0xD65A1872f2E2E26092A443CB86bb5d8572027E6E - // extracted using `H160::from_str("...")` then `as_bytes()` - pub const BRZ_ASSET_ACCOUNT_IN_BYTES: [u8; 20] = [ - 214, 90, 24, 114, 242, 226, 226, 96, 146, 164, 67, 203, 134, 187, 93, 133, 114, 2, 126, - 110, - ]; - - parachain_asset_location!( - BRZ, - X3( - Parachain(PARA_ID), - PalletInstance(ASSET_PALLET_INDEX), - AccountKey20 { network: None, key: BRZ_ASSET_ACCOUNT_IN_BYTES } - ) - ); } pub mod moonbase_alpha_relay { diff --git a/runtime/integration-tests/src/amplitude_tests.rs b/runtime/integration-tests/src/amplitude_tests.rs index 7d07f8f1e..ac2801bda 100644 --- a/runtime/integration-tests/src/amplitude_tests.rs +++ b/runtime/integration-tests/src/amplitude_tests.rs @@ -12,8 +12,6 @@ use crate::{ AMPLITUDE_ID, ASSETHUB_ID, SIBLING_ID, }; -use runtime_common::parachains::kusama::moonriver::PARA_ID as MOONRIVER_PARA_ID; - use frame_support::assert_ok; use statemine_runtime as kusama_asset_hub_runtime; use xcm::latest::NetworkId; @@ -49,16 +47,6 @@ decl_test_parachain! { } } -decl_test_parachain! { - pub struct MoonriverParachain { - Runtime = sibling::Runtime, - RuntimeOrigin = sibling::RuntimeOrigin, - XcmpMessageHandler = sibling::XcmpQueue, - DmpMessageHandler = sibling::DmpQueue, - new_ext = para_ext(ParachainType::Moonriver), - } -} - decl_test_parachain! { pub struct AssetHubParachain { Runtime = kusama_asset_hub_runtime::Runtime, @@ -76,7 +64,6 @@ decl_test_network! { (1000, AssetHubParachain), (2124, AmplitudeParachain), (9999, SiblingParachain), - (2023, MoonriverParachain), ], } } diff --git a/runtime/integration-tests/src/mock.rs b/runtime/integration-tests/src/mock.rs index 0e894ca02..cc9909f7e 100644 --- a/runtime/integration-tests/src/mock.rs +++ b/runtime/integration-tests/src/mock.rs @@ -10,7 +10,6 @@ use sp_io::TestExternalities; use sp_runtime::traits::AccountIdConversion; use xcm_emulator::Weight; -use runtime_common::parachains::kusama::moonriver::PARA_ID as MOONRIVER_PARA_ID; use runtime_common::parachains::polkadot::moonbeam::PARA_ID as MOONBEAM_PARA_ID; use statemine_runtime as kusama_asset_hub_runtime; use statemint_runtime as polkadot_asset_hub_runtime; @@ -120,7 +119,6 @@ pub enum ParachainType { Pendulum, Amplitude, Sibling, - Moonriver, Moonbeam } @@ -195,8 +193,6 @@ pub fn para_ext(chain: ParachainType) -> sp_io::TestExternalities { ParachainType::Amplitude => ExtBuilderParachain::amplitude_default().balances(vec![]).build(), ParachainType::Sibling => ExtBuilderParachain::sibling_default().balances(vec![]).build(), - ParachainType::Moonriver => - ExtBuilderParachain::moonriver_default().balances(vec![]).build(), ParachainType::Moonbeam => ExtBuilderParachain::moonbeam_default().balances(vec![]).build(), } @@ -210,7 +206,6 @@ impl ExtBuilderParachain { ParachainType::Pendulum => PENDULUM_ID, ParachainType::Sibling => SIBLING_ID, ParachainType::Amplitude => AMPLITUDE_ID, - ParachainType::Moonriver => MOONRIVER_PARA_ID, ParachainType::Moonbeam => MOONBEAM_PARA_ID, } } @@ -268,10 +263,6 @@ impl ExtBuilderParachain { Self { balances: vec![], chain: ParachainType::Sibling } } - pub fn moonriver_default() -> Self { - Self { balances: vec![], chain: ParachainType::Moonriver } - } - pub fn moonbeam_default() -> Self { Self { balances: vec![], chain: ParachainType::Moonbeam } } @@ -296,17 +287,6 @@ impl Builder for ExtBuilderParachain { SiblingCurrencyId ) }, - ParachainType::Moonriver => { - use sibling::{Runtime, System}; - build_parachain_with_orml!( - self, - Runtime, - System, - INITIAL_BALANCE, - ORML_INITIAL_BALANCE, - SiblingCurrencyId - ) - }, ParachainType::Moonbeam => { use sibling::{Runtime, System}; build_parachain_with_orml!( From 242db38f822bfda9a6e5e701ccf94e091bd11ffb Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Wed, 13 Dec 2023 14:43:50 -0300 Subject: [PATCH 07/11] re-add test macro --- runtime/amplitude/src/lib.rs | 1 - runtime/integration-tests/src/test_macros.rs | 36 +++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/runtime/amplitude/src/lib.rs b/runtime/amplitude/src/lib.rs index 895c0e366..9a968e9f2 100644 --- a/runtime/amplitude/src/lib.rs +++ b/runtime/amplitude/src/lib.rs @@ -1296,7 +1296,6 @@ impl pallet_proxy::Config for Runtime { type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; } - // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index c1e73fd50..322da874c 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -415,13 +415,47 @@ macro_rules! parachain1_transfer_asset_to_parachain2_and_back { WeightLimit::Unlimited )); + assert_eq!( + TEN_UNITS - 1 * UNIT, //initial balance - one unit + Tokens::balance(CurrencyId::XCM(1), &AccountId::from(BOB)) + ); + assert!(System::events().iter().any(|r| matches!( r.event, RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }) ))); for i in System::events().iter() { - println!("para 2 {}: {:?}\n", stringify!($para2_runtime), i); + println!("{}: {:?}\n", stringify!($para2_runtime), i); + } + }); + + $parachain1::execute_with(|| { + use $para1_runtime::*; + + for i in System::events().iter() { + println!("{}: {:?}\n", stringify!($para1_runtime), i); + } + + let events = System::events(); + match &events[events.len() - 2] { + &frame_system::EventRecord { + phase: frame_system::Phase::Initialization, + event: + RuntimeEvent::Assets(pallet_assets::Event::Issued { + asset_id: $para1_asset_id, + owner: _, + amount, + }), + topics: _, + } => { + // https://github.com/paritytech/cumulus/pull/1278 support using self sufficient asset + // for paying xcm execution fee. + // 990_000_000_000 for Statemint + // 988_423_297_485 for Statemine + assert_eq!(amount, Assets::balance($para1_asset_id, &AccountId::from(BOB))); + }, + other => panic!("wrong event: {other:?}"), } }); }}; From 54a0aa96423738f66194615a3e42d38bb27bb924 Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Wed, 13 Dec 2023 16:57:04 -0300 Subject: [PATCH 08/11] extracting a fee from handled asset --- runtime/common/src/custom_xcm_barrier.rs | 42 ++++++++++++------- runtime/integration-tests/src/test_macros.rs | 9 +++- runtime/pendulum/src/xcm_config.rs | 44 ++++++++++++++------ 3 files changed, 66 insertions(+), 29 deletions(-) diff --git a/runtime/common/src/custom_xcm_barrier.rs b/runtime/common/src/custom_xcm_barrier.rs index 4402f2ef9..31b8c3711 100644 --- a/runtime/common/src/custom_xcm_barrier.rs +++ b/runtime/common/src/custom_xcm_barrier.rs @@ -1,7 +1,7 @@ use core::marker::PhantomData; use frame_support::{ensure, log, traits::Contains}; -use xcm::latest::{prelude::*, Instruction, Weight as XCMWeight}; +use xcm::{latest::{prelude::*, Instruction, Weight as XCMWeight}}; use xcm_executor::traits::ShouldExecute; @@ -9,7 +9,7 @@ use scale_info::prelude::boxed::Box; use sp_std::vec::Vec; pub trait ReserveAssetDepositedMatcher: Sync { - fn matches(&self, multi_asset: &MultiAsset) -> bool; + fn matches(&self, multi_asset: &MultiAsset) -> Option; } pub trait DepositAssetMatcher { @@ -32,7 +32,7 @@ impl MatcherPair { MatcherPair { reserve_deposited_asset_matcher, deposit_asset_matcher } } - fn matches_reserve_deposited(&self, multi_asset: &MultiAsset) -> bool { + fn matches_reserve_deposited(&self, multi_asset: &MultiAsset) -> Option { self.reserve_deposited_asset_matcher.matches(multi_asset) } @@ -47,8 +47,9 @@ impl MatcherPair { pub trait MatcherConfig { fn get_matcher_pairs() -> Vec; - fn callback(length: u8, data: &[u8]) -> Result<(), ()>; + fn callback(length: u8, data: &[u8], amount: u128) -> Result<(), ()>; fn get_incoming_parachain_id() -> u32; + fn extract_fee(location: MultiLocation, amount: u128)-> u128; } pub struct AllowUnpaidExecutionFromCustom { @@ -83,32 +84,43 @@ impl, V: MatcherConfig> ShouldExecute // Iterate through the instructions, for // each match pair we allow for matcher_pair in matcher_pairs { - let mut reserve_deposited_matched = false; + let mut reserve_deposited_asset_matched: Option = None; + let mut amount_to_process: u128 = 0; + // Check for ReserveAssetDeposited instruction for instruction in instructions.iter() { if let Instruction::ReserveAssetDeposited(assets) = instruction { - if assets - .clone() - .into_inner() - .iter() - .any(|asset| matcher_pair.matches_reserve_deposited(asset)) - { - reserve_deposited_matched = true; - break + + for asset in assets.clone().into_inner().iter() { + if let Some(matched_asset) = matcher_pair.matches_reserve_deposited(asset) { + + // Check if the matched asset is fungible and extract the amount + if let MultiAsset { + id: Concrete(location), + fun: Fungibility::Fungible(amount_deposited), + } = matched_asset + { + reserve_deposited_asset_matched = Some(location); + amount_to_process = amount_deposited; + break; // Break as the matched asset is found and amount is extracted + } + } } } } // If ReserveAssetDeposited matches, then check for DepositAsset with the same matcher pair // and execute the callback - if reserve_deposited_matched { + if let Some(location) = reserve_deposited_asset_matched { for instruction in instructions.iter() { if let Instruction::DepositAsset { assets, beneficiary } = instruction { if let Some((length, data)) = matcher_pair.matches_deposit_asset(assets, beneficiary) { - V::callback(length, data); + + let amount_to_deposit = V::extract_fee(location, amount_to_process); + V::callback(length, data,amount_to_deposit); return Err(()) } } diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index 322da874c..ca3539a2c 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -618,6 +618,7 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { ) => {{ use crate::mock::{units, ALICE}; use polkadot_core_primitives::Balance; + use xcm::latest::{ Junction, Junction::{ GeneralKey, PalletInstance}, Junctions::{X1,X2, X3}, MultiLocation, WeightLimit, }; @@ -658,7 +659,7 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { }); $parachain1::execute_with(|| { - use $parachain1_runtime::{RuntimeEvent, System}; + use $parachain1_runtime::{RuntimeEvent, System, Tokens}; // given the configuration in pendulum's xcm_config, we expect the callback (in this case a Remark) // to be executed assert!(System::events().iter().any(|r| matches!( @@ -666,6 +667,12 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { RuntimeEvent::System(frame_system::Event::Remarked { .. }) ))); + // Assert also that the fee has been given to the treasury id + assert!(System::events().iter().any(|r| matches!( + r.event, + RuntimeEvent::Tokens(orml_tokens::Event::Deposited { .. }) + ))); + }); }}; } diff --git a/runtime/pendulum/src/xcm_config.rs b/runtime/pendulum/src/xcm_config.rs index 32ab5cd6a..4d8adbb2b 100644 --- a/runtime/pendulum/src/xcm_config.rs +++ b/runtime/pendulum/src/xcm_config.rs @@ -1,7 +1,9 @@ use super::{ AccountId, Balance, Balances, CurrencyId, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, System, Tokens, WeightToFee, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, System, Tokens, WeightToFee, XcmpQueue, Currencies, Treasury }; + +pub use sp_runtime::Perbill; use crate::{ assets::{ self, @@ -20,7 +22,7 @@ use frame_support::{ }; use orml_traits::{ location::{RelativeReserveProvider, Reserve}, - parameter_type_with_key, + parameter_type_with_key, MultiCurrency, }; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; @@ -33,7 +35,7 @@ use runtime_common::{ parachains::polkadot::{asset_hub, equilibrium, moonbeam, polkadex}, }; use scale_info::prelude::boxed::Box; -use sp_runtime::traits::Convert; +use sp_runtime::traits::{Convert, AccountIdConversion}; use sp_std::{vec, vec::Vec}; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ @@ -272,22 +274,22 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } // We will allow for BRZ location from moonbeam -struct ReserveAssetDepositedMatcher1; -impl ReserveAssetDepositedMatcher for ReserveAssetDepositedMatcher1 { - fn matches(&self, multi_asset: &MultiAsset) -> bool { +struct BRZMoonbeamAssetMatcher; +impl ReserveAssetDepositedMatcher for BRZMoonbeamAssetMatcher { + fn matches(&self, multi_asset: &MultiAsset) -> Option { let expected_multiloc = moonbeam::BRZ_location(); match multi_asset { MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => - return true, - _ => return false, + return Some(multi_asset.clone()), + _ => return None, } } } // TODO modify with automation's pallet instance -struct DepositAssetMatcher1; -impl DepositAssetMatcher for DepositAssetMatcher1 { +struct PendulumAutomationPalletMatcher; +impl DepositAssetMatcher for PendulumAutomationPalletMatcher { fn matches<'a>( &self, assets: &'a MultiAssetFilter, @@ -314,8 +316,8 @@ impl MatcherConfig for MatcherConfigPendulum { fn get_matcher_pairs() -> Vec { vec![ MatcherPair::new( - Box::new(ReserveAssetDepositedMatcher1), - Box::new(DepositAssetMatcher1), + Box::new(BRZMoonbeamAssetMatcher), + Box::new(PendulumAutomationPalletMatcher), ), // Additional matcher pairs to be defined in the future ] @@ -324,11 +326,27 @@ impl MatcherConfig for MatcherConfigPendulum { moonbeam::PARA_ID } - fn callback(_length: u8, _data: &[u8]) -> Result<(), ()> { + fn callback(_length: u8, _data: &[u8], _amount: u128) -> Result<(), ()> { // TODO change to call the actual automation pallet, with data and length System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0; 32])), [0; 1].to_vec()); Ok(()) } + + // TODO define actual desired implementation of fee extraction. + // In this placeholder implementation, some percentage is given to treasury account + // in the local currency representing the asset from + // ReserveDepositAsset (the original asset) + fn extract_fee(location: MultiLocation, amount: u128)-> u128 { + if let Some(currency_id) = CurrencyIdConvert::convert(location){ + + let fee = Perbill::from_percent(1) * amount; + >::deposit(currency_id, &Treasury::account_id(), fee); + amount - fee + }else{ + amount + } + + } } pub type Barrier = AllowUnpaidExecutionFromCustom; From 6db2cb9c7748da9dc53ef9cdf937afb352df21e5 Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Tue, 19 Dec 2023 13:12:57 -0300 Subject: [PATCH 09/11] use custom asset transactor to handle automation pallet call --- Cargo.lock | 1 + runtime/common/Cargo.toml | 2 + runtime/common/src/custom_transactor.rs | 158 +++++++++++++++++++ runtime/common/src/custom_xcm_barrier.rs | 136 ---------------- runtime/common/src/lib.rs | 2 +- runtime/integration-tests/src/test_macros.rs | 5 - runtime/pendulum/src/xcm_config.rs | 108 ++++--------- 7 files changed, 194 insertions(+), 218 deletions(-) create mode 100644 runtime/common/src/custom_transactor.rs delete mode 100644 runtime/common/src/custom_xcm_barrier.rs diff --git a/Cargo.lock b/Cargo.lock index 4f1526047..d35bdc13b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10071,6 +10071,7 @@ dependencies = [ "frame-system", "orml-asset-registry", "orml-traits", + "orml-xcm-support", "parity-scale-codec", "paste", "scale-info", diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 6ab9ec789..7bc227474 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -28,6 +28,7 @@ xcm-executor = { git = "https://github.com/paritytech/polkadot", default-feature orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.40" } orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.40" } +orml-xcm-support = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.40" } dia-oracle = { git = "https://github.com/pendulum-chain/oracle-pallet", default-features = false, branch = "polkadot-v0.9.40" } zenlink-protocol = { git = "https://github.com/pendulum-chain/Zenlink-DEX-Module", default-features = false, branch = "polkadot-v0.9.40-protocol" } @@ -54,6 +55,7 @@ std = [ "orml-traits/std", "dia-oracle/std", "orml-asset-registry/std", + "orml-xcm-support/std", "zenlink-protocol/std", "spacewalk-primitives/std", ] diff --git a/runtime/common/src/custom_transactor.rs b/runtime/common/src/custom_transactor.rs new file mode 100644 index 000000000..9502583aa --- /dev/null +++ b/runtime/common/src/custom_transactor.rs @@ -0,0 +1,158 @@ + +use sp_runtime::codec::FullCodec; +use sp_runtime::{ + traits::{Convert, MaybeSerializeDeserialize, SaturatedConversion}, +}; +use sp_std::{ + cmp::{Eq, PartialEq}, + fmt::Debug, + marker::PhantomData, + prelude::*, + result, +}; + +use xcm::v3::{prelude::*, Error as XcmError, MultiAsset, MultiLocation, Result}; +use xcm_executor::{ + traits::{Convert as MoreConvert, MatchesFungible, TransactAsset}, + Assets, +}; +use orml_xcm_support::{UnknownAsset as UnknownAssetT,OnDepositFail}; + + +/// Asset transaction errors. +enum Error { + /// Failed to match fungible. + FailedToMatchFungible, + /// `MultiLocation` to `AccountId` Conversion failed. + AccountIdConversionFailed, + /// `CurrencyId` conversion failed. + CurrencyIdConversionFailed, +} + +impl From for XcmError { + fn from(e: Error) -> Self { + match e { + Error::FailedToMatchFungible => XcmError::FailedToTransactAsset("FailedToMatchFungible"), + Error::AccountIdConversionFailed => XcmError::FailedToTransactAsset("AccountIdConversionFailed"), + Error::CurrencyIdConversionFailed => XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), + } + } +} + +pub trait AutomationPalletConfig { + fn matches_asset(asset: &MultiAsset) -> Option; + fn matches_beneficiary(beneficiary_location: &MultiLocation) -> Option<(u8, [u8;32])>; + fn callback(length: u8, data: [u8;32], amount: u128) -> Result; +} + +#[allow(clippy::type_complexity)] +pub struct CustomMultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Match, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, + DepositFailureHandler, + AutomationPalletConfigT, +>( + PhantomData<( + MultiCurrency, + UnknownAsset, + Match, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, + DepositFailureHandler, + AutomationPalletConfigT, + )>, +); + +impl< + MultiCurrency: orml_traits::MultiCurrency, + UnknownAsset: UnknownAssetT, + Match: MatchesFungible, + AccountId: sp_std::fmt::Debug + Clone, + AccountIdConvert: MoreConvert, + CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, + CurrencyIdConvert: Convert>, + DepositFailureHandler: OnDepositFail, + AutomationPalletConfigT: AutomationPalletConfig + > TransactAsset + for CustomMultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Match, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, + DepositFailureHandler, + AutomationPalletConfigT, + > +{ + fn deposit_asset(asset: &MultiAsset, location: &MultiLocation, _context: &XcmContext) -> Result { + if let Some(amount_deposited) = AutomationPalletConfigT::matches_asset(asset){ + + if let Some((length,data)) = AutomationPalletConfigT::matches_beneficiary(location){ + AutomationPalletConfigT::callback(length, data, amount_deposited); + return Ok(()); + } + } + match ( + AccountIdConvert::convert_ref(location), + CurrencyIdConvert::convert(asset.clone()), + Match::matches_fungible(asset), + ) { + // known asset + (Ok(who), Some(currency_id), Some(amount)) => MultiCurrency::deposit(currency_id, &who, amount) + .or_else(|err| DepositFailureHandler::on_deposit_currency_fail(err, currency_id, &who, amount)), + // unknown asset + _ => UnknownAsset::deposit(asset, location) + .or_else(|err| DepositFailureHandler::on_deposit_unknown_asset_fail(err, asset, location)), + } + } + + fn withdraw_asset( + asset: &MultiAsset, + location: &MultiLocation, + _maybe_context: Option<&XcmContext>, + ) -> result::Result { + UnknownAsset::withdraw(asset, location).or_else(|_| { + let who = AccountIdConvert::convert_ref(location) + .map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; + let currency_id = CurrencyIdConvert::convert(asset.clone()) + .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; + let amount: MultiCurrency::Balance = Match::matches_fungible(asset) + .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? + .saturated_into(); + MultiCurrency::withdraw(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) + })?; + + Ok(asset.clone().into()) + } + + fn transfer_asset( + asset: &MultiAsset, + from: &MultiLocation, + to: &MultiLocation, + _context: &XcmContext, + ) -> result::Result { + let from_account = + AccountIdConvert::convert_ref(from).map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; + let to_account = + AccountIdConvert::convert_ref(to).map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; + let currency_id = CurrencyIdConvert::convert(asset.clone()) + .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; + let amount: MultiCurrency::Balance = Match::matches_fungible(asset) + .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? + .saturated_into(); + MultiCurrency::transfer(currency_id, &from_account, &to_account, amount) + .map_err(|e| XcmError::FailedToTransactAsset(e.into()))?; + + Ok(asset.clone().into()) + } +} + diff --git a/runtime/common/src/custom_xcm_barrier.rs b/runtime/common/src/custom_xcm_barrier.rs deleted file mode 100644 index 31b8c3711..000000000 --- a/runtime/common/src/custom_xcm_barrier.rs +++ /dev/null @@ -1,136 +0,0 @@ -use core::marker::PhantomData; -use frame_support::{ensure, log, traits::Contains}; - -use xcm::{latest::{prelude::*, Instruction, Weight as XCMWeight}}; - -use xcm_executor::traits::ShouldExecute; - -use scale_info::prelude::boxed::Box; -use sp_std::vec::Vec; - -pub trait ReserveAssetDepositedMatcher: Sync { - fn matches(&self, multi_asset: &MultiAsset) -> Option; -} - -pub trait DepositAssetMatcher { - fn matches<'a>( - &self, - assets: &'a MultiAssetFilter, - beneficiary: &'a MultiLocation, - ) -> Option<(u8, &'a [u8])>; -} -pub struct MatcherPair { - reserve_deposited_asset_matcher: Box, - deposit_asset_matcher: Box, -} - -impl MatcherPair { - pub fn new( - reserve_deposited_asset_matcher: Box, - deposit_asset_matcher: Box, - ) -> Self { - MatcherPair { reserve_deposited_asset_matcher, deposit_asset_matcher } - } - - fn matches_reserve_deposited(&self, multi_asset: &MultiAsset) -> Option { - self.reserve_deposited_asset_matcher.matches(multi_asset) - } - - fn matches_deposit_asset<'a>( - &'a self, - assets: &'a MultiAssetFilter, - beneficiary: &'a MultiLocation, - ) -> Option<(u8, &'a [u8])> { - self.deposit_asset_matcher.matches(assets, beneficiary) - } -} - -pub trait MatcherConfig { - fn get_matcher_pairs() -> Vec; - fn callback(length: u8, data: &[u8], amount: u128) -> Result<(), ()>; - fn get_incoming_parachain_id() -> u32; - fn extract_fee(location: MultiLocation, amount: u128)-> u128; -} - -pub struct AllowUnpaidExecutionFromCustom { - _phantom: PhantomData<(T, V)>, -} -impl, V: MatcherConfig> ShouldExecute - for AllowUnpaidExecutionFromCustom -{ - fn should_execute( - origin: &MultiLocation, - instructions: &mut [Instruction], - _max_weight: XCMWeight, - _weight_credit: &mut XCMWeight, - ) -> Result<(), ()> { - log::info!( - target: "xcm::barriers", - "AllowUnpaidExecutionFromCustom origin: {:?}, instructions: {:?}, max_weight: {:?}, weight_credit: {:?}", - origin, instructions, _max_weight, _weight_credit, - ); - log::info!("origin {:?}", origin); - let incoming_parachain_id = V::get_incoming_parachain_id(); - - ensure!(T::contains(origin), ()); - - // Check if the origin is the specific parachain - if let MultiLocation { parents: 1, interior: X1(Parachain(parachain_id)) } = origin { - log::info!("paraid {:?}", *parachain_id); - if *parachain_id == incoming_parachain_id { - log::info!("parachain match"); - - let matcher_pairs = V::get_matcher_pairs(); - // Iterate through the instructions, for - // each match pair we allow - for matcher_pair in matcher_pairs { - let mut reserve_deposited_asset_matched: Option = None; - let mut amount_to_process: u128 = 0; - - - // Check for ReserveAssetDeposited instruction - for instruction in instructions.iter() { - if let Instruction::ReserveAssetDeposited(assets) = instruction { - - for asset in assets.clone().into_inner().iter() { - if let Some(matched_asset) = matcher_pair.matches_reserve_deposited(asset) { - - // Check if the matched asset is fungible and extract the amount - if let MultiAsset { - id: Concrete(location), - fun: Fungibility::Fungible(amount_deposited), - } = matched_asset - { - reserve_deposited_asset_matched = Some(location); - amount_to_process = amount_deposited; - break; // Break as the matched asset is found and amount is extracted - } - } - } - } - } - - // If ReserveAssetDeposited matches, then check for DepositAsset with the same matcher pair - // and execute the callback - if let Some(location) = reserve_deposited_asset_matched { - for instruction in instructions.iter() { - if let Instruction::DepositAsset { assets, beneficiary } = instruction { - if let Some((length, data)) = - matcher_pair.matches_deposit_asset(assets, beneficiary) - { - - let amount_to_deposit = V::extract_fee(location, amount_to_process); - V::callback(length, data,amount_to_deposit); - return Err(()) - } - } - } - } - } - } - } - - - Ok(()) - } -} diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 2eac8b8a4..375a919a5 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -8,7 +8,7 @@ use sp_runtime::{ pub mod asset_registry; pub mod chain_ext; -pub mod custom_xcm_barrier; +pub mod custom_transactor; mod proxy_type; pub mod stellar; pub mod zenlink; diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index c06de58ee..fff87474e 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -668,11 +668,6 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { RuntimeEvent::System(frame_system::Event::Remarked { .. }) ))); - // Assert also that the fee has been given to the treasury id - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::Tokens(orml_tokens::Event::Deposited { .. }) - ))); }); }}; diff --git a/runtime/pendulum/src/xcm_config.rs b/runtime/pendulum/src/xcm_config.rs index 0d6e0e146..d42b6d774 100644 --- a/runtime/pendulum/src/xcm_config.rs +++ b/runtime/pendulum/src/xcm_config.rs @@ -6,28 +6,22 @@ use frame_support::{ }; use orml_traits::{ location::{RelativeReserveProvider, Reserve}, - parameter_type_with_key, MultiCurrency -}; + parameter_type_with_key,}; use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; -use sp_runtime::{Perbill,traits::Convert}; -use sp_std::{vec, vec::Vec}; -use scale_info::prelude::boxed::Box; +use sp_runtime::{traits::Convert}; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ - AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, + AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds,AllowUnpaidExecutionFrom, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, UsingComponents, }; use xcm_executor::{traits::ShouldExecute, XcmExecutor}; use runtime_common::{ - custom_xcm_barrier::{ - AllowUnpaidExecutionFromCustom, DepositAssetMatcher, MatcherConfig, MatcherPair, - ReserveAssetDepositedMatcher, - }, + custom_transactor::{CustomMultiCurrencyAdapter, AutomationPalletConfig}, parachains::polkadot::{asset_hub, equilibrium, moonbeam, polkadex}, }; @@ -156,17 +150,7 @@ where } } -/// Means for transacting the currencies of this parachain -pub type LocalAssetTransactor = MultiCurrencyAdapter< - Currencies, - (), // We don't handle unknown assets. - IsNativeConcrete, - AccountId, - LocationToAccountId, - CurrencyId, - CurrencyIdConvert, - DepositToAlternative, ->; + /// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, /// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can @@ -269,82 +253,54 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } // We will allow for BRZ location from moonbeam -struct BRZMoonbeamAssetMatcher; -impl ReserveAssetDepositedMatcher for BRZMoonbeamAssetMatcher { - fn matches(&self, multi_asset: &MultiAsset) -> Option { +pub struct AutomationPalletConfigPendulum; + +impl AutomationPalletConfig for AutomationPalletConfigPendulum { + fn matches_asset(asset: &MultiAsset) -> Option { let expected_multiloc = moonbeam::BRZ_location(); - match multi_asset { - MultiAsset { id: AssetId::Concrete(loc), .. } if loc == &expected_multiloc => - return Some(multi_asset.clone()), + match asset { + MultiAsset { id: AssetId::Concrete(loc), fun: Fungibility::Fungible(amount_deposited) } if loc == &expected_multiloc => + return Some(*amount_deposited), _ => return None, } } -} -// TODO modify with automation's pallet instance -struct PendulumAutomationPalletMatcher; -impl DepositAssetMatcher for PendulumAutomationPalletMatcher { - fn matches<'a>( - &self, - assets: &'a MultiAssetFilter, - beneficiary: &'a MultiLocation, - ) -> Option<(u8, &'a [u8])> { - if let ( - Wild(AllCounted(1)), + // TODO modify with automation's pallet instance + fn matches_beneficiary(beneficiary_location: &MultiLocation) -> Option<(u8, [u8;32])> { + if let MultiLocation { parents: 0, interior: X2(PalletInstance(99), GeneralKey { length, data }), - }, - ) = (assets, beneficiary) + } + = beneficiary_location { - Some((*length, &*data)) + Some((*length, *data)) } else { None } } -} -pub struct MatcherConfigPendulum; - -impl MatcherConfig for MatcherConfigPendulum { - fn get_matcher_pairs() -> Vec { - vec![ - MatcherPair::new( - Box::new(BRZMoonbeamAssetMatcher), - Box::new(PendulumAutomationPalletMatcher), - ), - // Additional matcher pairs to be defined in the future - ] - } - fn get_incoming_parachain_id() -> u32 { - moonbeam::PARA_ID - } - - fn callback(_length: u8, _data: &[u8], _amount: u128) -> Result<(), ()> { + fn callback(_length: u8, _data: [u8;32], _amount: u128) -> Result<(), XcmError> { // TODO change to call the actual automation pallet, with data and length System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0; 32])), [0; 1].to_vec()); Ok(()) } - // TODO define actual desired implementation of fee extraction. - // In this placeholder implementation, some percentage is given to treasury account - // in the local currency representing the asset from - // ReserveDepositAsset (the original asset) - fn extract_fee(location: MultiLocation, amount: u128)-> u128 { - if let Some(currency_id) = CurrencyIdConvert::convert(location){ - - let fee = Perbill::from_percent(1) * amount; - >::deposit(currency_id, &Treasury::account_id(), fee); - amount - fee - }else{ - amount - } - - } } - -pub type Barrier = AllowUnpaidExecutionFromCustom; +/// Means for transacting the currencies of this parachain +pub type LocalAssetTransactor = CustomMultiCurrencyAdapter< + Currencies, + (), // We don't handle unknown assets. + IsNativeConcrete, + AccountId, + LocationToAccountId, + CurrencyId, + CurrencyIdConvert, + DepositToAlternative, + AutomationPalletConfigPendulum, +>; +pub type Barrier = AllowUnpaidExecutionFrom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { From 7967cbf641d917c21d60489c28023013bfbd6bf7 Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Tue, 19 Dec 2023 13:32:06 -0300 Subject: [PATCH 10/11] use if let with tuple --- runtime/common/src/custom_transactor.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/runtime/common/src/custom_transactor.rs b/runtime/common/src/custom_transactor.rs index 9502583aa..b426531eb 100644 --- a/runtime/common/src/custom_transactor.rs +++ b/runtime/common/src/custom_transactor.rs @@ -94,13 +94,13 @@ impl< > { fn deposit_asset(asset: &MultiAsset, location: &MultiLocation, _context: &XcmContext) -> Result { - if let Some(amount_deposited) = AutomationPalletConfigT::matches_asset(asset){ + + if let (Some(amount_deposited), Some((length, data))) = + (AutomationPalletConfigT::matches_asset(asset), AutomationPalletConfigT::matches_beneficiary(location)) { + AutomationPalletConfigT::callback(length, data, amount_deposited); + return Ok(()); + } - if let Some((length,data)) = AutomationPalletConfigT::matches_beneficiary(location){ - AutomationPalletConfigT::callback(length, data, amount_deposited); - return Ok(()); - } - } match ( AccountIdConvert::convert_ref(location), CurrencyIdConvert::convert(asset.clone()), From e1f1ee05c168b93b6dd96b17150b45349689e87a Mon Sep 17 00:00:00 2001 From: Gianfranco Tasteri Date: Thu, 21 Dec 2023 12:20:45 -0300 Subject: [PATCH 11/11] refactor to use MultiCurrencyAdapter as a wrapped AssetTransactor --- runtime/amplitude/src/xcm_config.rs | 2 +- runtime/common/src/custom_transactor.rs | 142 ++++-------------- runtime/foucoco/src/xcm_config.rs | 2 +- runtime/integration-tests/src/mock.rs | 5 +- .../integration-tests/src/pendulum_tests.rs | 6 +- runtime/integration-tests/src/test_macros.rs | 1 - runtime/pendulum/src/xcm_config.rs | 50 +++--- 7 files changed, 63 insertions(+), 145 deletions(-) diff --git a/runtime/amplitude/src/xcm_config.rs b/runtime/amplitude/src/xcm_config.rs index b157fa09a..de13eff70 100644 --- a/runtime/amplitude/src/xcm_config.rs +++ b/runtime/amplitude/src/xcm_config.rs @@ -358,4 +358,4 @@ impl Convert for AccountIdToMultiLocation { impl cumulus_pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; -} \ No newline at end of file +} diff --git a/runtime/common/src/custom_transactor.rs b/runtime/common/src/custom_transactor.rs index b426531eb..65917b6b2 100644 --- a/runtime/common/src/custom_transactor.rs +++ b/runtime/common/src/custom_transactor.rs @@ -1,6 +1,5 @@ - -use sp_runtime::codec::FullCodec; use sp_runtime::{ + codec::FullCodec, traits::{Convert, MaybeSerializeDeserialize, SaturatedConversion}, }; use sp_std::{ @@ -11,108 +10,49 @@ use sp_std::{ result, }; +use orml_xcm_support::{OnDepositFail, UnknownAsset as UnknownAssetT}; use xcm::v3::{prelude::*, Error as XcmError, MultiAsset, MultiLocation, Result}; use xcm_executor::{ traits::{Convert as MoreConvert, MatchesFungible, TransactAsset}, Assets, }; -use orml_xcm_support::{UnknownAsset as UnknownAssetT,OnDepositFail}; - -/// Asset transaction errors. -enum Error { - /// Failed to match fungible. - FailedToMatchFungible, - /// `MultiLocation` to `AccountId` Conversion failed. - AccountIdConversionFailed, - /// `CurrencyId` conversion failed. - CurrencyIdConversionFailed, -} - -impl From for XcmError { - fn from(e: Error) -> Self { - match e { - Error::FailedToMatchFungible => XcmError::FailedToTransactAsset("FailedToMatchFungible"), - Error::AccountIdConversionFailed => XcmError::FailedToTransactAsset("AccountIdConversionFailed"), - Error::CurrencyIdConversionFailed => XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), - } - } +pub struct AssetData { + pub length: u8, + pub data: [u8; 32], } pub trait AutomationPalletConfig { fn matches_asset(asset: &MultiAsset) -> Option; - fn matches_beneficiary(beneficiary_location: &MultiLocation) -> Option<(u8, [u8;32])>; - fn callback(length: u8, data: [u8;32], amount: u128) -> Result; + fn matches_beneficiary(beneficiary_location: &MultiLocation) -> Option; + fn callback(length: u8, data: [u8; 32], amount: u128) -> Result; } -#[allow(clippy::type_complexity)] -pub struct CustomMultiCurrencyAdapter< - MultiCurrency, - UnknownAsset, - Match, - AccountId, - AccountIdConvert, - CurrencyId, - CurrencyIdConvert, - DepositFailureHandler, - AutomationPalletConfigT, ->( - PhantomData<( - MultiCurrency, - UnknownAsset, - Match, - AccountId, - AccountIdConvert, - CurrencyId, - CurrencyIdConvert, - DepositFailureHandler, - AutomationPalletConfigT, - )>, +pub struct CustomTransactorInterceptor( + PhantomData<(WrappedTransactor, AutomationPalletConfigT)>, ); -impl< - MultiCurrency: orml_traits::MultiCurrency, - UnknownAsset: UnknownAssetT, - Match: MatchesFungible, - AccountId: sp_std::fmt::Debug + Clone, - AccountIdConvert: MoreConvert, - CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, - CurrencyIdConvert: Convert>, - DepositFailureHandler: OnDepositFail, - AutomationPalletConfigT: AutomationPalletConfig - > TransactAsset - for CustomMultiCurrencyAdapter< - MultiCurrency, - UnknownAsset, - Match, - AccountId, - AccountIdConvert, - CurrencyId, - CurrencyIdConvert, - DepositFailureHandler, - AutomationPalletConfigT, - > +impl + TransactAsset for CustomTransactorInterceptor { - fn deposit_asset(asset: &MultiAsset, location: &MultiLocation, _context: &XcmContext) -> Result { - - if let (Some(amount_deposited), Some((length, data))) = - (AutomationPalletConfigT::matches_asset(asset), AutomationPalletConfigT::matches_beneficiary(location)) { - AutomationPalletConfigT::callback(length, data, amount_deposited); - return Ok(()); - } - - match ( - AccountIdConvert::convert_ref(location), - CurrencyIdConvert::convert(asset.clone()), - Match::matches_fungible(asset), + fn deposit_asset( + asset: &MultiAsset, + location: &MultiLocation, + _context: &XcmContext, + ) -> Result { + if let (Some(amount_deposited), Some(asset_data)) = ( + AutomationPalletConfigT::matches_asset(asset), + AutomationPalletConfigT::matches_beneficiary(location), ) { - // known asset - (Ok(who), Some(currency_id), Some(amount)) => MultiCurrency::deposit(currency_id, &who, amount) - .or_else(|err| DepositFailureHandler::on_deposit_currency_fail(err, currency_id, &who, amount)), - // unknown asset - _ => UnknownAsset::deposit(asset, location) - .or_else(|err| DepositFailureHandler::on_deposit_unknown_asset_fail(err, asset, location)), + AutomationPalletConfigT::callback( + asset_data.length, + asset_data.data, + amount_deposited, + )?; + return Ok(()) } + + WrappedTransactor::deposit_asset(asset, location, _context) } fn withdraw_asset( @@ -120,18 +60,7 @@ impl< location: &MultiLocation, _maybe_context: Option<&XcmContext>, ) -> result::Result { - UnknownAsset::withdraw(asset, location).or_else(|_| { - let who = AccountIdConvert::convert_ref(location) - .map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; - let currency_id = CurrencyIdConvert::convert(asset.clone()) - .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; - let amount: MultiCurrency::Balance = Match::matches_fungible(asset) - .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? - .saturated_into(); - MultiCurrency::withdraw(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) - })?; - - Ok(asset.clone().into()) + WrappedTransactor::withdraw_asset(asset, location, _maybe_context) } fn transfer_asset( @@ -140,19 +69,6 @@ impl< to: &MultiLocation, _context: &XcmContext, ) -> result::Result { - let from_account = - AccountIdConvert::convert_ref(from).map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; - let to_account = - AccountIdConvert::convert_ref(to).map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; - let currency_id = CurrencyIdConvert::convert(asset.clone()) - .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; - let amount: MultiCurrency::Balance = Match::matches_fungible(asset) - .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? - .saturated_into(); - MultiCurrency::transfer(currency_id, &from_account, &to_account, amount) - .map_err(|e| XcmError::FailedToTransactAsset(e.into()))?; - - Ok(asset.clone().into()) + WrappedTransactor::transfer_asset(asset, from, to, _context) } } - diff --git a/runtime/foucoco/src/xcm_config.rs b/runtime/foucoco/src/xcm_config.rs index 4be8677a6..18425d58a 100644 --- a/runtime/foucoco/src/xcm_config.rs +++ b/runtime/foucoco/src/xcm_config.rs @@ -357,4 +357,4 @@ impl Convert for AccountIdToMultiLocation { impl cumulus_pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; -} \ No newline at end of file +} diff --git a/runtime/integration-tests/src/mock.rs b/runtime/integration-tests/src/mock.rs index 1d1add86b..eb6a36b6b 100644 --- a/runtime/integration-tests/src/mock.rs +++ b/runtime/integration-tests/src/mock.rs @@ -117,7 +117,7 @@ pub enum ParachainType { Pendulum, Amplitude, Sibling, - Moonbeam + Moonbeam, } pub struct ExtBuilderParachain { @@ -191,8 +191,7 @@ pub fn para_ext(chain: ParachainType) -> sp_io::TestExternalities { ParachainType::Amplitude => ExtBuilderParachain::amplitude_default().balances(vec![]).build(), ParachainType::Sibling => ExtBuilderParachain::sibling_default().balances(vec![]).build(), - ParachainType::Moonbeam => - ExtBuilderParachain::moonbeam_default().balances(vec![]).build(), + ParachainType::Moonbeam => ExtBuilderParachain::moonbeam_default().balances(vec![]).build(), } } diff --git a/runtime/integration-tests/src/pendulum_tests.rs b/runtime/integration-tests/src/pendulum_tests.rs index 0f4118e29..01b189592 100644 --- a/runtime/integration-tests/src/pendulum_tests.rs +++ b/runtime/integration-tests/src/pendulum_tests.rs @@ -2,21 +2,21 @@ use crate::{ mock::{para_ext, polkadot_relay_ext, ParachainType, USDT_ASSET_ID}, sibling, test_macros::{ - parachain1_transfer_asset_to_parachain2, parachain1_transfer_asset_to_parachain2_and_back, + moonbeam_transfers_token_and_handle_automation, parachain1_transfer_asset_to_parachain2, + parachain1_transfer_asset_to_parachain2_and_back, parachain1_transfer_incorrect_asset_to_parachain2_should_fail, transfer_10_relay_token_from_parachain_to_relay_chain, transfer_20_relay_token_from_relay_chain_to_parachain, transfer_native_token_from_parachain1_to_parachain2_and_back, - moonbeam_transfers_token_and_handle_automation }, ASSETHUB_ID, PENDULUM_ID, SIBLING_ID, }; use frame_support::assert_ok; +use runtime_common::parachains::polkadot::moonbeam::PARA_ID as MOONBEAM_PARA_ID; use statemint_runtime as polkadot_asset_hub_runtime; use xcm::latest::NetworkId; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; -use runtime_common::parachains::polkadot::moonbeam::PARA_ID as MOONBEAM_PARA_ID; const DOT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 3200000000; //The fees that relay chain will charge when transfer DOT to parachain. sovereign account of some parachain will receive transfer_amount - DOT_FEE diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index fff87474e..85e713bff 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -619,7 +619,6 @@ macro_rules! moonbeam_transfers_token_and_handle_automation { ) => {{ use crate::mock::{units, ALICE}; use polkadot_core_primitives::Balance; - use xcm::latest::{ Junction, Junction::{ GeneralKey, PalletInstance}, Junctions::{X1,X2, X3}, MultiLocation, WeightLimit, }; diff --git a/runtime/pendulum/src/xcm_config.rs b/runtime/pendulum/src/xcm_config.rs index d42b6d774..67278aba6 100644 --- a/runtime/pendulum/src/xcm_config.rs +++ b/runtime/pendulum/src/xcm_config.rs @@ -6,22 +6,23 @@ use frame_support::{ }; use orml_traits::{ location::{RelativeReserveProvider, Reserve}, - parameter_type_with_key,}; + parameter_type_with_key, +}; use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; -use sp_runtime::{traits::Convert}; +use sp_runtime::traits::Convert; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ - AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds,AllowUnpaidExecutionFrom, + AccountId32Aliases, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, UsingComponents, }; use xcm_executor::{traits::ShouldExecute, XcmExecutor}; use runtime_common::{ - custom_transactor::{CustomMultiCurrencyAdapter, AutomationPalletConfig}, + custom_transactor::{AssetData, AutomationPalletConfig, CustomTransactorInterceptor}, parachains::polkadot::{asset_hub, equilibrium, moonbeam, polkadex}, }; @@ -40,10 +41,9 @@ use crate::{ use super::{ AccountId, Balance, Balances, Currencies, CurrencyId, ParachainInfo, ParachainSystem, PendulumTreasuryAccount, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - WeightToFee, XcmpQueue, Treasury, System + System, Treasury, WeightToFee, XcmpQueue, }; - parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayNetwork: NetworkId = NetworkId::Polkadot; @@ -53,6 +53,9 @@ parameter_types! { X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())); } +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( // The parent (Relay-chain) origin converts to the parent `AccountId`. ParentIsPreset, @@ -150,8 +153,6 @@ where } } - - /// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, /// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can /// biases the kind of local `Origin` it will become. @@ -260,36 +261,37 @@ impl AutomationPalletConfig for AutomationPalletConfigPendulum { let expected_multiloc = moonbeam::BRZ_location(); match asset { - MultiAsset { id: AssetId::Concrete(loc), fun: Fungibility::Fungible(amount_deposited) } if loc == &expected_multiloc => - return Some(*amount_deposited), + MultiAsset { + id: AssetId::Concrete(loc), + fun: Fungibility::Fungible(amount_deposited), + } if loc == &expected_multiloc => return Some(*amount_deposited), _ => return None, } } // TODO modify with automation's pallet instance - fn matches_beneficiary(beneficiary_location: &MultiLocation) -> Option<(u8, [u8;32])> { - if let - MultiLocation { - parents: 0, - interior: X2(PalletInstance(99), GeneralKey { length, data }), - } - = beneficiary_location + fn matches_beneficiary(beneficiary_location: &MultiLocation) -> Option { + if let MultiLocation { + parents: 0, + interior: X2(PalletInstance(99), GeneralKey { length, data }), + } = beneficiary_location { - Some((*length, *data)) + let asset_data = AssetData { length: *length, data: *data }; + Some(asset_data) } else { None } } - fn callback(_length: u8, _data: [u8;32], _amount: u128) -> Result<(), XcmError> { + fn callback(_length: u8, _data: [u8; 32], _amount: u128) -> Result<(), XcmError> { // TODO change to call the actual automation pallet, with data and length System::remark_with_event(RuntimeOrigin::signed(AccountId::from([0; 32])), [0; 1].to_vec()); Ok(()) } - } + /// Means for transacting the currencies of this parachain -pub type LocalAssetTransactor = CustomMultiCurrencyAdapter< +type Transactor = MultiCurrencyAdapter< Currencies, (), // We don't handle unknown assets. IsNativeConcrete, @@ -298,8 +300,10 @@ pub type LocalAssetTransactor = CustomMultiCurrencyAdapter< CurrencyId, CurrencyIdConvert, DepositToAlternative, - AutomationPalletConfigPendulum, >; + +pub type LocalAssetTransactor = + CustomTransactorInterceptor; pub type Barrier = AllowUnpaidExecutionFrom; pub struct XcmConfig; @@ -414,4 +418,4 @@ impl Convert for AccountIdToMultiLocation { impl cumulus_pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; -} \ No newline at end of file +}