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. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/>.
================================================
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 (
<Button
onClick={() => setUser({ address, username, image })}
className="h-8 pl-1 pr-2 py-0 bg-white border text-black rounded-md shadow-none text-sm font-normal hover:bg-white hover:opacity-70 transition-opacity"
>
<div className="flex items-center">
<img
src={image ? image : "/rasters/default.png"}
width={22}
height={22}
alt={`${user} Twitter pfp`}
className="rounded-md"
/>
<span className="pl-2">{user}</span>
{favorites[address.toLowerCase()] && (
// Is favorited
<span className="ml-2">
<StarFilledIcon className="stroke-amber-400 text-amber-400" />
</span>
)}
</div>
</Button>
);
}
================================================
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
<div className="flex flex-col bg-white border-[1px] border-bitmex-strong-border h-full">
{/* Card header */}
<div className="flex items-center justify-between bg-bitmex-strong py-0.5">
{/* Card header: left */}
<div className="flex items-center">
{/* Resizer */}
<div className="drag-handle">
<DragHandleDots2Icon className="text-zinc-500" />
</div>
{/* Component title */}
<span className="pl-1 text-sm font-bold">{title}</span>
</div>
{/* Card header: right */}
{updated && (
<span className="text-zinc-500 text-xs font-light pr-2">
{updated}
</span>
)}
</div>
{/* Card content */}
<div className="bg-bitmex-widget overflow-auto flex-1">{children}</div>
</div>
);
}
================================================
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 (
<div className="sticky top-0 z-50">
{/* Sub header */}
<div className="bg-black border-b border-zinc-800 flex items-center justify-center py-0.5">
<span className="text-xs text-zinc-400">
An{" "}
<a
href="https://github.com/anish-agnihotri/friendmex"
target="_blank"
rel="noopen noreferrer"
className="hover:opacity-70 transition-opacity underline"
>
open-source
</a>{" "}
project by{" "}
<a
href="https://anishagnihotri.com"
target="_blank"
rel="noopen noreferrer"
className="hover:opacity-70 transition-opacity underline"
>
Anish Agnihotri
</a>
.
</span>
</div>
{/* Main header */}
<div className="flex justify-between h-14 px-4 items-center bg-black">
<div>
<Link href="/" className="hover:opacity-70 transition-opacity">
<Image
src="/vectors/logo.svg"
height={30}
width={165}
alt="FriendMEX logo"
priority
/>
</Link>
</div>
<div className="flex items-center gap-4">
<div className="flex border border-zinc-600 text-zinc-300">
<button
onClick={() => setCurrency(Currency.USD)}
className={`px-1 hover:opacity-70 ${
currency === Currency.USD ? "bg-zinc-500" : ""
}`}
>
USD
</button>
<button
onClick={() => setCurrency(Currency.ETH)}
className={`px-1 hover:opacity-70 ${
currency === Currency.ETH ? "bg-zinc-500" : ""
}`}
>
ETH
</button>
</div>
<div className="md:flex hidden">
<ConnectButton />
</div>
</div>
</div>
</div>
);
}
================================================
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)
<Global.Provider initialState={user}>
<div>
{/* Meta tags */}
<Meta />
{/* Header */}
<Header />
<div>{children}</div>
</div>
</Global.Provider>
);
}
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 (
<Head>
{/* Primary Meta Tags */}
<title>{meta.title}</title>
<meta name="title" content={meta.title} />
<meta name="description" content={meta.description} />
{/* Favicon */}
<link rel="icon" href="https://friendmex.com/favicon.ico" sizes="any" />
{/* OG + Facebook */}
<meta property="og:type" content="website" />
<meta property="og:url" content={meta.url} />
<meta property="og:title" content={meta.title} />
<meta property="og:description" content={meta.description} />
<meta property="og:image" content={meta.image} />
{/* Twitter */}
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:url" content={meta.url} />
<meta property="twitter:title" content={meta.title} />
<meta property="twitter:description" content={meta.description} />
<meta property="twitter:image" content={meta.image} />
</Head>
);
}
================================================
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 ? (
<TableRow className="bg-buy-30">{children}</TableRow>
) : (
<TableRow className="bg-sell-30">{children}</TableRow>
);
}
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 (
<Table className="min-w-[950px] [&_td]:py-1">
<TableHeader className="sticky top-0">
<TableRow>
<TableHead>Hash</TableHead>
<TableHead>Time Since</TableHead>
<TableHead>Block #</TableHead>
<TableHead>From</TableHead>
<TableHead>Token</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Net</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{trades.map((trade, i) => {
const tradeCost: string = calculateTradeCost(trade.cost);
return (
<ColoredRow isBuy={trade.isBuy} key={i}>
<TableCell>
<a
href={`https://basescan.org/tx/${trade.hash}`}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{truncateAddress(trade.hash, 6)}
</a>
</TableCell>
<TableCell suppressHydrationWarning={true}>
{formatDistance(new Date(trade.timestamp * 1000), new Date(), {
addSuffix: true,
})}
</TableCell>
<TableCell>
<a
href={`https://basescan.org/block/${trade.blockNumber}`}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{trade.blockNumber}
</a>
</TableCell>
<TableCell>
<Address
address={trade.fromAddress}
username={trade.fromUser.twitterUsername}
image={trade.fromUser.twitterPfpUrl}
/>
</TableCell>
<TableCell>
<Address
address={trade.subjectAddress}
username={trade.subjectUser.twitterUsername}
image={trade.subjectUser.twitterPfpUrl}
/>
</TableCell>
<TableCell>
{trade.isBuy ? "+" : "-"}
{trade.amount}
</TableCell>
<TableCell>
{trade.isBuy ? (
<span className="text-buy">{tradeCost}</span>
) : (
<span className="text-sell">{tradeCost}</span>
)}
</TableCell>
</ColoredRow>
);
})}
</TableBody>
</Table>
);
}
================================================
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 (
<div className="flex flex-col border rounded-lg bg-white">
{/* Top section */}
<div className="p-2 flex flex-row items-center justify-between w-full">
{/* Top left (image, handle, address) */}
<div className="flex items-center">
<img
src={image}
alt={alt}
width={30}
height={30}
className="rounded-md"
/>
<div className="flex text-xs flex-col pl-2 [&>a:hover]:opacity-70">
{/* Username */}
<a href={usernameLink} target="_blank" rel="noopener noreferrer">
{username}
</a>
{/* Address */}
<a
href={addressLink}
className="text-zinc-400"
target="_blank"
rel="noopener noreferrer"
>
{address}
</a>
</div>
</div>
{/* Top right */}
<div className="flex items-center">
{/* Favorite button */}
<button
className="mr-2"
onClick={() =>
toggleFavorite({
address: data.address.toLowerCase(),
image,
username,
})
}
>
{favorites[data.address.toLowerCase()] ? (
<StarFilledIcon className="stroke-amber-400 text-amber-400" />
) : (
<StarIcon className="stroke-zinc-200" />
)}
</button>
{/* Trade button */}
<Button
onClick={() =>
setUser({
address: data.address,
username: data.twitterUsername,
image: data.twitterPfpUrl,
})
}
disabled={user.address === data.address}
className="text-xs h-7 px-2 py-0 bg-buy hover:bg-buy hover:opacity-70 transition-opacity"
>
{isMinimal ? (
<span>Buy</span>
) : currency === Currency.USD ? (
<span>${parseUSD(data.cost * eth)}</span>
) : (
<span>{data.cost.toFixed(4)} Ξ</span>
)}
</Button>
</div>
</div>
{/* Bottom section */}
{!isMinimal && (
<div className="flex border-t items-center justify-between px-2 py-1 text-xs text-zinc-500">
<span>
{data.supply} key{data.supply == 1 ? "" : "s"}
</span>
<span>
MC:{" "}
{currency === Currency.USD ? (
<span>${parseUSD(marketCap * eth)}</span>
) : (
<span>{marketCap.toFixed(2)} Ξ</span>
)}
</span>
</div>
)}
</div>
);
}
================================================
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<number>(0);
const [sell, setSell] = useState<number>(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 (
<Card title="Buy/Sell">
<div className="h-full p-4">
{!isConnected ? (
// Not connected state
<div className="flex flex-col items-center justify-center h-full border border-dashed rounded-md">
<ButtonIcon className="w-12 h-12 text-zinc-500" />
<span className="text-zinc-500">Connect wallet to trade</span>
<div className="mt-4">
<ConnectButton />
</div>
</div>
) : (
<div className="flex flex-col h-full gap-3">
<div>
<span className="flex break-word text-sm items-center">
You own {Number(ownedAmount ?? 0)} key(s) of{" "}
<span className="pl-2">
<Address
address={user.address}
username={user.username}
image={user.image}
/>
</span>
.
</span>
</div>
{/* Buy keys */}
<Card title="Buy keys">
<div className="p-2">
<Input value={buy} disabled />
<div className="flex [&>button]:flex-1 gap-3 mt-3">
<Button
variant="outline"
onClick={() => {
if (buy > 0) setBuy((previous) => previous - 1);
}}
disabled={buy === 0}
>
-
</Button>
<Button
variant="outline"
onClick={() => setBuy((previous) => previous + 1)}
>
+
</Button>
</div>
<Button
className="mt-2 w-full bg-buy hover:bg-buy hover:opacity-70"
onClick={() => executeBuy()}
disabled={buy === 0 || buyLoading}
>
{buyLoading ? (
<div className="flex items-center">
<SymbolIcon className="h-4 w-4 animate-spin" />
<span className="pr-2">Executing buy...</span>
</div>
) : (
<span>
Buy {buy} key(s){" "}
{buyPrice
? `for ${
currency === Currency.ETH
? `${(Number(buyPrice) / 1e18).toFixed(6)} Ξ`
: `$${parseUSD((Number(buyPrice) / 1e18) * eth)}`
}`
: ""}
</span>
)}
</Button>
</div>
</Card>
{/* Sell keys */}
<Card title="Sell keys">
<div className="p-2">
<Input value={sell} disabled />
<div className="flex [&>button]:flex-1 gap-3 mt-3">
<Button
variant="outline"
onClick={() => {
if (sell > 0) setSell((previous) => previous - 1);
}}
disabled={sell === 0}
>
-
</Button>
<Button
variant="outline"
onClick={() => {
if (sell < Number(ownedAmount ?? 0)) {
setSell((previous) => previous + 1);
}
}}
disabled={sell >= Number(ownedAmount ?? 0)}
>
+
</Button>
</div>
<Button
className="mt-2 w-full bg-sell hover:bg-sell hover:opacity-70"
onClick={() => executeSell()}
disabled={sell === 0 || sellLoading}
>
{sellLoading ? (
<div className="flex items-center">
<SymbolIcon className="h-4 w-4 animate-spin" />
<span className="pr-2">Executing sell...</span>
</div>
) : (
<span>
Sell {sell} key(s){" "}
{sellPrice
? `for ${
currency === Currency.ETH
? `${(Number(sellPrice) / 1e18).toFixed(6)} Ξ`
: `$${parseUSD((Number(sellPrice) / 1e18) * eth)}`
}`
: ""}
</span>
)}
</Button>
</div>
</Card>
</div>
)}
</div>
</Card>
);
}
================================================
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 (
<Card
title="Token Chart"
updated={`${
user.username ? `@${user.username}` : truncateAddress(user.address, 6)
}, ${renderTimeSince(lastChecked)} ago`}
>
<div className="w-full h-full p-4">
<LineChart
className="h-full"
data={data}
index="timestamp"
categories={["Price (ETH)"]}
/>
</div>
</Card>
);
}
================================================
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<boolean>(false);
// Results
const [results, setResults] = useState<UserInfo[]>([]);
/**
* 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<string>("");
// 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 (
<Card title="Discover" updated={`${renderTimeSince(lastChecked)} ago`}>
<div className="h-full relative">
{/* Search users */}
<Input
value={search}
onChange={(e) => 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"
/>
<div className="pt-11 pb-3 px-3 flex">
{debouncedSearch !== "" ? (
// Search exists
<div className="h-full flex flex-1">
{searchLoading ? (
<div className="pt-4 flex flex-col w-full items-center text-zinc-500">
<SymbolIcon className="h-8 w-8 animate-spin" />
<span className="pt-2 text-sm pr-2">Loading friends...</span>
</div>
) : searchResults.length > 0 ? (
<div className="flex w-full flex-col gap-y-3">
{searchResults.map((user: UserInfo, i: number) => (
<User key={i} data={user} />
))}
</div>
) : (
<div className="pt-4 flex flex-col w-full items-center text-zinc-500">
<CrossCircledIcon className="h-8 w-8" />
<span className="pt-2 text-sm pr-2">No results found</span>
</div>
)}
</div>
) : (
// No search, return leaderboard
<div className="flex w-full flex-col gap-y-3">
{leaderboard.map((user: UserInfo, i: number) => (
<User key={i} data={user} />
))}
</div>
)}
</div>
</div>
</Card>
);
}
================================================
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<StateUser[]>(
`/api/user?address=${Object.keys(favorites).join("&address=")}`,
[],
15 * 1000
);
return (
<Card title="Favorites" updated={`${renderTimeSince(lastChecked)} ago`}>
<div className="h-full">
<div className="p-3 h-full">
{Object.keys(favorites).length === 0 ? (
// No favorites saved
<div className="flex h-full flex-col items-center justify-center border border-dashed rounded-md text-zinc-500">
<CrossCircledIcon className="w-12 h-12" />
<span className="pt-2">No favorites saved</span>
</div>
) : loading && data.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center border border-dashed rounded-md text-zinc-500">
<SymbolIcon className="h-12 w-12 animate-spin" />
<span className="pt-2">Loading favorites...</span>
</div>
) : data.length === 0 ? (
// No favorites found
<div className="flex h-full flex-col items-center justify-center border border-dashed rounded-md text-zinc-500">
<CrossCircledIcon className="h-12 w-12" />
<span className="pt-2">No favorites found</span>
</div>
) : (
// Favorites data
<div className="flex w-full flex-col gap-y-3 pb-3">
{data.map((user: StateUser, i: number) => (
<User
key={i}
data={{
address: user.address,
twitterPfpUrl: user.image ?? null,
twitterUsername: user.username ?? null,
// Defaults to adhere
...FORCED_DEFAULTS,
}}
isMinimal={true}
/>
))}
</div>
)}
</div>
</div>
</Card>
);
}
================================================
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 (
<Card title="Portfolio" updated={`${renderTimeSince(lastChecked)} ago`}>
{!isConnected ? (
// Not connected state
<div className="h-full p-4">
<div className="flex h-full flex-col items-center justify-center border border-dashed rounded-md">
<ButtonIcon className="w-12 h-12 text-zinc-500" />
<span className="text-zinc-500">
Connect wallet to track holdings
</span>
<div className="mt-4">
<ConnectButton />
</div>
</div>
</div>
) : (
<div className="h-full">
{loading && holdings.length === 0 && (
// Initial load
<div className="h-full p-4">
<div className="flex h-full flex-col items-center justify-center border border-dashed rounded-md">
<SymbolIcon className="h-12 w-12 animate-spin" />
<span className="text-lg pt-2">Loading portfolio...</span>
</div>
</div>
)}
{!loading && holdings.length === 0 && (
// No holdings found
<div className="h-full p-4">
<div className="flex h-full flex-col items-center justify-center border border-dashed rounded-md">
<CrossCircledIcon className="h-12 w-12" />
<span className="text-lg pt-2">Portfolio is empty</span>
</div>
</div>
)}
{holdings.length > 0 && (
// Some holdings found, render table
<Table>
<TableHeader>
<TableRow>
<TableHead>Friend</TableHead>
<TableHead>Balance</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{holdings.map((holding, i: number) => (
<TableRow key={i}>
<TableCell>
<Address
address={holding.address}
username={holding.twitterUsername}
image={holding.twitterPfpUrl}
/>
</TableCell>
<TableCell>{holding.balance}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
)}
</Card>
);
}
================================================
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 (
<Card title="Newest users" updated={`${renderTimeSince(lastChecked)} ago`}>
<div className="flex flex-col p-3 gap-3">
{users.map((user: UserInfo, i: number) => (
<User key={i} data={user} />
))}
</div>
</Card>
);
}
================================================
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 (
<Card
title="Realized Profit"
updated={`${renderTimeSince(lastChecked)} ago`}
>
<div>
<Table className="[&_td]:py-1">
<TableHeader>
<TableRow>
<TableHead>Address</TableHead>
<TableHead>Profit</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.map((p, i) => {
const profit: string =
currency === Currency.USD
? `$${parseUSD(p.profit * eth)}`
: `${p.profit.toFixed(2)} Ξ`;
return (
<TableRow key={i}>
<TableCell>
<Address
address={p.address}
username={p.twitterUsername}
image={p.twitterPfpUrl}
/>
</TableCell>
<TableCell>
{p.profit > 0 ? (
<span className="text-buy">{profit}</span>
) : (
<span className="text-sell">{profit}</span>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
</Card>
);
}
================================================
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<TradeWithTwitterUser[]>(
`/api/token/trades?address=${user.address}`,
[],
15 * 1000
);
return (
<Card
title="Token trades"
updated={`${
user.username ? `@${user.username}` : truncateAddress(user.address, 6)
}, ${renderTimeSince(lastChecked)} ago`}
>
<div className="h-full">
{loading && trades.length === 0 && (
<div className="flex mx-auto mt-4 items-center flex-col justify-center w-[calc(100%-2rem)] h-[calc(100%-2rem)] border-2 border-dashed rounded-md">
<SymbolIcon className="h-12 w-12 animate-spin" />
<span className="text-lg pt-2">Loading trades...</span>
</div>
)}
{trades.length === 0 && (
<div className="flex mt-4 mx-auto items-center flex-col justify-center w-[calc(100%-2rem)] h-[calc(100%-2rem)] border-2 border-dashed rounded-md">
<CrossCircledIcon className="h-12 w-12" />
<span className="text-lg pt-2">
{!user.address ? "Select an address" : "No trades found"}
</span>
</div>
)}
{trades.length > 0 && <TradeTable trades={trades} />}
</div>
</Card>
);
}
================================================
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 (
<Card title="Recent trades" updated={`${renderTimeSince(lastChecked)} ago`}>
<div>
<TradeTable trades={trades} />
</div>
</Card>
);
}
================================================
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<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
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<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-zinc-950 dark:bg-zinc-950 dark:text-zinc-50",
className
)}
{...props}
/>
))
Command.displayName = CommandPrimitive.displayName
interface CommandDialogProps extends DialogProps {}
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-zinc-500 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5 dark:[&_[cmdk-group-heading]]:text-zinc-400">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<MagnifyingGlassIcon className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-zinc-400",
className
)}
{...props}
/>
</div>
))
CommandInput.displayName = CommandPrimitive.Input.displayName
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
))
CommandList.displayName = CommandPrimitive.List.displayName
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
))
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-zinc-950 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-zinc-500 dark:text-zinc-50 dark:[&_[cmdk-group-heading]]:text-zinc-400",
className
)}
{...props}
/>
))
CommandGroup.displayName = CommandPrimitive.Group.displayName
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-zinc-200 dark:bg-zinc-800", className)}
{...props}
/>
))
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-zinc-100 aria-selected:text-zinc-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:aria-selected:bg-zinc-800 dark:aria-selected:text-zinc-50",
className
)}
{...props}
/>
))
CommandItem.displayName = CommandPrimitive.Item.displayName
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-zinc-500 dark:text-zinc-400",
className
)}
{...props}
/>
)
}
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) => (
<DialogPrimitive.Portal className={cn(className)} {...props} />
)
DialogPortal.displayName = DialogPrimitive.Portal.displayName
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-white/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 dark:bg-zinc-950/80",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-zinc-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full dark:border-zinc-800 dark:bg-zinc-950",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-zinc-100 data-[state=open]:text-zinc-500 dark:ring-offset-zinc-950 dark:focus:ring-zinc-300 dark:data-[state=open]:bg-zinc-800 dark:data-[state=open]:text-zinc-400">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-zinc-500 dark:text-zinc-400", className)}
{...props}
/>
))
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<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-zinc-200 border-zinc-200 bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-zinc-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-800 dark:border-zinc-800 dark:placeholder:text-zinc-400 dark:focus-visible:ring-zinc-300",
className
)}
ref={ref}
{...props}
/>
)
}
)
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<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border border-zinc-200 bg-white p-4 text-zinc-950 shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
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<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
));
Table.displayName = "Table";
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
));
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
));
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"bg-zinc-900 font-medium text-zinc-50 dark:bg-zinc-50 dark:text-zinc-900",
className
)}
{...props}
/>
));
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-zinc-100/50 data-[state=selected]:bg-zinc-100 dark:hover:bg-zinc-800/50 dark:data-[state=selected]:bg-zinc-800",
className
)}
{...props}
/>
));
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-10 px-2 text-left align-middle font-medium text-zinc-500 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] dark:text-zinc-400",
className
)}
{...props}
/>
));
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn(
"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
));
TableCell.displayName = "TableCell";
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-zinc-500 dark:text-zinc-400", className)}
{...props}
/>
));
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
<WagmiConfig config={wagmiConfig}>
<RainbowKitProvider chains={chains} theme={darkTheme()}>
<Component {...pageProps} />
</RainbowKitProvider>
</WagmiConfig>
);
}
================================================
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<UserInfo[]>} leaderboard users
*/
export async function getLeaderboardUsers(): Promise<UserInfo[]> {
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<UserInfo[]>} newest users
*/
export async function getNewestUsers(): Promise<UserInfo[]> {
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<RealizedProfitUser[]> {
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<TradeWithTwitterUser[]>} newest trades
*/
export async function getLatestTrades(): Promise<TradeWithTwitterUser[]> {
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<CachedData, "lastChecked"> & {
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<string, number> = {};
let subjectToUser: Record<string, User> = {};
// 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<CachedHoldings, "lastChecked"> & {
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<CachedData, "lastChecked"> & {
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<StateUser>}
*/
export async function getStateUser(address: string): Promise<StateUser> {
// 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 (
<Layout user={user}>
<ResponsiveGridLayout
layouts={layout}
draggableHandle=".drag-handle"
cols={{ lg: 36, md: 24, sm: 12, xs: 6, xxs: 3 }}
>
{/* Discover */}
<div key="discover">
<Discover leaderboard={leaderboardUsers} />
</div>
{/* Trading chart */}
<div key="chart">
<Chart />
</div>
{/* Buy + Sell controller */}
<div key="buy_sell">
<BuySell />
</div>
{/* Recent trades */}
<div key="recent_trades">
<RecentTrades trades={latestTrades} />
</div>
{/* Favorites */}
<div key="favorites">
<Favorites />
</div>
{/* Portfolio */}
<div key="holdings">
<Holdings />
</div>
{/* Recent token trades */}
<div key="recent_token_trades">
<RecentTokenTrades />
</div>
{/* Most profitable users, temp disabled */}
{/* <div key="realized_profit">
<RealizedProfit profit={realizedProfit} />
</div> */}
{/* Newest users */}
<div key="newest_users">
<NewestUsers users={newestUsers} />
</div>
</ResponsiveGridLayout>
</Layout>
);
}
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<StateUser>(initialState);
// Currency
const [currency, setCurrency] = useState<Currency>(Currency.ETH);
// ETH Price
const [eth, setEth] = useState<number>(0);
// Favorites
const [favorites, setFavorites] = useState<Record<string, StateUser>>({});
// 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<T>(
endpoint: string,
initial: T,
frequency?: number
) {
// Loading status
const [loading, setLoading] = useState<boolean>(true);
// Stored data
const [data, setData] = useState<T>(initial);
// Time since last checked
const [lastChecked, setLastChecked] = useState<number>(0);
/**
* Call backend, collect some generic data, set data
*/
const collectData = useCallback(async (): Promise<void> => {
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<void> {
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<void> {
// 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<string> = new Set();
// User to token supply (address => token supply)
private supply: Record<string, number> = {};
// 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<number>} block number
*/
async getChainBlock(): Promise<number> {
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<number>} block number
*/
async getSyncedBlock(): Promise<number> {
// 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<void> {
// 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<void> {
// 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<string> = 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<string> = new Set();
// List of new, untracked users
let newUsers: Set<string> = 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<void> {
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<void> {
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<void> {
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<string, number> = {};
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<void> {
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<void> {
// 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<T>(arr: T[], n: number): Generator<T[], void> {
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
}
}
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
SYMBOL INDEX (89 symbols across 42 files)
FILE: frontend/components/Address.tsx
function Address (line 6) | function Address({
FILE: frontend/components/Card.tsx
function Card (line 4) | function Card({
FILE: frontend/components/Header.tsx
function Header (line 6) | function Header() {
FILE: frontend/components/Layout.tsx
function Layout (line 6) | function Layout({
function Meta (line 29) | function Meta() {
FILE: frontend/components/TradeTable.tsx
function ColoredRow (line 20) | function ColoredRow({
function TradeTable (line 34) | function TradeTable({
FILE: frontend/components/User.tsx
type UserInfo (line 11) | type UserInfo = User & {
function User (line 15) | function User({
FILE: frontend/components/trading/BuySell.tsx
function BuySell (line 13) | function BuySell() {
FILE: frontend/components/trading/Chart.tsx
function Chart (line 8) | function Chart() {
FILE: frontend/components/trading/Discover.tsx
function useSearch (line 11) | function useSearch(search: string) {
function Leaderboard (line 64) | function Leaderboard({
FILE: frontend/components/trading/Favorites.tsx
constant FORCED_DEFAULTS (line 8) | const FORCED_DEFAULTS = {
function Favorites (line 16) | function Favorites() {
FILE: frontend/components/trading/Holdings.tsx
function Holdings (line 22) | function Holdings() {
FILE: frontend/components/trading/NewestUsers.tsx
function NewestUsers (line 10) | function NewestUsers({
FILE: frontend/components/trading/ProfitableUsers.tsx
function RealizedProfit (line 17) | function RealizedProfit({
FILE: frontend/components/trading/RecentTokenTrades.tsx
function RecentTokenTrades (line 10) | function RecentTokenTrades() {
FILE: frontend/components/trading/RecentTrades.tsx
function RecentTrades (line 7) | function RecentTrades({
FILE: frontend/components/ui/button.tsx
type ButtonProps (line 37) | interface ButtonProps
FILE: frontend/components/ui/command.tsx
type CommandDialogProps (line 24) | interface CommandDialogProps extends DialogProps {}
FILE: frontend/components/ui/input.tsx
type InputProps (line 5) | interface InputProps
FILE: frontend/pages/_app.tsx
function FriendMEX (line 37) | function FriendMEX({ Component, pageProps }: AppProps) {
FILE: frontend/pages/api/eth.ts
constant CG_ETHUSD (line 6) | const CG_ETHUSD: string =
FILE: frontend/pages/api/stats/leaderboard.ts
function getLeaderboardUsers (line 9) | async function getLeaderboardUsers(): Promise<UserInfo[]> {
function handler (line 17) | async function handler(_: NextApiRequest, res: NextApiResponse) {
FILE: frontend/pages/api/stats/newest.ts
function getNewestUsers (line 9) | async function getNewestUsers(): Promise<UserInfo[]> {
function handler (line 15) | async function handler(_: NextApiRequest, res: NextApiResponse) {
FILE: frontend/pages/api/stats/realized.ts
type RealizedProfitUser (line 4) | type RealizedProfitUser = {
function getRealizedProfits (line 15) | async function getRealizedProfits(): Promise<RealizedProfitUser[]> {
function handler (line 21) | async function handler(_: NextApiRequest, res: NextApiResponse) {
FILE: frontend/pages/api/stats/trades.ts
type TradeWithTwitterUser (line 5) | type TradeWithTwitterUser = Trade & {
function getLatestTrades (line 20) | async function getLatestTrades(): Promise<TradeWithTwitterUser[]> {
function handler (line 28) | async function handler(_: NextApiRequest, res: NextApiResponse) {
FILE: frontend/pages/api/token/chart.ts
type ChartData (line 8) | type ChartData = { timestamp: Date; "Price (ETH)": number }[];
type CachedData (line 9) | type CachedData = { lastChecked: Date; chart: ChartData; supply: number };
function processTrades (line 11) | function processTrades(trades: Trade[], existing?: CachedData): CachedDa...
function handler (line 47) | async function handler(
FILE: frontend/pages/api/token/holdings.ts
type Holding (line 6) | type Holding = User & { balance: number };
type ExtendedTrade (line 7) | type ExtendedTrade = Trade & { subjectUser: User };
type CachedHoldings (line 8) | type CachedHoldings = { lastChecked: Date; holdings: Holding[] };
function processHoldings (line 10) | function processHoldings(
function handler (line 63) | async function handler(
FILE: frontend/pages/api/token/trades.ts
type CachedData (line 6) | type CachedData = { lastChecked: Date; trades: TradeWithTwitterUser[] };
function handler (line 8) | async function handler(
FILE: frontend/pages/api/user.ts
function getStateUser (line 12) | async function getStateUser(address: string): Promise<StateUser> {
FILE: frontend/pages/index.tsx
function Home (line 36) | function Home({
function getServerSideProps (line 131) | async function getServerSideProps(ctx: NextPageContext) {
FILE: frontend/state/global.ts
type StateUser (line 8) | type StateUser = {
type Currency (line 14) | enum Currency {
function useGlobal (line 19) | function useGlobal(initialState: StateUser = constants.COBIE) {
FILE: frontend/utils.ts
function cn (line 4) | function cn(...inputs: ClassValue[]) {
function truncateAddress (line 14) | function truncateAddress(address: string, numTruncated: number): string {
function getPrice (line 29) | function getPrice(supply: number, amount: number): number {
constant CONTRACT_ADDRESS (line 46) | const CONTRACT_ADDRESS = "0xcf205808ed36593aa40a44f10c7f7c2f67d4a4d4";
constant ABI (line 51) | const ABI = [
FILE: frontend/utils/cache.ts
constant REDIS_URL (line 4) | const REDIS_URL: string = process.env.REDIS_URL ?? "redis://127.0.0.1:63...
FILE: frontend/utils/constants.ts
constant COBIE (line 4) | const COBIE: StateUser = {
FILE: frontend/utils/time.ts
function renderTimeSince (line 7) | function renderTimeSince(s: number): string {
FILE: frontend/utils/usd.ts
function parseUSD (line 6) | function parseUSD(value: number): string {
FILE: frontend/utils/usePollData.ts
function usePollData (line 4) | function usePollData<T>(
FILE: indexer/src/index.ts
function execute (line 8) | async function execute(): Promise<void> {
FILE: indexer/src/keeper.ts
class Keeper (line 12) | class Keeper {
method constructor (line 31) | constructor(rpc_url: string, redis_url: string) {
method getChainBlock (line 43) | async getChainBlock(): Promise<number> {
method getSyncedBlock (line 65) | async getSyncedBlock(): Promise<number> {
method loadUsersAndSupplies (line 82) | async loadUsersAndSupplies(): Promise<void> {
method getTradeCost (line 109) | getTradeCost(subject: string, amount: number, buy: boolean): number {
method chunkTxCall (line 133) | async chunkTxCall(batch: RPCMethod[]) {
method syncTradeRange (line 168) | async syncTradeRange(startBlock: number, endBlock: number): Promise<vo...
method syncTrades (line 376) | async syncTrades() {
method sync (line 408) | async sync() {
FILE: indexer/src/profile.ts
class Profile (line 13) | class Profile {
method constructor (line 24) | constructor() {
method syncUser (line 37) | async syncUser(address: string) {
method syncProfiles (line 92) | async syncProfiles() {
method sync (line 117) | async sync() {
FILE: indexer/src/stats.ts
class Stats (line 7) | class Stats {
method constructor (line 17) | constructor(redis_url: string) {
method updateNewestUsers (line 27) | async updateNewestUsers(): Promise<void> {
method udpateRecentTrades (line 47) | async udpateRecentTrades(): Promise<void> {
method tokenLeaderboard (line 72) | async tokenLeaderboard(): Promise<void> {
method mostProfitableUsers (line 96) | async mostProfitableUsers() {
method sync15s (line 146) | async sync15s(): Promise<void> {
method sync30m (line 158) | async sync30m(): Promise<void> {
FILE: indexer/src/utils/math.ts
function getPrice (line 8) | function getPrice(supply: number, amount: number): number {
FILE: indexer/src/utils/types.ts
type RPCMethod (line 4) | type RPCMethod = {
type Transaction (line 14) | type Transaction = {
Condensed preview — 68 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (177K chars).
[
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 276,
"preview": "# friendmex.com\n\n[BitMEX](https://www.bitmex.com/app/trade/XBTUSD)-inspired trading interface for [friend.tech](https://"
},
{
"path": "frontend/.eslintrc.json",
"chars": 146,
"preview": "{\n \"extends\": \"next/core-web-vitals\",\n \"rules\": {\n \"@next/next/no-img-element\": \"off\",\n \"import/no-anonymous-def"
},
{
"path": "frontend/.gitignore",
"chars": 402,
"preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
},
{
"path": "frontend/README.md",
"chars": 283,
"preview": "# Frontend\n\n[BitMEX](https://www.bitmex.com/app/trade/XBTUSD)-inspired frontend for [friend.tech](https://www.friend.tec"
},
{
"path": "frontend/components/Address.tsx",
"chars": 1389,
"preview": "import { Global } from \"state/global\";\nimport { Button } from \"./ui/button\";\nimport { truncateAddress } from \"utils\";\nim"
},
{
"path": "frontend/components/Card.tsx",
"chars": 1139,
"preview": "import { ReactElement } from \"react\";\nimport { DragHandleDots2Icon } from \"@radix-ui/react-icons\";\n\nexport default funct"
},
{
"path": "frontend/components/Header.tsx",
"chars": 2292,
"preview": "import Link from \"next/link\";\nimport Image from \"next/image\";\nimport { Global, Currency } from \"state/global\";\nimport { "
},
{
"path": "frontend/components/Layout.tsx",
"chars": 1891,
"preview": "import Head from \"next/head\";\nimport Header from \"components/Header\";\nimport type { ReactElement } from \"react\";\nimport "
},
{
"path": "frontend/components/TradeTable.tsx",
"chars": 3876,
"preview": "import {\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from \"components/ui/table\";\nimport"
},
{
"path": "frontend/components/User.tsx",
"chars": 4140,
"preview": "import { parseUSD } from \"utils/usd\";\nimport { Button } from \"./ui/button\";\nimport { truncateAddress } from \"utils\";\nimp"
},
{
"path": "frontend/components/trading/BuySell.tsx",
"chars": 6777,
"preview": "import Card from \"components/Card\";\nimport { parseUSD } from \"utils/usd\";\nimport Address from \"components/Address\";\nimpo"
},
{
"path": "frontend/components/trading/Chart.tsx",
"chars": 973,
"preview": "import Card from \"components/Card\";\nimport { truncateAddress } from \"utils\";\nimport { LineChart } from \"@tremor/react\";\n"
},
{
"path": "frontend/components/trading/Discover.tsx",
"chars": 3945,
"preview": "import axios from \"axios\";\nimport Card from \"components/Card\";\nimport { Input } from \"components/ui/input\";\nimport { ren"
},
{
"path": "frontend/components/trading/Favorites.tsx",
"chars": 2517,
"preview": "import User from \"components/User\";\nimport Card from \"components/Card\";\nimport { Global, StateUser } from \"state/global\""
},
{
"path": "frontend/components/trading/Holdings.tsx",
"chars": 3218,
"preview": "import {\n ButtonIcon,\n CrossCircledIcon,\n SymbolIcon,\n} from \"@radix-ui/react-icons\";\nimport {\n Table,\n TableBody,\n"
},
{
"path": "frontend/components/trading/NewestUsers.tsx",
"chars": 840,
"preview": "import axios from \"axios\";\nimport Card from \"components/Card\";\nimport Address from \"components/Address\";\nimport { format"
},
{
"path": "frontend/components/trading/ProfitableUsers.tsx",
"chars": 2009,
"preview": "import {\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from \"components/ui/table\";\nimport"
},
{
"path": "frontend/components/trading/RecentTokenTrades.tsx",
"chars": 1818,
"preview": "import Card from \"components/Card\";\nimport { truncateAddress } from \"utils\";\nimport { renderTimeSince } from \"utils/time"
},
{
"path": "frontend/components/trading/RecentTrades.tsx",
"chars": 640,
"preview": "import Card from \"components/Card\";\nimport { renderTimeSince } from \"utils/time\";\nimport TradeTable from \"components/Tra"
},
{
"path": "frontend/components/ui/button.tsx",
"chars": 2107,
"preview": "import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class"
},
{
"path": "frontend/components/ui/command.tsx",
"chars": 5085,
"preview": "import * as React from \"react\"\nimport { DialogProps } from \"@radix-ui/react-dialog\"\nimport { MagnifyingGlassIcon } from "
},
{
"path": "frontend/components/ui/dialog.tsx",
"chars": 4164,
"preview": "import * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { Cross2Icon } from \"@ra"
},
{
"path": "frontend/components/ui/input.tsx",
"chars": 916,
"preview": "import * as React from \"react\"\n\nimport { cn } from \"utils\"\n\nexport interface InputProps\n extends React.InputHTMLAttribu"
},
{
"path": "frontend/components/ui/popover.tsx",
"chars": 1284,
"preview": "import * as React from \"react\"\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\"\n\nimport { cn } from \"utils\"\n\n"
},
{
"path": "frontend/components/ui/table.tsx",
"chars": 2972,
"preview": "import * as React from \"react\";\n\nimport { cn } from \"utils\";\n\nconst Table = React.forwardRef<\n HTMLTableElement,\n Reac"
},
{
"path": "frontend/components.json",
"chars": 313,
"preview": "{\n \"$schema\": \"https://ui.shadcn.com/schema.json\",\n \"style\": \"new-york\",\n \"rsc\": false,\n \"tsx\": true,\n \"tailwind\": "
},
{
"path": "frontend/global.css",
"chars": 59,
"preview": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n"
},
{
"path": "frontend/next.config.js",
"chars": 257,
"preview": "/** @type {import('next').NextConfig} */\nconst nextConfig = {\n reactStrictMode: true,\n swcMinify: true,\n webpack: (co"
},
{
"path": "frontend/package.json",
"chars": 1372,
"preview": "{\n \"name\": \"frontend\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"next dev\",\n \"build\": \"pri"
},
{
"path": "frontend/pages/_app.tsx",
"chars": 1214,
"preview": "import { Global } from \"state/global\";\nimport type { AppProps } from \"next/app\";\n\n// CSS imports\nimport \"global.css\";\nim"
},
{
"path": "frontend/pages/api/eth.ts",
"chars": 1100,
"preview": "import axios from \"axios\";\nimport cache from \"utils/cache\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";"
},
{
"path": "frontend/pages/api/stats/leaderboard.ts",
"chars": 944,
"preview": "import cache from \"utils/cache\";\nimport type { UserInfo } from \"components/User\";\nimport type { NextApiRequest, NextApiR"
},
{
"path": "frontend/pages/api/stats/newest.ts",
"chars": 882,
"preview": "import cache from \"utils/cache\";\nimport type { UserInfo } from \"components/User\";\nimport { NextApiRequest, NextApiRespon"
},
{
"path": "frontend/pages/api/stats/realized.ts",
"chars": 1012,
"preview": "import cache from \"utils/cache\";\nimport { NextApiRequest, NextApiResponse } from \"next\";\n\nexport type RealizedProfitUser"
},
{
"path": "frontend/pages/api/stats/trades.ts",
"chars": 1158,
"preview": "import cache from \"utils/cache\";\nimport type { Trade } from \"@prisma/client\";\nimport { NextApiRequest, NextApiResponse }"
},
{
"path": "frontend/pages/api/token/chart.ts",
"chars": 4034,
"preview": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport { getPrice } from \"utils\";\nimport type { Trade } "
},
{
"path": "frontend/pages/api/token/holdings.ts",
"chars": 4408,
"preview": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport type { Trade, User } from \"@prisma/client\";\nimpor"
},
{
"path": "frontend/pages/api/token/search.ts",
"chars": 1287,
"preview": "import db from \"prisma/index\";\nimport { getPrice } from \"utils\";\nimport type { User } from \"@prisma/client\";\nimport type"
},
{
"path": "frontend/pages/api/token/trades.ts",
"chars": 3913,
"preview": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport type { NextApiRequest, NextApiResponse } from \"ne"
},
{
"path": "frontend/pages/api/user.ts",
"chars": 2114,
"preview": "import db from \"prisma/index\";\nimport cache from \"utils/cache\";\nimport { getPrice } from \"utils\";\nimport type { StateUse"
},
{
"path": "frontend/pages/index.tsx",
"chars": 4809,
"preview": "import dynamic from \"next/dynamic\";\nimport Layout from \"components/Layout\";\nimport constants from \"utils/constants\";\nimp"
},
{
"path": "frontend/postcss.config.js",
"chars": 154,
"preview": "module.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n ...(process.env.NODE_ENV === \"production\""
},
{
"path": "frontend/prisma/index.ts",
"chars": 352,
"preview": "import { PrismaClient } from \"@prisma/client\";\n\n// Setup global prisma\nconst globalForPrisma = globalThis as unknown as "
},
{
"path": "frontend/prisma/schema.prisma",
"chars": 1149,
"preview": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator clien"
},
{
"path": "frontend/state/global.ts",
"chars": 2302,
"preview": "import axios from \"axios\";\nimport constants from \"utils/constants\";\nimport { useRouter } from \"next/router\";\nimport { us"
},
{
"path": "frontend/tailwind.config.js",
"chars": 4633,
"preview": "/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n darkMode: [\"class\"],\n content: [\n \"./pages/**/*.{ts"
},
{
"path": "frontend/tsconfig.json",
"chars": 530,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n \"allowJs\": true,\n \"sk"
},
{
"path": "frontend/utils/cache.ts",
"chars": 220,
"preview": "import Redis from \"ioredis\";\n\n// Redis URL (default or env)\nconst REDIS_URL: string = process.env.REDIS_URL ?? \"redis://"
},
{
"path": "frontend/utils/constants.ts",
"chars": 285,
"preview": "import type { StateUser } from \"state/global\";\n\n// Default user\nconst COBIE: StateUser = {\n address: \"0x4e5f7e4a774bd30"
},
{
"path": "frontend/utils/time.ts",
"chars": 520,
"preview": "/**\n * Given some time in seconds, returns formatted string in format \"{value}{unit}\"\n * @dev Assumes that things will f"
},
{
"path": "frontend/utils/usd.ts",
"chars": 279,
"preview": "/**\n * Parse USD numeric in appropriate dollar format\n * @param {number} value to parse\n * @returns {string} parsed\n */\n"
},
{
"path": "frontend/utils/usePollData.ts",
"chars": 1867,
"preview": "import axios from \"axios\";\nimport { useState, useEffect, useCallback } from \"react\";\n\nexport function usePollData<T>(\n "
},
{
"path": "frontend/utils.ts",
"chars": 7124,
"preview": "import { twMerge } from \"tailwind-merge\";\nimport { type ClassValue, clsx } from \"clsx\";\n\nexport function cn(...inputs: C"
},
{
"path": "indexer/.gitignore",
"chars": 2178,
"preview": "# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore\n\n# Logs\n\n*.log\nlogs\n_.log\nnpm-debug.lo"
},
{
"path": "indexer/README.md",
"chars": 551,
"preview": "# Indexer\n\nIndexes the [FriendtechSharesV1](https://basescan.org/address/0xcf205808ed36593aa40a44f10c7f7c2f67d4a4d4#code"
},
{
"path": "indexer/package.json",
"chars": 498,
"preview": "{\n \"name\": \"indexer\",\n \"author\": \"Anish Agnihotri\",\n \"main\": \"dist/index.js\",\n \"scripts\": {\n \"build\": \"npx prisma"
},
{
"path": "indexer/prisma/schema.prisma",
"chars": 1110,
"preview": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator clien"
},
{
"path": "indexer/src/index.ts",
"chars": 998,
"preview": "import Stats from \"./stats\";\nimport Keeper from \"./keeper\";\nimport Profile from \"./profile\";\n\n/**\n * Indexer execution l"
},
{
"path": "indexer/src/keeper.ts",
"chars": 12486,
"preview": "import Redis from \"ioredis\";\nimport { ethers } from \"ethers\";\nimport logger from \"./utils/logger\";\nimport { getPrice } f"
},
{
"path": "indexer/src/profile.ts",
"chars": 2908,
"preview": "import logger from \"./utils/logger\";\nimport constants from \"./utils/constants\";\nimport { PrismaClient } from \"@prisma/cl"
},
{
"path": "indexer/src/stats.ts",
"chars": 4032,
"preview": "import Redis from \"ioredis\";\nimport logger from \"./utils/logger\";\nimport { getPrice } from \"./utils/math\";\nimport consta"
},
{
"path": "indexer/src/utils/constants.ts",
"chars": 382,
"preview": "export default {\n // Friendshares contract deploy block\n CONTRACT_DEPLOY_BLOCK: 2430440,\n // Contract address\n CONTR"
},
{
"path": "indexer/src/utils/helpers.ts",
"chars": 266,
"preview": "/**\n * Generic generator to chunk array\n * @param {T[]} arr to chunk\n * @param {number} n max size per chunk\n */\nexport "
},
{
"path": "indexer/src/utils/logger.ts",
"chars": 600,
"preview": "import * as winston from \"winston\"; // Logging\n\n// Setup winston logger\nconst logger = winston.createLogger({\n level: \""
},
{
"path": "indexer/src/utils/math.ts",
"chars": 691,
"preview": "/**\n * getPrice function transcribed from solidity\n * @dev https://basescan.org/address/0xcf205808ed36593aa40a44f10c7f7c"
},
{
"path": "indexer/src/utils/types.ts",
"chars": 337,
"preview": "/**\n * JSONRPC method\n */\nexport type RPCMethod = {\n id: number;\n jsonrpc: string;\n params: any[];\n method: string;\n"
},
{
"path": "indexer/tsconfig.json",
"chars": 327,
"preview": "{\n \"compilerOptions\": {\n \"lib\": [\"ES6\"],\n \"target\": \"ES6\",\n \"module\": \"CommonJS\",\n \"moduleResolution\": \"nod"
}
]
About this extraction
This page contains the full source code of the Anish-Agnihotri/friendmex GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 68 files (161.4 KB), approximately 42.3k tokens, and a symbol index with 89 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.