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