[
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# friendmex.com\n\n[BitMEX](https://www.bitmex.com/app/trade/XBTUSD)-inspired trading interface for [friend.tech](https://www.friend.tech/).\n\n- [Indexer](./indexer): Sync trades and users\n- [Frontend](./frontend): Trading interface\n\n## License\n\n[GNU Affero GPL v3.0](./LICENSE)\n"
  },
  {
    "path": "frontend/.eslintrc.json",
    "content": "{\n  \"extends\": \"next/core-web-vitals\",\n  \"rules\": {\n    \"@next/next/no-img-element\": \"off\",\n    \"import/no-anonymous-default-export\": \"off\"\n  }\n}\n"
  },
  {
    "path": "frontend/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# next.js\n/.next/\n/out/\n\n# production\n/build\n\n# misc\n.DS_Store\n*.pem\n\n# debug\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n.pnpm-debug.log*\n\n# local env files\n.env*.local\n\n# vercel\n.vercel\n\n# typescript\n*.tsbuildinfo\nnext-env.d.ts\n\n# VSCode\n.vscode"
  },
  {
    "path": "frontend/README.md",
    "content": "# Frontend\n\n[BitMEX](https://www.bitmex.com/app/trade/XBTUSD)-inspired frontend for [friend.tech](https://www.friend.tech/) trading.\n\n## Run locally\n\n```bash\n# Populate env vars\ncp .env.sample .env.local && vim .env.local\n\n# Install dependencies\npnpm install\n\n# Run\npnpm run dev\n```\n"
  },
  {
    "path": "frontend/components/Address.tsx",
    "content": "import { Global } from \"state/global\";\nimport { Button } from \"./ui/button\";\nimport { truncateAddress } from \"utils\";\nimport { StarFilledIcon } from \"@radix-ui/react-icons\";\n\nexport default function Address({\n  address,\n  username,\n  image,\n}: {\n  address: string;\n  username?: string | null;\n  image?: string | null;\n}) {\n  // Global state\n  const { favorites, setUser } = Global.useContainer();\n\n  // Conditional renders\n  const name: string | null | undefined =\n    username && username.length > 20 ? username?.slice(0, 20) : username;\n  const user: string = username ? `@${name}` : truncateAddress(address, 6);\n\n  return (\n    <Button\n      onClick={() => setUser({ address, username, image })}\n      className=\"h-8 pl-1 pr-2 py-0 bg-white border text-black rounded-md shadow-none text-sm font-normal hover:bg-white hover:opacity-70 transition-opacity\"\n    >\n      <div className=\"flex items-center\">\n        <img\n          src={image ? image : \"/rasters/default.png\"}\n          width={22}\n          height={22}\n          alt={`${user} Twitter pfp`}\n          className=\"rounded-md\"\n        />\n        <span className=\"pl-2\">{user}</span>\n\n        {favorites[address.toLowerCase()] && (\n          // Is favorited\n          <span className=\"ml-2\">\n            <StarFilledIcon className=\"stroke-amber-400 text-amber-400\" />\n          </span>\n        )}\n      </div>\n    </Button>\n  );\n}\n"
  },
  {
    "path": "frontend/components/Card.tsx",
    "content": "import { ReactElement } from \"react\";\nimport { DragHandleDots2Icon } from \"@radix-ui/react-icons\";\n\nexport default function Card({\n  title,\n  updated,\n  children,\n}: {\n  title: string;\n  updated?: string;\n  children: ReactElement | ReactElement[];\n}) {\n  return (\n    // Card component\n    <div className=\"flex flex-col bg-white border-[1px] border-bitmex-strong-border h-full\">\n      {/* Card header */}\n      <div className=\"flex items-center justify-between bg-bitmex-strong py-0.5\">\n        {/* Card header: left */}\n        <div className=\"flex items-center\">\n          {/* Resizer */}\n          <div className=\"drag-handle\">\n            <DragHandleDots2Icon className=\"text-zinc-500\" />\n          </div>\n\n          {/* Component title */}\n          <span className=\"pl-1 text-sm font-bold\">{title}</span>\n        </div>\n\n        {/* Card header: right */}\n        {updated && (\n          <span className=\"text-zinc-500 text-xs font-light pr-2\">\n            {updated}\n          </span>\n        )}\n      </div>\n\n      {/* Card content */}\n      <div className=\"bg-bitmex-widget overflow-auto flex-1\">{children}</div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/Header.tsx",
    "content": "import Link from \"next/link\";\nimport Image from \"next/image\";\nimport { Global, Currency } from \"state/global\";\nimport { ConnectButton } from \"@rainbow-me/rainbowkit\";\n\nexport default function Header() {\n  const { currency, setCurrency } = Global.useContainer();\n\n  return (\n    <div className=\"sticky top-0 z-50\">\n      {/* Sub header */}\n      <div className=\"bg-black border-b border-zinc-800 flex items-center justify-center py-0.5\">\n        <span className=\"text-xs text-zinc-400\">\n          An{\" \"}\n          <a\n            href=\"https://github.com/anish-agnihotri/friendmex\"\n            target=\"_blank\"\n            rel=\"noopen noreferrer\"\n            className=\"hover:opacity-70 transition-opacity underline\"\n          >\n            open-source\n          </a>{\" \"}\n          project by{\" \"}\n          <a\n            href=\"https://anishagnihotri.com\"\n            target=\"_blank\"\n            rel=\"noopen noreferrer\"\n            className=\"hover:opacity-70 transition-opacity underline\"\n          >\n            Anish Agnihotri\n          </a>\n          .\n        </span>\n      </div>\n\n      {/* Main header */}\n      <div className=\"flex justify-between h-14 px-4 items-center bg-black\">\n        <div>\n          <Link href=\"/\" className=\"hover:opacity-70 transition-opacity\">\n            <Image\n              src=\"/vectors/logo.svg\"\n              height={30}\n              width={165}\n              alt=\"FriendMEX logo\"\n              priority\n            />\n          </Link>\n        </div>\n\n        <div className=\"flex items-center gap-4\">\n          <div className=\"flex border border-zinc-600 text-zinc-300\">\n            <button\n              onClick={() => setCurrency(Currency.USD)}\n              className={`px-1 hover:opacity-70 ${\n                currency === Currency.USD ? \"bg-zinc-500\" : \"\"\n              }`}\n            >\n              USD\n            </button>\n            <button\n              onClick={() => setCurrency(Currency.ETH)}\n              className={`px-1 hover:opacity-70 ${\n                currency === Currency.ETH ? \"bg-zinc-500\" : \"\"\n              }`}\n            >\n              ETH\n            </button>\n          </div>\n\n          <div className=\"md:flex hidden\">\n            <ConnectButton />\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/Layout.tsx",
    "content": "import Head from \"next/head\";\nimport Header from \"components/Header\";\nimport type { ReactElement } from \"react\";\nimport { Global, type StateUser } from \"state/global\";\n\nexport default function Layout({\n  user,\n  children,\n}: {\n  user: StateUser;\n  children: ReactElement | ReactElement[];\n}) {\n  return (\n    // Wrap in global state provider (at layout level)\n    <Global.Provider initialState={user}>\n      <div>\n        {/* Meta tags */}\n        <Meta />\n\n        {/* Header */}\n        <Header />\n\n        <div>{children}</div>\n      </div>\n    </Global.Provider>\n  );\n}\n\nfunction Meta() {\n  const meta = {\n    url: \"https://friendmex.com\",\n    image: \"https://friendmex.com/meta.png\",\n    title: \"FriendMEX | Advanced friend.tech trading platform\",\n    description:\n      \"FriendMEX is THE pro trading platform for friend.tech users. No invite code necessary, real-time statistics, analytics, and more.\",\n  };\n\n  return (\n    <Head>\n      {/* Primary Meta Tags */}\n      <title>{meta.title}</title>\n      <meta name=\"title\" content={meta.title} />\n      <meta name=\"description\" content={meta.description} />\n\n      {/* Favicon */}\n      <link rel=\"icon\" href=\"https://friendmex.com/favicon.ico\" sizes=\"any\" />\n\n      {/* OG + Facebook */}\n      <meta property=\"og:type\" content=\"website\" />\n      <meta property=\"og:url\" content={meta.url} />\n      <meta property=\"og:title\" content={meta.title} />\n      <meta property=\"og:description\" content={meta.description} />\n      <meta property=\"og:image\" content={meta.image} />\n\n      {/* Twitter */}\n      <meta property=\"twitter:card\" content=\"summary_large_image\" />\n      <meta property=\"twitter:url\" content={meta.url} />\n      <meta property=\"twitter:title\" content={meta.title} />\n      <meta property=\"twitter:description\" content={meta.description} />\n      <meta property=\"twitter:image\" content={meta.image} />\n    </Head>\n  );\n}\n"
  },
  {
    "path": "frontend/components/TradeTable.tsx",
    "content": "import {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from \"components/ui/table\";\nimport React from \"react\";\nimport { parseUSD } from \"utils/usd\";\nimport { truncateAddress } from \"utils\";\nimport Address from \"components/Address\";\nimport type { ReactElement } from \"react\";\nimport { formatDistance } from \"date-fns\";\nimport type { Prisma } from \"@prisma/client\";\nimport { Global, Currency } from \"state/global\";\nimport type { TradeWithTwitterUser } from \"pages/api/stats/trades\";\n\n// Render row background depending on trade type\nfunction ColoredRow({\n  isBuy,\n  children,\n}: {\n  isBuy: boolean;\n  children: ReactElement[];\n}) {\n  return isBuy ? (\n    <TableRow className=\"bg-buy-30\">{children}</TableRow>\n  ) : (\n    <TableRow className=\"bg-sell-30\">{children}</TableRow>\n  );\n}\n\nexport default function TradeTable({\n  trades,\n}: {\n  trades: TradeWithTwitterUser[];\n}) {\n  const { eth, currency } = Global.useContainer();\n\n  /**\n   * Calculate cost of trade based on selected currency\n   * @param {Prisma.Decima} cost from DB\n   * @returns {string} formatted\n   */\n  const calculateTradeCost = (cost: Prisma.Decimal): string => {\n    // Calculate trade cost\n    return currency === Currency.USD\n      ? `$${parseUSD((Number(cost) / 1e18) * eth)}`\n      : `${(Number(cost) / 1e18).toFixed(6)} Ξ`;\n  };\n\n  return (\n    <Table className=\"min-w-[950px] [&_td]:py-1\">\n      <TableHeader className=\"sticky top-0\">\n        <TableRow>\n          <TableHead>Hash</TableHead>\n          <TableHead>Time Since</TableHead>\n          <TableHead>Block #</TableHead>\n          <TableHead>From</TableHead>\n          <TableHead>Token</TableHead>\n          <TableHead>Amount</TableHead>\n          <TableHead>Net</TableHead>\n        </TableRow>\n      </TableHeader>\n      <TableBody>\n        {trades.map((trade, i) => {\n          const tradeCost: string = calculateTradeCost(trade.cost);\n\n          return (\n            <ColoredRow isBuy={trade.isBuy} key={i}>\n              <TableCell>\n                <a\n                  href={`https://basescan.org/tx/${trade.hash}`}\n                  target=\"_blank\"\n                  rel=\"noopener noreferrer\"\n                  className=\"underline\"\n                >\n                  {truncateAddress(trade.hash, 6)}\n                </a>\n              </TableCell>\n              <TableCell suppressHydrationWarning={true}>\n                {formatDistance(new Date(trade.timestamp * 1000), new Date(), {\n                  addSuffix: true,\n                })}\n              </TableCell>\n              <TableCell>\n                <a\n                  href={`https://basescan.org/block/${trade.blockNumber}`}\n                  target=\"_blank\"\n                  rel=\"noopener noreferrer\"\n                  className=\"underline\"\n                >\n                  {trade.blockNumber}\n                </a>\n              </TableCell>\n              <TableCell>\n                <Address\n                  address={trade.fromAddress}\n                  username={trade.fromUser.twitterUsername}\n                  image={trade.fromUser.twitterPfpUrl}\n                />\n              </TableCell>\n              <TableCell>\n                <Address\n                  address={trade.subjectAddress}\n                  username={trade.subjectUser.twitterUsername}\n                  image={trade.subjectUser.twitterPfpUrl}\n                />\n              </TableCell>\n              <TableCell>\n                {trade.isBuy ? \"+\" : \"-\"}\n                {trade.amount}\n              </TableCell>\n              <TableCell>\n                {trade.isBuy ? (\n                  <span className=\"text-buy\">{tradeCost}</span>\n                ) : (\n                  <span className=\"text-sell\">{tradeCost}</span>\n                )}\n              </TableCell>\n            </ColoredRow>\n          );\n        })}\n      </TableBody>\n    </Table>\n  );\n}\n"
  },
  {
    "path": "frontend/components/User.tsx",
    "content": "import { parseUSD } from \"utils/usd\";\nimport { Button } from \"./ui/button\";\nimport { truncateAddress } from \"utils\";\nimport type { User } from \"@prisma/client\";\nimport { Global, Currency, StateUser } from \"state/global\";\nimport { StarFilledIcon, StarIcon } from \"@radix-ui/react-icons\";\n\n/**\n * Extended user object including token cost\n */\nexport type UserInfo = User & {\n  cost: number;\n};\n\nexport default function User({\n  data,\n  isMinimal = false,\n}: {\n  data: UserInfo;\n  isMinimal?: boolean;\n}) {\n  // Global state\n  const { user, setUser, currency, eth, favorites, toggleFavorite } =\n    Global.useContainer();\n\n  // Profile image\n  const image: string = data.twitterPfpUrl ?? \"/rasters/default.png\";\n  const alt: string = data.twitterUsername\n    ? `@${data.twitterUsername} profile picture`\n    : `${data.address} profile picture`;\n\n  // Username\n  const address: string = truncateAddress(data.address, 6);\n  const username: string = data.twitterUsername\n    ? `@${data.twitterUsername}`\n    : address;\n  const addressLink: string = `https://basescan.org/address/${data.address}`;\n  const usernameLink: string = data.twitterUsername\n    ? `https://twitter.com/${data.twitterUsername}`\n    : addressLink;\n\n  // Market cap\n  const marketCap: number =\n    Math.pow(data.supply, 3) / 48000 +\n    Math.pow(data.supply, 2) / 32000 +\n    data.supply / 96000;\n\n  return (\n    <div className=\"flex flex-col border rounded-lg bg-white\">\n      {/* Top section */}\n      <div className=\"p-2 flex flex-row items-center justify-between w-full\">\n        {/* Top left (image, handle, address) */}\n        <div className=\"flex items-center\">\n          <img\n            src={image}\n            alt={alt}\n            width={30}\n            height={30}\n            className=\"rounded-md\"\n          />\n\n          <div className=\"flex text-xs flex-col pl-2 [&>a:hover]:opacity-70\">\n            {/* Username */}\n            <a href={usernameLink} target=\"_blank\" rel=\"noopener noreferrer\">\n              {username}\n            </a>\n\n            {/* Address */}\n            <a\n              href={addressLink}\n              className=\"text-zinc-400\"\n              target=\"_blank\"\n              rel=\"noopener noreferrer\"\n            >\n              {address}\n            </a>\n          </div>\n        </div>\n\n        {/* Top right */}\n        <div className=\"flex items-center\">\n          {/* Favorite button */}\n          <button\n            className=\"mr-2\"\n            onClick={() =>\n              toggleFavorite({\n                address: data.address.toLowerCase(),\n                image,\n                username,\n              })\n            }\n          >\n            {favorites[data.address.toLowerCase()] ? (\n              <StarFilledIcon className=\"stroke-amber-400 text-amber-400\" />\n            ) : (\n              <StarIcon className=\"stroke-zinc-200\" />\n            )}\n          </button>\n\n          {/* Trade button */}\n          <Button\n            onClick={() =>\n              setUser({\n                address: data.address,\n                username: data.twitterUsername,\n                image: data.twitterPfpUrl,\n              })\n            }\n            disabled={user.address === data.address}\n            className=\"text-xs h-7 px-2 py-0 bg-buy hover:bg-buy hover:opacity-70 transition-opacity\"\n          >\n            {isMinimal ? (\n              <span>Buy</span>\n            ) : currency === Currency.USD ? (\n              <span>${parseUSD(data.cost * eth)}</span>\n            ) : (\n              <span>{data.cost.toFixed(4)} Ξ</span>\n            )}\n          </Button>\n        </div>\n      </div>\n\n      {/* Bottom section */}\n      {!isMinimal && (\n        <div className=\"flex border-t items-center justify-between px-2 py-1 text-xs text-zinc-500\">\n          <span>\n            {data.supply} key{data.supply == 1 ? \"\" : \"s\"}\n          </span>\n          <span>\n            MC:{\" \"}\n            {currency === Currency.USD ? (\n              <span>${parseUSD(marketCap * eth)}</span>\n            ) : (\n              <span>{marketCap.toFixed(2)} Ξ</span>\n            )}\n          </span>\n        </div>\n      )}\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/BuySell.tsx",
    "content": "import Card from \"components/Card\";\nimport { parseUSD } from \"utils/usd\";\nimport Address from \"components/Address\";\nimport { useEffect, useState } from \"react\";\nimport { Input } from \"components/ui/input\";\nimport { Button } from \"components/ui/button\";\nimport { ABI, CONTRACT_ADDRESS } from \"utils\";\nimport { Global, Currency } from \"state/global\";\nimport { ConnectButton } from \"@rainbow-me/rainbowkit\";\nimport { ButtonIcon, SymbolIcon } from \"@radix-ui/react-icons\";\nimport { useAccount, useContractRead, useContractWrite } from \"wagmi\";\n\nexport default function BuySell() {\n  // Global state\n  const { eth, currency, user } = Global.useContainer();\n\n  // Local state\n  const [buy, setBuy] = useState<number>(0);\n  const [sell, setSell] = useState<number>(0);\n\n  // Wagmi\n  const { address, isConnected } = useAccount();\n  const { data: ownedAmount }: { data: BigInt | undefined } = useContractRead({\n    address: CONTRACT_ADDRESS,\n    abi: ABI,\n    functionName: \"sharesBalance\",\n    args: [user.address, address],\n  });\n  const { data: buyPrice }: { data: BigInt | undefined } = useContractRead({\n    address: CONTRACT_ADDRESS,\n    abi: ABI,\n    functionName: \"getBuyPriceAfterFee\",\n    args: [user.address, buy],\n  });\n  const { data: sellPrice }: { data: BigInt | undefined } = useContractRead({\n    address: CONTRACT_ADDRESS,\n    abi: ABI,\n    functionName: \"getSellPriceAfterFee\",\n    args: [user.address, sell],\n  });\n  const { write: executeBuy, isLoading: buyLoading } = useContractWrite({\n    address: CONTRACT_ADDRESS,\n    abi: ABI,\n    functionName: \"buyShares\",\n    args: [user.address, buy],\n    value: (buyPrice as bigint) ?? undefined,\n  });\n  const { write: executeSell, isLoading: sellLoading } = useContractWrite({\n    address: CONTRACT_ADDRESS,\n    abi: ABI,\n    functionName: \"sellShares\",\n    args: [user.address, sell],\n  });\n\n  // Reset on user change\n  useEffect(() => {\n    setBuy(0);\n    setSell(0);\n  }, [user]);\n\n  return (\n    <Card title=\"Buy/Sell\">\n      <div className=\"h-full p-4\">\n        {!isConnected ? (\n          // Not connected state\n          <div className=\"flex flex-col items-center justify-center h-full border border-dashed rounded-md\">\n            <ButtonIcon className=\"w-12 h-12 text-zinc-500\" />\n            <span className=\"text-zinc-500\">Connect wallet to trade</span>\n            <div className=\"mt-4\">\n              <ConnectButton />\n            </div>\n          </div>\n        ) : (\n          <div className=\"flex flex-col h-full gap-3\">\n            <div>\n              <span className=\"flex break-word text-sm items-center\">\n                You own {Number(ownedAmount ?? 0)} key(s) of{\" \"}\n                <span className=\"pl-2\">\n                  <Address\n                    address={user.address}\n                    username={user.username}\n                    image={user.image}\n                  />\n                </span>\n                .\n              </span>\n            </div>\n\n            {/* Buy keys */}\n            <Card title=\"Buy keys\">\n              <div className=\"p-2\">\n                <Input value={buy} disabled />\n\n                <div className=\"flex [&>button]:flex-1 gap-3 mt-3\">\n                  <Button\n                    variant=\"outline\"\n                    onClick={() => {\n                      if (buy > 0) setBuy((previous) => previous - 1);\n                    }}\n                    disabled={buy === 0}\n                  >\n                    -\n                  </Button>\n                  <Button\n                    variant=\"outline\"\n                    onClick={() => setBuy((previous) => previous + 1)}\n                  >\n                    +\n                  </Button>\n                </div>\n\n                <Button\n                  className=\"mt-2 w-full bg-buy hover:bg-buy hover:opacity-70\"\n                  onClick={() => executeBuy()}\n                  disabled={buy === 0 || buyLoading}\n                >\n                  {buyLoading ? (\n                    <div className=\"flex items-center\">\n                      <SymbolIcon className=\"h-4 w-4 animate-spin\" />\n                      <span className=\"pr-2\">Executing buy...</span>\n                    </div>\n                  ) : (\n                    <span>\n                      Buy {buy} key(s){\" \"}\n                      {buyPrice\n                        ? `for ${\n                            currency === Currency.ETH\n                              ? `${(Number(buyPrice) / 1e18).toFixed(6)} Ξ`\n                              : `$${parseUSD((Number(buyPrice) / 1e18) * eth)}`\n                          }`\n                        : \"\"}\n                    </span>\n                  )}\n                </Button>\n              </div>\n            </Card>\n\n            {/* Sell keys */}\n            <Card title=\"Sell keys\">\n              <div className=\"p-2\">\n                <Input value={sell} disabled />\n\n                <div className=\"flex [&>button]:flex-1 gap-3 mt-3\">\n                  <Button\n                    variant=\"outline\"\n                    onClick={() => {\n                      if (sell > 0) setSell((previous) => previous - 1);\n                    }}\n                    disabled={sell === 0}\n                  >\n                    -\n                  </Button>\n                  <Button\n                    variant=\"outline\"\n                    onClick={() => {\n                      if (sell < Number(ownedAmount ?? 0)) {\n                        setSell((previous) => previous + 1);\n                      }\n                    }}\n                    disabled={sell >= Number(ownedAmount ?? 0)}\n                  >\n                    +\n                  </Button>\n                </div>\n\n                <Button\n                  className=\"mt-2 w-full bg-sell hover:bg-sell hover:opacity-70\"\n                  onClick={() => executeSell()}\n                  disabled={sell === 0 || sellLoading}\n                >\n                  {sellLoading ? (\n                    <div className=\"flex items-center\">\n                      <SymbolIcon className=\"h-4 w-4 animate-spin\" />\n                      <span className=\"pr-2\">Executing sell...</span>\n                    </div>\n                  ) : (\n                    <span>\n                      Sell {sell} key(s){\" \"}\n                      {sellPrice\n                        ? `for ${\n                            currency === Currency.ETH\n                              ? `${(Number(sellPrice) / 1e18).toFixed(6)} Ξ`\n                              : `$${parseUSD((Number(sellPrice) / 1e18) * eth)}`\n                          }`\n                        : \"\"}\n                    </span>\n                  )}\n                </Button>\n              </div>\n            </Card>\n          </div>\n        )}\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/Chart.tsx",
    "content": "import Card from \"components/Card\";\nimport { truncateAddress } from \"utils\";\nimport { LineChart } from \"@tremor/react\";\nimport { renderTimeSince } from \"utils/time\";\nimport { usePollData } from \"utils/usePollData\";\nimport { Global, StateUser } from \"state/global\";\n\nexport default function Chart() {\n  // Token address\n  const { user }: { user: StateUser } = Global.useContainer();\n  // Data\n  const { data, lastChecked } = usePollData<\n    { timestamp: number; \"Price (ETH)\": number }[]\n  >(`/api/token/chart?address=${user.address}`, [], 15 * 1000);\n\n  return (\n    <Card\n      title=\"Token Chart\"\n      updated={`${\n        user.username ? `@${user.username}` : truncateAddress(user.address, 6)\n      }, ${renderTimeSince(lastChecked)} ago`}\n    >\n      <div className=\"w-full h-full p-4\">\n        <LineChart\n          className=\"h-full\"\n          data={data}\n          index=\"timestamp\"\n          categories={[\"Price (ETH)\"]}\n        />\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/Discover.tsx",
    "content": "import axios from \"axios\";\nimport Card from \"components/Card\";\nimport { Input } from \"components/ui/input\";\nimport { renderTimeSince } from \"utils/time\";\nimport { usePollData } from \"utils/usePollData\";\nimport { useDebounce } from \"@uidotdev/usehooks\";\nimport User, { type UserInfo } from \"components/User\";\nimport { useState, useCallback, useEffect } from \"react\";\nimport { SymbolIcon, CrossCircledIcon } from \"@radix-ui/react-icons\";\n\nfunction useSearch(search: string) {\n  // Loading state\n  const [loading, setLoading] = useState<boolean>(false);\n  // Results\n  const [results, setResults] = useState<UserInfo[]>([]);\n\n  /**\n   * Collect search results from backend\n   */\n  const getResults = useCallback(async () => {\n    try {\n      // Toggle loading\n      setLoading(true);\n\n      // Request from backend\n      const { data } = await axios.post(\"/api/token/search\", {\n        search,\n      });\n      setResults(data);\n    } catch (e: unknown) {\n      // If known error\n      if (e instanceof Error) {\n        // Log message\n        console.error(e.message);\n      } else {\n        // Else, log full object\n        console.error(e);\n      }\n    } finally {\n      // Toggle loading\n      setLoading(false);\n    }\n  }, [search]);\n\n  // On search change, call for new data\n  useEffect(() => {\n    async function execute() {\n      await getResults();\n    }\n\n    // If no input, set default\n    if (search === \"\") {\n      setLoading(false);\n      setResults([]);\n    } else {\n      // Else, process collection\n      execute();\n    }\n  }, [search, getResults]);\n\n  return { results, loading };\n}\n\nexport default function Leaderboard({\n  leaderboard: ssrLeaderboard,\n}: {\n  leaderboard: any;\n}) {\n  // Local state\n  const [search, setSearch] = useState<string>(\"\");\n  // Debounce search input to 150ms\n  const debouncedSearch: string = useDebounce(search, 300);\n  // Search results\n  const { results: searchResults, loading: searchLoading } =\n    useSearch(debouncedSearch);\n\n  // Backend data (leaderboard)\n  const { data: leaderboard, lastChecked } = usePollData(\n    \"/api/stats/leaderboard\",\n    ssrLeaderboard,\n    15 * 1000\n  );\n\n  return (\n    <Card title=\"Discover\" updated={`${renderTimeSince(lastChecked)} ago`}>\n      <div className=\"h-full relative\">\n        {/* Search users */}\n        <Input\n          value={search}\n          onChange={(e) => setSearch(e.target.value)}\n          placeholder=\"Search friends...\"\n          className=\"h-8 w-[calc(100%-2px)] fixed focus-visible:ring-0 shadow-none border-l-0 border-r-0 border-t-0 border-b rounded-none bg-zinc-100\"\n        />\n\n        <div className=\"pt-11 pb-3 px-3 flex\">\n          {debouncedSearch !== \"\" ? (\n            // Search exists\n            <div className=\"h-full flex flex-1\">\n              {searchLoading ? (\n                <div className=\"pt-4 flex flex-col w-full items-center text-zinc-500\">\n                  <SymbolIcon className=\"h-8 w-8 animate-spin\" />\n                  <span className=\"pt-2 text-sm pr-2\">Loading friends...</span>\n                </div>\n              ) : searchResults.length > 0 ? (\n                <div className=\"flex w-full flex-col gap-y-3\">\n                  {searchResults.map((user: UserInfo, i: number) => (\n                    <User key={i} data={user} />\n                  ))}\n                </div>\n              ) : (\n                <div className=\"pt-4 flex flex-col w-full items-center text-zinc-500\">\n                  <CrossCircledIcon className=\"h-8 w-8\" />\n                  <span className=\"pt-2 text-sm pr-2\">No results found</span>\n                </div>\n              )}\n            </div>\n          ) : (\n            // No search, return leaderboard\n            <div className=\"flex w-full flex-col gap-y-3\">\n              {leaderboard.map((user: UserInfo, i: number) => (\n                <User key={i} data={user} />\n              ))}\n            </div>\n          )}\n        </div>\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/Favorites.tsx",
    "content": "import User from \"components/User\";\nimport Card from \"components/Card\";\nimport { Global, StateUser } from \"state/global\";\nimport { renderTimeSince } from \"utils/time\";\nimport { usePollData } from \"utils/usePollData\";\nimport { CrossCircledIcon, SymbolIcon } from \"@radix-ui/react-icons\";\n\nconst FORCED_DEFAULTS = {\n  cost: 0,\n  supply: 0,\n  profileChecked: false,\n  createdAt: new Date(),\n  updatedAt: new Date(),\n};\n\nexport default function Favorites() {\n  // Favorites list\n  const { favorites } = Global.useContainer();\n  // Backend data\n  const { data, lastChecked, loading } = usePollData<StateUser[]>(\n    `/api/user?address=${Object.keys(favorites).join(\"&address=\")}`,\n    [],\n    15 * 1000\n  );\n\n  return (\n    <Card title=\"Favorites\" updated={`${renderTimeSince(lastChecked)} ago`}>\n      <div className=\"h-full\">\n        <div className=\"p-3 h-full\">\n          {Object.keys(favorites).length === 0 ? (\n            // No favorites saved\n            <div className=\"flex h-full flex-col items-center justify-center border border-dashed rounded-md text-zinc-500\">\n              <CrossCircledIcon className=\"w-12 h-12\" />\n              <span className=\"pt-2\">No favorites saved</span>\n            </div>\n          ) : loading && data.length === 0 ? (\n            <div className=\"flex h-full flex-col items-center justify-center border border-dashed rounded-md text-zinc-500\">\n              <SymbolIcon className=\"h-12 w-12 animate-spin\" />\n              <span className=\"pt-2\">Loading favorites...</span>\n            </div>\n          ) : data.length === 0 ? (\n            // No favorites found\n            <div className=\"flex h-full flex-col items-center justify-center border border-dashed rounded-md text-zinc-500\">\n              <CrossCircledIcon className=\"h-12 w-12\" />\n              <span className=\"pt-2\">No favorites found</span>\n            </div>\n          ) : (\n            // Favorites data\n            <div className=\"flex w-full flex-col gap-y-3 pb-3\">\n              {data.map((user: StateUser, i: number) => (\n                <User\n                  key={i}\n                  data={{\n                    address: user.address,\n                    twitterPfpUrl: user.image ?? null,\n                    twitterUsername: user.username ?? null,\n                    // Defaults to adhere\n                    ...FORCED_DEFAULTS,\n                  }}\n                  isMinimal={true}\n                />\n              ))}\n            </div>\n          )}\n        </div>\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/Holdings.tsx",
    "content": "import {\n  ButtonIcon,\n  CrossCircledIcon,\n  SymbolIcon,\n} from \"@radix-ui/react-icons\";\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from \"components/ui/table\";\nimport Card from \"components/Card\";\nimport { useAccount } from \"wagmi\";\nimport Address from \"components/Address\";\nimport type { User } from \"@prisma/client\";\nimport { renderTimeSince } from \"utils/time\";\nimport { usePollData } from \"utils/usePollData\";\nimport { ConnectButton } from \"@rainbow-me/rainbowkit\";\n\nexport default function Holdings() {\n  // Wagmi\n  const { address, isConnected } = useAccount();\n\n  // Holdings\n  const {\n    data: holdings,\n    lastChecked,\n    loading,\n  } = usePollData<(User & { balance: number })[]>(\n    `/api/token/holdings?address=${address}`,\n    [],\n    60 * 1000\n  );\n\n  return (\n    <Card title=\"Portfolio\" updated={`${renderTimeSince(lastChecked)} ago`}>\n      {!isConnected ? (\n        // Not connected state\n        <div className=\"h-full p-4\">\n          <div className=\"flex h-full flex-col items-center justify-center border border-dashed rounded-md\">\n            <ButtonIcon className=\"w-12 h-12 text-zinc-500\" />\n            <span className=\"text-zinc-500\">\n              Connect wallet to track holdings\n            </span>\n            <div className=\"mt-4\">\n              <ConnectButton />\n            </div>\n          </div>\n        </div>\n      ) : (\n        <div className=\"h-full\">\n          {loading && holdings.length === 0 && (\n            // Initial load\n            <div className=\"h-full p-4\">\n              <div className=\"flex h-full flex-col items-center justify-center border border-dashed rounded-md\">\n                <SymbolIcon className=\"h-12 w-12 animate-spin\" />\n                <span className=\"text-lg pt-2\">Loading portfolio...</span>\n              </div>\n            </div>\n          )}\n\n          {!loading && holdings.length === 0 && (\n            // No holdings found\n            <div className=\"h-full p-4\">\n              <div className=\"flex h-full flex-col items-center justify-center border border-dashed rounded-md\">\n                <CrossCircledIcon className=\"h-12 w-12\" />\n                <span className=\"text-lg pt-2\">Portfolio is empty</span>\n              </div>\n            </div>\n          )}\n\n          {holdings.length > 0 && (\n            // Some holdings found, render table\n            <Table>\n              <TableHeader>\n                <TableRow>\n                  <TableHead>Friend</TableHead>\n                  <TableHead>Balance</TableHead>\n                </TableRow>\n              </TableHeader>\n              <TableBody>\n                {holdings.map((holding, i: number) => (\n                  <TableRow key={i}>\n                    <TableCell>\n                      <Address\n                        address={holding.address}\n                        username={holding.twitterUsername}\n                        image={holding.twitterPfpUrl}\n                      />\n                    </TableCell>\n                    <TableCell>{holding.balance}</TableCell>\n                  </TableRow>\n                ))}\n              </TableBody>\n            </Table>\n          )}\n        </div>\n      )}\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/NewestUsers.tsx",
    "content": "import axios from \"axios\";\nimport Card from \"components/Card\";\nimport Address from \"components/Address\";\nimport { formatDistance } from \"date-fns\";\nimport { useState, useEffect } from \"react\";\nimport User, { type UserInfo } from \"components/User\";\nimport { usePollData } from \"utils/usePollData\";\nimport { renderTimeSince } from \"utils/time\";\n\nexport default function NewestUsers({\n  users: ssrUsers,\n}: {\n  users: UserInfo[];\n}) {\n  // Newest users list\n  const { data: users, lastChecked } = usePollData(\n    \"/api/stats/newest\",\n    ssrUsers,\n    15 * 1000\n  );\n\n  return (\n    <Card title=\"Newest users\" updated={`${renderTimeSince(lastChecked)} ago`}>\n      <div className=\"flex flex-col p-3 gap-3\">\n        {users.map((user: UserInfo, i: number) => (\n          <User key={i} data={user} />\n        ))}\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/ProfitableUsers.tsx",
    "content": "import {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from \"components/ui/table\";\nimport Card from \"components/Card\";\nimport { parseUSD } from \"utils/usd\";\nimport Address from \"components/Address\";\nimport { renderTimeSince } from \"utils/time\";\nimport { usePollData } from \"utils/usePollData\";\nimport { Global, Currency } from \"state/global\";\nimport { RealizedProfitUser } from \"pages/api/stats/realized\";\n\nexport default function RealizedProfit({\n  profit: ssrProfit,\n}: {\n  profit: RealizedProfitUser[];\n}) {\n  const { eth, currency } = Global.useContainer();\n  const { data, lastChecked } = usePollData(\n    \"/api/stats/realized\",\n    ssrProfit,\n    3 * 60 * 1000\n  );\n\n  return (\n    <Card\n      title=\"Realized Profit\"\n      updated={`${renderTimeSince(lastChecked)} ago`}\n    >\n      <div>\n        <Table className=\"[&_td]:py-1\">\n          <TableHeader>\n            <TableRow>\n              <TableHead>Address</TableHead>\n              <TableHead>Profit</TableHead>\n            </TableRow>\n          </TableHeader>\n          <TableBody>\n            {data.map((p, i) => {\n              const profit: string =\n                currency === Currency.USD\n                  ? `$${parseUSD(p.profit * eth)}`\n                  : `${p.profit.toFixed(2)} Ξ`;\n\n              return (\n                <TableRow key={i}>\n                  <TableCell>\n                    <Address\n                      address={p.address}\n                      username={p.twitterUsername}\n                      image={p.twitterPfpUrl}\n                    />\n                  </TableCell>\n                  <TableCell>\n                    {p.profit > 0 ? (\n                      <span className=\"text-buy\">{profit}</span>\n                    ) : (\n                      <span className=\"text-sell\">{profit}</span>\n                    )}\n                  </TableCell>\n                </TableRow>\n              );\n            })}\n          </TableBody>\n        </Table>\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/RecentTokenTrades.tsx",
    "content": "import Card from \"components/Card\";\nimport { truncateAddress } from \"utils\";\nimport { renderTimeSince } from \"utils/time\";\nimport TradeTable from \"components/TradeTable\";\nimport { usePollData } from \"utils/usePollData\";\nimport { Global, StateUser } from \"state/global\";\nimport { TradeWithTwitterUser } from \"pages/api/stats/trades\";\nimport { CrossCircledIcon, SymbolIcon } from \"@radix-ui/react-icons\";\n\nexport default function RecentTokenTrades() {\n  // Token address\n  const { user }: { user: StateUser } = Global.useContainer();\n  // Trades\n  const {\n    data: trades,\n    lastChecked,\n    loading,\n  } = usePollData<TradeWithTwitterUser[]>(\n    `/api/token/trades?address=${user.address}`,\n    [],\n    15 * 1000\n  );\n\n  return (\n    <Card\n      title=\"Token trades\"\n      updated={`${\n        user.username ? `@${user.username}` : truncateAddress(user.address, 6)\n      }, ${renderTimeSince(lastChecked)} ago`}\n    >\n      <div className=\"h-full\">\n        {loading && trades.length === 0 && (\n          <div className=\"flex mx-auto mt-4 items-center flex-col justify-center w-[calc(100%-2rem)] h-[calc(100%-2rem)] border-2 border-dashed rounded-md\">\n            <SymbolIcon className=\"h-12 w-12 animate-spin\" />\n            <span className=\"text-lg pt-2\">Loading trades...</span>\n          </div>\n        )}\n\n        {trades.length === 0 && (\n          <div className=\"flex mt-4 mx-auto items-center flex-col justify-center w-[calc(100%-2rem)] h-[calc(100%-2rem)] border-2 border-dashed rounded-md\">\n            <CrossCircledIcon className=\"h-12 w-12\" />\n            <span className=\"text-lg pt-2\">\n              {!user.address ? \"Select an address\" : \"No trades found\"}\n            </span>\n          </div>\n        )}\n\n        {trades.length > 0 && <TradeTable trades={trades} />}\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/trading/RecentTrades.tsx",
    "content": "import Card from \"components/Card\";\nimport { renderTimeSince } from \"utils/time\";\nimport TradeTable from \"components/TradeTable\";\nimport { usePollData } from \"utils/usePollData\";\nimport type { TradeWithTwitterUser } from \"pages/api/stats/trades\";\n\nexport default function RecentTrades({\n  trades: ssrTrades,\n}: {\n  trades: TradeWithTwitterUser[];\n}) {\n  const { data: trades, lastChecked } = usePollData(\n    \"/api/stats/trades\",\n    ssrTrades,\n    15 * 1000\n  );\n\n  return (\n    <Card title=\"Recent trades\" updated={`${renderTimeSince(lastChecked)} ago`}>\n      <div>\n        <TradeTable trades={trades} />\n      </div>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/button.tsx",
    "content": "import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"utils\"\n\nconst buttonVariants = cva(\n  \"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:pointer-events-none disabled:opacity-50 dark:focus-visible:ring-zinc-300\",\n  {\n    variants: {\n      variant: {\n        default:\n          \"bg-zinc-900 text-zinc-50 shadow hover:bg-zinc-900/90 dark:bg-zinc-50 dark:text-zinc-900 dark:hover:bg-zinc-50/90\",\n        destructive:\n          \"bg-red-500 text-zinc-50 shadow-sm hover:bg-red-500/90 dark:bg-red-900 dark:text-zinc-50 dark:hover:bg-red-900/90\",\n        outline:\n          \"border border-zinc-200 bg-transparent shadow-sm hover:bg-zinc-100 hover:text-zinc-900 dark:border-zinc-800 dark:hover:bg-zinc-800 dark:hover:text-zinc-50\",\n        secondary:\n          \"bg-zinc-100 text-zinc-900 shadow-sm hover:bg-zinc-100/80 dark:bg-zinc-800 dark:text-zinc-50 dark:hover:bg-zinc-800/80\",\n        ghost: \"hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-50\",\n        link: \"text-zinc-900 underline-offset-4 hover:underline dark:text-zinc-50\",\n      },\n      size: {\n        default: \"h-9 px-4 py-2\",\n        sm: \"h-8 rounded-md px-3 text-xs\",\n        lg: \"h-10 rounded-md px-8\",\n        icon: \"h-9 w-9\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n      size: \"default\",\n    },\n  }\n)\n\nexport interface ButtonProps\n  extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n    VariantProps<typeof buttonVariants> {\n  asChild?: boolean\n}\n\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\n  ({ className, variant, size, asChild = false, ...props }, ref) => {\n    const Comp = asChild ? Slot : \"button\"\n    return (\n      <Comp\n        className={cn(buttonVariants({ variant, size, className }))}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nButton.displayName = \"Button\"\n\nexport { Button, buttonVariants }\n"
  },
  {
    "path": "frontend/components/ui/command.tsx",
    "content": "import * as React from \"react\"\nimport { DialogProps } from \"@radix-ui/react-dialog\"\nimport { MagnifyingGlassIcon } from \"@radix-ui/react-icons\"\nimport { Command as CommandPrimitive } from \"cmdk\"\n\nimport { cn } from \"utils\"\nimport { Dialog, DialogContent } from \"components/ui/dialog\"\n\nconst Command = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive\n    ref={ref}\n    className={cn(\n      \"flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-zinc-950 dark:bg-zinc-950 dark:text-zinc-50\",\n      className\n    )}\n    {...props}\n  />\n))\nCommand.displayName = CommandPrimitive.displayName\n\ninterface CommandDialogProps extends DialogProps {}\n\nconst CommandDialog = ({ children, ...props }: CommandDialogProps) => {\n  return (\n    <Dialog {...props}>\n      <DialogContent className=\"overflow-hidden p-0\">\n        <Command className=\"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-zinc-500 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5 dark:[&_[cmdk-group-heading]]:text-zinc-400\">\n          {children}\n        </Command>\n      </DialogContent>\n    </Dialog>\n  )\n}\n\nconst CommandInput = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Input>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>\n>(({ className, ...props }, ref) => (\n  <div className=\"flex items-center border-b px-3\" cmdk-input-wrapper=\"\">\n    <MagnifyingGlassIcon className=\"mr-2 h-4 w-4 shrink-0 opacity-50\" />\n    <CommandPrimitive.Input\n      ref={ref}\n      className={cn(\n        \"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-zinc-400\",\n        className\n      )}\n      {...props}\n    />\n  </div>\n))\n\nCommandInput.displayName = CommandPrimitive.Input.displayName\n\nconst CommandList = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.List\n    ref={ref}\n    className={cn(\"max-h-[300px] overflow-y-auto overflow-x-hidden\", className)}\n    {...props}\n  />\n))\n\nCommandList.displayName = CommandPrimitive.List.displayName\n\nconst CommandEmpty = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Empty>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>\n>((props, ref) => (\n  <CommandPrimitive.Empty\n    ref={ref}\n    className=\"py-6 text-center text-sm\"\n    {...props}\n  />\n))\n\nCommandEmpty.displayName = CommandPrimitive.Empty.displayName\n\nconst CommandGroup = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Group>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.Group\n    ref={ref}\n    className={cn(\n      \"overflow-hidden p-1 text-zinc-950 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-zinc-500 dark:text-zinc-50 dark:[&_[cmdk-group-heading]]:text-zinc-400\",\n      className\n    )}\n    {...props}\n  />\n))\n\nCommandGroup.displayName = CommandPrimitive.Group.displayName\n\nconst CommandSeparator = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 h-px bg-zinc-200 dark:bg-zinc-800\", className)}\n    {...props}\n  />\n))\nCommandSeparator.displayName = CommandPrimitive.Separator.displayName\n\nconst CommandItem = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-zinc-100 aria-selected:text-zinc-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:aria-selected:bg-zinc-800 dark:aria-selected:text-zinc-50\",\n      className\n    )}\n    {...props}\n  />\n))\n\nCommandItem.displayName = CommandPrimitive.Item.displayName\n\nconst CommandShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\n        \"ml-auto text-xs tracking-widest text-zinc-500 dark:text-zinc-400\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\nCommandShortcut.displayName = \"CommandShortcut\"\n\nexport {\n  Command,\n  CommandDialog,\n  CommandInput,\n  CommandList,\n  CommandEmpty,\n  CommandGroup,\n  CommandItem,\n  CommandShortcut,\n  CommandSeparator,\n}\n"
  },
  {
    "path": "frontend/components/ui/dialog.tsx",
    "content": "import * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { Cross2Icon } from \"@radix-ui/react-icons\"\n\nimport { cn } from \"utils\"\n\nconst Dialog = DialogPrimitive.Root\n\nconst DialogTrigger = DialogPrimitive.Trigger\n\nconst DialogPortal = ({\n  className,\n  ...props\n}: DialogPrimitive.DialogPortalProps) => (\n  <DialogPrimitive.Portal className={cn(className)} {...props} />\n)\nDialogPortal.displayName = DialogPrimitive.Portal.displayName\n\nconst DialogOverlay = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Overlay\n    ref={ref}\n    className={cn(\n      \"fixed inset-0 z-50 bg-white/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 dark:bg-zinc-950/80\",\n      className\n    )}\n    {...props}\n  />\n))\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName\n\nconst DialogContent = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <DialogPortal>\n    <DialogOverlay />\n    <DialogPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-zinc-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full dark:border-zinc-800 dark:bg-zinc-950\",\n        className\n      )}\n      {...props}\n    >\n      {children}\n      <DialogPrimitive.Close className=\"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-zinc-100 data-[state=open]:text-zinc-500 dark:ring-offset-zinc-950 dark:focus:ring-zinc-300 dark:data-[state=open]:bg-zinc-800 dark:data-[state=open]:text-zinc-400\">\n        <Cross2Icon className=\"h-4 w-4\" />\n        <span className=\"sr-only\">Close</span>\n      </DialogPrimitive.Close>\n    </DialogPrimitive.Content>\n  </DialogPortal>\n))\nDialogContent.displayName = DialogPrimitive.Content.displayName\n\nconst DialogHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col space-y-1.5 text-center sm:text-left\",\n      className\n    )}\n    {...props}\n  />\n)\nDialogHeader.displayName = \"DialogHeader\"\n\nconst DialogFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n      className\n    )}\n    {...props}\n  />\n)\nDialogFooter.displayName = \"DialogFooter\"\n\nconst DialogTitle = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Title\n    ref={ref}\n    className={cn(\n      \"text-lg font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nDialogTitle.displayName = DialogPrimitive.Title.displayName\n\nconst DialogDescription = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-zinc-500 dark:text-zinc-400\", className)}\n    {...props}\n  />\n))\nDialogDescription.displayName = DialogPrimitive.Description.displayName\n\nexport {\n  Dialog,\n  DialogTrigger,\n  DialogContent,\n  DialogHeader,\n  DialogFooter,\n  DialogTitle,\n  DialogDescription,\n}\n"
  },
  {
    "path": "frontend/components/ui/input.tsx",
    "content": "import * as React from \"react\"\n\nimport { cn } from \"utils\"\n\nexport interface InputProps\n  extends React.InputHTMLAttributes<HTMLInputElement> {}\n\nconst Input = React.forwardRef<HTMLInputElement, InputProps>(\n  ({ className, type, ...props }, ref) => {\n    return (\n      <input\n        type={type}\n        className={cn(\n          \"flex h-9 w-full rounded-md border border-zinc-200 border-zinc-200 bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-zinc-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-800 dark:border-zinc-800 dark:placeholder:text-zinc-400 dark:focus-visible:ring-zinc-300\",\n          className\n        )}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nInput.displayName = \"Input\"\n\nexport { Input }\n"
  },
  {
    "path": "frontend/components/ui/popover.tsx",
    "content": "import * as React from \"react\"\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\"\n\nimport { cn } from \"utils\"\n\nconst Popover = PopoverPrimitive.Root\n\nconst PopoverTrigger = PopoverPrimitive.Trigger\n\nconst PopoverContent = React.forwardRef<\n  React.ElementRef<typeof PopoverPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = \"center\", sideOffset = 4, ...props }, ref) => (\n  <PopoverPrimitive.Portal>\n    <PopoverPrimitive.Content\n      ref={ref}\n      align={align}\n      sideOffset={sideOffset}\n      className={cn(\n        \"z-50 w-72 rounded-md border border-zinc-200 bg-white p-4 text-zinc-950 shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50\",\n        className\n      )}\n      {...props}\n    />\n  </PopoverPrimitive.Portal>\n))\nPopoverContent.displayName = PopoverPrimitive.Content.displayName\n\nexport { Popover, PopoverTrigger, PopoverContent }\n"
  },
  {
    "path": "frontend/components/ui/table.tsx",
    "content": "import * as React from \"react\";\n\nimport { cn } from \"utils\";\n\nconst Table = React.forwardRef<\n  HTMLTableElement,\n  React.HTMLAttributes<HTMLTableElement>\n>(({ className, ...props }, ref) => (\n  <div className=\"w-full overflow-auto\">\n    <table\n      ref={ref}\n      className={cn(\"w-full caption-bottom text-sm\", className)}\n      {...props}\n    />\n  </div>\n));\nTable.displayName = \"Table\";\n\nconst TableHeader = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <thead ref={ref} className={cn(\"[&_tr]:border-b\", className)} {...props} />\n));\nTableHeader.displayName = \"TableHeader\";\n\nconst TableBody = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <tbody\n    ref={ref}\n    className={cn(\"[&_tr:last-child]:border-0\", className)}\n    {...props}\n  />\n));\nTableBody.displayName = \"TableBody\";\n\nconst TableFooter = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <tfoot\n    ref={ref}\n    className={cn(\n      \"bg-zinc-900 font-medium text-zinc-50 dark:bg-zinc-50 dark:text-zinc-900\",\n      className\n    )}\n    {...props}\n  />\n));\nTableFooter.displayName = \"TableFooter\";\n\nconst TableRow = React.forwardRef<\n  HTMLTableRowElement,\n  React.HTMLAttributes<HTMLTableRowElement>\n>(({ className, ...props }, ref) => (\n  <tr\n    ref={ref}\n    className={cn(\n      \"border-b transition-colors hover:bg-zinc-100/50 data-[state=selected]:bg-zinc-100 dark:hover:bg-zinc-800/50 dark:data-[state=selected]:bg-zinc-800\",\n      className\n    )}\n    {...props}\n  />\n));\nTableRow.displayName = \"TableRow\";\n\nconst TableHead = React.forwardRef<\n  HTMLTableCellElement,\n  React.ThHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n  <th\n    ref={ref}\n    className={cn(\n      \"h-10 px-2 text-left align-middle font-medium text-zinc-500 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] dark:text-zinc-400\",\n      className\n    )}\n    {...props}\n  />\n));\nTableHead.displayName = \"TableHead\";\n\nconst TableCell = React.forwardRef<\n  HTMLTableCellElement,\n  React.TdHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n  <td\n    ref={ref}\n    className={cn(\n      \"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]\",\n      className\n    )}\n    {...props}\n  />\n));\nTableCell.displayName = \"TableCell\";\n\nconst TableCaption = React.forwardRef<\n  HTMLTableCaptionElement,\n  React.HTMLAttributes<HTMLTableCaptionElement>\n>(({ className, ...props }, ref) => (\n  <caption\n    ref={ref}\n    className={cn(\"mt-4 text-sm text-zinc-500 dark:text-zinc-400\", className)}\n    {...props}\n  />\n));\nTableCaption.displayName = \"TableCaption\";\n\nexport {\n  Table,\n  TableHeader,\n  TableBody,\n  TableFooter,\n  TableHead,\n  TableRow,\n  TableCell,\n  TableCaption,\n};\n"
  },
  {
    "path": "frontend/components.json",
    "content": "{\n  \"$schema\": \"https://ui.shadcn.com/schema.json\",\n  \"style\": \"new-york\",\n  \"rsc\": false,\n  \"tsx\": true,\n  \"tailwind\": {\n    \"config\": \"tailwind.config.js\",\n    \"css\": \"global.css\",\n    \"baseColor\": \"zinc\",\n    \"cssVariables\": false\n  },\n  \"aliases\": {\n    \"components\": \"components\",\n    \"utils\": \"utils\"\n  }\n}\n"
  },
  {
    "path": "frontend/global.css",
    "content": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n"
  },
  {
    "path": "frontend/next.config.js",
    "content": "/** @type {import('next').NextConfig} */\nconst nextConfig = {\n  reactStrictMode: true,\n  swcMinify: true,\n  webpack: (config) => {\n    config.resolve.fallback = { fs: false, net: false, tls: false };\n    return config;\n  },\n};\n\nmodule.exports = nextConfig;\n"
  },
  {
    "path": "frontend/package.json",
    "content": "{\n  \"name\": \"frontend\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"prisma generate && next build\",\n    \"start\": \"next start -p $PORT\",\n    \"lint\": \"next lint\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"4.16.2\",\n    \"@radix-ui/react-dialog\": \"^1.0.4\",\n    \"@radix-ui/react-icons\": \"^1.3.0\",\n    \"@radix-ui/react-popover\": \"^1.0.6\",\n    \"@radix-ui/react-slot\": \"^1.0.2\",\n    \"@rainbow-me/rainbowkit\": \"^1.0.8\",\n    \"@tremor/react\": \"^3.6.1\",\n    \"@uidotdev/usehooks\": \"2.1.0\",\n    \"axios\": \"^1.4.0\",\n    \"class-variance-authority\": \"^0.7.0\",\n    \"clsx\": \"^2.0.0\",\n    \"cmdk\": \"^0.2.0\",\n    \"date-fns\": \"^2.30.0\",\n    \"ioredis\": \"^5.3.2\",\n    \"next\": \"13.4.13\",\n    \"react\": \"18.2.0\",\n    \"react-dom\": \"18.2.0\",\n    \"react-grid-layout\": \"^1.3.4\",\n    \"react-resizable\": \"^3.0.5\",\n    \"tailwind-merge\": \"^1.14.0\",\n    \"tailwindcss-animate\": \"^1.0.6\",\n    \"unstated-next\": \"^1.1.0\",\n    \"viem\": \"^1.6.0\",\n    \"wagmi\": \"^1.3.10\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"20.4.10\",\n    \"@types/react\": \"18.2.20\",\n    \"@types/react-dom\": \"18.2.7\",\n    \"@types/react-grid-layout\": \"^1.3.2\",\n    \"autoprefixer\": \"^10.4.14\",\n    \"cssnano\": \"^6.0.1\",\n    \"eslint\": \"8.47.0\",\n    \"eslint-config-next\": \"13.4.13\",\n    \"postcss\": \"^8.4.27\",\n    \"prisma\": \"4.16.2\",\n    \"tailwindcss\": \"^3.3.3\",\n    \"typescript\": \"5.1.6\"\n  }\n}\n"
  },
  {
    "path": "frontend/pages/_app.tsx",
    "content": "import { Global } from \"state/global\";\nimport type { AppProps } from \"next/app\";\n\n// CSS imports\nimport \"global.css\";\nimport \"react-resizable/css/styles.css\";\nimport \"react-grid-layout/css/styles.css\";\nimport \"@rainbow-me/rainbowkit/styles.css\";\n\n// RainbowKit\nimport { base } from \"wagmi/chains\";\nimport { publicProvider } from \"wagmi/providers/public\";\nimport { configureChains, createConfig, WagmiConfig } from \"wagmi\";\nimport {\n  darkTheme,\n  getDefaultWallets,\n  RainbowKitProvider,\n} from \"@rainbow-me/rainbowkit\";\n\n// Setup provider\nconst { chains, publicClient } = configureChains([base], [publicProvider()]);\n\n// Setup connector\nconst { connectors } = getDefaultWallets({\n  appName: \"FriendMEX\",\n  projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID ?? \"\",\n  chains,\n});\n\n// Setup Wagmi config\nconst wagmiConfig = createConfig({\n  autoConnect: true,\n  connectors,\n  publicClient,\n});\n\nexport default function FriendMEX({ Component, pageProps }: AppProps) {\n  return (\n    // Wrap in RainbowKit providers\n    <WagmiConfig config={wagmiConfig}>\n      <RainbowKitProvider chains={chains} theme={darkTheme()}>\n        <Component {...pageProps} />\n      </RainbowKitProvider>\n    </WagmiConfig>\n  );\n}\n"
  },
  {
    "path": "frontend/pages/api/eth.ts",
    "content": "import axios from \"axios\";\nimport cache from \"utils/cache\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\n\n// CoinGecko endpoint\nconst CG_ETHUSD: string =\n  \"https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd\";\n\nexport default async function (req: NextApiRequest, res: NextApiResponse) {\n  try {\n    // Check cache\n    const price: string | null = await cache.get(\"eth_price\");\n    if (price) return res.status(200).json(Number(price));\n\n    // Collect data\n    const {\n      data: {\n        ethereum: { usd },\n      },\n    }: { data: { ethereum: { usd: number } } } = await axios.get(CG_ETHUSD);\n\n    // Update cache with 5m TTL\n    const ok = await cache.set(\"eth_usd\", usd, \"EX\", 60 * 5);\n    if (ok !== \"OK\") throw new Error(\"Error updating cache\");\n\n    // Return price\n    return res.status(200).json(usd);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/stats/leaderboard.ts",
    "content": "import cache from \"utils/cache\";\nimport type { UserInfo } from \"components/User\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\n\n/**\n * Collect leaderboard users (limit: 50) from 15s Redis cache\n * @returns {Promise<UserInfo[]>} leaderboard users\n */\nexport async function getLeaderboardUsers(): Promise<UserInfo[]> {\n  const res: string | null = await cache.get(\"leaderboard\");\n  if (!res) return [];\n\n  // Parse as leaderboard users\n  return JSON.parse(res) as UserInfo[];\n}\n\nexport default async function handler(_: NextApiRequest, res: NextApiResponse) {\n  try {\n    // Get leaderboard users\n    const users = await getLeaderboardUsers();\n    return res.status(200).json(users);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/stats/newest.ts",
    "content": "import cache from \"utils/cache\";\nimport type { UserInfo } from \"components/User\";\nimport { NextApiRequest, NextApiResponse } from \"next\";\n\n/**\n * Collect newest users (limit: 50) from 15s Redis cache\n * @returns {Promise<UserInfo[]>} newest users\n */\nexport async function getNewestUsers(): Promise<UserInfo[]> {\n  const res: string | null = await cache.get(\"latest_users\");\n  if (!res) return [];\n  return JSON.parse(res) as UserInfo[];\n}\n\nexport default async function handler(_: NextApiRequest, res: NextApiResponse) {\n  try {\n    // Get newest users\n    const users = await getNewestUsers();\n    return res.status(200).json(users);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/stats/realized.ts",
    "content": "import cache from \"utils/cache\";\nimport { NextApiRequest, NextApiResponse } from \"next\";\n\nexport type RealizedProfitUser = {\n  address: string;\n  twitterPfpUrl?: string | null;\n  twitterUsername?: string | null;\n  profit: number;\n};\n\n/**\n * Collect realized profits (limit: 100) from 15s Redis cache\n * @returns {RealizedProfitUser[]} address to realized profit\n */\nexport async function getRealizedProfits(): Promise<RealizedProfitUser[]> {\n  const res: string | null = await cache.get(\"realized_profit\");\n  if (!res) return [];\n  return JSON.parse(res);\n}\n\nexport default async function handler(_: NextApiRequest, res: NextApiResponse) {\n  try {\n    // Get realized profits\n    const profits = await getRealizedProfits();\n    return res.status(200).json(profits);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/stats/trades.ts",
    "content": "import cache from \"utils/cache\";\nimport type { Trade } from \"@prisma/client\";\nimport { NextApiRequest, NextApiResponse } from \"next\";\n\nexport type TradeWithTwitterUser = Trade & {\n  fromUser: {\n    twitterUsername?: string | null;\n    twitterPfpUrl?: string | null;\n  };\n  subjectUser: {\n    twitterUsername?: string | null;\n    twitterPfpUrl?: string | null;\n  };\n};\n\n/**\n * Collect newest trades (limit: 100)\n * @returns {Promise<TradeWithTwitterUser[]>} newest trades\n */\nexport async function getLatestTrades(): Promise<TradeWithTwitterUser[]> {\n  const res: string | null = await cache.get(\"latest_trades\");\n  if (!res) return [];\n\n  // Parse as Trades\n  return JSON.parse(res) as TradeWithTwitterUser[];\n}\n\nexport default async function handler(_: NextApiRequest, res: NextApiResponse) {\n  try {\n    // Get latest trades\n    const trades = await getLatestTrades();\n    return res.status(200).json(trades);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/token/chart.ts",
    "content": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport { getPrice } from \"utils\";\nimport type { Trade } from \"@prisma/client\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\n\n// Types\ntype ChartData = { timestamp: Date; \"Price (ETH)\": number }[];\ntype CachedData = { lastChecked: Date; chart: ChartData; supply: number };\n\nfunction processTrades(trades: Trade[], existing?: CachedData): CachedData {\n  let supply: number = 0,\n    data: ChartData = [];\n\n  // If existing chart data\n  if (existing) {\n    // Track trades\n    data.push(...existing.chart);\n    // Append supply\n    supply += existing.supply;\n  }\n\n  // Take remaining, new trades\n  for (const trade of trades) {\n    // Modify amounts\n    if (trade.isBuy) supply += trade.amount;\n    else supply -= trade.amount;\n\n    // Calculate new price for 1 token given supply change\n    const price = getPrice(supply, 1);\n    const fees = price * 0.1;\n\n    // Add new plot data\n    data.push({\n      timestamp: new Date(trade.timestamp * 1000),\n      \"Price (ETH)\": price - fees,\n    });\n  }\n\n  return {\n    lastChecked: new Date(),\n    chart: data,\n    supply,\n  };\n}\n\nexport default async function handler(\n  req: NextApiRequest,\n  res: NextApiResponse\n) {\n  // Collect token address\n  let { address } = req.query;\n  if (!address) return res.status(400).json({ error: \"Missing token address\" });\n  // Only accept first query parameter\n  if (Array.isArray(address)) address = address[0];\n  address = address.toLowerCase();\n\n  try {\n    // Check cache to see if chart exists\n    const cacheData = await cache.get(`fmex_chart_${address}`);\n\n    let processed: CachedData;\n    if (cacheData) {\n      // If cache exists, check cache last update time\n      let parsedData: Omit<CachedData, \"lastChecked\"> & {\n        lastChecked: string;\n      } = JSON.parse(cacheData);\n      const parsedToType: CachedData = {\n        ...parsedData,\n        lastChecked: new Date(parsedData.lastChecked),\n      };\n\n      // Time since last update > 5m\n      const timeDiffInMS =\n        new Date().getTime() - parsedToType.lastChecked.getTime();\n      if (timeDiffInMS > 5 * 60 * 1000) {\n        // Collect new trades to occur since lastChecked time\n        const trades: Trade[] = await db.trade.findMany({\n          orderBy: {\n            timestamp: \"asc\",\n          },\n          where: {\n            subjectAddress: address.toLowerCase(),\n            createdAt: {\n              gte: parsedToType.lastChecked,\n            },\n          },\n        });\n\n        // If no new updates in last 5m\n        if (trades.length === 0) {\n          // Update cache and return latest\n          const ok = await cache.set(\n            `fmex_chart_${address}`,\n            JSON.stringify({\n              ...parsedToType,\n              lastChecked: new Date(),\n            })\n          );\n          if (ok != \"OK\") throw new Error(\"Errored storing in cache\");\n          return res.status(200).json(parsedToType.chart);\n        }\n\n        // Augment existing trades\n        processed = processTrades(trades, parsedToType);\n      } else {\n        // Simply return cached data\n        return res.status(200).json(parsedData.chart);\n      }\n    } else {\n      // If cache does not exist, retrieve all trades\n      const trades: Trade[] = await db.trade.findMany({\n        orderBy: {\n          timestamp: \"asc\",\n        },\n        where: {\n          subjectAddress: address.toLowerCase(),\n        },\n      });\n\n      // Process trades\n      processed = processTrades(trades);\n    }\n\n    // Store in Redis\n    const ok = await cache.set(\n      `fmex_chart_${address}`,\n      JSON.stringify(processed)\n    );\n    if (ok != \"OK\") throw new Error(\"Errored storing in cache\");\n\n    // Return new data\n    return res.status(200).json(processed.chart);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/token/holdings.ts",
    "content": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport type { Trade, User } from \"@prisma/client\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\n\ntype Holding = User & { balance: number };\ntype ExtendedTrade = Trade & { subjectUser: User };\ntype CachedHoldings = { lastChecked: Date; holdings: Holding[] };\n\nfunction processHoldings(\n  trades: ExtendedTrade[],\n  existing?: Holding[]\n): Holding[] {\n  // Setup balances and users\n  let subjectToBalance: Record<string, number> = {};\n  let subjectToUser: Record<string, User> = {};\n\n  // If existing cached holdings\n  if (existing) {\n    // Update local states\n    for (const holding of existing) {\n      subjectToBalance[holding.address] = holding.balance;\n      const { balance, ...rest } = holding;\n      subjectToUser[holding.address] = rest;\n    }\n  }\n\n  // For each trade\n  for (const trade of trades) {\n    // Initialize:\n    if (!subjectToBalance[trade.subjectAddress]) {\n      // Initialize balance\n      subjectToBalance[trade.subjectAddress] = 0;\n      // Initialize data\n      subjectToUser[trade.subjectAddress] = trade.subjectUser;\n    }\n\n    // Process trade\n    if (trade.isBuy) {\n      subjectToBalance[trade.subjectAddress] += trade.amount;\n    } else {\n      subjectToBalance[trade.subjectAddress] -= trade.amount;\n    }\n  }\n\n  // Recompile to return format\n  let holdings: (User & { balance: number })[] = [];\n  for (const address of Object.keys(subjectToBalance)) {\n    if (subjectToBalance[address] > 0) {\n      holdings.push({\n        ...subjectToUser[address],\n        balance: subjectToBalance[address],\n      });\n    }\n  }\n\n  // Sort by most owned first\n  holdings = holdings.sort((a, b) => b.balance - a.balance);\n\n  return holdings;\n}\n\nexport default async function handler(\n  req: NextApiRequest,\n  res: NextApiResponse\n) {\n  // Collect token address\n  let { address } = req.query;\n  if (!address) return res.status(400).json({ error: \"Missing token address\" });\n  // Only accept first query parameter\n  if (Array.isArray(address)) address = address[0];\n  address = address.toLowerCase();\n\n  let data: CachedHoldings;\n  try {\n    // Check for cached holdings\n    const cachedString = await cache.get(`holdings_${address}`);\n\n    // If cache exists\n    if (cachedString) {\n      // Parse cache\n      const parseString: Omit<CachedHoldings, \"lastChecked\"> & {\n        lastChecked: string;\n      } = JSON.parse(cachedString);\n      const parsed: CachedHoldings = {\n        ...parseString,\n        lastChecked: new Date(parseString.lastChecked),\n      };\n\n      // Collect new trades since last checked date\n      const trades: ExtendedTrade[] = await db.trade.findMany({\n        where: {\n          fromAddress: address,\n          createdAt: {\n            gte: parsed.lastChecked,\n          },\n        },\n        orderBy: {\n          timestamp: \"asc\",\n        },\n        include: {\n          subjectUser: true,\n        },\n      });\n\n      // If no new trades, simply return\n      if (trades.length === 0) {\n        // Update last checked time\n        const ok = await cache.set(\n          `holdings_${address}`,\n          JSON.stringify({\n            ...parsed,\n            lastChecked: new Date(),\n          })\n        );\n        if (!ok) throw new Error(\"Could not save to Redis\");\n        return res.status(200).send(parsed.holdings);\n      }\n\n      // Parse new trades\n      data = {\n        lastChecked: new Date(),\n        holdings: processHoldings(trades, parsed.holdings),\n      };\n    } else {\n      // If no cache, collect all trades by token address\n      const trades: ExtendedTrade[] = await db.trade.findMany({\n        where: {\n          fromAddress: address,\n        },\n        orderBy: {\n          timestamp: \"asc\",\n        },\n        include: {\n          subjectUser: true,\n        },\n      });\n\n      // Assign data\n      data = {\n        lastChecked: new Date(),\n        holdings: processHoldings(trades),\n      };\n    }\n\n    // Store new changes in Redis\n    const ok = await cache.set(`holdings_${address}`, JSON.stringify(data));\n    if (!ok) throw new Error(\"Could not save to Redis\");\n\n    return res.status(200).json(data.holdings);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/token/search.ts",
    "content": "import db from \"prisma/index\";\nimport { getPrice } from \"utils\";\nimport type { User } from \"@prisma/client\";\nimport type { UserInfo } from \"components/User\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\n\nexport default async function (req: NextApiRequest, res: NextApiResponse) {\n  // Collect search query\n  const { search }: { search: string } = req.body;\n  if (!search) return res.status(400).json({ error: \"Missing search query\" });\n\n  try {\n    // Search prisma (faking fuzzy search, Prisma limitation)\n    let users: User[] = await db.user.findMany({\n      where: {\n        OR: [\n          {\n            address: {\n              search: search.toLowerCase(),\n            },\n          },\n          {\n            twitterUsername: {\n              search,\n            },\n          },\n        ],\n      },\n      take: 10,\n    });\n\n    // Augment users with cost\n    const augmented: UserInfo[] = users.map((user) => ({\n      ...user,\n      cost: getPrice(user.supply, 1),\n    }));\n\n    return res.status(200).send(augmented);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/token/trades.ts",
    "content": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\nimport type { TradeWithTwitterUser } from \"../stats/trades\";\n\ntype CachedData = { lastChecked: Date; trades: TradeWithTwitterUser[] };\n\nexport default async function handler(\n  req: NextApiRequest,\n  res: NextApiResponse\n) {\n  // Collect token address\n  let { address } = req.query;\n  if (!address) return res.status(400).json({ error: \"Missing token address\" });\n  // Only accept first query parameter\n  if (Array.isArray(address)) address = address[0];\n  address = address.toLowerCase();\n\n  try {\n    // Check cache\n    const cachedString = await cache.get(`cach_trades_${address}`);\n\n    let data: CachedData;\n    // If cached data exists\n    if (cachedString) {\n      // Parse cache\n      const parseString: Omit<CachedData, \"lastChecked\"> & {\n        lastChecked: string;\n      } = JSON.parse(cachedString);\n      const parsed: CachedData = {\n        ...parseString,\n        lastChecked: new Date(parseString.lastChecked),\n      };\n\n      // Time since last update > 5m\n      const timeDiffInMS = new Date().getTime() - parsed.lastChecked.getTime();\n      if (timeDiffInMS > 5 * 60 * 1000) {\n        // Collect new data from lastChecked point\n        const trades = await db.trade.findMany({\n          orderBy: {\n            timestamp: \"desc\",\n          },\n          where: {\n            subjectAddress: address.toLowerCase(),\n            createdAt: {\n              gte: parsed.lastChecked,\n            },\n          },\n          include: {\n            fromUser: {\n              select: {\n                twitterPfpUrl: true,\n                twitterUsername: true,\n              },\n            },\n            subjectUser: {\n              select: {\n                twitterPfpUrl: true,\n                twitterUsername: true,\n              },\n            },\n          },\n          take: 100,\n        });\n\n        // If no new trades, return cached\n        if (trades.length === 0) {\n          // Update last checked time\n          const ok = await cache.set(\n            `cach_trades_${address}`,\n            JSON.stringify({\n              lastChecked: new Date(),\n              trades: parsed.trades,\n            })\n          );\n          if (ok != \"OK\") throw new Error(\"Errored storing in cache\");\n\n          return res.status(200).json(parsed.trades);\n        }\n\n        // Else, augment new trades and store\n        data = {\n          lastChecked: new Date(),\n          // Remove number of new trades from beginning\n          trades: [...trades, ...parsed.trades].slice(0, -1 * trades.length),\n        };\n      } else {\n        // Return cached data\n        return res.status(200).json(parsed.trades);\n      }\n    } else {\n      // If no cached data, collect trades from DB\n      const trades = await db.trade.findMany({\n        orderBy: {\n          timestamp: \"desc\",\n        },\n        where: {\n          subjectAddress: address.toLowerCase(),\n        },\n        include: {\n          fromUser: {\n            select: {\n              twitterPfpUrl: true,\n              twitterUsername: true,\n            },\n          },\n          subjectUser: {\n            select: {\n              twitterPfpUrl: true,\n              twitterUsername: true,\n            },\n          },\n        },\n        take: 100,\n      });\n\n      // Update local data\n      data = {\n        lastChecked: new Date(),\n        trades,\n      };\n    }\n\n    // Store in redis cache\n    const ok = await cache.set(`cach_trades_${address}`, JSON.stringify(data));\n    if (ok != \"OK\") throw new Error(\"Errored storing in cache\");\n\n    return res.status(200).json(data.trades);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/api/user.ts",
    "content": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport { getPrice } from \"utils\";\nimport type { StateUser } from \"state/global\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\n\n/**\n * Collects StateUser object for address or throws\n * @param {string} address to collect\n * @returns {Promise<StateUser>}\n */\nexport async function getStateUser(address: string): Promise<StateUser> {\n  // Force lowercase\n  const lowerAddress: string = address.toLowerCase();\n\n  // Check for cache\n  const cached = await cache.get(`state_user_${lowerAddress}`);\n  // If cached, return\n  if (cached) return JSON.parse(cached) as StateUser;\n\n  // Collect from db\n  const { twitterPfpUrl: image, twitterUsername: username } =\n    await db.user.findUniqueOrThrow({\n      where: {\n        address: lowerAddress,\n      },\n      select: {\n        twitterPfpUrl: true,\n        twitterUsername: true,\n      },\n    });\n\n  // Setup user\n  const user: StateUser = {\n    address: lowerAddress,\n    image,\n    username,\n  };\n\n  // Store in cache\n  const ok = await cache.set(\n    `state_user_${lowerAddress}`,\n    JSON.stringify(user)\n  );\n  if (ok !== \"OK\") throw new Error(\"Error updating cache\");\n\n  // Return data\n  return user;\n}\n\nexport default async function (req: NextApiRequest, res: NextApiResponse) {\n  // Collect address from body\n  let { address } = req.query;\n  // Throw if missing parameter\n  if (!address) return res.status(400).json({ error: \"Missing address\" });\n  if (!Array.isArray(address)) address = [address];\n\n  try {\n    // Check for users\n    const requests = address.map((addr) => getStateUser(addr.toLowerCase()));\n    const results = await Promise.allSettled(requests);\n    let fulfilled = [];\n    for (const res of results) {\n      if (res.status === \"fulfilled\") fulfilled.push(res.value);\n    }\n\n    return res.status(200).json(fulfilled);\n  } catch (e: unknown) {\n    // Catch errors\n    if (e instanceof Error) {\n      return res.status(500).json({ message: e.message });\n    }\n\n    // Return default error\n    return res.status(500).json({ message: \"Internal server error\" });\n  }\n}\n"
  },
  {
    "path": "frontend/pages/index.tsx",
    "content": "import dynamic from \"next/dynamic\";\nimport Layout from \"components/Layout\";\nimport constants from \"utils/constants\";\nimport type { StateUser } from \"state/global\";\nimport { WidthProvider, Responsive } from \"react-grid-layout\";\n\n// Trading views\nimport Chart from \"components/trading/Chart\";\nimport Discover from \"components/trading/Discover\";\nimport NewestUsers from \"components/trading/NewestUsers\";\nimport RecentTrades from \"components/trading/RecentTrades\";\n// import RealizedProfit from \"components/trading/ProfitableUsers\";\nimport RecentTokenTrades from \"components/trading/RecentTokenTrades\";\n\n// API\nimport { getNewestUsers } from \"./api/stats/newest\";\nimport { type TradeWithTwitterUser, getLatestTrades } from \"./api/stats/trades\";\nimport { getLeaderboardUsers } from \"./api/stats/leaderboard\";\n// import {\n//   type RealizedProfitUser,\n//   getRealizedProfits,\n// } from \"./api/stats/realized\";\nimport type { UserInfo } from \"components/User\";\nimport type { NextPageContext } from \"next\";\nimport { getStateUser } from \"./api/user\";\nimport Favorites from \"components/trading/Favorites\";\n\nconst ResponsiveGridLayout = WidthProvider(Responsive);\nconst BuySell = dynamic(() => import(\"components/trading/BuySell\"), {\n  ssr: false,\n});\nconst Holdings = dynamic(() => import(\"components/trading/Holdings\"), {\n  ssr: false,\n});\n\nexport default function Home({\n  newestUsers,\n  latestTrades,\n  leaderboardUsers,\n  // realizedProfit,\n  user,\n}: {\n  newestUsers: UserInfo[];\n  latestTrades: TradeWithTwitterUser[];\n  leaderboardUsers: UserInfo[];\n  // realizedProfit: RealizedProfitUser[];\n  user: StateUser;\n}) {\n  // Layout setting\n  const layout = {\n    md: [\n      { i: \"chart\", x: 0, y: 0.6, w: 24, h: 3 },\n      { i: \"discover\", x: 6.6, y: 0, w: 24, h: 3 },\n      { i: \"holdings\", x: 21.6, y: 24, w: 24, h: 3 },\n      { i: \"favorites\", x: 21.6, y: 24, w: 24, h: 3 },\n      { i: \"recent_trades\", x: 9.6, y: 0, w: 24, h: 3 },\n      { i: \"buy_sell\", x: 3.6, y: 0, w: 24, h: 3 },\n      { i: \"recent_token_trades\", x: 12, y: 0, w: 24, h: 3 },\n      { i: \"realized_profit\", x: 15.6, y: 0, w: 24, h: 3 },\n      { i: \"newest_users\", x: 18.6, y: 0, w: 24, h: 3 },\n    ],\n    lg: [\n      { i: \"chart\", x: 0, y: 0, w: 20, h: 3 },\n      { i: \"buy_sell\", x: 20, y: 0, w: 8, h: 3 },\n      { i: \"discover\", x: 28, y: 0, w: 8, h: 3 },\n      { i: \"recent_trades\", x: 0, y: 6, w: 28, h: 3 },\n      { i: \"favorites\", x: 28, y: 6, w: 8, h: 3 },\n      { i: \"recent_token_trades\", x: 0, y: 12, w: 25, h: 3 },\n      { i: \"realized_profit\", x: 18, y: 18, w: 9, h: 3 },\n      { i: \"newest_users\", x: 27, y: 18, w: 11, h: 3 },\n      { i: \"holdings\", x: 0, y: 24, w: 36, h: 3 },\n    ],\n  };\n\n  return (\n    <Layout user={user}>\n      <ResponsiveGridLayout\n        layouts={layout}\n        draggableHandle=\".drag-handle\"\n        cols={{ lg: 36, md: 24, sm: 12, xs: 6, xxs: 3 }}\n      >\n        {/* Discover */}\n        <div key=\"discover\">\n          <Discover leaderboard={leaderboardUsers} />\n        </div>\n\n        {/* Trading chart */}\n        <div key=\"chart\">\n          <Chart />\n        </div>\n\n        {/* Buy + Sell controller */}\n        <div key=\"buy_sell\">\n          <BuySell />\n        </div>\n\n        {/* Recent trades */}\n        <div key=\"recent_trades\">\n          <RecentTrades trades={latestTrades} />\n        </div>\n\n        {/* Favorites */}\n        <div key=\"favorites\">\n          <Favorites />\n        </div>\n\n        {/* Portfolio */}\n        <div key=\"holdings\">\n          <Holdings />\n        </div>\n\n        {/* Recent token trades */}\n        <div key=\"recent_token_trades\">\n          <RecentTokenTrades />\n        </div>\n\n        {/* Most profitable users, temp disabled */}\n        {/* <div key=\"realized_profit\">\n          <RealizedProfit profit={realizedProfit} />\n        </div> */}\n\n        {/* Newest users */}\n        <div key=\"newest_users\">\n          <NewestUsers users={newestUsers} />\n        </div>\n      </ResponsiveGridLayout>\n    </Layout>\n  );\n}\n\nexport async function getServerSideProps(ctx: NextPageContext) {\n  // Collect query params\n  let { address } = ctx.query;\n  // If array, select first\n  if (Array.isArray(address)) {\n    address = address[0];\n  }\n\n  let user: StateUser;\n  try {\n    // If no address throw\n    if (!address) throw new Error(\"No address found\");\n\n    // Collect user by address\n    user = await getStateUser(address);\n  } catch {\n    // If error, default to Cobie\n    user = constants.COBIE;\n  }\n\n  // Collect data\n  const newestUsers = await getNewestUsers();\n  const latestTrades = await getLatestTrades();\n  const leaderboardUsers = await getLeaderboardUsers();\n  // const realizedProfit = await getRealizedProfits();\n\n  return {\n    props: {\n      newestUsers,\n      latestTrades,\n      leaderboardUsers,\n      // realizedProfit,\n      user,\n    },\n  };\n}\n"
  },
  {
    "path": "frontend/postcss.config.js",
    "content": "module.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n    ...(process.env.NODE_ENV === \"production\" ? { cssnano: {} } : {}),\n  },\n};\n"
  },
  {
    "path": "frontend/prisma/index.ts",
    "content": "import { PrismaClient } from \"@prisma/client\";\n\n// Setup global prisma\nconst globalForPrisma = globalThis as unknown as {\n  prisma: PrismaClient | undefined;\n};\n\n// Export db\nconst db = globalForPrisma.prisma ?? new PrismaClient();\nexport default db;\n\n// Assign to global (cache)\nif (process.env.NODE_ENV !== \"production\") globalForPrisma.prisma = db;\n"
  },
  {
    "path": "frontend/prisma/schema.prisma",
    "content": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider = \"prisma-client-js\"\n  previewFeatures = [\"fullTextSearch\"]\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel User {\n  address         String   @id @unique\n  twitterUsername String?\n  twitterPfpUrl   String?\n  profileChecked  Boolean  @default(false)\n  supply          Int      @default(0)\n  createdAt       DateTime @default(now())\n  updatedAt       DateTime @updatedAt\n\n  createdTrades Trade[] @relation(\"fromUser\")\n  subjectTrades Trade[] @relation(\"subjectUser\")\n}\n\nmodel Trade {\n  hash           String   @id @unique\n  timestamp      Int\n  blockNumber    Int\n  fromAddress    String\n  subjectAddress String\n  isBuy          Boolean\n  amount         Int\n  cost           Decimal  @db.Decimal(65, 0)\n  createdAt      DateTime @default(now())\n  updatedAt      DateTime @updatedAt\n\n  fromUser    User @relation(name: \"fromUser\", fields: [fromAddress], references: [address])\n  subjectUser User @relation(name: \"subjectUser\", fields: [subjectAddress], references: [address])\n}\n"
  },
  {
    "path": "frontend/state/global.ts",
    "content": "import axios from \"axios\";\nimport constants from \"utils/constants\";\nimport { useRouter } from \"next/router\";\nimport { useEffect, useState } from \"react\";\nimport { createContainer } from \"unstated-next\";\n\n// Global state user\nexport type StateUser = {\n  address: string;\n  username?: string | null;\n  image?: string | null;\n};\n\nexport enum Currency {\n  USD,\n  ETH,\n}\n\nfunction useGlobal(initialState: StateUser = constants.COBIE) {\n  // Routing\n  const { push } = useRouter();\n\n  // Default: @cobie\n  const [user, setUser] = useState<StateUser>(initialState);\n  // Currency\n  const [currency, setCurrency] = useState<Currency>(Currency.ETH);\n  // ETH Price\n  const [eth, setEth] = useState<number>(0);\n  // Favorites\n  const [favorites, setFavorites] = useState<Record<string, StateUser>>({});\n\n  // On page load\n  useEffect(() => {\n    // Load eth price\n    async function collectEthPrice() {\n      const { data } = await axios.get(\"/api/eth\");\n      setEth(data);\n    }\n    collectEthPrice();\n\n    // Load favorites from local storage\n    const localFavorites = localStorage.getItem(\"friendmex_favorites\");\n    if (localFavorites) setFavorites(JSON.parse(localFavorites));\n  }, []);\n\n  // Update query params on user change\n  useEffect(() => {\n    // Shallow update url\n    push(`/?address=${user.address}`, undefined, { shallow: true });\n  }, [push, user.address]);\n\n  /**\n   * Track favorite user\n   * @param {StateUser} user\n   */\n  const addFavorite = (user: StateUser) => {\n    const newFavorites = { ...favorites, [user.address]: user };\n    setFavorites({ ...newFavorites });\n    localStorage.setItem(\"friendmex_favorites\", JSON.stringify(newFavorites));\n  };\n\n  /**\n   * Remove favorite user\n   * @param {StateUser} user\n   */\n  const removeFavorite = (user: StateUser) => {\n    const { [user.address]: _, ...rest } = favorites;\n    setFavorites({ ...rest });\n    localStorage.setItem(\"friendmex_favorites\", JSON.stringify(rest));\n  };\n\n  /**\n   * Toggles favorite user\n   * @param {StateUser} user\n   */\n  const toggleFavorite = (user: StateUser) =>\n    user.address in favorites ? removeFavorite(user) : addFavorite(user);\n\n  return {\n    eth,\n    user,\n    setUser,\n    currency,\n    setCurrency,\n    favorites,\n    toggleFavorite,\n  };\n}\n\nexport const Global = createContainer(useGlobal);\n"
  },
  {
    "path": "frontend/tailwind.config.js",
    "content": "/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n  darkMode: [\"class\"],\n  content: [\n    \"./pages/**/*.{ts,tsx}\",\n    \"./components/**/*.{ts,tsx}\",\n    \"./app/**/*.{ts,tsx}\",\n    \"./src/**/*.{ts,tsx}\",\n    \"./node_modules/@tremor/**/*.{js,ts,jsx,tsx}\", // Tremor module\n  ],\n  theme: {\n    container: {\n      center: true,\n      padding: \"2rem\",\n      screens: {\n        \"2xl\": \"1400px\",\n      },\n    },\n    extend: {\n      keyframes: {\n        \"accordion-down\": {\n          from: { height: 0 },\n          to: { height: \"var(--radix-accordion-content-height)\" },\n        },\n        \"accordion-up\": {\n          from: { height: \"var(--radix-accordion-content-height)\" },\n          to: { height: 0 },\n        },\n      },\n      animation: {\n        \"accordion-down\": \"accordion-down 0.2s ease-out\",\n        \"accordion-up\": \"accordion-up 0.2s ease-out\",\n      },\n      boxShadow: {\n        // light\n        \"tremor-input\": \"0 1px 2px 0 rgb(0 0 0 / 0.05)\",\n        \"tremor-card\":\n          \"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)\",\n        \"tremor-dropdown\":\n          \"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)\",\n        // dark\n        \"dark-tremor-input\": \"0 1px 2px 0 rgb(0 0 0 / 0.05)\",\n        \"dark-tremor-card\":\n          \"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)\",\n        \"dark-tremor-dropdown\":\n          \"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)\",\n      },\n      borderRadius: {\n        \"tremor-small\": \"0.375rem\",\n        \"tremor-default\": \"0.5rem\",\n        \"tremor-full\": \"9999px\",\n      },\n      fontSize: {\n        \"tremor-label\": [\"0.75rem\"],\n        \"tremor-default\": [\"0.875rem\", { lineHeight: \"1.25rem\" }],\n        \"tremor-title\": [\"1.125rem\", { lineHeight: \"1.75rem\" }],\n        \"tremor-metric\": [\"1.875rem\", { lineHeight: \"2.25rem\" }],\n      },\n      colors: {\n        buy: \"#00A969\",\n        \"buy-30\": \"#00A9690D\",\n        sell: \"#DF0E29\",\n        \"sell-30\": \"#DF0E290D\",\n        \"bitmex-widget\": \"#FAFAFA\",\n        \"bitmex-strong\": \"#EAECEF\",\n        \"bitmex-strong-border\": \"#CBD0D7\",\n        tremor: {\n          brand: {\n            faint: \"#eff6ff\", // blue-50\n            muted: \"#bfdbfe\", // blue-200\n            subtle: \"#60a5fa\", // blue-400\n            DEFAULT: \"#3b82f6\", // blue-500\n            emphasis: \"#1d4ed8\", // blue-700\n            inverted: \"#ffffff\", // white\n          },\n          background: {\n            muted: \"#f9fafb\", // gray-50\n            subtle: \"#f3f4f6\", // gray-100\n            DEFAULT: \"#ffffff\", // white\n            emphasis: \"#374151\", // gray-700\n          },\n          border: {\n            DEFAULT: \"#e5e7eb\", // gray-200\n          },\n          ring: {\n            DEFAULT: \"#e5e7eb\", // gray-200\n          },\n          content: {\n            subtle: \"#9ca3af\", // gray-400\n            DEFAULT: \"#6b7280\", // gray-500\n            emphasis: \"#374151\", // gray-700\n            strong: \"#111827\", // gray-900\n            inverted: \"#ffffff\", // white\n          },\n        },\n      },\n    },\n  },\n  safelist: [\n    {\n      pattern:\n        /^(bg-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,\n      variants: [\"hover\", \"ui-selected\"],\n    },\n    {\n      pattern:\n        /^(text-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,\n      variants: [\"hover\", \"ui-selected\"],\n    },\n    {\n      pattern:\n        /^(border-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,\n      variants: [\"hover\", \"ui-selected\"],\n    },\n    {\n      pattern:\n        /^(ring-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,\n    },\n    {\n      pattern:\n        /^(stroke-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,\n    },\n    {\n      pattern:\n        /^(fill-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,\n    },\n  ],\n  plugins: [require(\"tailwindcss-animate\")],\n};\n"
  },
  {
    "path": "frontend/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noEmit\": true,\n    \"esModuleInterop\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"preserve\",\n    \"incremental\": true,\n    \"baseUrl\": \"./\"\n  },\n  \"include\": [\"next-env.d.ts\", \"**/*.ts\", \"**/*.tsx\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "frontend/utils/cache.ts",
    "content": "import Redis from \"ioredis\";\n\n// Redis URL (default or env)\nconst REDIS_URL: string = process.env.REDIS_URL ?? \"redis://127.0.0.1:6379\";\n// Export redis provider\nconst cache = new Redis(REDIS_URL);\nexport default cache;\n"
  },
  {
    "path": "frontend/utils/constants.ts",
    "content": "import type { StateUser } from \"state/global\";\n\n// Default user\nconst COBIE: StateUser = {\n  address: \"0x4e5f7e4a774bd30b9bdca7eb84ce3681a71676e1\",\n  username: \"cobie\",\n  image:\n    \"https://pbs.twimg.com/profile_images/1688496375707701248/WwWz33DI.jpg\",\n};\n\nexport default { COBIE };\n"
  },
  {
    "path": "frontend/utils/time.ts",
    "content": "/**\n * Given some time in seconds, returns formatted string in format \"{value}{unit}\"\n * @dev Assumes that things will fail much before a transition beyond 59m 59s\n * @param {number} s seconds value\n * @returns {string} formatted string\n */\nexport function renderTimeSince(s: number): string {\n  // If minutes not relevant, return seconds\n  if (s < 60) return `${s}s`;\n  // Else, get number of minutes\n  const seconds: number = s % 60;\n  const minutes: number = (s - seconds) / 60;\n  return `${minutes}m ${seconds}s`;\n}\n"
  },
  {
    "path": "frontend/utils/usd.ts",
    "content": "/**\n * Parse USD numeric in appropriate dollar format\n * @param {number} value to parse\n * @returns {string} parsed\n */\nexport function parseUSD(value: number): string {\n  return value.toLocaleString(\"us-en\", {\n    minimumFractionDigits: 2,\n    maximumFractionDigits: 2,\n  });\n}\n"
  },
  {
    "path": "frontend/utils/usePollData.ts",
    "content": "import axios from \"axios\";\nimport { useState, useEffect, useCallback } from \"react\";\n\nexport function usePollData<T>(\n  endpoint: string,\n  initial: T,\n  frequency?: number\n) {\n  // Loading status\n  const [loading, setLoading] = useState<boolean>(true);\n  // Stored data\n  const [data, setData] = useState<T>(initial);\n  // Time since last checked\n  const [lastChecked, setLastChecked] = useState<number>(0);\n\n  /**\n   * Call backend, collect some generic data, set data\n   */\n  const collectData = useCallback(async (): Promise<void> => {\n    try {\n      // Toggle loading\n      setLoading(true);\n      // Collect data\n      const { data: newData }: { data: T } = await axios.get(endpoint);\n      // Update data\n      setData(newData);\n    } catch (e) {\n      // If known error\n      if (e instanceof Error) {\n        // Log message\n        console.error(e.message);\n      } else {\n        // Else, log full object\n        console.error(e);\n      }\n    } finally {\n      // Toggle loading\n      setLoading(false);\n    }\n  }, [endpoint]);\n\n  /**\n   * Collect data at some interval\n   */\n  useEffect(() => {\n    /**\n     * Collection execution function\n     */\n    async function execute(): Promise<void> {\n      await collectData();\n      setLastChecked(0);\n    }\n\n    execute();\n\n    // If some update frequency exists\n    if (frequency) {\n      // Execute at set frequency\n      const executeInterval = setInterval(() => execute(), frequency);\n      // Increment lastChecked\n      const checkInterval = setInterval(\n        () => setLastChecked((previous) => previous + 1),\n        1 * 1000 // Every second\n      );\n\n      // On dismount\n      return () => {\n        // Clear intervals\n        clearInterval(executeInterval);\n        clearInterval(checkInterval);\n      };\n    }\n  }, [endpoint, collectData, frequency]);\n\n  return { data, lastChecked, loading };\n}\n"
  },
  {
    "path": "frontend/utils.ts",
    "content": "import { twMerge } from \"tailwind-merge\";\nimport { type ClassValue, clsx } from \"clsx\";\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\n/**\n * Truncates address to format 0xAAAA...AAAA\n * @param {string} address to truncate\n * @param {number} numTruncated numbers to truncate\n * @returns {string} truncated\n */\nexport function truncateAddress(address: string, numTruncated: number): string {\n  return (\n    address.slice(0, numTruncated + 2) +\n    \"...\" +\n    address.substring(address.length - numTruncated)\n  );\n}\n\n/**\n * getPrice function transcribed from solidity\n * @dev https://basescan.org/address/0xcf205808ed36593aa40a44f10c7f7c2f67d4a4d4#code\n * @param {number} supply of user token\n * @param {number} amount of user token to buy or sell\n * @returns {number} price of action (received or given)\n */\nexport function getPrice(supply: number, amount: number): number {\n  const sum1 =\n    supply === 0 ? 0 : ((supply - 1) * supply * (2 * (supply - 1) + 1)) / 6;\n  const sum2 =\n    supply === 0 && amount === 1\n      ? 0\n      : ((supply - 1 + amount) *\n          (supply + amount) *\n          (2 * (supply - 1 + amount) + 1)) /\n        6;\n  const summation = sum2 - sum1;\n  return summation / 16000;\n}\n\n/**\n * Contract address\n */\nexport const CONTRACT_ADDRESS = \"0xcf205808ed36593aa40a44f10c7f7c2f67d4a4d4\";\n\n/**\n * Contract ABI\n */\nexport const ABI = [\n  {\n    anonymous: false,\n    inputs: [\n      {\n        indexed: true,\n        internalType: \"address\",\n        name: \"previousOwner\",\n        type: \"address\",\n      },\n      {\n        indexed: true,\n        internalType: \"address\",\n        name: \"newOwner\",\n        type: \"address\",\n      },\n    ],\n    name: \"OwnershipTransferred\",\n    type: \"event\",\n  },\n  {\n    anonymous: false,\n    inputs: [\n      {\n        indexed: false,\n        internalType: \"address\",\n        name: \"trader\",\n        type: \"address\",\n      },\n      {\n        indexed: false,\n        internalType: \"address\",\n        name: \"subject\",\n        type: \"address\",\n      },\n      { indexed: false, internalType: \"bool\", name: \"isBuy\", type: \"bool\" },\n      {\n        indexed: false,\n        internalType: \"uint256\",\n        name: \"shareAmount\",\n        type: \"uint256\",\n      },\n      {\n        indexed: false,\n        internalType: \"uint256\",\n        name: \"ethAmount\",\n        type: \"uint256\",\n      },\n      {\n        indexed: false,\n        internalType: \"uint256\",\n        name: \"protocolEthAmount\",\n        type: \"uint256\",\n      },\n      {\n        indexed: false,\n        internalType: \"uint256\",\n        name: \"subjectEthAmount\",\n        type: \"uint256\",\n      },\n      {\n        indexed: false,\n        internalType: \"uint256\",\n        name: \"supply\",\n        type: \"uint256\",\n      },\n    ],\n    name: \"Trade\",\n    type: \"event\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"sharesSubject\", type: \"address\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"buyShares\",\n    outputs: [],\n    stateMutability: \"payable\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"sharesSubject\", type: \"address\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"getBuyPrice\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"sharesSubject\", type: \"address\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"getBuyPriceAfterFee\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"uint256\", name: \"supply\", type: \"uint256\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"getPrice\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"pure\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"sharesSubject\", type: \"address\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"getSellPrice\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"sharesSubject\", type: \"address\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"getSellPriceAfterFee\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [],\n    name: \"owner\",\n    outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [],\n    name: \"protocolFeeDestination\",\n    outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [],\n    name: \"protocolFeePercent\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [],\n    name: \"renounceOwnership\",\n    outputs: [],\n    stateMutability: \"nonpayable\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"sharesSubject\", type: \"address\" },\n      { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n    ],\n    name: \"sellShares\",\n    outputs: [],\n    stateMutability: \"payable\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"_feeDestination\", type: \"address\" },\n    ],\n    name: \"setFeeDestination\",\n    outputs: [],\n    stateMutability: \"nonpayable\",\n    type: \"function\",\n  },\n  {\n    inputs: [{ internalType: \"uint256\", name: \"_feePercent\", type: \"uint256\" }],\n    name: \"setProtocolFeePercent\",\n    outputs: [],\n    stateMutability: \"nonpayable\",\n    type: \"function\",\n  },\n  {\n    inputs: [{ internalType: \"uint256\", name: \"_feePercent\", type: \"uint256\" }],\n    name: \"setSubjectFeePercent\",\n    outputs: [],\n    stateMutability: \"nonpayable\",\n    type: \"function\",\n  },\n  {\n    inputs: [\n      { internalType: \"address\", name: \"\", type: \"address\" },\n      { internalType: \"address\", name: \"\", type: \"address\" },\n    ],\n    name: \"sharesBalance\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n    name: \"sharesSupply\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [],\n    name: \"subjectFeePercent\",\n    outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n    stateMutability: \"view\",\n    type: \"function\",\n  },\n  {\n    inputs: [{ internalType: \"address\", name: \"newOwner\", type: \"address\" }],\n    name: \"transferOwnership\",\n    outputs: [],\n    stateMutability: \"nonpayable\",\n    type: \"function\",\n  },\n];\n"
  },
  {
    "path": "indexer/.gitignore",
    "content": "# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore\n\n# Logs\n\n*.log\nlogs\n_.log\nnpm-debug.log_\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n.pnpm-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\n\nreport.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json\n\n# Runtime data\n\npids\n_.pid\n_.seed\n\\*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\n\nlib-cov\n\n# Coverage directory used by tools like istanbul\n\ncoverage\n\\*.lcov\n\n# nyc test coverage\n\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n\n.grunt\n\n# Bower dependency directory (https://bower.io/)\n\nbower_components\n\n# node-waf configuration\n\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\n\nbuild/Release\n\n# Dependency directories\n\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\n\nweb_modules/\n\n# TypeScript cache\n\n\\*.tsbuildinfo\n\n# Optional npm cache directory\n\n.npm\n\n# Optional eslint cache\n\n.eslintcache\n\n# Optional stylelint cache\n\n.stylelintcache\n\n# Microbundle cache\n\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n\n.node_repl_history\n\n# Output of 'npm pack'\n\n\\*.tgz\n\n# Yarn Integrity file\n\n.yarn-integrity\n\n# dotenv environment variable files\n\n.env\n.env.development.local\n.env.test.local\n.env.production.local\n.env.local\n\n# parcel-bundler cache (https://parceljs.org/)\n\n.cache\n.parcel-cache\n\n# Next.js build output\n\n.next\nout\n\n# Nuxt.js build / generate output\n\n.nuxt\ndist\n\n# Gatsby files\n\n.cache/\n\n# Comment in the public line in if your project uses Gatsby and not Next.js\n\n# https://nextjs.org/blog/next-9-1#public-directory-support\n\n# public\n\n# vuepress build output\n\n.vuepress/dist\n\n# vuepress v2.x temp and cache directory\n\n.temp\n.cache\n\n# Docusaurus cache and generated files\n\n.docusaurus\n\n# Serverless directories\n\n.serverless/\n\n# FuseBox cache\n\n.fusebox/\n\n# DynamoDB Local files\n\n.dynamodb/\n\n# TernJS port file\n\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n\n.vscode-test\n\n# yarn v2\n\n.yarn/cache\n.yarn/unplugged\n.yarn/build-state.yml\n.yarn/install-state.gz\n.pnp.\\*\n"
  },
  {
    "path": "indexer/README.md",
    "content": "# Indexer\n\nIndexes the [FriendtechSharesV1](https://basescan.org/address/0xcf205808ed36593aa40a44f10c7f7c2f67d4a4d4#code) contract on [Base](https://base.org/) for all `buyShares` or `sellShares` function calls.\n\nTracks:\n\n- All users\n- All trades\n- Statistics including:\n  - Top users by token supply\n  - Newest users by first seen date\n  - Recent trades\n  - Leaderboard by realized profit\n\n## Run locally\n\n```bash\n# Add env vars\ncp .env.sample .env && vim .env\n\n# Install dependencies\npnpm install\n\n# Run locally\npnpm run build && pnpm run start\n```\n"
  },
  {
    "path": "indexer/package.json",
    "content": "{\n  \"name\": \"indexer\",\n  \"author\": \"Anish Agnihotri\",\n  \"main\": \"dist/index.js\",\n  \"scripts\": {\n    \"build\": \"npx prisma generate && tsc\",\n    \"start\": \"node dist/index.js\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^20.4.10\",\n    \"typescript\": \"^5.1.6\"\n  },\n  \"peerDependencies\": {\n    \"typescript\": \"^5.0.0\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"5.1.1\",\n    \"axios\": \"^1.4.0\",\n    \"ethers\": \"^5.7.2\",\n    \"ioredis\": \"^5.3.2\",\n    \"prisma\": \"^5.1.1\",\n    \"winston\": \"^3.10.0\"\n  }\n}\n"
  },
  {
    "path": "indexer/prisma/schema.prisma",
    "content": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel User {\n  address         String   @id @unique\n  twitterUsername String?\n  twitterPfpUrl   String?\n  profileChecked  Boolean  @default(false)\n  supply          Int      @default(0)\n  createdAt       DateTime @default(now())\n  updatedAt       DateTime @updatedAt\n\n  createdTrades Trade[] @relation(\"fromUser\")\n  subjectTrades Trade[] @relation(\"subjectUser\")\n}\n\nmodel Trade {\n  hash           String   @id @unique\n  timestamp      Int\n  blockNumber    Int\n  fromAddress    String\n  subjectAddress String\n  isBuy          Boolean\n  amount         Int\n  cost           Decimal  @db.Decimal(65, 0)\n  createdAt      DateTime @default(now())\n  updatedAt      DateTime @updatedAt\n\n  fromUser    User @relation(name: \"fromUser\", fields: [fromAddress], references: [address])\n  subjectUser User @relation(name: \"subjectUser\", fields: [subjectAddress], references: [address])\n}\n"
  },
  {
    "path": "indexer/src/index.ts",
    "content": "import Stats from \"./stats\";\nimport Keeper from \"./keeper\";\nimport Profile from \"./profile\";\n\n/**\n * Indexer execution lifecycle\n */\nasync function execute(): Promise<void> {\n  // Collect env vars\n  const RPC_URL: string | undefined = process.env.RPC_URL;\n  const REDIS_URL: string = process.env.REDIS_URL ?? \"redis://127.0.0.1:6379\";\n\n  // Ensure env vars exist\n  if (!RPC_URL) throw new Error(\"Missing env vars\");\n\n  // Create new keeper\n  const keeper = new Keeper(RPC_URL, REDIS_URL);\n  // Create new stats agent\n  const stats = new Stats(REDIS_URL);\n  // Create new profile agent\n  const profile = new Profile();\n  await Promise.all([\n    // Run keeper sync\n    keeper.sync(),\n    // Run stats 15s collection\n    stats.sync15s(),\n    // Run stats 30m collection\n    stats.sync30m(),\n    // Run profile sync\n    profile.sync(),\n  ]);\n}\n\n(async () => {\n  try {\n    // Run execution lifecycle\n    await execute();\n  } catch (err: unknown) {\n    console.error(err);\n    process.exit(1);\n  }\n})();\n"
  },
  {
    "path": "indexer/src/keeper.ts",
    "content": "import Redis from \"ioredis\";\nimport { ethers } from \"ethers\";\nimport logger from \"./utils/logger\";\nimport { getPrice } from \"./utils/math\";\nimport { chunks } from \"./utils/helpers\";\nimport constants from \"./utils/constants\";\nimport { PrismaClient } from \"@prisma/client\";\nimport type { Result } from \"ethers/lib/utils\";\nimport axios, { type AxiosInstance } from \"axios\";\nimport type { RPCMethod, Transaction } from \"./utils/types\";\n\nexport default class Keeper {\n  // Database\n  private db: PrismaClient;\n  // Redis cache\n  private redis: Redis;\n  // RPC client\n  private rpc: AxiosInstance;\n  // All tracked user address\n  private users: Set<string> = new Set();\n  // User to token supply (address => token supply)\n  private supply: Record<string, number> = {};\n  // Locally consistent latest synced block\n  private latestSyncedBlock: number | undefined;\n\n  /**\n   * Create new Keeper\n   * @param {string} rpc_url Base RPC\n   * @param {string} redis_url Cache URL\n   */\n  constructor(rpc_url: string, redis_url: string) {\n    this.db = new PrismaClient();\n    this.redis = new Redis(redis_url);\n    this.rpc = axios.create({\n      baseURL: rpc_url,\n    });\n  }\n\n  /**\n   * Get chain head number\n   * @returns {Promise<number>} block number\n   */\n  async getChainBlock(): Promise<number> {\n    try {\n      // Send request\n      const { data } = await this.rpc.post(\"/\", {\n        id: 0,\n        jsonrpc: \"2.0\",\n        method: \"eth_blockNumber\",\n        params: [],\n      });\n\n      // Parse hex to number\n      return Number(data.result);\n    } catch {\n      logger.error(\"Failed to collect chain head number\");\n      throw new Error(\"Could not collect chain head number\");\n    }\n  }\n\n  /**\n   * Get latest synced block from cache\n   * @returns {Promise<number>} block number\n   */\n  async getSyncedBlock(): Promise<number> {\n    // If latest synced block exists locally, return\n    if (this.latestSyncedBlock) return this.latestSyncedBlock;\n    // Else, get value from cache\n    const value: string | null = await this.redis.get(\"synced_block\");\n\n    // If value exists\n    return value\n      ? // Return numeric\n        Number(value)\n      : // Else return 1 block before contract deploy\n        constants.CONTRACT_DEPLOY_BLOCK - 1;\n  }\n\n  /**\n   * Loads user addresses and token supplies from backend\n   */\n  async loadUsersAndSupplies(): Promise<void> {\n    // Collect all users from database\n    const users: { address: string; supply: number }[] =\n      await this.db.user.findMany({\n        select: {\n          address: true,\n          supply: true,\n        },\n      });\n\n    for (const user of users) {\n      // Assign to list of users\n      this.users.add(user.address);\n      // Assign to local supply cache\n      this.supply[user.address] = user.supply;\n    }\n\n    logger.info(`Loaded ${users.length} users locally`);\n  }\n\n  /**\n   * Calculates trade cost based on bonding curve\n   * @param {string} subject address\n   * @param {number} amount to buy or sell\n   * @param {boolean} buy is a buy tx or a sell tx\n   * @returns {number} cost\n   */\n  getTradeCost(subject: string, amount: number, buy: boolean): number {\n    // If subject supply is not tracked locally\n    if (!this.supply.hasOwnProperty(subject)) {\n      // Update to 0\n      this.supply[subject] = 0;\n    }\n\n    if (buy) {\n      // Return price to buy tokens\n      const cost = getPrice(this.supply[subject], amount);\n      const fees = cost * constants.FEE * 2;\n      return cost + fees;\n    } else {\n      // Return price to sell tokens\n      const cost = getPrice(this.supply[subject] - amount, amount);\n      const fees = cost * constants.FEE * 2;\n      return cost - fees;\n    }\n  }\n\n  /**\n   * Chunks batch data request processing to avoid 1K request limit\n   * @param {RPCMethod[]} batch to execute\n   */\n  async chunkTxCall(batch: RPCMethod[]) {\n    let txData: {\n      result: {\n        transactionHash: string;\n        status: \"0x0\" | \"0x1\";\n      };\n    }[] = [];\n\n    // Execute batch data request in chunks of 950\n    for (const chunk of [...chunks(batch, 950)]) {\n      // Execute request for batch tx data\n      const {\n        data,\n      }: {\n        data: {\n          result: {\n            transactionHash: string;\n            status: \"0x0\" | \"0x1\";\n          };\n        }[];\n      } = await this.rpc.post(\"/\", chunk);\n\n      // Concat results\n      txData.push(...data);\n    }\n\n    // Return tx data\n    return txData;\n  }\n\n  /**\n   * Syncs trades between a certain range of blocks\n   * @param {number} startBlock beginning index\n   * @param {number} endBlock ending index\n   */\n  async syncTradeRange(startBlock: number, endBlock: number): Promise<void> {\n    // Create block + transaction collection requests\n    const numBlocks: number = endBlock - startBlock;\n    logger.info(`Collecting ${numBlocks} blocks: ${startBlock} -> ${endBlock}`);\n\n    // Create batch requests array\n    const batchBlockRequests: RPCMethod[] = new Array(numBlocks)\n      .fill(0)\n      .map((_, i: number) => ({\n        method: \"eth_getBlockByNumber\",\n        // Hex block number, true => return all transactions\n        params: [`0x${(startBlock + i).toString(16)}`, true],\n        id: i,\n        jsonrpc: \"2.0\",\n      }));\n\n    // Execute request for batch blocks + transactions\n    const {\n      data: blockData,\n    }: {\n      data: {\n        result: {\n          number: string;\n          timestamp: string;\n          transactions: {\n            from: string;\n            hash: string;\n            to: string;\n            input: string;\n          }[];\n        };\n      }[];\n    } = await this.rpc.post(\"/\", batchBlockRequests);\n\n    // Setup contract\n    const contractAddress: string = constants.CONTRACT_ADDRESS.toLowerCase();\n    const contractSignatures: string[] = [\n      constants.SIGNATURES.BUY,\n      constants.SIGNATURES.SELL,\n    ];\n\n    // Filter for transaction hashes that are either BUY or SELL to friend.tech contract\n    let txHashes: string[] = [];\n    for (const block of blockData) {\n      for (const tx of block.result.transactions) {\n        if (\n          // If transaction is to contract\n          tx.to === contractAddress &&\n          // And, transaction is of format buyShares or sellShares\n          contractSignatures.includes(tx.input.slice(0, 10))\n        ) {\n          // Track tx hash\n          txHashes.push(tx.hash);\n        }\n      }\n    }\n\n    // If no relevant tx hashes\n    if (txHashes.length === 0) {\n      // Update latest synced block\n      const ok = await this.redis.set(\"synced_block\", endBlock);\n      if (!ok) {\n        logger.error(\"Error storing synced_block in cache\");\n        throw new Error(\"Could not synced_block store in Redis\");\n      }\n      logger.info(\"Skipping because 0 relevant txs found\");\n\n      return;\n    }\n\n    // Check all relevant transaction hashes for success status\n    const txBatchRequests: RPCMethod[] = new Array(txHashes.length)\n      .fill(0)\n      .map((_, i: number) => ({\n        method: \"eth_getTransactionReceipt\",\n        // Hex block number, true => return all transactions\n        params: [txHashes[i]],\n        id: i,\n        jsonrpc: \"2.0\",\n      }));\n\n    // Execute request for batch tx data\n    const txData = await this.chunkTxCall(txBatchRequests);\n\n    // Create set of successful transactions\n    const successTxHash: Set<string> = new Set();\n    for (const tx of txData) {\n      // Filter for success\n      if (tx.result.status === \"0x1\") {\n        successTxHash.add(tx.result.transactionHash.toLowerCase());\n      }\n    }\n\n    // Transform only successful transactions\n    let txs: Transaction[] = [];\n\n    // List of users with modified supply balances\n    let userDiff: Set<string> = new Set();\n    // List of new, untracked users\n    let newUsers: Set<string> = new Set();\n\n    // We iterate over blockData to preserve ordering\n    // This is necessary to appropriately calculate cost locally\n    for (const block of blockData) {\n      // For each transaction in block\n      for (const tx of block.result.transactions) {\n        // Filter for only successful transactions\n        if (successTxHash.has(tx.hash.toLowerCase())) {\n          // Decode tx input\n          const result: Result = ethers.utils.defaultAbiCoder.decode(\n            [\"address\", \"uint256\"],\n            ethers.utils.hexDataSlice(tx.input, 4)\n          );\n\n          // Collect params and create tx\n          const subject = result[0].toLowerCase();\n          const amount = result[1].toNumber();\n          const isBuy: boolean =\n            tx.input.slice(0, 10) === constants.SIGNATURES.BUY;\n\n          // Calculate cost of transaction\n          const cost: number = this.getTradeCost(subject, amount, isBuy);\n\n          // Push newly tracked transaction\n          const transaction = {\n            hash: tx.hash,\n            timestamp: Number(block.result.timestamp),\n            blockNumber: Number(block.result.number),\n            from: tx.from.toLowerCase(),\n            subject,\n            isBuy,\n            amount,\n            cost: Math.trunc(cost * 1e18),\n          };\n          txs.push(transaction);\n\n          // Apply user token supply update\n          if (isBuy) {\n            this.supply[subject] += amount;\n          } else {\n            this.supply[subject] -= amount;\n          }\n          // Track user with supply diff\n          userDiff.add(subject);\n\n          // Track new users\n          if (!this.users.has(transaction.from)) {\n            this.users.add(transaction.from);\n            newUsers.add(transaction.from);\n          }\n          if (!this.users.has(transaction.subject)) {\n            this.users.add(transaction.subject);\n            newUsers.add(transaction.subject);\n          }\n        }\n      }\n    }\n\n    logger.info(`Collected ${txs.length} transactions`);\n\n    // Setup subject updates\n    let subjectUpserts = [];\n    for (const subject of new Set([...userDiff, ...newUsers])) {\n      subjectUpserts.push(\n        this.db.user.upsert({\n          where: {\n            address: subject,\n          },\n          create: {\n            address: subject,\n            supply: this.supply[subject] ?? 0,\n          },\n          update: {\n            supply: this.supply[subject] ?? 0,\n          },\n        })\n      );\n    }\n\n    // Setup trade updates\n    let tradeInsert = this.db.trade.createMany({\n      data: txs.map((tx) => ({\n        hash: tx.hash,\n        timestamp: tx.timestamp,\n        blockNumber: tx.blockNumber,\n        fromAddress: tx.from,\n        subjectAddress: tx.subject,\n        isBuy: tx.isBuy,\n        amount: tx.amount,\n        cost: tx.cost,\n      })),\n    });\n\n    // Insert subjects and trades as atomic transaction\n    await this.db.$transaction([...subjectUpserts, tradeInsert]);\n    logger.info(\n      `Added ${subjectUpserts.length} subject updates, ${txs.length} trades`\n    );\n\n    // Update latest synced block\n    const ok = await this.redis.set(\"synced_block\", endBlock);\n    if (!ok) {\n      logger.error(\"Error storing synced_block in cache\");\n      throw new Error(\"Could not synced_block store in Redis\");\n    }\n    logger.info(`Set last synced block to ${endBlock}`);\n  }\n\n  async syncTrades() {\n    // Latest blocks\n    const latestChainBlock: number = await this.getChainBlock();\n    const latestSyncedBlock: number = await this.getSyncedBlock();\n\n    // Calculate remaining blocks to sync\n    const diffSync: number = latestChainBlock - latestSyncedBlock;\n    logger.info(`Remaining blocks to sync: ${diffSync}`);\n\n    // If diff > 0, poll by 100 blocks at a time\n    if (diffSync > 0) {\n      // Max 100 blocks to collect\n      const numToSync: number = Math.min(diffSync, 100);\n\n      // (Start, End) sync blocks\n      let startBlock: number = latestSyncedBlock;\n      let endBlock: number = latestSyncedBlock + numToSync;\n\n      // Sync between block ranges\n      try {\n        // Sync start -> end blocks\n        await this.syncTradeRange(startBlock, endBlock);\n        // Update last synced block\n        this.latestSyncedBlock = endBlock;\n        // Recursively resync if diffSync > 0\n        await this.syncTrades();\n      } catch (e) {\n        logger.error(\"Error when syncing between range\", e);\n      }\n    }\n  }\n\n  async sync() {\n    // Sync users and token supplies if first startup\n    if (Object.keys(this.supply).length === 0) {\n      await this.loadUsersAndSupplies();\n    }\n\n    // Sync trades\n    await this.syncTrades();\n\n    // Recollect in 5s\n    logger.info(\"Sleeping for 5s\");\n    setTimeout(() => this.sync(), 1000 * 5);\n  }\n}\n"
  },
  {
    "path": "indexer/src/profile.ts",
    "content": "import logger from \"./utils/logger\";\nimport constants from \"./utils/constants\";\nimport { PrismaClient } from \"@prisma/client\";\nimport axios, { type AxiosInstance } from \"axios\";\n\n/**\n * Sleep for period of time\n * @param {number} ms milliseconds to sleep\n * @returns {Promise} resolves when sleep period finished\n */\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport default class Profile {\n  // Database\n  db: PrismaClient;\n  // Kosetto API client\n  client: AxiosInstance;\n  // Timeout duration\n  timeout: number = 500;\n\n  /**\n   * Create profile manager\n   */\n  constructor() {\n    // Setup db\n    this.db = new PrismaClient();\n    // Setup api client\n    this.client = axios.create({\n      baseURL: constants.API,\n    });\n  }\n\n  /**\n   * Syncs users metadata\n   * @param address\n   */\n  async syncUser(address: string) {\n    try {\n      // Collect user details\n      const {\n        data,\n      }: {\n        data:\n          | { message: string }\n          | { twitterUsername: string; twitterPfpUrl: string };\n      } = await this.client.get(`/users/${address}`);\n\n      // Check for no message\n      if (\"message\" in data) {\n        // Update user to profile checked\n        await this.db.user.update({\n          where: {\n            address,\n          },\n          data: {\n            profileChecked: true,\n          },\n        });\n        return;\n      } else {\n        // Update data\n        await this.db.user.update({\n          where: {\n            address,\n          },\n          data: {\n            twitterUsername: data.twitterUsername,\n            twitterPfpUrl: data.twitterPfpUrl,\n            profileChecked: true,\n          },\n        });\n      }\n\n      // If successful, reduce timeout back to 1/2s\n      this.timeout = 500;\n\n      // Log user\n      logger.info(`Profile: collected @${data.twitterUsername}: ${address}`);\n    } catch {\n      // Timeout for a few seconds, exponential backoff\n      this.timeout *= 2;\n      await sleep(this.timeout);\n      logger.error(\n        `Error on profile collection, sleeping for ${this.timeout / 1000}s`\n      );\n    }\n  }\n\n  /**\n   * Syncs profile metadata to database\n   */\n  async syncProfiles() {\n    // Collect all users that have not been checked (250 at a time)\n    const users: { address: string }[] = await this.db.user.findMany({\n      orderBy: {\n        // Get highest supply users first\n        supply: \"desc\",\n      },\n      select: {\n        address: true,\n      },\n      where: {\n        profileChecked: false,\n      },\n      take: 250,\n    });\n\n    logger.info(`Collected ${users.length} to collect profile info`);\n\n    // For each user\n    for (const user of users) {\n      // Sync metadata\n      await this.syncUser(user.address);\n    }\n  }\n\n  async sync() {\n    await this.syncProfiles();\n\n    logger.info(\"Sleeping metadata sync for 1m\");\n    setTimeout(() => this.syncProfiles, 1000 * 60 * 60);\n  }\n}\n"
  },
  {
    "path": "indexer/src/stats.ts",
    "content": "import Redis from \"ioredis\";\nimport logger from \"./utils/logger\";\nimport { getPrice } from \"./utils/math\";\nimport constants from \"./utils/constants\";\nimport { PrismaClient, type User } from \"@prisma/client\";\n\nexport default class Stats {\n  // Database\n  private db: PrismaClient;\n  // Redis cache\n  private redis: Redis;\n\n  /**\n   * Create new Stats\n   * @param {string} redis_url Cache URL\n   */\n  constructor(redis_url: string) {\n    // Setup db\n    this.db = new PrismaClient();\n    // Setup redis\n    this.redis = new Redis(redis_url);\n  }\n\n  /**\n   * Tracks newest 50 users\n   */\n  async updateNewestUsers(): Promise<void> {\n    const users: User[] = await this.db.user.findMany({\n      orderBy: {\n        createdAt: \"desc\",\n      },\n      take: 50,\n    });\n\n    // Augment data with cost\n    const augmented = users.map((user) => ({\n      ...user,\n      cost: getPrice(user.supply, 1),\n    }));\n\n    await this.redis.set(\"latest_users\", JSON.stringify(augmented));\n  }\n\n  /**\n   * Tracks latest 100 trades\n   */\n  async udpateRecentTrades(): Promise<void> {\n    const txs = await this.db.trade.findMany({\n      orderBy: {\n        timestamp: \"desc\",\n      },\n      include: {\n        fromUser: {\n          select: {\n            twitterUsername: true,\n            twitterPfpUrl: true,\n          },\n        },\n        subjectUser: {\n          select: {\n            twitterUsername: true,\n            twitterPfpUrl: true,\n          },\n        },\n      },\n      take: 100,\n    });\n\n    await this.redis.set(\"latest_trades\", JSON.stringify(txs));\n  }\n\n  async tokenLeaderboard(): Promise<void> {\n    const users: User[] = await this.db.user.findMany({\n      orderBy: {\n        supply: \"desc\",\n      },\n      take: 50,\n    });\n\n    let extended: (User & { cost: number })[] = [];\n    // Calculate cost per user\n    for (const user of users) {\n      // Calculate price to buy tokens\n      const cost = getPrice(user.supply, 1);\n      const fees = cost * constants.FEE * 2;\n\n      extended.push({\n        ...user,\n        cost: cost + fees,\n      });\n\n      await this.redis.set(\"leaderboard\", JSON.stringify(extended));\n    }\n  }\n\n  async mostProfitableUsers() {\n    const users = await this.db.user.findMany({\n      select: {\n        address: true,\n        twitterPfpUrl: true,\n        twitterUsername: true,\n        createdTrades: true,\n      },\n    });\n\n    let userToProfit: Record<string, number> = {};\n    for (const user of users) {\n      userToProfit[user.address] = 0;\n\n      for (const trade of user.createdTrades) {\n        if (trade.isBuy) {\n          userToProfit[user.address] -= trade.cost.toNumber();\n        } else {\n          userToProfit[user.address] += trade.cost.toNumber();\n        }\n      }\n    }\n\n    // Generate subset users\n    let subsetUsers: {\n      address: string;\n      twitterPfpUrl?: string | null;\n      twitterUsername?: string | null;\n      profit: number;\n    }[] = [];\n    for (const user of users) {\n      subsetUsers.push({\n        address: user.address,\n        twitterPfpUrl: user.twitterPfpUrl,\n        twitterUsername: user.twitterUsername,\n        profit: userToProfit[user.address],\n      });\n    }\n\n    // Sort users by profit\n    subsetUsers.sort((a, b) => b.profit - a.profit);\n    subsetUsers = subsetUsers.slice(0, 100); // Take top 100\n    subsetUsers = subsetUsers.map((u) => ({ ...u, profit: u.profit / 1e18 })); // Parse profit to ETH\n\n    await this.redis.set(\"realized_profit\", JSON.stringify(subsetUsers));\n  }\n\n  /**\n   * Stats synced at a 15s frequency\n   */\n  async sync15s(): Promise<void> {\n    await Promise.all([\n      this.updateNewestUsers(),\n      this.udpateRecentTrades(),\n      this.tokenLeaderboard(),\n    ]);\n\n    // Recollect in 15s\n    logger.info(\"Stats: Collected quarter-minute stats\");\n    setTimeout(() => this.sync15s(), 1000 * 15);\n  }\n\n  async sync30m(): Promise<void> {\n    // await this.mostProfitableUsers();\n\n    // Recollect in 1h\n    logger.info(\"Stats: Collected half-hourly stats\");\n    setTimeout(() => this.sync30m, 1000 * 60 * 60);\n  }\n}\n"
  },
  {
    "path": "indexer/src/utils/constants.ts",
    "content": "export default {\n  // Friendshares contract deploy block\n  CONTRACT_DEPLOY_BLOCK: 2430440,\n  // Contract address\n  CONTRACT_ADDRESS: \"0xCF205808Ed36593aa40a44F10c7f7C2F67d4A4d4\",\n  // Function signatures\n  SIGNATURES: {\n    BUY: \"0x6945b123\",\n    SELL: \"0xb51d0534\",\n  },\n  // Creator || Protoocl fee\n  FEE: 0.05,\n  // Backend API endpoint\n  API: \"https://prod-api.kosetto.com\",\n};\n"
  },
  {
    "path": "indexer/src/utils/helpers.ts",
    "content": "/**\n * Generic generator to chunk array\n * @param {T[]} arr to chunk\n * @param {number} n max size per chunk\n */\nexport function* chunks<T>(arr: T[], n: number): Generator<T[], void> {\n  for (let i = 0; i < arr.length; i += n) {\n    yield arr.slice(i, i + n);\n  }\n}\n"
  },
  {
    "path": "indexer/src/utils/logger.ts",
    "content": "import * as winston from \"winston\"; // Logging\n\n// Setup winston logger\nconst logger = winston.createLogger({\n  level: \"info\",\n  // Simple line-by-line output\n  format: winston.format.combine(\n    winston.format.colorize(),\n    winston.format.timestamp(),\n    winston.format.printf(\n      (info) => `[${info.timestamp} (${info.level})] ${info.message}`\n    )\n  ),\n  transports: [\n    // Output to console\n    new winston.transports.Console(),\n    // Output to logfile\n    new winston.transports.File({ filename: \"indexer.log\", level: \"debug\" }),\n  ],\n});\n\n// Export as default\nexport default logger;\n"
  },
  {
    "path": "indexer/src/utils/math.ts",
    "content": "/**\n * getPrice function transcribed from solidity\n * @dev https://basescan.org/address/0xcf205808ed36593aa40a44f10c7f7c2f67d4a4d4#code\n * @param {number} supply of user token\n * @param {number} amount of user token to buy or sell\n * @returns {number} price of action (received or given)\n */\nexport function getPrice(supply: number, amount: number): number {\n  const sum1 =\n    supply === 0 ? 0 : ((supply - 1) * supply * (2 * (supply - 1) + 1)) / 6;\n  const sum2 =\n    supply === 0 && amount === 1\n      ? 0\n      : ((supply - 1 + amount) *\n          (supply + amount) *\n          (2 * (supply - 1 + amount) + 1)) /\n        6;\n  const summation = sum2 - sum1;\n  return summation / 16000;\n}\n"
  },
  {
    "path": "indexer/src/utils/types.ts",
    "content": "/**\n * JSONRPC method\n */\nexport type RPCMethod = {\n  id: number;\n  jsonrpc: string;\n  params: any[];\n  method: string;\n};\n\n/**\n * Transformed transaction\n */\nexport type Transaction = {\n  hash: string;\n  timestamp: number;\n  blockNumber: number;\n  from: string;\n  subject: string;\n  isBuy: boolean;\n  amount: number;\n  cost: number;\n};\n"
  },
  {
    "path": "indexer/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"lib\": [\"ES6\"],\n    \"target\": \"ES6\",\n    \"module\": \"CommonJS\",\n    \"moduleResolution\": \"node\",\n    \"outDir\": \"./dist\",\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"sourceMap\": true,\n    \"esModuleInterop\": true,\n    \"strict\": true,\n    \"resolveJsonModule\": true\n  }\n}\n"
  }
]