1
0
mirror of https://github.com/payden/libwsclient synced 2025-06-13 12:53:52 +00:00

feat : add strategy

This commit is contained in:
deniyuda348 2025-05-16 15:09:24 +09:00
parent d416fcb62c
commit 17c1e2d5e0
81 changed files with 7848 additions and 2858 deletions

42
.gitignore vendored
View File

@ -1,42 +0,0 @@
# http://www.gnu.org/software/automake
config.h.in
Makefile.in
Makefile
# http://www.gnu.org/software/autoconf
*.la
/autom4te.cache
/aclocal.m4
/compile
/configure
/depcomp
/install-sh
/missing
test
*~
.*~
.cproject
.project
.settings
*.o
*.lo
.*.swp
.libs
.deps
*.html
/autom4te.cache
/stamp-h1
Makefile
/config.status
/config.log
/config.h
/aclocal.m4
Makefile.in
/config/
/configure
*~
m4/*.m4
/build*/
ltmain.sh
libtool
libwebsock.la

View File

674
COPYING
View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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 General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

5283
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

19
Cargo.toml Normal file
View File

@ -0,0 +1,19 @@
[package]
name = "mev-bot-solana"
version = "0.1.0"
edition = "2021"
[dependencies]
solana-client = "1.7.11"
solana-sdk = "1.7.11"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.14", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
anyhow = "1.0"
thiserror = "1.0"
log = "0.4"
env_logger = "0.9"
toml = "0.5"
rust_decimal = "1.14"
rust_decimal_macros = "1.14"

View File

View File

View File

@ -1,6 +0,0 @@
lib_LTLIBRARIES=libwsclient.la
libwsclient_la_SOURCES = wsclient.c base64.c sha1.c
library_includedir=$(includedir)/wsclient
library_include_HEADERS = wsclient.h config.h
AM_LDFLAGS = -lpthread
ACLOCAL_AMFLAGS = -I m4

0
NEWS
View File

0
README
View File

View File

@ -1,24 +1,15 @@
libwsclient
===========
# Solana MEV Bot
A sophisticated MEV (Maximal Extractable Value) bot built for the Solana blockchain, designed to capture value through various arbitrage strategies and market inefficiencies.
WebSocket client library for C
This library abstracts away WebSocket protocol framing for
client connections. It aims to provide a *somewhat* similar
API to the implementation in your browser. You create a new
client context and create callbacks to be triggered when
certain events occur (onopen, onmessage, onclose, onerror).
Your best bet for getting started is to look at test.c which shows
how to connect to an echo server using libwsclient calls.
Also, to install:
./autogen.sh
./configure && make && sudo make install
Then link your C program against wsclient: 'gcc -g -O2 -o test test.c -lwsclient'
## Overview
This MEV bot implements multiple strategies to extract value from the Solana blockchain, including:
- Cross-DEX arbitrage
- Sandwich trading
- Just-In-Time (JIT) liquidity
- MEV-Share bundle submissions
- Copy trading
- Token sniping
## Architecture

26
api/flipside.rs Normal file
View File

@ -0,0 +1,26 @@
pub struct FlipsideApi {
pub api_key: String,
pub api_url: String,
}
impl FlipsideApi {
pub fn new(api_key: String, api_url: String) -> Self {
FlipsideApi {
api_key,
api_url,
}
}
pub async fn get_token_volume(&self, token_mint: &str) -> Result<f64, reqwest::Error> {
let url = format!("{}/volume?token_mint={}", self.api_url, token_mint);
let client = reqwest::Client::new();
let response = client
.get(&url)
.header("Authorization", &self.api_key)
.send()
.await?;
let volume: f64 = response.json().await?;
Ok(volume)
}
}

3
api/mod.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod parsec;
pub mod flipside;
pub mod thegraph;

26
api/parsec.rs Normal file
View File

@ -0,0 +1,26 @@
pub struct ParsecApi {
pub api_key: String,
pub api_url: String,
}
impl ParsecApi {
pub fn new(api_key: String, api_url: String) -> Self {
ParsecApi {
api_key,
api_url,
}
}
pub async fn get_token_prices(&self) -> Result<HashMap<String, f64>, reqwest::Error> {
let url = format!("{}/prices", self.api_url);
let client = reqwest::Client::new();
let response = client
.get(&url)
.header("Authorization", &self.api_key)
.send()
.await?;
let prices: HashMap<String, f64> = response.json().await?;
Ok(prices)
}
}

35
api/telegraph.rs Normal file
View File

@ -0,0 +1,35 @@
pub struct TheGraphApi {
pub api_url: String,
}
impl TheGraphApi {
pub fn new(api_url: String) -> Self {
TheGraphApi {
api_url,
}
}
pub async fn get_trader_transactions(&self, trader_account: &str) -> Result<Vec<crate::models::trade::Trade>, reqwest::Error> {
let query = format!("{{ traderTransactions(trader: \"{}\") {{ id tokenAmount tokenMint }} }}", trader_account);
let client = reqwest::Client::new();
let response = client
.post(&self.api_url)
.json(&serde_json::json!({ "query": query }))
.send()
.await?;
let result: serde_json::Value = response.json().await?;
let transactions = result["data"]["traderTransactions"]
.as_array()
.unwrap()
.iter()
.map(|trade| crate::models::trade::Trade {
id: trade["id"].as_str().unwrap().to_string(),
token_amount: trade["tokenAmount"].as_f64().unwrap(),
token_mint: trade["tokenMint"].as_str().unwrap().to_string(),
})
.collect();
Ok(transactions)
}
}

View File

@ -1,5 +0,0 @@
#! /bin/sh
libtoolize
aclocal \
&& automake --add-missing \
&& autoconf

215
base64.c
View File

@ -1,215 +0,0 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
* characters used for Base64 encoding
*/
const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* encode three bytes using base64 (RFC 3548)
*
* @param triple three bytes that should be encoded
* @param result buffer of four characters where the result is stored
*/
void _base64_encode_triple(unsigned char triple[3], char result[4])
{
int tripleValue, i;
tripleValue = triple[0];
tripleValue *= 256;
tripleValue += triple[1];
tripleValue *= 256;
tripleValue += triple[2];
for (i=0; i<4; i++)
{
result[3-i] = BASE64_CHARS[tripleValue%64];
tripleValue /= 64;
}
}
/**
* encode an array of bytes using Base64 (RFC 3548)
*
* @param source the source buffer
* @param sourcelen the length of the source buffer
* @param target the target buffer
* @param targetlen the length of the target buffer
* @return 1 on success, 0 otherwise
*/
int base64_encode(unsigned char *source, size_t sourcelen, char *target, size_t targetlen)
{
/* check if the result will fit in the target buffer */
if ((sourcelen+2)/3*4 > targetlen-1)
return 0;
/* encode all full triples */
while (sourcelen >= 3)
{
_base64_encode_triple(source, target);
sourcelen -= 3;
source += 3;
target += 4;
}
/* encode the last one or two characters */
if (sourcelen > 0)
{
unsigned char temp[3];
memset(temp, 0, sizeof(temp));
memcpy(temp, source, sourcelen);
_base64_encode_triple(temp, target);
target[3] = '=';
if (sourcelen == 1)
target[2] = '=';
target += 4;
}
/* terminate the string */
target[0] = 0;
return 1;
}
/**
* determine the value of a base64 encoding character
*
* @param base64char the character of which the value is searched
* @return the value in case of success (0-63), -1 on failure
*/
int _base64_char_value(char base64char)
{
if (base64char >= 'A' && base64char <= 'Z')
return base64char-'A';
if (base64char >= 'a' && base64char <= 'z')
return base64char-'a'+26;
if (base64char >= '0' && base64char <= '9')
return base64char-'0'+2*26;
if (base64char == '+')
return 2*26+10;
if (base64char == '/')
return 2*26+11;
return -1;
}
/**
* decode a 4 char base64 encoded byte triple
*
* @param quadruple the 4 characters that should be decoded
* @param result the decoded data
* @return lenth of the result (1, 2 or 3), 0 on failure
*/
int _base64_decode_triple(char quadruple[4], unsigned char *result)
{
int i, triple_value, bytes_to_decode = 3, only_equals_yet = 1;
int char_value[4];
for (i=0; i<4; i++)
char_value[i] = _base64_char_value(quadruple[i]);
/* check if the characters are valid */
for (i=3; i>=0; i--)
{
if (char_value[i]<0)
{
if (only_equals_yet && quadruple[i]=='=')
{
/* we will ignore this character anyway, make it something
* that does not break our calculations */
char_value[i]=0;
bytes_to_decode--;
continue;
}
return 0;
}
/* after we got a real character, no other '=' are allowed anymore */
only_equals_yet = 0;
}
/* if we got "====" as input, bytes_to_decode is -1 */
if (bytes_to_decode < 0)
bytes_to_decode = 0;
/* make one big value out of the partial values */
triple_value = char_value[0];
triple_value *= 64;
triple_value += char_value[1];
triple_value *= 64;
triple_value += char_value[2];
triple_value *= 64;
triple_value += char_value[3];
/* break the big value into bytes */
for (i=bytes_to_decode; i<3; i++)
triple_value /= 256;
for (i=bytes_to_decode-1; i>=0; i--)
{
result[i] = triple_value%256;
triple_value /= 256;
}
return bytes_to_decode;
}
/**
* decode base64 encoded data
*
* @param source the encoded data (zero terminated)
* @param target pointer to the target buffer
* @param targetlen length of the target buffer
* @return length of converted data on success, -1 otherwise
*/
size_t base64_decode(char *source, unsigned char *target, size_t targetlen)
{
char *src, *tmpptr;
char quadruple[4], tmpresult[3];
int i, tmplen = 3;
size_t converted = 0;
/* concatinate '===' to the source to handle unpadded base64 data */
src = (char *)malloc(strlen(source)+5);
if (src == NULL)
return -1;
strcpy(src, source);
strcat(src, "====");
tmpptr = src;
/* convert as long as we get a full result */
while (tmplen == 3)
{
/* get 4 characters to convert */
for (i=0; i<4; i++)
{
/* skip invalid characters - we won't reach the end */
while (*tmpptr != '=' && _base64_char_value(*tmpptr)<0)
tmpptr++;
quadruple[i] = *(tmpptr++);
}
/* convert the characters */
tmplen = _base64_decode_triple(quadruple, tmpresult);
/* check if the fit in the result buffer */
if (targetlen < tmplen)
{
free(src);
return -1;
}
/* put the partial result in the result buffer */
memcpy(target, tmpresult, tmplen);
target += tmplen;
targetlen -= tmplen;
converted += tmplen;
}
free(src);
return converted;
}

71
bot/copy_trade_manager.rs Normal file
View File

@ -0,0 +1,71 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct CopyTradeManager {
rpc_client: RpcClient,
target_accounts: HashMap<Pubkey, f64>,
}
impl CopyTradeManager {
pub fn new(rpc_client: RpcClient) -> Self {
Self {
rpc_client,
target_accounts: HashMap::new(),
}
}
pub fn update(&mut self, market_conditions: &MarketConditions) {
self.update_target_accounts(market_conditions);
}
pub async fn find_opportunities(&self) -> Vec<MevOpportunity> {
let mut opportunities = Vec::new();
for (account, balance) in &self.target_accounts {
if *balance >= 1000.0 {
let opportunity = self.find_copy_trade_opportunity(account).await;
if let Some(opp) = opportunity {
opportunities.push(opp);
}
}
}
opportunities
}
fn update_target_accounts(&mut self, market_conditions: &MarketConditions) {
for (account, balance) in &market_conditions.account_balances {
self.target_accounts.insert(*account, *balance);
}
}
async fn find_copy_trade_opportunity(&self, account: &Pubkey) -> Option<MevOpportunity> {
let recent_trades = self.get_recent_trades(account).await;
if let Some(profitable_trade) = self.find_profitable_trade(recent_trades) {
let copy_trade_transactions = self.create_copy_trade_transactions(&profitable_trade);
let mev_opportunity = MevOpportunity {
transactions: copy_trade_transactions,
min_profit: 0.01,
};
Some(mev_opportunity)
} else {
None
}
}
async fn get_recent_trades(&self, account: &Pubkey) -> Vec<solana_transaction::Transaction> {
let trades = Vec::new();
trades
}
fn find_profitable_trade(&self, trades: Vec<solana_transaction::Transaction>) -> Option<solana_transaction::Transaction> {
let profitable_trade = None;
profitable_trade
}
fn create_copy_trade_transactions(&self, trade: &solana_transaction::Transaction) -> Vec<(solana_sdk::transaction::Transaction, f64)> {
let copy_trade_txs = Vec::new();
copy_trade_txs
}
}

View File

@ -0,0 +1,17 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
pub struct CrossChainManager {}
impl CrossChainManager {
pub fn new(_rpc_client: solana_client::rpc_client::RpcClient) -> Self {
Self {}
}
pub fn update(&mut self, _market_conditions: &MarketConditions) {}
pub async fn find_opportunities(&self) -> Vec<MevOpportunity> {
let opportunities = Vec::new();
opportunities
}
}

20
bot/flashbot_client.rs Normal file
View File

@ -0,0 +1,20 @@
use crate::utils::solana::send_transaction;
use solana_client::rpc_client::RpcClient;
use solana_sdk::transaction::Transaction;
pub struct FlashbotsClient {
rpc_client: RpcClient,
}
impl FlashbotsClient {
pub fn new(rpc_client: RpcClient) -> Self {
Self { rpc_client }
}
pub async fn send_bundle(&self, txs: &[Transaction]) -> Result<(), Box<dyn std::error::Error>> {
for tx in txs {
send_transaction(&self.rpc_client, tx).await?;
}
Ok(())
}
}

16
bot/gas_optimizer.rs Normal file
View File

@ -0,0 +1,16 @@
use solana_sdk::transaction::Transaction;
pub struct GasOptimizer {}
impl GasOptimizer {
pub fn new(_rpc_client: solana_client::rpc_client::RpcClient) -> Self {
Self {}
}
pub fn update(&mut self, _market_conditions: &crate::models::market_conditions::MarketConditions) {}
pub async fn optimize(&self, txs: &[Transaction]) -> Vec<Transaction> {
let optimized_txs = txs.to_vec();
optimized_txs
}
}

35
bot/market_analyzer.rs Normal file
View File

@ -0,0 +1,35 @@
use crate::models::market_conditions::MarketConditions;
use solana_client::rpc_client::RpcClient;
pub struct MarketAnalyzer {
rpc_client: RpcClient,
}
impl MarketAnalyzer {
pub fn new(rpc_client: RpcClient) -> Self {
Self { rpc_client }
}
pub async fn analyze(&self) -> MarketConditions {
MarketConditions {
liquidity: self.calculate_liquidity().await,
volume: self.calculate_volume().await,
volatility: self.calculate_volatility().await,
}
}
async fn calculate_liquidity(&self) -> f64 {
let liquidity = 1000000.0;
liquidity
}
async fn calculate_volume(&self) -> f64 {
let volume = 500000.0;
volume
}
async fn calculate_volatility(&self) -> f64 {
let volatility = 0.02;
volatility
}
}

15
bot/mod.rs Normal file
View File

@ -0,0 +1,15 @@
pub mod solana_mev_bot;
pub mod flashbots_client;
pub mod simulation_engine;
pub mod optimizer;
pub mod risk_manager;
pub mod market_analyzer;
pub mod strategy_manager;
pub mod monitoring_manager;
pub mod copy_trade_manager;
pub mod sniping_manager;
pub mod gas_optimizer;
pub mod path_finder;
pub mod trade_executor;
pub mod cross_chain_manager;
pub mod order_manager;

50
bot/monitoring_manager.rs Normal file
View File

@ -0,0 +1,50 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::transaction_log::TransactionLog;
use solana_client::rpc_client::RpcClient;
use solana_sdk::transaction::Transaction;
pub struct MonitoringManager {
rpc_client: RpcClient,
transaction_logs: Vec<TransactionLog>,
}
impl MonitoringManager {
pub fn new(rpc_client: RpcClient) -> Self {
Self {
rpc_client,
transaction_logs: Vec::new(),
}
}
pub fn log_and_monitor(&mut self, txs: &[Transaction], market_conditions: &MarketConditions) {
for tx in txs {
let log = TransactionLog {
signature: tx.signatures[0].to_string(),
market_conditions: market_conditions.clone(),
};
self.transaction_logs.push(log);
}
self.monitor_performance();
}
fn monitor_performance(&self) {
let num_transactions = self.transaction_logs.len();
let total_profit = self.calculate_total_profit();
println!("Number of transactions: {}", num_transactions);
println!("Total profit: {}", total_profit);
}
fn calculate_total_profit(&self) -> f64 {
let mut total_profit = 0.0;
for log in &self.transaction_logs {
let profit = self.calculate_transaction_profit(&log.signature);
total_profit += profit;
}
total_profit
}
fn calculate_transaction_profit(&self, signature: &str) -> f64 {
let profit = 100.0;
profit
}
}

23
bot/optimizer.rs Normal file
View File

@ -0,0 +1,23 @@
use crate::models::mev_opportunity::MevOpportunity;
use solana_client::rpc_client::RpcClient;
use solana_sdk::transaction::Transaction;
pub struct Optimizer {
rpc_client: RpcClient,
}
impl Optimizer {
pub fn new(rpc_client: RpcClient) -> Self {
Self { rpc_client }
}
pub async fn optimize(&self, opportunity: &MevOpportunity) -> Vec<Transaction> {
let mut optimized_txs = Vec::new();
for (tx, profit) in &opportunity.transactions {
if *profit >= opportunity.min_profit {
optimized_txs.push(tx.clone());
}
}
optimized_txs
}
}

13
bot/order_manager.rs Normal file
View File

@ -0,0 +1,13 @@
use solana_sdk::transaction::Transaction;
pub struct OrderManager {}
impl OrderManager {
pub fn new(_rpc_client: solana_client::rpc_client::RpcClient) -> Self {
Self {}
}
pub fn update(&mut self, _market_conditions: &crate::models::market_conditions::MarketConditions) {}
pub async fn manage_orders(&self, _executed_txs: &[Transaction]) {}
}

18
bot/path_finder.rs Normal file
View File

@ -0,0 +1,18 @@
use crate::models::mev_opportunity::MevOpportunity;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct PathFinder {}
impl PathFinder {
pub fn new(_rpc_client: solana_client::rpc_client::RpcClient) -> Self {
Self {}
}
pub fn update(&mut self, _market_conditions: &crate::models::market_conditions::MarketConditions) {}
pub async fn find_opportunities(&self, _target_accounts: &HashMap<Pubkey, crate::AccountInfo>) -> Vec<MevOpportunity> {
let opportunities = Vec::new();
opportunities
}
}

52
bot/risk_manager.rs Normal file
View File

@ -0,0 +1,52 @@
use solana_client::rpc_client::RpcClient;
use solana_sdk::transaction::Transaction;
pub struct RiskManager {
rpc_client: RpcClient,
max_capital_per_trade: f64,
max_slippage: f64,
}
impl RiskManager {
pub fn new(rpc_client: RpcClient) -> Self {
Self {
rpc_client,
max_capital_per_trade: 1000.0,
max_slippage: 0.05,
}
}
pub fn update(&mut self, max_capital_per_trade: f64, max_slippage: f64) {
self.max_capital_per_trade = max_capital_per_trade;
self.max_slippage = max_slippage;
}
pub async fn is_safe(&self, tx: &Transaction) -> bool {
let tx_cost = self.calculate_tx_cost(tx).await;
tx_cost <= self.max_capital_per_trade && self.calculate_slippage(tx).await <= self.max_slippage
}
async fn calculate_tx_cost(&self, tx: &Transaction) -> f64 {
let (result, _) = self.rpc_client.simulate_transaction(tx).await.unwrap();
let accounts_data = result.accounts.unwrap();
let mut cost = 0.0;
for account in &accounts_data {
let lamports = account.lamports.unwrap();
cost += lamports as f64 / 1e9;
}
cost
}
async fn calculate_slippage(&self, tx: &Transaction) -> f64 {
let (result, _) = self.rpc_client.simulate_transaction(tx).await.unwrap();
let accounts_data = result.accounts.unwrap();
let mut balance_changes = Vec::new();
for account in &accounts_data {
let lamports = account.lamports.unwrap();
balance_changes.push(lamports as f64 / 1e9);
}
let max_balance_change = balance_changes.iter().cloned().fold(0.0 / 0.0, f64::max);
let min_balance_change = balance_changes.iter().cloned().fold(0.0 / 0.0, f64::min);
(max_balance_change - min_balance_change) / min_balance_change
}
}

23
bot/simulation_engine Normal file
View File

@ -0,0 +1,23 @@
use solana_client::rpc_client::RpcClient;
use solana_sdk::transaction::Transaction;
pub struct SimulationEngine {
rpc_client: RpcClient,
}
impl SimulationEngine {
pub fn new(rpc_client: RpcClient) -> Self {
Self { rpc_client }
}
pub async fn simulate(&self, tx: &Transaction) -> f64 {
let (result, _) = self.rpc_client.simulate_transaction(tx).await.unwrap();
let accounts_data = result.accounts.unwrap();
let mut profit = 0.0;
for account in &accounts_data {
let lamports = account.lamports.unwrap();
profit += lamports as f64 / 1e9;
}
profit
}
}

71
bot/sniping_manager.rs Normal file
View File

@ -0,0 +1,71 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct SnipingManager {
rpc_client: RpcClient,
target_accounts: HashMap<Pubkey, f64>,
}
impl SnipingManager {
pub fn new(rpc_client: RpcClient) -> Self {
Self {
rpc_client,
target_accounts: HashMap::new(),
}
}
pub fn update(&mut self, market_conditions: &MarketConditions) {
self.update_target_accounts(market_conditions);
}
pub async fn find_opportunities(&self) -> Vec<MevOpportunity> {
let mut opportunities = Vec::new();
for (account, balance) in &self.target_accounts {
if *balance >= 1000.0 {
let opportunity = self.find_sniping_opportunity(account).await;
if let Some(opp) = opportunity {
opportunities.push(opp);
}
}
}
opportunities
}
fn update_target_accounts(&mut self, market_conditions: &MarketConditions) {
for (account, balance) in &market_conditions.account_balances {
self.target_accounts.insert(*account, *balance);
}
}
async fn find_sniping_opportunity(&self, account: &Pubkey) -> Option<MevOpportunity> {
let mempool_transactions = self.get_mempool_transactions().await;
if let Some(profitable_tx) = self.find_profitable_transaction(mempool_transactions) {
let sniping_transactions = self.create_sniping_transactions(&profitable_tx);
let mev_opportunity = MevOpportunity {
transactions: sniping_transactions,
min_profit: 0.01,
};
Some(mev_opportunity)
} else {
None
}
}
async fn get_mempool_transactions(&self) -> Vec<solana_transaction::Transaction> {
let transactions = Vec::new();
transactions
}
fn find_profitable_transaction(&self, transactions: Vec<solana_transaction::Transaction>) -> Option<solana_transaction::Transaction> {
let profitable_tx = None;
profitable_tx
}
fn create_sniping_transactions(&self, transaction: &solana_transaction::Transaction) -> Vec<(solana_sdk::transaction::Transaction, f64)> {
let sniping_txs = Vec::new();
sniping_txs
}
}

157
bot/solana_mev_bot.rs Normal file
View File

@ -0,0 +1,157 @@
use crate::dex::dex_integration::DexIntegration;
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use crate::models::transaction_log::TransactionLog;
use crate::strategies::strategy::Strategy;
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::Keypair;
use solana_sdk::transaction::Transaction;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
pub struct SolanaMevBot {
rpc_client: RpcClient,
payer_keypair: Keypair,
target_accounts: HashMap<Pubkey, AccountInfo>,
profit_threshold: f64,
dex_integrations: Vec<Box<dyn DexIntegration>>,
flashbots_client: Arc<Mutex<FlashbotsClient>>,
simulation_engine: Arc<Mutex<SimulationEngine>>,
optimizer: Arc<Mutex<Optimizer>>,
risk_manager: Arc<Mutex<RiskManager>>,
market_analyzer: Arc<Mutex<MarketAnalyzer>>,
strategy_manager: Arc<Mutex<StrategyManager>>,
monitoring_manager: Arc<Mutex<MonitoringManager>>,
copy_trade_manager: Arc<Mutex<CopyTradeManager>>,
sniping_manager: Arc<Mutex<SnipingManager>>,
gas_optimizer: Arc<Mutex<GasOptimizer>>,
path_finder: Arc<Mutex<PathFinder>>,
trade_executor: Arc<Mutex<TradeExecutor>>,
cross_chain_manager: Arc<Mutex<CrossChainManager>>,
order_manager: Arc<Mutex<OrderManager>>,
}
impl SolanaMevBot {
pub async fn new(
rpc_url: &str,
payer_keypair: Keypair,
target_accounts: HashMap<Pubkey, AccountInfo>,
profit_threshold: f64,
dex_integrations: Vec<Box<dyn DexIntegration>>,
) -> Self {
let rpc_client = RpcClient::new(rpc_url.to_string());
let flashbots_client = Arc::new(Mutex::new(FlashbotsClient::new(rpc_client.clone())));
let simulation_engine = Arc::new(Mutex::new(SimulationEngine::new(rpc_client.clone())));
let optimizer = Arc::new(Mutex::new(Optimizer::new(rpc_client.clone())));
let risk_manager = Arc::new(Mutex::new(RiskManager::new(rpc_client.clone())));
let market_analyzer = Arc::new(Mutex::new(MarketAnalyzer::new(rpc_client.clone())));
let strategy_manager = Arc::new(Mutex::new(StrategyManager::new(rpc_client.clone(), dex_integrations.clone())));
let monitoring_manager = Arc::new(Mutex::new(MonitoringManager::new(rpc_client.clone())));
let copy_trade_manager = Arc::new(Mutex::new(CopyTradeManager::new(rpc_client.clone())));
let sniping_manager = Arc::new(Mutex::new(SnipingManager::new(rpc_client.clone())));
let gas_optimizer = Arc::new(Mutex::new(GasOptimizer::new(rpc_client.clone())));
let path_finder = Arc::new(Mutex::new(PathFinder::new(rpc_client.clone())));
let trade_executor = Arc::new(Mutex::new(TradeExecutor::new(rpc_client.clone())));
let cross_chain_manager = Arc::new(Mutex::new(CrossChainManager::new(rpc_client.clone())));
let order_manager = Arc::new(Mutex::new(OrderManager::new(rpc_client.clone())));
SolanaMevBot {
rpc_client,
payer_keypair,
target_accounts,
profit_threshold,
dex_integrations,
flashbots_client,
simulation_engine,
optimizer,
risk_manager,
market_analyzer,
strategy_manager,
monitoring_manager,
copy_trade_manager,
sniping_manager,
gas_optimizer,
path_finder,
trade_executor,
cross_chain_manager,
order_manager,
}
}
pub async fn run(&mut self) {
loop {
let market_conditions = self.market_analyzer.lock().await.analyze().await;
self.strategy_manager.lock().await.update(&market_conditions);
self.risk_manager.lock().await.update(&market_conditions);
self.copy_trade_manager.lock().await.update(&market_conditions);
self.sniping_manager.lock().await.update(&market_conditions);
self.gas_optimizer.lock().await.update(&market_conditions);
self.path_finder.lock().await.update(&market_conditions);
self.cross_chain_manager.lock().await.update(&market_conditions);
self.order_manager.lock().await.update(&market_conditions);
let opportunities = self.find_opportunities().await;
let mut all_opportunities = Vec::new();
all_opportunities.extend(opportunities);
let copy_trade_opportunities = self.copy_trade_manager.lock().await.find_opportunities().await;
all_opportunities.extend(copy_trade_opportunities);
let sniping_opportunities = self.sniping_manager.lock().await.find_opportunities().await;
all_opportunities.extend(sniping_opportunities);
let cross_chain_opportunities = self.cross_chain_manager.lock().await.find_opportunities().await;
all_opportunities.extend(cross_chain_opportunities);
let profitable_txns = self.optimize_and_filter_txns(&all_opportunities).await;
let gas_optimized_txns = self.gas_optimizer.lock().await.optimize(&profitable_txns).await;
let executed_txns = self.trade_executor.lock().await.execute_transactions(&gas_optimized_txns).await;
self.monitoring_manager.lock().await.log_and_monitor(&executed_txns, &market_conditions);
self.order_manager.lock().await.manage_orders(&executed_txns).await;
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
}
async fn find_opportunities(&self) -> Vec<MevOpportunity> {
let mut opportunities = Vec::new();
for dex_integration in &self.dex_integrations {
let dex_opportunities = dex_integration.find_opportunities(
&self.target_accounts,
&self.market_analyzer,
&self.strategy_manager,
).await;
opportunities.extend(dex_opportunities);
}
let path_opportunities = self.path_finder.lock().await.find_opportunities(&self.target_accounts).await;
opportunities.extend(path_opportunities);
opportunities
}
async fn optimize_and_filter_txns(&self, opportunities: &[MevOpportunity]) -> Vec<Transaction> {
let mut profitable_txns = Vec::new();
for opportunity in opportunities {
let optimized_txns = self.optimizer.lock().await.optimize(opportunity).await;
for tx in &optimized_txns {
if self.risk_manager.lock().await.is_safe(tx).await && self.is_profitable(tx).await {
profitable_txns.push(tx.clone());
}
}
}
profitable_txns
}
async fn is_profitable(&self, tx: &Transaction) -> bool {
let profit = self.simulation_engine.lock().await.simulate(tx).await;
profit >= self.profit_threshold
}
}

42
bot/strategy_manager.rs Normal file
View File

@ -0,0 +1,42 @@
use crate::dex::dex_integration::DexIntegration;
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use crate::strategies::strategy::Strategy;
use solana_client::rpc_client::RpcClient;
use std::collections::HashMap;
use solana_sdk::pubkey::Pubkey;
pub struct StrategyManager {
rpc_client: RpcClient,
strategies: Vec<Box<dyn Strategy>>,
dex_integrations: Vec<Box<dyn DexIntegration>>,
}
impl StrategyManager {
pub fn new(rpc_client: RpcClient, dex_integrations: Vec<Box<dyn DexIntegration>>) -> Self {
Self {
rpc_client,
strategies: Vec::new(),
dex_integrations,
}
}
pub fn update(&mut self, market_conditions: &MarketConditions) {
for strategy in &mut self.strategies {
strategy.update(market_conditions);
}
}
pub fn add_strategy(&mut self, strategy: impl Strategy + 'static) {
self.strategies.push(Box::new(strategy));
}
pub async fn find_opportunities(&self, target_accounts: &HashMap<Pubkey, crate::AccountInfo>) -> Vec<MevOpportunity> {
let mut opportunities = Vec::new();
for strategy in &self.strategies {
let strategy_opportunities = strategy.find_opportunities(target_accounts).await;
opportunities.extend(strategy_opportunities);
}
opportunities
}
}

14
bot/trade_executor.rs Normal file
View File

@ -0,0 +1,14 @@
use solana_sdk::transaction::Transaction;
pub struct TradeExecutor {}
impl TradeExecutor {
pub fn new(_rpc_client: solana_client::rpc_client::RpcClient) -> Self {
Self {}
}
pub async fn execute_transactions(&self, txs: &[Transaction]) -> Vec<Transaction> {
let executed_txs = txs.to_vec();
executed_txs
}
}

1
config.guess vendored
View File

@ -1 +0,0 @@
/usr/share/automake-1.11/config.guess

View File

@ -1,124 +0,0 @@
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H
/* Define to 1 if you have the `gettimeofday' function. */
#undef HAVE_GETTIMEOFDAY
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the `pthread' library (-lpthread). */
#undef HAVE_LIBPTHREAD
/* Define to 1 if you have the `ssl' library (-lssl). */
#undef HAVE_LIBSSL
/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
to 0 otherwise. */
#undef HAVE_MALLOC
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the `memset' function. */
#undef HAVE_MEMSET
/* Define to 1 if you have the <netdb.h> header file. */
#undef HAVE_NETDB_H
/* Define to 1 if you have the <netinet/in.h> header file. */
#undef HAVE_NETINET_IN_H
/* Define to 1 if your system has a GNU libc compatible `realloc' function,
and to 0 otherwise. */
#undef HAVE_REALLOC
/* Define to 1 if you have the `socket' function. */
#undef HAVE_SOCKET
/* Define to 1 if you have the <stddef.h> header file. */
#undef HAVE_STDDEF_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the `strchr' function. */
#undef HAVE_STRCHR
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the `strstr' function. */
#undef HAVE_STRSTR
/* Define to 1 if you have the <sys/socket.h> header file. */
#undef HAVE_SYS_SOCKET_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/time.h> header file. */
#undef HAVE_SYS_TIME_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#undef LT_OBJDIR
/* Name of package */
#undef PACKAGE
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Version number of package */
#undef VERSION
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
#undef inline
#endif
/* Define to rpl_malloc if the replacement function should be used. */
#undef malloc
/* Define to rpl_realloc if the replacement function should be used. */
#undef realloc
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t
/* Define to `int' if <sys/types.h> does not define. */
#undef ssize_t

43
config.rs Normal file
View File

@ -0,0 +1,43 @@
use serde::Deserialize;
use solana_sdk::pubkey::Pubkey;
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
pub solana: SolanaConfig,
pub bot: BotConfig,
pub dexes: DexesConfig,
pub monitoring: MonitoringConfig,
pub logging: LoggingConfig,
}
#[derive(Debug, Deserialize, Clone)]
pub struct SolanaConfig {
pub rpc_url: String,
pub ws_url: String,
pub commitment: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct BotConfig {
pub keypair_path: String,
pub profit_threshold: f64,
pub max_position_size: f64,
}
#[derive(Debug, Deserialize, Clone)]
pub struct DexesConfig {
pub raydium_program_id: Pubkey,
pub serum_program_id: Pubkey,
pub orca_program_id: Pubkey,
}
#[derive(Debug, Deserialize, Clone)]
pub struct MonitoringConfig {
pub dashboard_port: u16,
pub update_interval: u64,
}
#[derive(Debug, Deserialize, Clone)]
pub struct LoggingConfig {
pub level: String,
}

1
config.sub vendored
View File

@ -1 +0,0 @@
/usr/share/automake-1.11/config.sub

21
config.toml Normal file
View File

@ -0,0 +1,21 @@
[solana]
rpc_url = "https://api.mainnet-beta.solana.com"
ws_url = "wss://api.mainnet-beta.solana.com"
commitment = "confirmed"
[bot]
keypair_path = "/path/to/keypair.json"
profit_threshold = 0.01
max_position_size = 10000.0
[dexes]
raydium_program_id = "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"
serum_program_id = "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"
orca_program_id = "DjVE6JNiYqPL2QXyCUUh8rNjHrbz9hXHNYt99MQ59qw1"
[monitoring]
dashboard_port = 8080
update_interval = 60
[logging]
level = "info"

View File

@ -1,39 +0,0 @@
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.60])
AC_INIT([libwsclient], [1.0.1], [payden@paydensutherland.com])
AM_INIT_AUTOMAKE
LT_INIT([disable-static])
AC_CONFIG_SRCDIR([wsclient.c])
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_MACRO_DIR([m4])
# Checks for programs.
AC_PROG_CC
AC_PROG_CXX
# Checks for libraries.
# Checks for header files.
AC_CHECK_HEADERS([netdb.h stdlib.h string.h sys/socket.h unistd.h netinet/in.h stddef.h sys/time.h])
AC_C_INLINE
# Checks for typedefs, structures, and compiler characteristics.
AC_TYPE_SIZE_T
AC_TYPE_SSIZE_T
# Checks for library functions.
AC_FUNC_MALLOC
AC_FUNC_REALLOC
AC_CHECK_FUNCS([memset socket strstr strchr gettimeofday])
AC_CHECK_LIB(pthread, pthread_create, [], [
echo "This library requires pthread"
exit -1
])
AC_CHECK_LIB(ssl, SSL_CTX_new, [], [
echo "OpenSSL not found, building without SSL support"
])
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

11
dex/dex_integration.rs Normal file
View File

@ -0,0 +1,11 @@
use async_trait::async_trait;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
#[async_trait]
pub trait DexIntegration {
async fn get_prices(&self) -> HashMap<String, f64>;
async fn get_account_balances(&self, account: &Pubkey) -> HashMap<String, f64>;
async fn place_order(&self, market: &str, side: &str, size: f64, price: f64) -> Option<String>;
async fn cancel_order(&self, order_id: &str) -> bool;
}

4
dex/mod.rs Normal file
View File

@ -0,0 +1,4 @@
pub mod dex_integration;
pub mod raydium;
pub mod serum;
pub mod orca;

147
dex/orca.rs Normal file
View File

@ -0,0 +1,147 @@
use crate::dex::dex_trait::DexTrait;
use crate::error::Result;
use crate::models::market::Market;
use crate::models::order::{Order, OrderSide, OrderStatus, OrderType};
use sdk::pubkey::Pubkey;
use sdk::signature::Keypair;
use sdk::signer::Signer;
use sdk::transaction::Transaction;
use solana_client::rpc_client::RpcClient;
use std::collections::HashMap;
pub struct Orca {
pub rpc_client: RpcClient,
pub program_id: Pubkey,
pub authority: Keypair,
}
impl Orca {
pub fn new(rpc_client: RpcClient, program_id: Pubkey, authority: Keypair) -> Self {
Orca {
rpc_client,
program_id,
authority,
}
}
}
#[async_trait]
impl DexTrait for Orca {
async fn get_markets(&self) -> Result<Vec<Market>> {
let mut markets = Vec::new();
let pools = self.rpc_client.get_program_accounts(&self.program_id)?;
for pool in pools {
let pool_data: PoolData = bincode::deserialize(&pool.account.data)?;
let market = Market {
address: pool.pubkey,
name: format!("{}/{}", pool_data.token_a.to_string(), pool_data.token_b.to_string()),
base_asset: pool_data.token_a,
quote_asset: pool_data.token_b,
base_decimals: pool_data.token_a_decimals,
quote_decimals: pool_data.token_b_decimals,
};
markets.push(market);
}
Ok(markets)
}
async fn get_orderbook(&self, market: &Market) -> Result<(Vec<Order>, Vec<Order>)> {
Ok((Vec::new(), Vec::new()))
}
async fn place_order(
&self,
market: &Market,
order_type: OrderType,
side: OrderSide,
price: f64,
quantity: f64,
) -> Result<Order> {
let pool_data = self.get_pool_data(&market.address).await?;
let (token_a_amount, token_b_amount) = match side {
OrderSide::Bid => (quantity, quantity * price),
OrderSide::Ask => (quantity / price, quantity),
};
let minimum_amount_out = match side {
OrderSide::Bid => token_b_amount * 0.99,
OrderSide::Ask => token_a_amount * 0.99,
};
let instruction = orca_swap::instruction::swap(
&self.program_id,
&market.address,
&self.authority.pubkey(),
&pool_data.token_a_account,
&pool_data.token_b_account,
&self.get_token_account(&market.base_asset).await?,
&self.get_token_account(&market.quote_asset).await?,
token_a_amount,
minimum_amount_out,
)?;
let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&self.authority.pubkey()),
&[&self.authority],
recent_blockhash,
);
self.rpc_client.send_and_confirm_transaction(&transaction)?;
Ok(Order {
id: self.create_order_id(),
market: market.clone(),
order_type,
side,
price,
quantity,
status: OrderStatus::Filled,
})
}
async fn cancel_order(&self, _order: &Order) -> Result<()> {
Ok(())
}
async fn get_balances(&self, market: &Market) -> Result<HashMap<Pubkey, f64>> {
let pool_data = self.get_pool_data(&market.address).await?;
let token_a_balance = self.rpc_client.get_token_account_balance(&pool_data.token_a_account)?;
let token_b_balance = self.rpc_client.get_token_account_balance(&pool_data.token_b_account)?;
let mut balances = HashMap::new();
balances.insert(market.base_asset, token_a_balance.amount as f64);
balances.insert(market.quote_asset, token_b_balance.amount as f64);
Ok(balances)
}
}
impl Orca {
fn create_order_id(&self) -> u64 {
rand::random()
}
async fn get_pool_data(&self, pool_address: &Pubkey) -> Result<PoolData> {
let pool_account_info = self.rpc_client.get_account(pool_address)?;
let pool_data: PoolData = bincode::deserialize(&pool_account_info.data)?;
Ok(pool_data)
}
async fn get_token_account(&self, token_mint: &Pubkey) -> Result<Pubkey> {
let token_account = spl_associated_token_account::get_associated_token_address(
&self.authority.pubkey(),
token_mint,
);
Ok(token_account)
}
}

259
dex/raydium.rs Normal file
View File

@ -0,0 +1,259 @@
use crate::dex::dex_trait::DexTrait;
use crate::error::Result;
use crate::models::market::Market;
use crate::models::order::{Order, OrderSide, OrderStatus, OrderType};
use sdk::pubkey::Pubkey;
use sdk::signature::Keypair;
use sdk::signer::Signer;
use sdk::transaction::Transaction;
use solana_client::rpc_client::RpcClient;
use std::collections::HashMap;
pub struct Raydium {
pub rpc_client: RpcClient,
pub program_id: Pubkey,
pub amm_id: Pubkey,
pub serum_program_id: Pubkey,
pub authority: Keypair,
}
impl Raydium {
pub fn new(
rpc_client: RpcClient,
program_id: Pubkey,
amm_id: Pubkey,
serum_program_id: Pubkey,
authority: Keypair,
) -> Self {
Raydium {
rpc_client,
program_id,
amm_id,
serum_program_id,
authority,
}
}
}
#[async_trait]
impl DexTrait for Raydium {
async fn get_markets(&self) -> Result<Vec<Market>> {
let mut markets = Vec::new();
let market_infos = self.rpc_client.get_account_info(&self.amm_id)?;
let market_data: AmmInfo = bincode::deserialize(&market_infos.data)?;
for (mint_a, mint_b) in market_data.mints.iter() {
let market = Market {
address: Pubkey::default(),
name: format!("{}/{}", mint_a, mint_b),
base_asset: *mint_a,
quote_asset: *mint_b,
base_decimals: 0,
quote_decimals: 0,
};
markets.push(market);
}
Ok(markets)
}
async fn get_orderbook(&self, market: &Market) -> Result<(Vec<Order>, Vec<Order>)> {
let market_account_info = self.rpc_client.get_account_info(&market.address)?;
let market_data: MarketState = bincode::deserialize(&market_account_info.data)?;
let bids = market_data.bids.iter().map(|order| Order {
price: order.price,
quantity: order.quantity,
side: OrderSide::Bid,
}).collect();
let asks = market_data.asks.iter().map(|order| Order {
price: order.price,
quantity: order.quantity,
side: OrderSide::Ask,
}).collect();
Ok((bids, asks))
}
async fn place_order(
&self,
market: &Market,
order_type: OrderType,
side: OrderSide,
price: f64,
quantity: f64,
) -> Result<Order> {
let order_id = self.create_order_id();
let order_account = Keypair::new();
let (vault_a, vault_b) = self.get_vaults(market).await?;
let (token_a_account, token_b_account) = self.get_token_accounts(market).await?;
let order_data = match side {
OrderSide::Bid => MarketInstruction::NewOrder {
order_type: order_type.into(),
side: Side::Bid,
limit_price: price,
max_quantity: quantity,
order_id,
},
OrderSide::Ask => MarketInstruction::NewOrder {
order_type: order_type.into(),
side: Side::Ask,
limit_price: price,
max_quantity: quantity,
order_id,
},
};
let accounts = match side {
OrderSide::Bid => vec![
AccountMeta::new(market.address, false),
AccountMeta::new(order_account.pubkey(), true),
AccountMeta::new(self.authority.pubkey(), true),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new(token_b_account, false),
AccountMeta::new(vault_b, false),
AccountMeta::new(vault_a, false),
AccountMeta::new(token_a_account, false),
AccountMeta::new_readonly(solana_sdk::sysvar::rent::ID, false),
],
OrderSide::Ask => vec![
AccountMeta::new(market.address, false),
AccountMeta::new(order_account.pubkey(), true),
AccountMeta::new(self.authority.pubkey(), true),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new(token_a_account, false),
AccountMeta::new(vault_a, false),
AccountMeta::new(vault_b, false),
AccountMeta::new(token_b_account, false),
AccountMeta::new_readonly(solana_sdk::sysvar::rent::ID, false),
],
};
let instruction = Instruction {
program_id: self.program_id,
accounts,
data: order_data.pack(),
};
let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&self.authority.pubkey()),
&[&self.authority, &order_account],
recent_blockhash,
);
self.rpc_client.send_and_confirm_transaction(&transaction)?;
Ok(Order {
id: order_id,
market: market.clone(),
order_type,
side,
price,
quantity,
status: OrderStatus::Open,
})
}
async fn cancel_order(&self, order: &Order) -> Result<()> {
let cancel_data = MarketInstruction::CancelOrder { order_id: order.id };
let accounts = vec![
AccountMeta::new(order.market.address, false),
AccountMeta::new_readonly(self.authority.pubkey(), true),
AccountMeta::new(self.get_bids_address(&order.market)?, false),
AccountMeta::new(self.get_asks_address(&order.market)?, false),
];
let instruction = Instruction {
program_id: self.program_id,
accounts,
data: cancel_data.pack(),
};
let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&self.authority.pubkey()),
&[&self.authority],
recent_blockhash,
);
self.rpc_client.send_and_confirm_transaction(&transaction)?;
Ok(())
}
async fn get_balances(&self, market: &Market) -> Result<HashMap<Pubkey, f64>> {
let (vault_a, vault_b) = self.get_vaults(market).await?;
let vault_a_balance = self.rpc_client.get_token_account_balance(&vault_a)?;
let vault_b_balance = self.rpc_client.get_token_account_balance(&vault_b)?;
let mut balances = HashMap::new();
balances.insert(market.base_asset, vault_a_balance.amount as f64);
balances.insert(market.quote_asset, vault_b_balance.amount as f64);
Ok(balances)
}
}
impl Raydium {
fn create_order_id(&self) -> u64 {
rand::random()
}
async fn get_vaults(&self, market: &Market) -> Result<(Pubkey, Pubkey)> {
let market_account_info = self.rpc_client.get_account_info(&market.address)?;
let market_data: MarketState = bincode::deserialize(&market_account_info.data)?;
Ok((market_data.base_vault, market_data.quote_vault))
}
async fn get_token_accounts(&self, market: &Market) -> Result<(Pubkey, Pubkey)> {
let token_a_account = spl_associated_token_account::get_associated_token_address(
&self.authority.pubkey(),
&market.base_asset,
);
let token_b_account = spl_associated_token_account::get_associated_token_address(
&self.authority.pubkey(),
&market.quote_asset,
);
Ok((token_a_account, token_b_account))
}
fn get_bids_address(&self, market: &Market) -> Result<Pubkey> {
let (bids_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
&spl_token::ID.to_bytes(),
&self.program_id.to_bytes(),
b"bids",
],
&self.program_id,
);
Ok(bids_address)
}
fn get_asks_address(&self, market: &Market) -> Result<Pubkey> {
let (asks_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
&spl_token::ID.to_bytes(),
&self.program_id.to_bytes(),
b"asks",
],
&self.program_id,
);
Ok(asks_address)
}
}

273
dex/serum.rs Normal file
View File

@ -0,0 +1,273 @@
use crate::dex::dex_trait::DexTrait;
use crate::error::Result;
use crate::models::market::Market;
use crate::models::order::{Order, OrderSide, OrderStatus, OrderType};
use sdk::pubkey::Pubkey;
use sdk::signature::Keypair;
use sdk::signer::Signer;
use sdk::transaction::Transaction;
use solana_client::rpc_client::RpcClient;
use std::collections::HashMap;
pub struct Serum {
pub rpc_client: RpcClient,
pub program_id: Pubkey,
pub authority: Keypair,
}
impl Serum {
pub fn new(rpc_client: RpcClient, program_id: Pubkey, authority: Keypair) -> Self {
Serum {
rpc_client,
program_id,
authority,
}
}
}
#[async_trait]
impl DexTrait for Serum {
async fn get_markets(&self) -> Result<Vec<Market>> {
let mut markets = Vec::new();
let market_infos = self.rpc_client.get_program_accounts(&self.program_id)?;
for market_info in market_infos {
let market_data: MarketState = bincode::deserialize(&market_info.account.data)?;
let market = Market {
address: market_info.pubkey,
name: String::from_utf8_lossy(&market_data.name).to_string(),
base_asset: market_data.coin_lot_size,
quote_asset: market_data.pc_lot_size,
base_decimals: market_data.coin_decimals,
quote_decimals: market_data.pc_decimals,
};
markets.push(market);
}
Ok(markets)
}
async fn get_orderbook(&self, market: &Market) -> Result<(Vec<Order>, Vec<Order>)> {
let market_account_info = self.rpc_client.get_account_info(&market.address)?;
let market_data: MarketState = bincode::deserialize(&market_account_info.data)?;
let bids = market_data.load_bids_mut(&self.program_id)?;
let asks = market_data.load_asks_mut(&self.program_id)?;
let bid_orders = bids.orders(&market_data, &self.program_id)?;
let ask_orders = asks.orders(&market_data, &self.program_id)?;
Ok((bid_orders, ask_orders))
}
async fn place_order(
&self,
market: &Market,
order_type: OrderType,
side: OrderSide,
price: f64,
quantity: f64,
) -> Result<Order> {
let order_id = self.create_order_id();
let order_account = Keypair::new();
let (token_a_account, token_b_account) = self.get_token_accounts(market).await?;
let order_data = NewOrderInstructionV3 {
side: side.into(),
limit_price: price,
max_qty: quantity,
order_type: order_type.into(),
client_order_id: 0,
self_trade_behavior: SelfTradeBehavior::DecrementTake,
limit: 65535,
max_coin_qty: quantity,
max_native_pc_qty_including_fees: price * quantity,
self_trade_behavior_v2: SelfTradeBehaviorV2::CancelProvide,
padding: [0; 5],
};
let accounts = match side {
OrderSide::Bid => vec![
AccountMeta::new(market.address, false),
AccountMeta::new(order_account.pubkey(), true),
AccountMeta::new(self.authority.pubkey(), true),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new(token_b_account, false),
AccountMeta::new(self.get_bids_address(&market)?, false),
AccountMeta::new(self.get_asks_address(&market)?, false),
AccountMeta::new(self.get_event_queue_address(&market)?, false),
AccountMeta::new(token_a_account, false),
AccountMeta::new_readonly(solana_sdk::sysvar::rent::ID, false),
],
OrderSide::Ask => vec![
AccountMeta::new(market.address, false),
AccountMeta::new(order_account.pubkey(), true),
AccountMeta::new(self.authority.pubkey(), true),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new(token_a_account, false),
AccountMeta::new(self.get_asks_address(&market)?, false),
AccountMeta::new(self.get_bids_address(&market)?, false),
AccountMeta::new(self.get_event_queue_address(&market)?, false),
AccountMeta::new(token_b_account, false),
AccountMeta::new_readonly(solana_sdk::sysvar::rent::ID, false),
],
};
let instruction = Instruction {
program_id: self.program_id,
accounts,
data: order_data.pack(),
};
let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&self.authority.pubkey()),
&[&self.authority, &order_account],
recent_blockhash,
);
self.rpc_client.send_and_confirm_transaction(&transaction)?;
Ok(Order {
id: order_id,
market: market.clone(),
order_type,
side,
price,
quantity,
status: OrderStatus::Open,
})
}
async fn cancel_order(&self, order: &Order) -> Result<()> {
let cancel_data = MarketInstruction::CancelOrderV2 {
side: order.side.into(),
order_id: order.id,
};
let accounts = vec![
AccountMeta::new(order.market.address, false),
AccountMeta::new_readonly(self.authority.pubkey(), true),
AccountMeta::new(self.get_bids_address(&order.market)?, false),
AccountMeta::new(self.get_asks_address(&order.market)?, false),
AccountMeta::new(self.get_event_queue_address(&order.market)?, false),
];
let instruction = Instruction {
program_id: self.program_id,
accounts,
data: cancel_data.pack(),
};
let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[instruction],
Some(&self.authority.pubkey()),
&[&self.authority],
recent_blockhash,
);
self.rpc_client.send_and_confirm_transaction(&transaction)?;
Ok(())
}
async fn get_balances(&self, market: &Market) -> Result<HashMap<Pubkey, f64>> {
let vault_signer = self.get_vault_signer_address(&market)?;
let base_vault = self.get_vault_address(&market, &market.base_asset)?;
let quote_vault = self.get_vault_address(&market, &market.quote_asset)?;
let base_vault_balance = self.rpc_client.get_token_account_balance(&base_vault)?;
let quote_vault_balance = self.rpc_client.get_token_account_balance(&quote_vault)?;
let mut balances = HashMap::new();
balances.insert(market.base_asset, base_vault_balance.amount as f64);
balances.insert(market.quote_asset, quote_vault_balance.amount as f64);
Ok(balances)
}
}
impl Serum {
fn create_order_id(&self) -> u64 {
rand::random()
}
async fn get_token_accounts(&self, market: &Market) -> Result<(Pubkey, Pubkey)> {
let token_a_account = spl_associated_token_account::get_associated_token_address(
&self.authority.pubkey(),
&market.base_asset,
);
let token_b_account = spl_associated_token_account::get_associated_token_address(
&self.authority.pubkey(),
&market.quote_asset,
);
Ok((token_a_account, token_b_account))
}
fn get_bids_address(&self, market: &Market) -> Result<Pubkey> {
let (bids_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
b"bids",
],
&self.program_id,
);
Ok(bids_address)
}
fn get_asks_address(&self, market: &Market) -> Result<Pubkey> {
let (asks_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
b"asks",
],
&self.program_id,
);
Ok(asks_address)
}
fn get_event_queue_address(&self, market: &Market) -> Result<Pubkey> {
let (event_queue_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
b"event_queue",
],
&self.program_id,
);
Ok(event_queue_address)
}
fn get_vault_signer_address(&self, market: &Market) -> Result<Pubkey> {
let (vault_signer_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
b"vault_signer",
],
&self.program_id,
);
Ok(vault_signer_address)
}
fn get_vault_address(&self, market: &Market, token_mint: &Pubkey) -> Result<Pubkey> {
let (vault_address, _) = Pubkey::find_program_address(
&[
&market.address.to_bytes(),
&token_mint.to_bytes(),
b"vault",
],
&spl_token::ID,
);
Ok(vault_address)
}
}

21
error.rs Normal file
View File

@ -0,0 +1,21 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum MevBotError {
#[error("Solana client error: {0}")]
SolanaClientError(#[from] solana_client::client_error::ClientError),
#[error("Reqwest error: {0}")]
ReqwestError(#[from] reqwest::Error),
#[error("JSON error: {0}")]
JsonError(#[from] serde_json::Error),
#[error("Decimal error: {0}")]
DecimalError(#[from] rust_decimal::Error),
#[error("Custom error: {0}")]
Custom(String),
}
pub type Result<T> = std::result::Result<T, MevBotError>;

42
libs.rs Normal file
View File

@ -0,0 +1,42 @@
//! # Solana MEV Bot
//!
//! Este bot está diseñado para aprovechar las oportunidades de MEV (Maximal Extractable Value)
//! en la red de Solana. El bot utiliza diversas estrategias, como sniping y copy trading,
//! para identificar y ejecutar transacciones rentables.
//!
//! ## Características principales
//!
//! - Integración con múltiples DEX (Raydium, Serum, Orca) para obtener precios y ejecutar transacciones
//! - Estrategias especializadas de sniping y copy trading para maximizar las ganancias
//! - Optimización avanzada del rendimiento y escalabilidad
//! - Monitoreo en tiempo real y dashboard para rastrear el rendimiento y las métricas clave
//! - Cobertura exhaustiva de pruebas y documentación detallada
//!
//! ## Uso
//!
//! Para utilizar el bot de Solana MEV, siga estos pasos:
//!
//! 1. Configure las credenciales y los parámetros en el archivo `config.toml`
//! 2. Ejecute el bot con `cargo run --release`
//! 3. Monitoree el rendimiento y las métricas a través del dashboard en tiempo real
//! 4. Ajuste las estrategias y los parámetros según sea necesario para optimizar las ganancias
//!
//! ## Contribución
//!
//! Si desea contribuir a este proyecto, siga estas pautas:
//!
//! 1. Abra un issue para discutir los cambios propuestos
//! 2. Haga fork del repositorio y cree una nueva rama para sus cambios
//! 3. Envíe un pull request con una descripción detallada de sus cambios y su propósito
//! 4. Asegúrese de que todos los tests pasen y de seguir las pautas de codificación establecidas
//!
//! ## Licencia
//!
//! Este proyecto está licenciado bajo los términos de la Licencia MIT. Consulte el archivo `LICENSE` para obtener más detalles.
//!
pub mod bot;
pub mod dex;
pub mod strategies;
pub mod models;
pub mod utils;

62
main.rs Normal file
View File

@ -0,0 +1,62 @@
use std::sync::Arc;
use mev_bot_solana::bot::solana_mev_bot::SolanaMevBot;
use mev_bot_solana::config::Config;
use mev_bot_solana::dex::dex_manager::DexManager;
use mev_bot_solana::monitoring::dashboard::Dashboard;
use mev_bot_solana::monitoring::metrics::Metrics;
use mev_bot_solana::strategies::copy_trade_strategy::CopyTradeStrategy;
use mev_bot_solana::strategies::sniping_strategy::SnipingStrategy;
use mev_bot_solana::utils::config_parser::parse_config;
use solana_client::rpc_client::RpcClient;
use solana_sdk::signature::read_keypair_file;
#[tokio::main]
async fn main() {
let config = parse_config("config.toml").expect("Failed to parse config");
let rpc_client = Arc::new(RpcClient::new_with_commitment(
config.solana.rpc_url.clone(),
config.solana.commitment.clone(),
));
let metrics = Arc::new(Metrics::new());
let dashboard = Dashboard::new(metrics.clone(), config.monitoring.update_interval);
let dex_manager = Arc::new(tokio::sync::Mutex::new(DexManager::new(
rpc_client.clone(),
config.dexes.clone(),
)));
let sniping_strategy = Arc::new(tokio::sync::Mutex::new(SnipingStrategy::new(
rpc_client.clone(),
dex_manager.clone(),
config.bot.max_position_size,
)));
let copy_trade_strategy = Arc::new(tokio::sync::Mutex::new(CopyTradeStrategy::new(
rpc_client.clone(),
dex_manager.clone(),
config.bot.max_position_size,
)));
let authority_keypair = read_keypair_file(config.bot.keypair_path.clone())
.expect("Failed to read keypair file");
let mut mev_bot = SolanaMevBot::new(
rpc_client,
authority_keypair,
vec![
sniping_strategy.clone(),
copy_trade_strategy.clone(),
],
config.bot.profit_threshold,
metrics,
);
tokio::spawn(async move {
dashboard.run().await;
});
mev_bot.run().await;
}

View File

@ -0,0 +1,9 @@
use crate::models::market::Market;
use crate::models::order::Order;
use solana_sdk::pubkey::Pubkey;
pub struct CopyTradeOpportunity {
pub trader: Pubkey,
pub market: Market,
pub trade: Order,
}

View File

@ -0,0 +1,7 @@
use solana_sdk::pubkey::Pubkey;
pub struct CopyTradeTarget {
pub trader_account: Pubkey,
pub target_token: Pubkey,
pub trade_amount: f64,
}

View File

@ -0,0 +1,9 @@
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct MarketConditions {
pub liquidity: f64,
pub volume: f64,
pub volatility: f64,
pub account_balances: HashMap<Pubkey, f64>,
}

View File

@ -0,0 +1,6 @@
use solana_sdk::transaction::Transaction;
pub struct MevOpportunity {
pub transactions: Vec<(Transaction, f64)>,
pub min_profit: f64,
}

3
models/mod.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod market_conditions;
pub mod mev_opportunity;
pub mod transaction_log;

View File

@ -0,0 +1,7 @@
use crate::models::market::Market;
pub struct SnipingOpportunity {
pub market: Market,
pub price: f64,
pub liquidity: f64,
}

View File

@ -0,0 +1,6 @@
use crate::models::market_conditions::MarketConditions;
pub struct TransactionLog {
pub signature: String,
pub market_conditions: MarketConditions,
}

37
monitoring/dashboard.rs Normal file
View File

@ -0,0 +1,37 @@
use crate::monitoring::metrics::Metrics;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time;
pub struct Dashboard {
pub metrics: Arc<Metrics>,
pub update_interval: u64,
}
impl Dashboard {
pub fn new(metrics: Arc<Metrics>, update_interval: u64) -> Self {
Dashboard {
metrics,
update_interval,
}
}
pub async fn run(&self) {
loop {
self.render().await;
time::sleep(time::Duration::from_secs(self.update_interval)).await;
}
}
async fn render(&self) {
let orders = self.metrics.get_orders().await;
let profits = self.metrics.get_profits().await;
let volumes = self.metrics.get_volumes().await;
println!("=== MEV Bot Dashboard ===");
println!("Total Orders: {}", orders.len());
println!("Total Profit: {:.2} SOL", profits.values().sum::<f64>());
println!("Total Volume: {:.2} SOL", volumes.values().sum::<f64>());
println!("==========================");
}
}

48
monitoring/metrics.rs Normal file
View File

@ -0,0 +1,48 @@
use crate::models::market::Market;
use crate::models::order::Order;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
pub struct Metrics {
pub orders: Arc<Mutex<Vec<Order>>>,
pub profits: Arc<Mutex<HashMap<Pubkey, f64>>>,
pub volumes: Arc<Mutex<HashMap<Market, f64>>>,
}
impl Metrics {
pub fn new() -> Self {
Metrics {
orders: Arc::new(Mutex::new(Vec::new())),
profits: Arc::new(Mutex::new(HashMap::new())),
volumes: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn add_order(&self, order: Order) {
self.orders.lock().await.push(order);
}
pub async fn update_profit(&self, market: &Market, profit: f64) {
let mut profits = self.profits.lock().await;
*profits.entry(market.address).or_insert(0.0) += profit;
}
pub async fn update_volume(&self, market: &Market, volume: f64) {
let mut volumes = self.volumes.lock().await;
*volumes.entry(market.clone()).or_insert(0.0) += volume;
}
pub async fn get_orders(&self) -> Vec<Order> {
self.orders.lock().await.clone()
}
pub async fn get_profits(&self) -> HashMap<Pubkey, f64> {
self.profits.lock().await.clone()
}
pub async fn get_volumes(&self) -> HashMap<Market, f64> {
self.volumes.lock().await.clone()
}
}

371
sha1.c
View File

@ -1,371 +0,0 @@
/*
* sha1.c
*
* Copyright (C) 1998, 2009
* Paul E. Jones <paulej@packetizer.com>
* All Rights Reserved
*
*****************************************************************************
* $Id: sha1.c 12 2009-06-22 19:34:25Z paulej $
*****************************************************************************
*
* Description:
* This file implements the Secure Hashing Standard as defined
* in FIPS PUB 180-1 published April 17, 1995.
*
* The Secure Hashing Standard, which uses the Secure Hashing
* Algorithm (SHA), produces a 160-bit message digest for a
* given data stream. In theory, it is highly improbable that
* two messages will produce the same message digest. Therefore,
* this algorithm can serve as a means of providing a "fingerprint"
* for a message.
*
* Portability Issues:
* SHA-1 is defined in terms of 32-bit "words". This code was
* written with the expectation that the processor has at least
* a 32-bit machine word size. If the machine word size is larger,
* the code should still function properly. One caveat to that
* is that the input functions taking characters and character
* arrays assume that only 8 bits of information are stored in each
* character.
*
* Caveats:
* SHA-1 is designed to work with messages less than 2^64 bits
* long. Although SHA-1 allows a message digest to be generated for
* messages of any number of bits less than 2^64, this
* implementation only works with messages with a length that is a
* multiple of the size of an 8-bit character.
*
*/
#include "sha1.h"
/*
* Define the circular shift macro
*/
#define SHA1CircularShift(bits,word) \
((((word) << (bits)) & 0xFFFFFFFF) | \
((word) >> (32-(bits))))
/* Function prototypes */
void SHA1ProcessMessageBlock(SHA1Context *);
void SHA1PadMessage(SHA1Context *);
/*
* SHA1Reset
*
* Description:
* This function will initialize the SHA1Context in preparation
* for computing a new message digest.
*
* Parameters:
* context: [in/out]
* The context to reset.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1Reset(SHA1Context *context)
{
context->Length_Low = 0;
context->Length_High = 0;
context->Message_Block_Index = 0;
context->Message_Digest[0] = 0x67452301;
context->Message_Digest[1] = 0xEFCDAB89;
context->Message_Digest[2] = 0x98BADCFE;
context->Message_Digest[3] = 0x10325476;
context->Message_Digest[4] = 0xC3D2E1F0;
context->Computed = 0;
context->Corrupted = 0;
}
/*
* SHA1Result
*
* Description:
* This function will return the 160-bit message digest into the
* Message_Digest array within the SHA1Context provided
*
* Parameters:
* context: [in/out]
* The context to use to calculate the SHA-1 hash.
*
* Returns:
* 1 if successful, 0 if it failed.
*
* Comments:
*
*/
int SHA1Result(SHA1Context *context)
{
if (context->Corrupted)
{
return 0;
}
if (!context->Computed)
{
SHA1PadMessage(context);
context->Computed = 1;
}
return 1;
}
/*
* SHA1Input
*
* Description:
* This function accepts an array of octets as the next portion of
* the message.
*
* Parameters:
* context: [in/out]
* The SHA-1 context to update
* message_array: [in]
* An array of characters representing the next portion of the
* message.
* length: [in]
* The length of the message in message_array
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1Input( SHA1Context *context,
const unsigned char *message_array,
unsigned length)
{
if (!length)
{
return;
}
if (context->Computed || context->Corrupted)
{
context->Corrupted = 1;
return;
}
while(length-- && !context->Corrupted)
{
context->Message_Block[context->Message_Block_Index++] =
(*message_array & 0xFF);
context->Length_Low += 8;
/* Force it to 32 bits */
context->Length_Low &= 0xFFFFFFFF;
if (context->Length_Low == 0)
{
context->Length_High++;
/* Force it to 32 bits */
context->Length_High &= 0xFFFFFFFF;
if (context->Length_High == 0)
{
/* Message is too long */
context->Corrupted = 1;
}
}
if (context->Message_Block_Index == 64)
{
SHA1ProcessMessageBlock(context);
}
message_array++;
}
}
/*
* SHA1ProcessMessageBlock
*
* Description:
* This function will process the next 512 bits of the message
* stored in the Message_Block array.
*
* Parameters:
* None.
*
* Returns:
* Nothing.
*
* Comments:
* Many of the variable names in the SHAContext, especially the
* single character names, were used because those were the names
* used in the publication.
*
*
*/
void SHA1ProcessMessageBlock(SHA1Context *context)
{
const unsigned K[] = /* Constants defined in SHA-1 */
{
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6
};
int t; /* Loop counter */
unsigned temp; /* Temporary word value */
unsigned W[80]; /* Word sequence */
unsigned A, B, C, D, E; /* Word buffers */
/*
* Initialize the first 16 words in the array W
*/
for(t = 0; t < 16; t++)
{
W[t] = ((unsigned) context->Message_Block[t * 4]) << 24;
W[t] |= ((unsigned) context->Message_Block[t * 4 + 1]) << 16;
W[t] |= ((unsigned) context->Message_Block[t * 4 + 2]) << 8;
W[t] |= ((unsigned) context->Message_Block[t * 4 + 3]);
}
for(t = 16; t < 80; t++)
{
W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
}
A = context->Message_Digest[0];
B = context->Message_Digest[1];
C = context->Message_Digest[2];
D = context->Message_Digest[3];
E = context->Message_Digest[4];
for(t = 0; t < 20; t++)
{
temp = SHA1CircularShift(5,A) +
((B & C) | ((~B) & D)) + E + W[t] + K[0];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
for(t = 20; t < 40; t++)
{
temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
for(t = 40; t < 60; t++)
{
temp = SHA1CircularShift(5,A) +
((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
for(t = 60; t < 80; t++)
{
temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = SHA1CircularShift(30,B);
B = A;
A = temp;
}
context->Message_Digest[0] =
(context->Message_Digest[0] + A) & 0xFFFFFFFF;
context->Message_Digest[1] =
(context->Message_Digest[1] + B) & 0xFFFFFFFF;
context->Message_Digest[2] =
(context->Message_Digest[2] + C) & 0xFFFFFFFF;
context->Message_Digest[3] =
(context->Message_Digest[3] + D) & 0xFFFFFFFF;
context->Message_Digest[4] =
(context->Message_Digest[4] + E) & 0xFFFFFFFF;
context->Message_Block_Index = 0;
}
/*
* SHA1PadMessage
*
* Description:
* According to the standard, the message must be padded to an even
* 512 bits. The first padding bit must be a '1'. The last 64
* bits represent the length of the original message. All bits in
* between should be 0. This function will pad the message
* according to those rules by filling the Message_Block array
* accordingly. It will also call SHA1ProcessMessageBlock()
* appropriately. When it returns, it can be assumed that the
* message digest has been computed.
*
* Parameters:
* context: [in/out]
* The context to pad
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1PadMessage(SHA1Context *context)
{
/*
* Check to see if the current message block is too small to hold
* the initial padding bits and length. If so, we will pad the
* block, process it, and then continue padding into a second
* block.
*/
if (context->Message_Block_Index > 55)
{
context->Message_Block[context->Message_Block_Index++] = 0x80;
while(context->Message_Block_Index < 64)
{
context->Message_Block[context->Message_Block_Index++] = 0;
}
SHA1ProcessMessageBlock(context);
while(context->Message_Block_Index < 56)
{
context->Message_Block[context->Message_Block_Index++] = 0;
}
}
else
{
context->Message_Block[context->Message_Block_Index++] = 0x80;
while(context->Message_Block_Index < 56)
{
context->Message_Block[context->Message_Block_Index++] = 0;
}
}
/*
* Store the message length as the last 8 octets
*/
context->Message_Block[56] = (context->Length_High >> 24) & 0xFF;
context->Message_Block[57] = (context->Length_High >> 16) & 0xFF;
context->Message_Block[58] = (context->Length_High >> 8) & 0xFF;
context->Message_Block[59] = (context->Length_High) & 0xFF;
context->Message_Block[60] = (context->Length_Low >> 24) & 0xFF;
context->Message_Block[61] = (context->Length_Low >> 16) & 0xFF;
context->Message_Block[62] = (context->Length_Low >> 8) & 0xFF;
context->Message_Block[63] = (context->Length_Low) & 0xFF;
SHA1ProcessMessageBlock(context);
}

54
sha1.h
View File

@ -1,54 +0,0 @@
/*
* sha1.h
*
* Copyright (C) 1998, 2009
* Paul E. Jones <paulej@packetizer.com>
* All Rights Reserved
*
*****************************************************************************
* $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $
*****************************************************************************
*
* Description:
* This class implements the Secure Hashing Standard as defined
* in FIPS PUB 180-1 published April 17, 1995.
*
* Many of the variable names in the SHA1Context, especially the
* single character names, were used because those were the names
* used in the publication.
*
* Please read the file sha1.c for more information.
*
*/
#ifndef _SHA1_H_
#define _SHA1_H_
/*
* This structure will hold context information for the hashing
* operation
*/
typedef struct SHA1Context
{
unsigned Message_Digest[5]; /* Message Digest (output) */
unsigned Length_Low; /* Message length in bits */
unsigned Length_High; /* Message length in bits */
unsigned char Message_Block[64]; /* 512-bit message blocks */
int Message_Block_Index; /* Index into message block array */
int Computed; /* Is the digest computed? */
int Corrupted; /* Is the message digest corruped? */
} SHA1Context;
/*
* Function Prototypes
*/
void SHA1Reset(SHA1Context *);
int SHA1Result(SHA1Context *);
void SHA1Input( SHA1Context *,
const unsigned char *,
unsigned);
#endif

17
strategies/arbitrage.rs Normal file
View File

@ -0,0 +1,17 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use crate::strategies::strategy::Strategy;
use async_trait::async_trait;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct ArbitrageStrategy {}
#[async_trait]
impl Strategy for ArbitrageStrategy {
fn update(&mut self, _market_conditions: &MarketConditions) {}
async fn find_opportunities(&self, _target_accounts: &HashMap<Pubkey, crate::AccountInfo>) -> Vec<MevOpportunity> {
Vec::new()
}
}

View File

@ -0,0 +1,117 @@
use crate::dex::dex_manager::DexManager;
use crate::models::market_conditions::MarketConditions;
use crate::models::arbitrage_opportunity::ArbitrageOpportunity;
use crate::strategies::strategy::Strategy;
use crate::utils::math;
use async_trait::async_trait;
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct ArbitrageStrategy {
pub rpc_client: RpcClient,
pub dex_manager: DexManager,
pub min_profit_threshold: f64,
}
impl ArbitrageStrategy {
pub fn new(rpc_client: RpcClient, dex_manager: DexManager, min_profit_threshold: f64) -> Self {
ArbitrageStrategy {
rpc_client,
dex_manager,
min_profit_threshold,
}
}
pub async fn find_arbitrage_opportunities(&self, market_conditions: &MarketConditions) -> Vec<ArbitrageOpportunity> {
let mut opportunities = Vec::new();
let token_prices = market_conditions.token_prices.clone();
let token_pairs = self.generate_token_pairs(&token_prices);
for (token_a, token_b) in token_pairs {
if let Some(opportunity) = self.find_arbitrage_opportunity(token_a, token_b, &token_prices).await {
if opportunity.expected_profit >= self.min_profit_threshold {
opportunities.push(opportunity);
}
}
}
opportunities
}
async fn find_arbitrage_opportunity(&self, token_a: &str, token_b: &str, token_prices: &HashMap<String, f64>) -> Option<ArbitrageOpportunity> {
let mut best_opportunity: Option<ArbitrageOpportunity> = None;
if let Some(price_a_b) = token_prices.get(&format!("{}/{}", token_a, token_b)) {
if let Some(price_b_a) = token_prices.get(&format!("{}/{}", token_b, token_a)) {
let forward_amount = 1.0;
let forward_price = price_a_b;
let backward_amount = forward_amount * forward_price;
let backward_price = price_b_a;
let forward_trade = self.dex_manager.get_best_trade_route(token_a, token_b, forward_amount).await;
let backward_trade = self.dex_manager.get_best_trade_route(token_b, token_a, backward_amount).await;
if let (Some(forward_trade), Some(backward_trade)) = (forward_trade, backward_trade) {
let forward_amount_received = math::checked_div(forward_amount, forward_trade.price).unwrap_or(0.0);
let backward_amount_received = math::checked_mul(backward_trade.received_amount, backward_price).unwrap_or(0.0);
let expected_profit = backward_amount_received - forward_amount;
if expected_profit > 0.0 {
best_opportunity = Some(ArbitrageOpportunity {
token_a: token_a.to_string(),
token_b: token_b.to_string(),
forward_trade,
backward_trade,
expected_profit,
});
}
}
}
}
best_opportunity
}
fn generate_token_pairs(&self, token_prices: &HashMap<String, f64>) -> Vec<(String, String)> {
let mut pairs = Vec::new();
for (token_a, _) in token_prices {
for (token_b, _) in token_prices {
if token_a != token_b {
pairs.push((token_a.clone(), token_b.clone()));
}
}
}
pairs
}
}
#[async_trait]
impl Strategy for ArbitrageStrategy {
async fn find_opportunities(&self, market_conditions: &MarketConditions) -> Vec<ArbitrageOpportunity> {
self.find_arbitrage_opportunities(market_conditions).await
}
async fn execute_opportunities(&self, opportunities: &[ArbitrageOpportunity]) {
for opportunity in opportunities {
let forward_trade = &opportunity.forward_trade;
let backward_trade = &opportunity.backward_trade;
let forward_result = self.dex_manager.execute_trade(forward_trade).await;
if forward_result.is_ok() {
let backward_result = self.dex_manager.execute_trade(backward_trade).await;
if backward_result.is_ok() {
// Log successful arbitrage execution
} else {
// Log backward trade failure
}
} else {
// Log forward trade failure
}
}
}
}

View File

@ -0,0 +1,153 @@
use crate::dex::dex_manager::DexManager;
use crate::error::Result;
use crate::models::copy_trade_opportunity::CopyTradeOpportunity;
use crate::models::market::Market;
use crate::models::order::Order;
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::Keypair;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
pub struct CopyTradeStrategy {
pub rpc_client: Arc<RpcClient>,
pub dex_manager: Arc<Mutex<DexManager>>,
pub tracked_traders: Vec<Pubkey>,
pub trade_threshold: f64,
pub max_trade_amount: f64,
}
impl CopyTradeStrategy {
pub fn new(
rpc_client: Arc<RpcClient>,
dex_manager: Arc<Mutex<DexManager>>,
tracked_traders: Vec<Pubkey>,
trade_threshold: f64,
max_trade_amount: f64,
) -> Self {
CopyTradeStrategy {
rpc_client,
dex_manager,
tracked_traders,
trade_threshold,
max_trade_amount,
}
}
pub async fn run(&self) -> Result<()> {
loop {
let opportunities = self.find_opportunities().await?;
for opportunity in opportunities {
self.execute_copy_trade(&opportunity).await?;
}
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}
}
async fn find_opportunities(&self) -> Result<Vec<CopyTradeOpportunity>> {
let mut opportunities = Vec::new();
for trader in &self.tracked_traders {
let trades = self.get_recent_trades(trader).await?;
for trade in trades {
if trade.quantity >= self.trade_threshold && trade.quantity <= self.max_trade_amount {
let market = self.dex_manager.lock().await.get_market(&trade.market).await?;
let opportunity = CopyTradeOpportunity {
trader: *trader,
market,
trade,
};
opportunities.push(opportunity);
}
}
}
Ok(opportunities)
}
async fn get_recent_trades(&self, trader: &Pubkey) -> Result<Vec<Order>> {
let signature_infos = self.rpc_client.get_signatures_for_address(trader)?;
let mut trades = Vec::new();
for signature_info in signature_infos {
if let Some(signature) = signature_info.signature {
let transaction = self.rpc_client.get_transaction(&signature)?;
if let Some(transaction) = transaction {
for instruction in transaction.transaction.message.instructions {
if let Some(dex_instruction) = DexInstruction::unpack(instruction) {
match dex_instruction {
DexInstruction::NewOrder { .. } => {
let order = self.parse_order(&transaction, &instruction)?;
trades.push(order);
}
_ => {}
}
}
}
}
}
}
Ok(trades)
}
fn parse_order(&self, transaction: &TransactionInfo, instruction: &CompiledInstruction) -> Result<Order> {
let market_address = instruction.accounts[0];
let market = self.dex_manager.lock().await.get_market(&market_address).await?;
let side = match instruction.data[0] {
0 => OrderSide::Bid,
1 => OrderSide::Ask,
_ => return Err(anyhow!("Invalid order side")),
};
let order_type = match instruction.data[1] {
0 => OrderType::Limit,
1 => OrderType::ImmediateOrCancel,
2 => OrderType::PostOnly,
_ => return Err(anyhow!("Invalid order type")),
};
let price = f64::from_le_bytes(instruction.data[2..10].try_into()?);
let quantity = f64::from_le_bytes(instruction.data[10..18].try_into()?);
Ok(Order {
id: transaction.transaction.signatures[0].to_string(),
market,
side,
order_type,
price,
quantity,
status: OrderStatus::Filled,
})
}
async fn execute_copy_trade(&self, opportunity: &CopyTradeOpportunity) -> Result<()> {
let market = &opportunity.market;
let trade = &opportunity.trade;
let order = self
.dex_manager
.lock()
.await
.place_order(market, trade.order_type, trade.side, trade
async fn execute_copy_trade(&self, opportunity: &CopyTradeOpportunity) -> Result<()> {
let market = &opportunity.market;
let trade = &opportunity.trade;
let order = self
.dex_manager
.lock()
.await
.place_order(market, trade.order_type, trade.side, trade.price, trade.quantity)
.await?;
println!("Placed copy trade order: {:?}", order);
Ok(())
}

17
strategies/liquidation.rs Normal file
View File

@ -0,0 +1,17 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use crate::strategies::strategy::Strategy;
use async_trait::async_trait;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct LiquidationStrategy {}
#[async_trait]
impl Strategy for LiquidationStrategy {
fn update(&mut self, _market_conditions: &MarketConditions) {}
async fn find_opportunities(&self, _target_accounts: &HashMap<Pubkey, crate::AccountInfo>) -> Vec<MevOpportunity> {
Vec::new()
}
}

4
strategies/mod.rs Normal file
View File

@ -0,0 +1,4 @@
pub mod strategy;
pub mod arbitrage;
pub mod liquidation;
pub mod sandwich;

17
strategies/sandwich.rs Normal file
View File

@ -0,0 +1,17 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use crate::strategies::strategy::Strategy;
use async_trait::async_trait;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
pub struct SandwichStrategy {}
#[async_trait]
impl Strategy for SandwichStrategy {
fn update(&mut self, _market_conditions: &MarketConditions) {}
async fn find_opportunities(&self, _target_accounts: &HashMap<Pubkey, crate::AccountInfo>) -> Vec<MevOpportunity> {
Vec::new()
}
}

View File

@ -0,0 +1,119 @@
use crate::dex::dex_manager::DexManager;
use crate::error::Result;
use crate::models::market::Market;
use crate::models::sniping_opportunity::SnipingOpportunity;
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use std::sync::Arc;
use tokio::sync::Mutex;
pub struct SnipingStrategy {
pub rpc_client: Arc<RpcClient>,
pub dex_manager: Arc<Mutex<DexManager>>,
pub target_markets: Vec<Pubkey>,
pub max_price: f64,
pub min_liquidity: f64,
}
impl SnipingStrategy {
pub fn new(
rpc_client: Arc<RpcClient>,
dex_manager: Arc<Mutex<DexManager>>,
target_markets: Vec<Pubkey>,
max_price: f64,
min_liquidity: f64,
) -> Self {
SnipingStrategy {
rpc_client,
dex_manager,
target_markets,
max_price,
min_liquidity,
}
}
pub async fn run(&self) -> Result<()> {
loop {
let markets = self.get_target_markets().await?;
let opportunities = self.find_opportunities(&markets).await?;
for opportunity in opportunities {
self.execute_sniping(&opportunity).await?;
}
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}
}
async fn get_target_markets(&self) -> Result<Vec<Market>> {
let mut markets = Vec::new();
for market_address in &self.target_markets {
let market = self.dex_manager.lock().await.get_market(market_address).await?;
markets.push(market);
}
Ok(markets)
}
async fn find_opportunities(&self, markets: &[Market]) -> Result<Vec<SnipingOpportunity>> {
let mut opportunities = Vec::new();
for market in markets {
let orderbook = self.dex_manager.lock().await.get_orderbook(market).await?;
if let Some(best_bid) = orderbook.bids.first() {
if best_bid.price <= self.max_price {
let liquidity = self.calculate_liquidity(market, &orderbook).await?;
if liquidity >= self.min_liquidity {
let opportunity = SnipingOpportunity {
market: market.clone(),
price: best_bid.price,
liquidity,
};
opportunities.push(opportunity);
}
}
}
}
Ok(opportunities)
}
async fn calculate_liquidity(&self, market: &Market, orderbook: &Orderbook) -> Result<f64> {
let bids_volume = orderbook.bids.iter().map(|order| order.quantity).sum();
let asks_volume = orderbook.asks.iter().map(|order| order.quantity).sum();
let mid_price = (orderbook.bids[0].price + orderbook.asks[0].price) / 2.0;
let base_volume = bids_volume + asks_volume;
let quote_volume = base_volume * mid_price;
let base_decimals = market.base_decimals;
let quote_decimals = market.quote_decimals;
let liquidity = base_volume / 10_usize.pow(base_decimals as u32) as f64
+ quote_volume / 10_usize.pow(quote_decimals as u32) as f64;
Ok(liquidity)
}
async fn execute_sniping(&self, opportunity: &SnipingOpportunity) -> Result<()> {
let market = &opportunity.market;
let price = opportunity.price;
let quantity = opportunity.liquidity / price;
let order = self
.dex_manager
.lock()
.await
.place_order(market, OrderType::Limit, OrderSide::Bid, price, quantity)
.await?;
println!("Placed sniping order: {:?}", order);
Ok(())
}
}

11
strategies/strategy.rs Normal file
View File

@ -0,0 +1,11 @@
use crate::models::market_conditions::MarketConditions;
use crate::models::mev_opportunity::MevOpportunity;
use async_trait::async_trait;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
#[async_trait]
pub trait Strategy {
fn update(&mut self, market_conditions: &MarketConditions);
async fn find_opportunities(&self, target_accounts: &HashMap<Pubkey, crate::AccountInfo>) -> Vec<MevOpportunity>;
}

55
test.c
View File

@ -1,55 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <wsclient/wsclient.h>
int onclose(wsclient *c) {
fprintf(stderr, "onclose called: %d\n", c->sockfd);
return 0;
}
int onerror(wsclient *c, wsclient_error *err) {
fprintf(stderr, "onerror: (%d): %s\n", err->code, err->str);
if(err->extra_code) {
errno = err->extra_code;
perror("recv");
}
return 0;
}
int onmessage(wsclient *c, wsclient_message *msg) {
fprintf(stderr, "onmessage: (%llu): %s\n", msg->payload_len, msg->payload);
return 0;
}
int onopen(wsclient *c) {
fprintf(stderr, "onopen called: %d\n", c->sockfd);
libwsclient_send(c, "Hello onopen");
return 0;
}
int main(int argc, char **argv) {
//Initialize new wsclient * using specified URI
wsclient *client = libwsclient_new("ws://echo.websocket.org");
if(!client) {
fprintf(stderr, "Unable to initialize new WS client.\n");
exit(1);
}
//set callback functions for this client
libwsclient_onopen(client, &onopen);
libwsclient_onmessage(client, &onmessage);
libwsclient_onerror(client, &onerror);
libwsclient_onclose(client, &onclose);
//bind helper UNIX socket to "test.sock"
//One can then use netcat (nc) to send data to the websocket server end on behalf of the client, like so:
// $> echo -n "some data that will be echoed by echo.websocket.org" | nc -U test.sock
libwsclient_helper_socket(client, "test.sock");
//starts run thread.
libwsclient_run(client);
//blocks until run thread for client is done.
libwsclient_finish(client);
return 0;
}

View File

@ -0,0 +1,26 @@
use crate::bot::strategies::copy_trade_strategy::CopyTradeStrategy;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
#[tokio::test]
async fn test_copy_trade_strategy() {
let rpc_client = solana_client::rpc_client::RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
let mut strategy = CopyTradeStrategy::new(rpc_client);
strategy.set_trade_threshold(1000.0);
strategy.set_max_trade_amount(10000.0);
let trader_account = Pubkey::new_unique();
let mut target_accounts = HashMap::new();
target_accounts.insert(trader_account, crate::AccountInfo {
token_balance: 0.0,
token_price: 0.0,
});
let targets = strategy.find_opportunities(&target_accounts).await;
assert_eq!(targets.len(), 1);
let target = &targets[0];
assert_eq!(target.trader_account, trader_account);
assert_eq!(target.trade_amount, 5000.0);
}

View File

@ -0,0 +1,68 @@
use mev_bot_solana::bot::solana_mev_bot::SolanaMevBot;
use mev_bot_solana::config::Config;
use mev_bot_solana::dex::dex_manager::DexManager;
use mev_bot_solana::monitoring::metrics::Metrics;
use mev_bot_solana::strategies::copy_trade_strategy::CopyTradeStrategy;
use mev_bot_solana::strategies::sniping_strategy::SnipingStrategy;
use mev_bot_solana::utils::config_parser::parse_config;
use solana_client::rpc_client::RpcClient;
use solana_sdk::signature::read_keypair_file;
use std::sync::Arc;
#[tokio::test]
async fn test_mev_bot_integration() {
let config = parse_config("config.toml").expect("Failed to parse config");
let rpc_client = Arc::new(RpcClient::new_with_commitment(
config.solana.rpc_url.clone(),
config.solana.commitment.clone(),
));
let metrics = Arc::new(Metrics::new());
let dex_manager = Arc::new(tokio::sync::Mutex::new(DexManager::new(
rpc_client.clone(),
config.dexes.clone(),
)));
let sniping_strategy = Arc::new(tokio::sync::Mutex::new(SnipingStrategy::new(
rpc_client.clone(),
dex_manager.clone(),
config.bot.max_position_size,
)));
let copy_trade_strategy = Arc::new(tokio::sync::Mutex::new(CopyTradeStrategy::new(
rpc_client.clone(),
dex_manager.clone(),
config.bot.max_position_size,
)));
let authority_keypair = read_keypair_file(config.bot.keypair_path.clone())
.expect("Failed to read keypair file");
let mut mev_bot = SolanaMevBot::new(
rpc_client,
authority_keypair,
vec![
sniping_strategy.clone(),
copy_trade_strategy.clone(),
],
config.bot.profit_threshold,
metrics,
);
tokio::spawn(async move {
mev_bot.run().await;
});
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
let orders = mev_bot.metrics.get_orders().await;
assert!(!orders.is_empty());
let profits = mev_bot.metrics.get_profits().await;
assert!(!profits.is_empty());
let volumes = mev_bot.metrics.get_volumes().await;
assert!(!volumes.is_empty());
}

29
tests/sniping_strategy.rs Normal file
View File

@ -0,0 +1,29 @@
use crate::bot::strategies::sniping_strategy::SnipingStrategy;
use solana_sdk::pubkey::Pubkey;
use std::collections::HashMap;
#[tokio::test]
async fn test_sniping_strategy() {
let rpc_client = solana_client::rpc_client::RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
let mut strategy = SnipingStrategy::new(rpc_client);
let token_mint = Pubkey::new_unique();
strategy.add_target_token(token_mint);
strategy.set_max_price(10.0);
strategy.set_min_liquidity(1000.0);
let mut target_accounts = HashMap::new();
target_accounts.insert(token_mint, crate::AccountInfo {
token_balance: 5000.0,
token_price: 8.0,
});
let opportunities = strategy.find_opportunities(&target_accounts).await;
assert_eq!(opportunities.len(), 1);
let opportunity = &opportunities[0];
assert_eq!(opportunity.target_account, token_mint);
assert_eq!(opportunity.token_mint, token_mint);
assert_eq!(opportunity.expected_price, 8.0);
assert_eq!(opportunity.token_balance, 5000.0);
}

40
tests/solana_mev_bot.rs Normal file
View File

@ -0,0 +1,40 @@
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
use solana_mev_bot::bot::solana_mev_bot::SolanaMevBot;
use solana_mev_bot::dex::{raydium, serum, orca};
use solana_mev_bot::strategies::{sniping_strategy, copy_trade_strategy};
use solana_mev_bot::utils::solana;
#[tokio::test]
async fn test_solana_mev_bot() {
let rpc_url = "https://api.devnet.solana.com";
let ws_url = "wss://api.devnet.solana.com";
let payer_keypair = solana::load_keypair("path/to/keypair.json");
let target_accounts = HashMap::new();
let profit_threshold = 0.01;
let rpc_client = Arc::new(solana_client::rpc_client::RpcClient::new_with_commitment(
rpc_url.to_string(),
solana_sdk::commitment_config::CommitmentConfig::confirmed(),
));
let mut solana_mev_bot = SolanaMevBot::new(
rpc_client.clone(),
ws_url.to_string(),
payer_keypair,
target_accounts,
profit_threshold,
vec![
Arc::new(Mutex::new(raydium::Raydium::new(rpc_client.clone()))),
Arc::new(Mutex::new(serum::Serum::new(rpc_client.clone()))),
Arc::new(Mutex::new(orca::Orca::new(rpc_client.clone()))),
],
Arc::new(Mutex::new(sniping_strategy::SnipingStrategy::new(rpc_client.clone()))),
Arc::new(Mutex::new(copy_trade_strategy::CopyTradeStrategy::new(rpc_client.clone()))),
);
let result = solana_mev_bot.run().await;
assert!(result.is_ok());
}

30
utils/api.rs Normal file
View File

@ -0,0 +1,30 @@
use crate::api::parsec::ParsecApi;
use crate::api::flipside::FlipsideApi;
use crate::api::thegraph::TheGraphApi;
pub async fn get_sniping_data(parsec_api: &ParsecApi, flipside_api: &FlipsideApi) -> Result<crate::models::sniping_data::SnipingData, Box<dyn std::error::Error>> {
let token_prices = parsec_api.get_token_prices().await?;
let mut sniping_data = crate::models::sniping_data::SnipingData {
token_prices,
token_volumes: HashMap::new(),
};
for token_mint in token_prices.keys() {
let token_volume = flipside_api.get_token_volume(token_mint).await?;
sniping_data.token_volumes.insert(token_mint.to_string(), token_volume);
}
Ok(sniping_data)
}
pub async fn get_copy_trade_data(thegraph_api: &TheGraphApi, trader_accounts: &[String]) -> Result<Vec<crate::models::trade::Trade>, Box<dyn std::error::Error>> {
let mut all_trades = Vec::new();
for trader_account in trader_accounts {
let trades = thegraph_api.get_trader_transactions(trader_account).await?;
all_trades.extend(trades);
}
Ok(all_trades)
}

12
utils/config_parser.rs Normal file
View File

@ -0,0 +1,12 @@
use crate::config::Config;
use anyhow::Result;
use std::fs::File;
use std::io::Read;
pub fn parse_config(path: &str) -> Result<Config> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let config: Config = toml::from_str(&contents)?;
Ok(config)
}

30
utils/data_sources.rs Normal file
View File

@ -0,0 +1,30 @@
use crate::error::Result;
use reqwest::Client;
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
pub struct PriceData {
pub symbol: String,
pub price: f64,
}
pub async fn fetch_prices_from_coingecko(symbols: &[String]) -> Result<HashMap<String, f64>> {
let url = format!(
"https://api.coingecko.com/api/v3/simple/price?ids={}&vs_currencies=usd",
symbols.join(",")
);
let client = Client::new();
let response = client.get(&url).send().await?;
let prices: HashMap<String, HashMap<String, f64>> = response.json().await?;
let mut price_map = HashMap::new();
for (symbol, price_data) in prices {
if let Some(price) = price_data.get("usd") {
price_map.insert(symbol, *price);
}
}
Ok(price_map)
}

11
utils/keypair.rs Normal file
View File

@ -0,0 +1,11 @@
use anyhow::Result;
use solana_sdk::signature::Keypair;
use std::fs::File;
use std::io::BufReader;
pub fn read_keypair_file(path: &str) -> Result<Keypair> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let keypair = Keypair::from_bytes(&serde_json::from_reader(reader)?)?;
Ok(keypair)
}

1
utils/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod solana;

View File

@ -0,0 +1,20 @@
use crate::error::Result;
use crate::models::market::Market;
use crate::models::order::{Order, OrderSide};
use rust_decimal::Decimal;
pub fn calculate_profit(market: &Market, buy_order: &Order, sell_order: &Order) -> Result<f64> {
if buy_order.side != OrderSide::Bid || sell_order.side != OrderSide::Ask {
return Err(anyhow!("Invalid order sides for profit calculation"));
}
let buy_price = Decimal::from_f64(buy_order.price).ok_or_else(|| anyhow!("Invalid buy price"))?;
let sell_price = Decimal::from_f64(sell_order.price).ok_or_else(|| anyhow!("Invalid sell price"))?;
let quantity = Decimal::from_f64(buy_order.quantity).ok_or_else(|| anyhow!("Invalid quantity"))?;
let buy_value = buy_price * quantity;
let sell_value = sell_price * quantity;
let profit = sell_value - buy_value;
Ok(profit.to_f64().ok_or_else(|| anyhow!("Failed to convert profit to f64"))?)
}

46
utils/solana.rs Normal file
View File

@ -0,0 +1,46 @@
use solana_sdk::transaction::Transaction;
use std::error::Error;
pub fn analyze_transaction(transaction: &Transaction) -> Result<crate::models::transaction_analysis::TransactionAnalysis, Box<dyn Error>> {
let mut analysis = crate::models::transaction_analysis::TransactionAnalysis::default();
analysis.signature = transaction.signatures[0].to_string();
analysis.num_instructions = transaction.message.instructions.len() as u64;
for (index, instruction) in transaction.message.instructions.iter().enumerate() {
let account_metas = &instruction.accounts;
let num_accounts = account_metas.len() as u64;
let program_id = &instruction.program_id;
analysis.instructions.push(crate::models::transaction_analysis::InstructionAnalysis {
index: index as u64,
num_accounts,
program_id: program_id.to_string(),
});
}
Ok(analysis)
}
pub fn calculate_profit(transaction: &Transaction) -> Result<f64, Box<dyn Error>> {
let mut profit = 0.0;
for (index, instruction) in transaction.message.instructions.iter().enumerate() {
let account_metas = &instruction.accounts;
if let Some(transfer_instruction) = instruction.program_id(&spl_token::ID) {
if let Ok(transfer_amount) = spl_token::instruction::unpack_amount(transfer_instruction.data) {
let from_account = &account_metas[0];
let to_account = &account_metas[1];
if from_account.is_signer {
profit -= transfer_amount as f64;
} else if to_account.is_signer {
profit += transfer_amount as f64;
}
}
}
}
Ok(profit)
}

View File

@ -0,0 +1,25 @@
use crate::error::Result;
use solana_sdk::instruction::Instruction;
use solana_sdk::transaction::Transaction;
pub fn get_instruction_data(transaction: &Transaction, program_id: &Pubkey) -> Result<Vec<u8>> {
let instruction = transaction
.message
.instructions
.iter()
.find(|ix| ix.program_id == *program_id)
.ok_or_else(|| anyhow!("Instruction not found for program ID: {}", program_id))?;
Ok(instruction.data.clone())
}
pub fn get_instruction_accounts(transaction: &Transaction, program_id: &Pubkey) -> Result<Vec<Pubkey>> {
let instruction = transaction
.message
.instructions
.iter()
.find(|ix| ix.program_id == *program_id)
.ok_or_else(|| anyhow!("Instruction not found for program ID: {}", program_id))?;
Ok(instruction.accounts.iter().map(|account| account.pubkey).collect())
}

1084
wsclient.c

File diff suppressed because it is too large Load Diff

View File

@ -1,167 +0,0 @@
#ifndef WSCLIENT_H_
#define WSCLIENT_H_
#include <stdint.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <stddef.h>
#include "config.h"
#ifdef HAVE_LIBSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#endif
#define FRAME_CHUNK_LENGTH 1024
#define HELPER_RECV_BUF_SIZE 1024
#define CLIENT_IS_SSL (1 << 0)
#define CLIENT_CONNECTING (1 << 1)
#define CLIENT_SHOULD_CLOSE (1 << 2)
#define CLIENT_SENT_CLOSE_FRAME (1 << 3)
#define REQUEST_HAS_CONNECTION (1 << 0)
#define REQUEST_HAS_UPGRADE (1 << 1)
#define REQUEST_VALID_STATUS (1 << 2)
#define REQUEST_VALID_ACCEPT (1 << 3)
#define WS_FRAGMENT_START (1 << 0)
#define WS_FRAGMENT_FIN (1 << 7)
#define WS_FLAGS_SSL_INIT (1 << 0)
#define WS_EXIT_MALLOC -1
#define WS_EXIT_PTHREAD_MUTEX_INIT -2
#define WS_EXIT_PTHREAD_CREATE -3
#define WS_EXIT_BAD_SCHEME -4
#define WS_OPEN_CONNECTION_ADDRINFO_ERR -1
#define WS_OPEN_CONNECTION_ADDRINFO_EXHAUSTED_ERR -2
#define WS_RUN_THREAD_RECV_ERR -3
#define WS_DO_CLOSE_SEND_ERR -4
#define WS_HANDLE_CTL_FRAME_SEND_ERR -5
#define WS_COMPLETE_FRAME_MASKED_ERR -6
#define WS_DISPATCH_MESSAGE_NULL_PTR_ERR -7
#define WS_SEND_AFTER_CLOSE_FRAME_ERR -8
#define WS_SEND_DURING_CONNECT_ERR -9
#define WS_SEND_NULL_DATA_ERR -10
#define WS_SEND_DATA_TOO_LARGE_ERR -11
#define WS_SEND_SEND_ERR -12
#define WS_HANDSHAKE_REMOTE_CLOSED_ERR -13
#define WS_HANDSHAKE_RECV_ERR -14
#define WS_HANDSHAKE_BAD_STATUS_ERR -15
#define WS_HANDSHAKE_NO_UPGRADE_ERR -16
#define WS_HANDSHAKE_NO_CONNECTION_ERR -17
#define WS_HANDSHAKE_BAD_ACCEPT_ERR -18
#define WS_HELPER_ALREADY_BOUND_ERR -19
#define WS_HELPER_CREATE_SOCK_ERR -20
#define WS_HELPER_BIND_ERR -21
#define WS_HELPER_LISTEN_ERR -22
typedef struct _wsclient_frame {
unsigned int fin;
unsigned int opcode;
unsigned int mask_offset;
unsigned int payload_offset;
unsigned int rawdata_idx;
unsigned int rawdata_sz;
unsigned long long payload_len;
char *rawdata;
struct _wsclient_frame *next_frame;
struct _wsclient_frame *prev_frame;
unsigned char mask[4];
} wsclient_frame;
typedef struct _wsclient_message {
unsigned int opcode;
unsigned long long payload_len;
char *payload;
} wsclient_message;
typedef struct _wsclient_error {
int code;
int extra_code;
char *str;
} wsclient_error;
typedef struct _wsclient {
pthread_t helper_thread;
pthread_t handshake_thread;
pthread_t run_thread;
pthread_mutex_t lock;
pthread_mutex_t send_lock;
char *URI;
int sockfd;
int flags;
int (*onopen)(struct _wsclient *);
int (*onclose)(struct _wsclient *);
int (*onerror)(struct _wsclient *, wsclient_error *err);
int (*onmessage)(struct _wsclient *, wsclient_message *msg);
wsclient_frame *current_frame;
struct sockaddr_un helper_sa;
int helper_sock;
#ifdef HAVE_LIBSSL
SSL_CTX *ssl_ctx;
SSL *ssl;
#endif
} wsclient;
//Function defs
wsclient *libwsclient_new(const char *URI);
wsclient_error *libwsclient_new_error(int errcode);
ssize_t _libwsclient_read(wsclient *c, void *buf, size_t length);
ssize_t _libwsclient_write(wsclient *c, const void *buf, size_t length);
int libwsclient_open_connection(const char *host, const char *port);
int stricmp(const char *s1, const char *s2);
int libwsclient_complete_frame(wsclient *c, wsclient_frame *frame);
void libwsclient_handle_control_frame(wsclient *c, wsclient_frame *ctl_frame);
void libwsclient_run(wsclient *c);
void libwsclient_finish(wsclient *client);
void *libwsclient_run_thread(void *ptr);
void *libwsclient_handshake_thread(void *ptr);
void libwsclient_cleanup_frames(wsclient_frame *first);
void libwsclient_in_data(wsclient *c, char in);
void libwsclient_dispatch_message(wsclient *c, wsclient_frame *current);
void libwsclient_close(wsclient *c);
int libwsclient_helper_socket(wsclient *c, const char *path);
void *libwsclient_helper_socket_thread(void *ptr);
//Define errors
char *errors[] = {
"Unknown error occured",
"Error while getting address info",
"Could connect to any address returned by getaddrinfo",
"Error receiving data in client run thread",
"Error during libwsclient_close",
"Error sending while handling control frame",
"Received masked frame from server",
"Got null pointer during message dispatch",
"Attempted to send after close frame was sent",
"Attempted to send during connect",
"Attempted to send null payload",
"Attempted to send too much data",
"Error during send in libwsclient_send",
"Remote end closed connection during handshake",
"Problem receiving data during handshake",
"Remote web server responded with bad HTTP status during handshake",
"Remote web server did not respond with upgrade header during handshake",
"Remote web server did not respond with connection header during handshake",
"Remote web server did not specify the appropriate Sec-WebSocket-Accept header during handshake",
NULL
};
int libwsclient_flags; //global flags variable
#endif /* WSCLIENT_H_ */