Compare commits

...

61 Commits

Author SHA1 Message Date
afef9e468c Merge 4fcf5165d5 into 04e5ca7d27 2024-09-16 11:43:21 +08:00
4fcf5165d5 tsc & prettier 2024-04-30 10:54:57 -03:00
04e5ca7d27 update license mit -> gnu 2024-04-30 14:12:25 +02:00
1d90133370 remove irrelevant comment 2024-04-27 22:06:49 +02:00
74b257f14f Merge remote-tracking branch 'fdundjer/master' into fd-master 2024-04-27 18:39:48 +02:00
3c89ce5389 scope filters for each token 2024-04-27 18:39:36 +02:00
4fb00f3814 Merge branch 'warp-id:master' into master 2024-04-27 18:30:05 +02:00
be2b5fffab version bump 2024-04-27 17:59:40 +02:00
ba11c539f6 feat: filter cache 2024-04-27 17:18:46 +02:00
cb91e04d60 feat: improve exit position logic 2024-04-27 17:01:33 +02:00
58eae6bfd8 fix socials check 2024-04-27 14:15:24 +02:00
6bb1443bd3 Merge pull request #98 from fdundjer/master
cleanup: mutable and renounced filters
2024-04-27 14:12:32 +02:00
aded31983f Merge remote-tracking branch 'fdundjer/master' into fd-master 2024-04-27 14:08:29 +02:00
c76a5d3065 lint 2024-04-27 14:08:08 +02:00
68c37c1efe Merge branch 'warp-id:master' into master 2024-04-27 14:02:37 +02:00
2ce963e2f8 Merge remote-tracking branch 'fdundjer/master' into fd-master 2024-04-27 14:01:56 +02:00
cec68e2257 Merge pull request #94 from fdundjer/master
fix: add missing property
2024-04-27 14:01:46 +02:00
df2de7782d Merge branch 'warp-id:master' into master 2024-04-27 14:00:36 +02:00
b6ae5492c1 Merge pull request #97 from TheoBrigitte/social-filter
Add social filter
2024-04-27 13:59:55 +02:00
44a2006105 Merge branch 'refs/heads/social-filter' into fd-master 2024-04-27 13:59:32 +02:00
8335c98d19 filter cleanup 2024-04-27 13:56:43 +02:00
b1bdcd9365 Add social filter 2024-04-27 11:06:10 +02:00
91aa1645ed Merge pull request #95 from mcoder9/master
Added Jito-RPC Executer
2024-04-22 18:31:22 +02:00
1abcaac1ed custom fee checking if using jito 2024-04-22 20:17:03 +04:00
35cc982e8a fixed some typos 2024-04-22 20:09:15 +04:00
54317de112 Merge pull request #93 from TheoBrigitte/mutable
Add mutable filter
2024-04-22 17:47:39 +02:00
39ef59f5a6 Added Jito-RPC Executer 2024-04-22 07:27:59 +04:00
142a915e1a add missing property 2024-04-21 18:56:44 +02:00
c9dc532a29 Merge branch 'master' into mutable
Signed-off-by: Filip Dunđer <fdundjer@outlook.com>
2024-04-21 18:29:25 +02:00
95ae801a53 Merge pull request #92 from fdundjer/master
fix: disable filters when snipe list is on
2024-04-21 18:27:57 +02:00
19e012c8e1 set freezable and mutable filter to false by default 2024-04-21 16:28:33 +02:00
a7d435a209 bump version 2024-04-21 16:02:14 +02:00
1991390121 add @metaplex-foundation/mpl-token-metadata to package.json 2024-04-21 15:59:39 +02:00
3c850c4c1a move metadataSerializer into constructor 2024-04-21 15:58:58 +02:00
c7a7c9fb0e pass metadataPDA.publicKey directly 2024-04-21 15:52:23 +02:00
a34a609786 add mutable.filter.ts file 2024-04-21 15:37:31 +02:00
ef87a3608f fix: change log levels 2024-04-21 15:36:30 +02:00
a5d9fc1a88 Add mutable filter
Check if owner can change metadata
2024-04-21 15:36:00 +02:00
41075b7eb6 fix: fix output 2024-04-21 15:25:44 +02:00
610340146d fix: filters 2024-04-21 14:49:26 +02:00
3dbe5a5352 fix: disable filters when snipe list if on 2024-04-21 14:39:16 +02:00
6dbebe2169 Merge pull request #90 from TheoBrigitte/freezable
Add freezable filter
2024-04-21 14:19:33 +02:00
70ba5eed76 keep filter 2024-04-21 14:17:30 +02:00
c0999a59ee Merge pull request #91 from fdundjer/master
feat: warp errors
2024-04-21 14:05:38 +02:00
b92a9ee128 update README 2024-04-21 13:56:01 +02:00
40432eefeb Merge branch 'refs/heads/master' into fdundjer-master 2024-04-21 13:51:03 +02:00
e16929571c cleanup: warnings 2024-04-21 13:44:57 +02:00
d0b59102c9 feat: add error handling 2024-04-21 13:43:46 +02:00
ff0ebad6bd update error message 2024-04-20 11:54:33 +02:00
508e521433 Add freezable filter
Check if owner can freeze tokens
2024-04-20 11:38:15 +02:00
df38d332a0 Merge pull request #89 from warp-id/Journeytojah-patch-1
fix: Update LOG_LEVEL in .env.copy to trace
2024-04-19 20:34:20 +07:00
f98ff97f0d fix: Update LOG_LEVEL in .env.copy to trace
Updated the `LOG_LEVEL` to make the bot more chatty about what's happening.

Signed-off-by: Alexandru Higyedi <onerootboii@proton.me>
2024-04-19 20:33:57 +07:00
5a49cfd12a Merge pull request #88 from fdundjer/master
feat: real time pool filtering
2024-04-19 13:19:46 +02:00
5d9ffcbc43 docs: update readme 2024-04-19 13:18:00 +02:00
021507387d Merge branch 'refs/heads/master' into fdundjer-master 2024-04-19 12:10:12 +02:00
da9512b8bb feat: real time filtering 2024-04-19 12:09:56 +02:00
e49acb91ed Merge pull request #86 from warp-id/Journeytojah-patch-1
Update README.md
2024-04-18 20:44:55 +07:00
70147793f8 Update README.md
Signed-off-by: Alexandru Higyedi <onerootboii@proton.me>
2024-04-18 20:44:25 +07:00
a0ba6cd6ca Merge pull request #85 from fdundjer/master
fix: default values for fees
2024-04-18 13:15:27 +02:00
7186467d10 fix: default values for fees 2024-04-18 13:10:30 +02:00
0925fd8032 Merge pull request #84 from fdundjer/feat/v2
feat: warp transactions
2024-04-17 10:02:45 +02:00
61 changed files with 3942 additions and 692 deletions

View File

@ -7,39 +7,47 @@ RPC_WEBSOCKET_ENDPOINT=wss://api.mainnet-beta.solana.com
COMMITMENT_LEVEL=confirmed
# Bot
LOG_LEVEL=debug
ONE_TOKEN_AT_A_TIME=true
LOG_LEVEL=trace
MAX_TOKENS_AT_THE_TIME=1
PRE_LOAD_EXISTING_MARKETS=false
CACHE_NEW_MARKETS=false
# default or warp
# default or warp or jito
TRANSACTION_EXECUTOR=default
# if using default executor fee below will be applied
COMPUTE_UNIT_LIMIT=421197
COMPUTE_UNIT_PRICE=101337
# if using warp executor fee below will be applied
WARP_FEE=0.006
# if using default executor, fee below will be applied
COMPUTE_UNIT_LIMIT=101337
COMPUTE_UNIT_PRICE=421197
# if using warp or jito executor, fee below will be applied
CUSTOM_FEE=0.006
# Buy
QUOTE_MINT=WSOL
QUOTE_AMOUNT=0.001
AUTO_BUY_DELAY=0
MAX_BUY_RETRIES=10
BUY_SLIPPAGE=5
BUY_SLIPPAGE=20
# Sell
AUTO_SELL=true
MAX_SELL_RETRIES=10
AUTO_SELL_DELAY=0
PRICE_CHECK_INTERVAL=2000
PRICE_CHECK_DURATION=60000
TAKE_PROFIT=20
STOP_LOSS=15
SELL_SLIPPAGE=5
PRICE_CHECK_DURATION=600000
TAKE_PROFIT=40
STOP_LOSS=20
TRAILING_STOP_LOSS=true
SKIP_SELLING_IF_LOST_MORE_THAN=90
SELL_SLIPPAGE=20
# Filters
USE_SNIPE_LIST=false
SNIPE_LIST_REFRESH_INTERVAL=30000
FILTER_CHECK_DURATION=60000
FILTER_CHECK_INTERVAL=2000
CONSECUTIVE_FILTER_MATCHES=3
CHECK_IF_MUTABLE=false
CHECK_IF_SOCIALS=true
CHECK_IF_MINT_IS_RENOUNCED=true
CHECK_IF_BURNED=false
CHECK_IF_FREEZABLE=false
CHECK_IF_BURNED=true
MIN_POOL_SIZE=5
MAX_POOL_SIZE=50
MAX_POOL_SIZE=50

View File

@ -1,5 +1,6 @@
{
"singleQuote": true,
"singleQuote": false,
"trailingComma": "all",
"printWidth": 120
"printWidth": 120,
"useTabs": true
}

View File

@ -1,22 +1,674 @@
Microsoft Public License (Ms-PL)
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
Preamble
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,14 +1,14 @@
# Solana Trading Bot (Beta)
# Solana Sniper Bot (Poc)
This code is written as proof of concept to demonstrate how we can buy new tokens immediately after the liquidity pool is open for trading.
The Solana Trading Bot is a software tool designed to automate the buying and selling of tokens on the Solana blockchain.
It is configured to execute trades based on predefined parameters and strategies set by the user.
Script listens to new Raydium USDC or SOL pools and buys tokens for a fixed amount in USDC/SOL.
Depending on the speed of the RPC node, the purchase usually happens before the token is available on Raydium UI for swapping.
This is provided as is, for learning purposes.
The bot can monitor market conditions in real-time, such as pool burn, mint renounced and other factors, and it will execute trades when these conditions are fulfilled.
## Setup
To run the script you need to:
- Create a new empty Solana wallet
- Transfer some SOL to it.
- Convert some SOL to USDC or WSOL.
@ -24,53 +24,82 @@ You should see the following output:
### Configuration
#### Wallet
- `PRIVATE_KEY` - Your wallet's private key.
#### Connection
- `RPC_ENDPOINT` - HTTPS RPC endpoint for interacting with the Solana network.
- `RPC_WEBSOCKET_ENDPOINT` - WebSocket RPC endpoint for real-time updates from the Solana network.
- `COMMITMENT_LEVEL`- The commitment level of transactions (e.g., "finalized" for the highest level of security).
#### Bot
- `LOG_LEVEL` - Set logging level, e.g., `info`, `debug`, `trace`, etc.
- `ONE_TOKEN_AT_A_TIME` - Set to `true` to process buying one token at a time.
- `MAX_TOKENS_AT_A_TIME` - Set to `1` to process buying one token at a time.
- `COMPUTE_UNIT_LIMIT` - Compute limit used to calculate fees.
- `COMPUTE_UNIT_PRICE` - Compute price used to calculate fees.
- `PRE_LOAD_EXISTING_MARKETS` - Bot will load all existing markets in memory on start.
- This option should not be used with public RPC.
- `CACHE_NEW_MARKETS` - Set to `true` to cache new markets.
- This option should not be used with public RPC.
- `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions
- `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions, or set it to jito to use JSON-RPC jito executer
- For more details checkout [warp](#warp-transactions-beta) section
- `WARP_FEE` - If using warp executor this value will be used for transaction fees instead of `COMPUTE_UNIT_LIMIT` and `COMPUTE_UNIT_LIMIT`
- Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above
- `CUSTOM_FEE` - If using warp or jito executors this value will be used for transaction fees instead of `COMPUTE_UNIT_LIMIT` and `COMPUTE_UNIT_LIMIT`
- Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above
- On top of this fee, minimal solana network fee will be applied
#### Buy
- `QUOTE_MINT` - Amount used to buy each new token.
- `QUOTE_AMOUNT` - Which pools to snipe, USDC or WSOL.
- `QUOTE_MINT` - Which pools to snipe, USDC or WSOL.
- `QUOTE_AMOUNT` - Amount used to buy each new token.
- `AUTO_BUY_DELAY` - Delay in milliseconds before buying a token.
- `MAX_BUY_RETRIES` - Maximum number of retries for buying a token.
- `BUY_SLIPPAGE` - Slippage %
#### Sell
- `AUTO_SELL` - Set to `true` to enable automatic selling of tokens.
- If you want to manually sell bought tokens, disable this option.
- `MAX_SELL_RETRIES` - Maximum number of retries for selling a token.
- `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token.
- `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token.
- `PRICE_CHECK_INTERVAL` - Interval in milliseconds for checking the take profit and stop loss conditions.
- Set to zero to disable take profit and stop loss.
- `PRICE_CHECK_DURATION` - Time in milliseconds to wait for stop loss/take profit conditions.
- If you don't reach profit or loss bot will auto sell after this time.
- Set to zero to disable take profit and stop loss.
- `TAKE_PROFIT` - Percentage profit at which to take profit.
- Take profit is calculated based on quote mint.
- `STOP_LOSS` - Percentage loss at which to stop the loss.
- Stop loss is calculated based on quote mint.
- `TRAILING_STOP_LOSS` - Set to `true` to use trailing stop loss.
- `SKIP_SELLING_IF_LOST_MORE_THAN` - If token loses more than X% of value, bot will not try to sell
- This config is useful if you find yourself in a situation when rugpull happen, and you failed to sell. In this case there is a big loss of value, and sometimes it's more beneficial to keep the token, instead of selling it for almost nothing.
- `SELL_SLIPPAGE` - Slippage %.
#### Filters
#### Snipe list
- `USE_SNIPE_LIST` - Set to `true` to enable buying only tokens listed in `snipe-list.txt`.
- Pool must not exist before the script starts.
- Pool must not exist before the bot starts.
- If token can be traded before bot starts nothing will happen. Bot will not buy the token.
- `SNIPE_LIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the snipe list.
- You can update snipe list while bot is running. It will pickup the new changes each time it does refresh.
Note: When using snipe list filters below will be disabled.
#### Filters
- `FILTER_CHECK_INTERVAL` - Interval in milliseconds for checking if pool match the filters.
- Set to zero to disable filters.
- `FILTER_CHECK_DURATION` - Time in milliseconds to wait for pool to match the filters.
- If pool doesn't match the filter buy will not happen.
- Set to zero to disable filters.
- `CONSECUTIVE_FILTER_MATCHES` - How many times in a row pool needs to match the filters.
- This is useful because when pool is burned (and rugged), other filters may not report the same behavior. eg. pool size may still have old value
- `CHECK_IF_MUTABLE` - Set to `true` to buy tokens only if their metadata are not mutable.
- `CHECK_IF_SOCIALS` - Set to `true` to buy tokens only if they have at least 1 social.
- `CHECK_IF_MINT_IS_RENOUNCED` - Set to `true` to buy tokens only if their mint is renounced.
- `CHECK_IF_FREEZABLE` - Set to `true` to buy tokens only if they are not freezable.
- `CHECK_IF_BURNED` - Set to `true` to buy tokens only if their liquidity pool is burned.
- `MIN_POOL_SIZE` - Bot will buy only if the pool size is greater than or equal the specified amount.
- Set `0` to disable.
@ -78,12 +107,14 @@ You should see the following output:
- Set `0` to disable.
## Warp transactions (beta)
In case you experience a lot of failed transactions or transaction performance is too slow, you can try using `warp` for executing transactions.
Warp is hosted service that executes transactions using integrations with third party providers.
Using warp for transactions supports the team behind this project.
### Security
When using warp, transaction is sent to the hosted service.
**Payload that is being sent will NOT contain your wallet private key**. Fee transaction is signed on your machine.
Each request is processed by hosted service and sent to third party provider.
@ -92,20 +123,24 @@ Each request is processed by hosted service and sent to third party provider.
Note: Warp transactions are disabled by default.
### Fees
When using warp for transactions, fee is distributed between developers of warp and third party providers.
In case TX fails, no fee will be taken from your account.
## Common issues
If you have an error which is not listed here, please create a new issue in this repository.
To collect more information on an issue, please change `LOG_LEVEL` to `debug`.
### Unsupported RPC node
- If you see following error in your log file:
`Error: 410 Gone: {"jsonrpc":"2.0","error":{"code": 410, "message":"The RPC call or parameters have been disabled."}, "id": "986f3599-b2b7-47c4-b951-074c19842bad" }`
it means your RPC node doesn't support methods needed to execute script.
- FIX: Change your RPC node. You can use Helius or Quicknode.
### No token account
- If you see following error in your log file:
`Error: No SOL token account found in wallet: `
it means that wallet you provided doesn't have USDC/WSOL token account.
@ -114,13 +149,16 @@ To collect more information on an issue, please change `LOG_LEVEL` to `debug`.
![wsol](readme/wsol.png)
## Contact
[![](https://img.shields.io/discord/1201826085655023616?color=5865F2&logo=Discord&style=flat-square)](https://discord.gg/xYUETCA2aP)
- If you want to leave a tip, you can send it to the following address:
`7gm6BPQrSBaTAYaJheuRevBNXcmKsgbkfBCVSjBnt9aP`
`7gm6BPQrSBaTAYaJheuRevBNXcmKsgbkfBCVSjBnt9aP`
- If you need custom features or assistance, feel free to contact the admin team on discord for dedicated support.
## Disclaimer
Use this script at your own risk.
The Solana Trading Bot is provided as is, for learning purposes.
Trading cryptocurrencies and tokens involves risk, and past performance is not indicative of future results.
The use of this bot is at your own risk, and we are not responsible for any losses incurred while using the bot.

340
bot.js Normal file
View File

@ -0,0 +1,340 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bot = void 0;
const web3_js_1 = require("@solana/web3.js");
const spl_token_1 = require("@solana/spl-token");
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
const cache_1 = require("./cache");
const filters_1 = require("./filters");
const helpers_1 = require("./helpers");
const async_mutex_1 = require("async-mutex");
const bn_js_1 = __importDefault(require("bn.js"));
const warp_transaction_executor_1 = require("./transactions/warp-transaction-executor");
const jito_rpc_transaction_executor_1 = require("./transactions/jito-rpc-transaction-executor");
class Bot {
constructor(connection, marketStorage, poolStorage, txExecutor, config) {
this.connection = connection;
this.marketStorage = marketStorage;
this.poolStorage = poolStorage;
this.txExecutor = txExecutor;
this.config = config;
this.sellExecutionCount = 0;
this.stopLoss = new Map();
this.isWarp = false;
this.isJito = false;
this.isWarp = txExecutor instanceof warp_transaction_executor_1.WarpTransactionExecutor;
this.isJito = txExecutor instanceof jito_rpc_transaction_executor_1.JitoTransactionExecutor;
this.semaphore = new async_mutex_1.Semaphore(config.maxTokensAtTheTime);
if (this.config.useSnipeList) {
this.snipeListCache = new cache_1.SnipeListCache();
this.snipeListCache.init();
}
}
validate() {
return __awaiter(this, void 0, void 0, function* () {
try {
yield (0, spl_token_1.getAccount)(this.connection, this.config.quoteAta, this.connection.commitment);
}
catch (error) {
helpers_1.logger.error(`${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`);
return false;
}
return true;
});
}
buy(accountId, poolState) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
helpers_1.logger.trace({ mint: poolState.baseMint }, `Processing new pool...`);
if (this.config.useSnipeList && !((_a = this.snipeListCache) === null || _a === void 0 ? void 0 : _a.isInList(poolState.baseMint.toString()))) {
helpers_1.logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`);
return;
}
if (this.config.autoBuyDelay > 0) {
helpers_1.logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`);
yield (0, helpers_1.sleep)(this.config.autoBuyDelay);
}
const numberOfActionsBeingProcessed = this.config.maxTokensAtTheTime - this.semaphore.getValue() + this.sellExecutionCount;
if (this.semaphore.isLocked() || numberOfActionsBeingProcessed >= this.config.maxTokensAtTheTime) {
helpers_1.logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because max tokens to process at the same time is ${this.config.maxTokensAtTheTime} and currently ${numberOfActionsBeingProcessed} tokens is being processed`);
return;
}
yield this.semaphore.acquire();
try {
const [market, mintAta] = yield Promise.all([
this.marketStorage.get(poolState.marketId.toString()),
(0, spl_token_1.getAssociatedTokenAddress)(poolState.baseMint, this.config.wallet.publicKey),
]);
const poolKeys = (0, helpers_1.createPoolKeys)(accountId, poolState, market);
if (!this.config.useSnipeList) {
const match = yield this.filterMatch(poolKeys);
if (!match) {
helpers_1.logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`);
return;
}
}
for (let i = 0; i < this.config.maxBuyRetries; i++) {
try {
helpers_1.logger.info({ mint: poolState.baseMint.toString() }, `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`);
const tokenOut = new raydium_sdk_1.Token(spl_token_1.TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals);
const result = yield this.swap(poolKeys, this.config.quoteAta, mintAta, this.config.quoteToken, tokenOut, this.config.quoteAmount, this.config.buySlippage, this.config.wallet, 'buy');
if (result.confirmed) {
helpers_1.logger.info({
mint: poolState.baseMint.toString(),
signature: result.signature,
url: `https://solscan.io/tx/${result.signature}?cluster=${helpers_1.NETWORK}`,
}, `Confirmed buy tx`);
break;
}
helpers_1.logger.info({
mint: poolState.baseMint.toString(),
signature: result.signature,
error: result.error,
}, `Error confirming buy tx`);
}
catch (error) {
helpers_1.logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`);
}
}
}
catch (error) {
helpers_1.logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`);
}
finally {
this.semaphore.release();
}
});
}
sell(accountId, rawAccount) {
return __awaiter(this, void 0, void 0, function* () {
this.sellExecutionCount++;
try {
helpers_1.logger.trace({ mint: rawAccount.mint }, `Processing new token...`);
const poolData = yield this.poolStorage.get(rawAccount.mint.toString());
if (!poolData) {
helpers_1.logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`);
return;
}
const tokenIn = new raydium_sdk_1.Token(spl_token_1.TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber());
const tokenAmountIn = new raydium_sdk_1.TokenAmount(tokenIn, rawAccount.amount, true);
if (tokenAmountIn.isZero()) {
helpers_1.logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`);
return;
}
if (this.config.autoSellDelay > 0) {
helpers_1.logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`);
yield (0, helpers_1.sleep)(this.config.autoSellDelay);
}
const market = yield this.marketStorage.get(poolData.state.marketId.toString());
const poolKeys = (0, helpers_1.createPoolKeys)(new web3_js_1.PublicKey(poolData.id), poolData.state, market);
for (let i = 0; i < this.config.maxSellRetries; i++) {
try {
const shouldSell = yield this.waitForSellSignal(tokenAmountIn, poolKeys);
if (!shouldSell) {
return;
}
helpers_1.logger.info({ mint: rawAccount.mint }, `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`);
const result = yield this.swap(poolKeys, accountId, this.config.quoteAta, tokenIn, this.config.quoteToken, tokenAmountIn, this.config.sellSlippage, this.config.wallet, 'sell');
if (result.confirmed) {
helpers_1.logger.info({
dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`,
mint: rawAccount.mint.toString(),
signature: result.signature,
url: `https://solscan.io/tx/${result.signature}?cluster=${helpers_1.NETWORK}`,
}, `Confirmed sell tx`);
break;
}
helpers_1.logger.info({
mint: rawAccount.mint.toString(),
signature: result.signature,
error: result.error,
}, `Error confirming sell tx`);
}
catch (error) {
helpers_1.logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`);
}
}
}
catch (error) {
helpers_1.logger.error({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`);
}
finally {
this.sellExecutionCount--;
}
});
}
// noinspection JSUnusedLocalSymbols
swap(poolKeys, ataIn, ataOut, tokenIn, tokenOut, amountIn, slippage, wallet, direction) {
return __awaiter(this, void 0, void 0, function* () {
const slippagePercent = new raydium_sdk_1.Percent(slippage, 100);
const poolInfo = yield raydium_sdk_1.Liquidity.fetchInfo({
connection: this.connection,
poolKeys,
});
const computedAmountOut = raydium_sdk_1.Liquidity.computeAmountOut({
poolKeys,
poolInfo,
amountIn,
currencyOut: tokenOut,
slippage: slippagePercent,
});
const latestBlockhash = yield this.connection.getLatestBlockhash();
const { innerTransaction } = raydium_sdk_1.Liquidity.makeSwapFixedInInstruction({
poolKeys: poolKeys,
userKeys: {
tokenAccountIn: ataIn,
tokenAccountOut: ataOut,
owner: wallet.publicKey,
},
amountIn: amountIn.raw,
minAmountOut: computedAmountOut.minAmountOut.raw,
}, poolKeys.version);
const messageV0 = new web3_js_1.TransactionMessage({
payerKey: wallet.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
...(this.isWarp || this.isJito
? []
: [
web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }),
web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }),
]),
...(direction === 'buy'
? [
(0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(wallet.publicKey, ataOut, wallet.publicKey, tokenOut.mint),
]
: []),
...innerTransaction.instructions,
...(direction === 'sell' ? [(0, spl_token_1.createCloseAccountInstruction)(ataIn, wallet.publicKey, wallet.publicKey)] : []),
],
}).compileToV0Message();
const transaction = new web3_js_1.VersionedTransaction(messageV0);
transaction.sign([wallet, ...innerTransaction.signers]);
return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash);
});
}
filterMatch(poolKeys) {
return __awaiter(this, void 0, void 0, function* () {
if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) {
return true;
}
const filters = new filters_1.PoolFilters(this.connection, {
quoteToken: this.config.quoteToken,
minPoolSize: this.config.minPoolSize,
maxPoolSize: this.config.maxPoolSize,
});
const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval;
let timesChecked = 0;
let matchCount = 0;
do {
try {
const shouldBuy = yield filters.execute(poolKeys);
if (shouldBuy) {
matchCount++;
if (this.config.consecutiveMatchCount <= matchCount) {
helpers_1.logger.debug({ mint: poolKeys.baseMint.toString() }, `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`);
return true;
}
}
else {
matchCount = 0;
}
yield (0, helpers_1.sleep)(this.config.filterCheckInterval);
}
finally {
timesChecked++;
}
} while (timesChecked < timesToCheck);
return false;
});
}
waitForSellSignal(amountIn, poolKeys) {
return __awaiter(this, void 0, void 0, function* () {
if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) {
return true;
}
const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval;
const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new bn_js_1.default(100));
const profitAmount = new raydium_sdk_1.TokenAmount(this.config.quoteToken, profitFraction, true);
const takeProfit = this.config.quoteAmount.add(profitAmount);
let stopLoss;
if (!this.stopLoss.get(poolKeys.baseMint.toString())) {
const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new bn_js_1.default(100));
const lossAmount = new raydium_sdk_1.TokenAmount(this.config.quoteToken, lossFraction, true);
stopLoss = this.config.quoteAmount.subtract(lossAmount);
this.stopLoss.set(poolKeys.baseMint.toString(), stopLoss);
}
else {
stopLoss = this.stopLoss.get(poolKeys.baseMint.toString());
}
const slippage = new raydium_sdk_1.Percent(this.config.sellSlippage, 100);
let timesChecked = 0;
do {
try {
const poolInfo = yield raydium_sdk_1.Liquidity.fetchInfo({
connection: this.connection,
poolKeys,
});
const amountOut = raydium_sdk_1.Liquidity.computeAmountOut({
poolKeys,
poolInfo,
amountIn: amountIn,
currencyOut: this.config.quoteToken,
slippage,
}).amountOut;
if (this.config.trailingStopLoss) {
const trailingLossFraction = amountOut.mul(this.config.stopLoss).numerator.div(new bn_js_1.default(100));
const trailingLossAmount = new raydium_sdk_1.TokenAmount(this.config.quoteToken, trailingLossFraction, true);
const trailingStopLoss = amountOut.subtract(trailingLossAmount);
if (trailingStopLoss.gt(stopLoss)) {
helpers_1.logger.trace({ mint: poolKeys.baseMint.toString() }, `Updating trailing stop loss from ${stopLoss.toFixed()} to ${trailingStopLoss.toFixed()}`);
this.stopLoss.set(poolKeys.baseMint.toString(), trailingStopLoss);
stopLoss = trailingStopLoss;
}
}
if (this.config.skipSellingIfLostMoreThan > 0) {
const stopSellingFraction = this.config.quoteAmount
.mul(this.config.skipSellingIfLostMoreThan)
.numerator.div(new bn_js_1.default(100));
const stopSellingAmount = new raydium_sdk_1.TokenAmount(this.config.quoteToken, stopSellingFraction, true);
if (amountOut.lt(stopSellingAmount)) {
helpers_1.logger.debug({ mint: poolKeys.baseMint.toString() }, `Token dropped more than ${this.config.skipSellingIfLostMoreThan}%, sell stopped. Initial: ${this.config.quoteAmount.toFixed()} | Current: ${amountOut.toFixed()}`);
this.stopLoss.delete(poolKeys.baseMint.toString());
return false;
}
}
helpers_1.logger.debug({ mint: poolKeys.baseMint.toString() }, `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`);
if (amountOut.lt(stopLoss)) {
this.stopLoss.delete(poolKeys.baseMint.toString());
break;
}
if (amountOut.gt(takeProfit)) {
this.stopLoss.delete(poolKeys.baseMint.toString());
break;
}
yield (0, helpers_1.sleep)(this.config.priceCheckInterval);
}
catch (e) {
helpers_1.logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`);
}
finally {
timesChecked++;
}
} while (timesChecked < timesToCheck);
return true;
});
}
}
exports.Bot = Bot;

205
bot.ts
View File

@ -19,20 +19,19 @@ import { MarketCache, PoolCache, SnipeListCache } from './cache';
import { PoolFilters } from './filters';
import { TransactionExecutor } from './transactions';
import { createPoolKeys, logger, NETWORK, sleep } from './helpers';
import { Mutex } from 'async-mutex';
import { Semaphore } from 'async-mutex';
import BN from 'bn.js';
import { WarpTransactionExecutor } from './transactions/warp-transaction-executor';
import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor';
export interface BotConfig {
wallet: Keypair;
checkRenounced: boolean;
checkBurned: boolean;
minPoolSize: TokenAmount;
maxPoolSize: TokenAmount;
quoteToken: Token;
quoteAmount: TokenAmount;
quoteAta: PublicKey;
oneTokenAtATime: boolean;
maxTokensAtTheTime: number;
useSnipeList: boolean;
autoSell: boolean;
autoBuyDelay: number;
@ -43,22 +42,26 @@ export interface BotConfig {
unitPrice: number;
takeProfit: number;
stopLoss: number;
trailingStopLoss: boolean;
skipSellingIfLostMoreThan: number;
buySlippage: number;
sellSlippage: number;
priceCheckInterval: number;
priceCheckDuration: number;
filterCheckInterval: number;
filterCheckDuration: number;
consecutiveMatchCount: number;
}
export class Bot {
private readonly poolFilters: PoolFilters;
// snipe list
private readonly snipeListCache?: SnipeListCache;
// one token at the time
private readonly mutex: Mutex;
private readonly semaphore: Semaphore;
private sellExecutionCount = 0;
private readonly stopLoss = new Map<string, TokenAmount>();
public readonly isWarp: boolean = false;
public readonly isJito: boolean = false;
constructor(
private readonly connection: Connection,
@ -68,13 +71,8 @@ export class Bot {
readonly config: BotConfig,
) {
this.isWarp = txExecutor instanceof WarpTransactionExecutor;
this.mutex = new Mutex();
this.poolFilters = new PoolFilters(connection, {
quoteToken: this.config.quoteToken,
minPoolSize: this.config.minPoolSize,
maxPoolSize: this.config.maxPoolSize,
});
this.isJito = txExecutor instanceof JitoTransactionExecutor;
this.semaphore = new Semaphore(config.maxTokensAtTheTime);
if (this.config.useSnipeList) {
this.snipeListCache = new SnipeListCache();
@ -96,7 +94,7 @@ export class Bot {
}
public async buy(accountId: PublicKey, poolState: LiquidityStateV4) {
logger.trace({ mint: poolState.baseMint }, `Processing buy...`);
logger.trace({ mint: poolState.baseMint }, `Processing new pool...`);
if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) {
logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`);
@ -108,34 +106,36 @@ export class Bot {
await sleep(this.config.autoBuyDelay);
}
if (this.config.oneTokenAtATime) {
if (this.mutex.isLocked() || this.sellExecutionCount > 0) {
logger.debug(
{ mint: poolState.baseMint.toString() },
`Skipping buy because one token at a time is turned on and token is already being processed`,
);
return;
}
await this.mutex.acquire();
const numberOfActionsBeingProcessed =
this.config.maxTokensAtTheTime - this.semaphore.getValue() + this.sellExecutionCount;
if (this.semaphore.isLocked() || numberOfActionsBeingProcessed >= this.config.maxTokensAtTheTime) {
logger.debug(
{ mint: poolState.baseMint.toString() },
`Skipping buy because max tokens to process at the same time is ${this.config.maxTokensAtTheTime} and currently ${numberOfActionsBeingProcessed} tokens is being processed`,
);
return;
}
try {
const shouldBuy = await this.poolFilters.execute(poolState);
await this.semaphore.acquire();
if (!shouldBuy) {
logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because pool doesn't match filters`);
return;
try {
const [market, mintAta] = await Promise.all([
this.marketStorage.get(poolState.marketId.toString()),
getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey),
]);
const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market);
if (!this.config.useSnipeList) {
const match = await this.filterMatch(poolKeys);
if (!match) {
logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`);
return;
}
}
for (let i = 0; i < this.config.maxBuyRetries; i++) {
try {
const [market, mintAta] = await Promise.all([
this.marketStorage.get(poolState.marketId.toString()),
getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey),
]);
const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market);
logger.info(
{ mint: poolState.baseMint.toString() },
`Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`,
@ -166,10 +166,11 @@ export class Bot {
break;
}
logger.debug(
logger.info(
{
mint: poolState.baseMint.toString(),
signature: result.signature,
error: result.error,
},
`Error confirming buy tx`,
);
@ -180,19 +181,15 @@ export class Bot {
} catch (error) {
logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`);
} finally {
if (this.config.oneTokenAtATime) {
this.mutex.release();
}
this.semaphore.release();
}
}
public async sell(accountId: PublicKey, rawAccount: RawAccount) {
if (this.config.oneTokenAtATime) {
this.sellExecutionCount++;
}
this.sellExecutionCount++;
try {
logger.trace({ mint: rawAccount.mint }, `Processing sell...`);
logger.trace({ mint: rawAccount.mint }, `Processing new token...`);
const poolData = await this.poolStorage.get(rawAccount.mint.toString());
@ -214,12 +211,16 @@ export class Bot {
await sleep(this.config.autoSellDelay);
}
const market = await this.marketStorage.get(poolData.state.marketId.toString());
const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market);
for (let i = 0; i < this.config.maxSellRetries; i++) {
try {
const market = await this.marketStorage.get(poolData.state.marketId.toString());
const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market);
const shouldSell = await this.waitForSellSignal(tokenAmountIn, poolKeys);
await this.priceMatch(tokenAmountIn, poolKeys);
if (!shouldSell) {
return;
}
logger.info(
{ mint: rawAccount.mint },
@ -255,6 +256,7 @@ export class Bot {
{
mint: rawAccount.mint.toString(),
signature: result.signature,
error: result.error,
},
`Error confirming sell tx`,
);
@ -263,14 +265,13 @@ export class Bot {
}
}
} catch (error) {
logger.debug({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`);
logger.error({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`);
} finally {
if (this.config.oneTokenAtATime) {
this.sellExecutionCount--;
}
this.sellExecutionCount--;
}
}
// noinspection JSUnusedLocalSymbols
private async swap(
poolKeys: LiquidityPoolKeysV4,
ataIn: PublicKey,
@ -315,7 +316,7 @@ export class Bot {
payerKey: wallet.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
...(this.isWarp
...(this.isWarp || this.isJito
? []
: [
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }),
@ -342,19 +343,69 @@ export class Bot {
return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash);
}
private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) {
private async filterMatch(poolKeys: LiquidityPoolKeysV4) {
if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) {
return true;
}
const filters = new PoolFilters(this.connection, {
quoteToken: this.config.quoteToken,
minPoolSize: this.config.minPoolSize,
maxPoolSize: this.config.maxPoolSize,
});
const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval;
let timesChecked = 0;
let matchCount = 0;
do {
try {
const shouldBuy = await filters.execute(poolKeys);
if (shouldBuy) {
matchCount++;
if (this.config.consecutiveMatchCount <= matchCount) {
logger.debug(
{ mint: poolKeys.baseMint.toString() },
`Filter match ${matchCount}/${this.config.consecutiveMatchCount}`,
);
return true;
}
} else {
matchCount = 0;
}
await sleep(this.config.filterCheckInterval);
} finally {
timesChecked++;
}
} while (timesChecked < timesToCheck);
return false;
}
private async waitForSellSignal(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) {
if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) {
return;
return true;
}
const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval;
const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100));
const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true);
const takeProfit = this.config.quoteAmount.add(profitAmount);
let stopLoss: TokenAmount;
if (!this.stopLoss.get(poolKeys.baseMint.toString())) {
const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100));
const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true);
stopLoss = this.config.quoteAmount.subtract(lossAmount);
this.stopLoss.set(poolKeys.baseMint.toString(), stopLoss);
} else {
stopLoss = this.stopLoss.get(poolKeys.baseMint.toString())!;
}
const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100));
const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true);
const stopLoss = this.config.quoteAmount.subtract(lossAmount);
const slippage = new Percent(this.config.sellSlippage, 100);
let timesChecked = 0;
@ -371,7 +422,39 @@ export class Bot {
amountIn: amountIn,
currencyOut: this.config.quoteToken,
slippage,
}).amountOut;
}).amountOut as TokenAmount;
if (this.config.trailingStopLoss) {
const trailingLossFraction = amountOut.mul(this.config.stopLoss).numerator.div(new BN(100));
const trailingLossAmount = new TokenAmount(this.config.quoteToken, trailingLossFraction, true);
const trailingStopLoss = amountOut.subtract(trailingLossAmount);
if (trailingStopLoss.gt(stopLoss)) {
logger.trace(
{ mint: poolKeys.baseMint.toString() },
`Updating trailing stop loss from ${stopLoss.toFixed()} to ${trailingStopLoss.toFixed()}`,
);
this.stopLoss.set(poolKeys.baseMint.toString(), trailingStopLoss);
stopLoss = trailingStopLoss;
}
}
if (this.config.skipSellingIfLostMoreThan > 0) {
const stopSellingFraction = this.config.quoteAmount
.mul(this.config.skipSellingIfLostMoreThan)
.numerator.div(new BN(100));
const stopSellingAmount = new TokenAmount(this.config.quoteToken, stopSellingFraction, true);
if (amountOut.lt(stopSellingAmount)) {
logger.debug(
{ mint: poolKeys.baseMint.toString() },
`Token dropped more than ${this.config.skipSellingIfLostMoreThan}%, sell stopped. Initial: ${this.config.quoteAmount.toFixed()} | Current: ${amountOut.toFixed()}`,
);
this.stopLoss.delete(poolKeys.baseMint.toString());
return false;
}
}
logger.debug(
{ mint: poolKeys.baseMint.toString() },
@ -379,10 +462,12 @@ export class Bot {
);
if (amountOut.lt(stopLoss)) {
this.stopLoss.delete(poolKeys.baseMint.toString());
break;
}
if (amountOut.gt(takeProfit)) {
this.stopLoss.delete(poolKeys.baseMint.toString());
break;
}
@ -393,5 +478,7 @@ export class Bot {
timesChecked++;
}
} while (timesChecked < timesToCheck);
return true;
}
}

19
cache/index.js vendored Normal file
View File

@ -0,0 +1,19 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./market.cache"), exports);
__exportStar(require("./pool.cache"), exports);
__exportStar(require("./snipe-list.cache"), exports);

6
cache/index.ts vendored
View File

@ -1,3 +1,3 @@
export * from './market.cache';
export * from './pool.cache';
export * from './snipe-list.cache';
export * from "./market.cache";
export * from "./pool.cache";
export * from "./snipe-list.cache";

68
cache/market.cache.js vendored Normal file
View File

@ -0,0 +1,68 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarketCache = void 0;
const web3_js_1 = require("@solana/web3.js");
const helpers_1 = require("../helpers");
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
class MarketCache {
constructor(connection) {
this.connection = connection;
this.keys = new Map();
}
init(config) {
return __awaiter(this, void 0, void 0, function* () {
helpers_1.logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`);
const accounts = yield this.connection.getProgramAccounts(raydium_sdk_1.MAINNET_PROGRAM_ID.OPENBOOK_MARKET, {
commitment: this.connection.commitment,
dataSlice: {
offset: raydium_sdk_1.MARKET_STATE_LAYOUT_V3.offsetOf("eventQueue"),
length: helpers_1.MINIMAL_MARKET_STATE_LAYOUT_V3.span,
},
filters: [
{ dataSize: raydium_sdk_1.MARKET_STATE_LAYOUT_V3.span },
{
memcmp: {
offset: raydium_sdk_1.MARKET_STATE_LAYOUT_V3.offsetOf("quoteMint"),
bytes: config.quoteToken.mint.toBase58(),
},
},
],
});
for (const account of accounts) {
const market = helpers_1.MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data);
this.keys.set(account.pubkey.toString(), market);
}
helpers_1.logger.debug({}, `Cached ${this.keys.size} markets`);
});
}
save(marketId, keys) {
if (!this.keys.has(marketId)) {
helpers_1.logger.trace({}, `Caching new market: ${marketId}`);
this.keys.set(marketId, keys);
}
}
get(marketId) {
return __awaiter(this, void 0, void 0, function* () {
if (this.keys.has(marketId)) {
return this.keys.get(marketId);
}
helpers_1.logger.trace({}, `Fetching new market keys for ${marketId}`);
const market = yield this.fetch(marketId);
this.keys.set(marketId, market);
return market;
});
}
fetch(marketId) {
return (0, helpers_1.getMinimalMarketV3)(this.connection, new web3_js_1.PublicKey(marketId), this.connection.commitment);
}
}
exports.MarketCache = MarketCache;

94
cache/market.cache.ts vendored
View File

@ -1,58 +1,58 @@
import { Connection, PublicKey } from '@solana/web3.js';
import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers';
import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk';
import { Connection, PublicKey } from "@solana/web3.js";
import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from "../helpers";
import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from "@raydium-io/raydium-sdk";
export class MarketCache {
private readonly keys: Map<string, MinimalMarketLayoutV3> = new Map<string, MinimalMarketLayoutV3>();
constructor(private readonly connection: Connection) {}
private readonly keys: Map<string, MinimalMarketLayoutV3> = new Map<string, MinimalMarketLayoutV3>();
constructor(private readonly connection: Connection) {}
async init(config: { quoteToken: Token }) {
logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`);
async init(config: { quoteToken: Token }) {
logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`);
const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, {
commitment: this.connection.commitment,
dataSlice: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'),
length: MINIMAL_MARKET_STATE_LAYOUT_V3.span,
},
filters: [
{ dataSize: MARKET_STATE_LAYOUT_V3.span },
{
memcmp: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
bytes: config.quoteToken.mint.toBase58(),
},
},
],
});
const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, {
commitment: this.connection.commitment,
dataSlice: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf("eventQueue"),
length: MINIMAL_MARKET_STATE_LAYOUT_V3.span,
},
filters: [
{ dataSize: MARKET_STATE_LAYOUT_V3.span },
{
memcmp: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf("quoteMint"),
bytes: config.quoteToken.mint.toBase58(),
},
},
],
});
for (const account of accounts) {
const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data);
this.keys.set(account.pubkey.toString(), market);
}
for (const account of accounts) {
const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data);
this.keys.set(account.pubkey.toString(), market);
}
logger.debug({}, `Cached ${this.keys.size} markets`);
}
logger.debug({}, `Cached ${this.keys.size} markets`);
}
public save(marketId: string, keys: MinimalMarketLayoutV3) {
if (!this.keys.has(marketId)) {
logger.trace({}, `Caching new market: ${marketId}`);
this.keys.set(marketId, keys);
}
}
public save(marketId: string, keys: MinimalMarketLayoutV3) {
if (!this.keys.has(marketId)) {
logger.trace({}, `Caching new market: ${marketId}`);
this.keys.set(marketId, keys);
}
}
public async get(marketId: string): Promise<MinimalMarketLayoutV3> {
if (this.keys.has(marketId)) {
return this.keys.get(marketId)!;
}
public async get(marketId: string): Promise<MinimalMarketLayoutV3> {
if (this.keys.has(marketId)) {
return this.keys.get(marketId)!;
}
logger.trace({}, `Fetching new market keys for ${marketId}`);
const market = await this.fetch(marketId);
this.keys.set(marketId, market);
return market;
}
logger.trace({}, `Fetching new market keys for ${marketId}`);
const market = await this.fetch(marketId);
this.keys.set(marketId, market);
return market;
}
private fetch(marketId: string): Promise<MinimalMarketLayoutV3> {
return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment);
}
private fetch(marketId: string): Promise<MinimalMarketLayoutV3> {
return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment);
}
}

12
cache/optimize.js vendored Normal file

File diff suppressed because one or more lines are too long

30
cache/pool.cache.js vendored Normal file
View File

@ -0,0 +1,30 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PoolCache = void 0;
const helpers_1 = require("../helpers");
class PoolCache {
constructor() {
this.keys = new Map();
}
save(id, state) {
if (!this.keys.has(state.baseMint.toString())) {
helpers_1.logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`);
this.keys.set(state.baseMint.toString(), { id, state });
}
}
get(mint) {
return __awaiter(this, void 0, void 0, function* () {
return this.keys.get(mint);
});
}
}
exports.PoolCache = PoolCache;

30
cache/pool.cache.ts vendored
View File

@ -1,20 +1,20 @@
import { LiquidityStateV4 } from '@raydium-io/raydium-sdk';
import { logger } from '../helpers';
import { LiquidityStateV4 } from "@raydium-io/raydium-sdk";
import { logger } from "../helpers";
export class PoolCache {
private readonly keys: Map<string, { id: string; state: LiquidityStateV4 }> = new Map<
string,
{ id: string; state: LiquidityStateV4 }
>();
private readonly keys: Map<string, { id: string; state: LiquidityStateV4 }> = new Map<
string,
{ id: string; state: LiquidityStateV4 }
>();
public save(id: string, state: LiquidityStateV4) {
if (!this.keys.has(state.baseMint.toString())) {
logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`);
this.keys.set(state.baseMint.toString(), { id, state });
}
}
public save(id: string, state: LiquidityStateV4) {
if (!this.keys.has(state.baseMint.toString())) {
logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`);
this.keys.set(state.baseMint.toString(), { id, state });
}
}
public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4 }> {
return this.keys.get(mint)!;
}
public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4 }> {
return this.keys.get(mint)!;
}
}

35
cache/snipe-list.cache.js vendored Normal file
View File

@ -0,0 +1,35 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SnipeListCache = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const helpers_1 = require("../helpers");
class SnipeListCache {
constructor() {
this.snipeList = [];
this.fileLocation = path_1.default.join(__dirname, "../snipe-list.txt");
setInterval(() => this.loadSnipeList(), helpers_1.SNIPE_LIST_REFRESH_INTERVAL);
}
init() {
this.loadSnipeList();
}
isInList(mint) {
return this.snipeList.includes(mint);
}
loadSnipeList() {
helpers_1.logger.trace(`Refreshing snipe list...`);
const count = this.snipeList.length;
const data = fs_1.default.readFileSync(this.fileLocation, "utf-8");
this.snipeList = data
.split("\n")
.map((a) => a.trim())
.filter((a) => a);
if (this.snipeList.length != count) {
helpers_1.logger.info(`Loaded snipe list: ${this.snipeList.length}`);
}
}
}
exports.SnipeListCache = SnipeListCache;

View File

@ -1,35 +1,35 @@
import fs from 'fs';
import path from 'path';
import { logger, SNIPE_LIST_REFRESH_INTERVAL } from '../helpers';
import fs from "fs";
import path from "path";
import { logger, SNIPE_LIST_REFRESH_INTERVAL } from "../helpers";
export class SnipeListCache {
private snipeList: string[] = [];
private fileLocation = path.join(__dirname, '../snipe-list.txt');
private snipeList: string[] = [];
private fileLocation = path.join(__dirname, "../snipe-list.txt");
constructor() {
setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL);
}
constructor() {
setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL);
}
public init() {
this.loadSnipeList();
}
public init() {
this.loadSnipeList();
}
public isInList(mint: string) {
return this.snipeList.includes(mint);
}
public isInList(mint: string) {
return this.snipeList.includes(mint);
}
private loadSnipeList() {
logger.trace(`Refreshing snipe list...`);
private loadSnipeList() {
logger.trace(`Refreshing snipe list...`);
const count = this.snipeList.length;
const data = fs.readFileSync(this.fileLocation, 'utf-8');
this.snipeList = data
.split('\n')
.map((a) => a.trim())
.filter((a) => a);
const count = this.snipeList.length;
const data = fs.readFileSync(this.fileLocation, "utf-8");
this.snipeList = data
.split("\n")
.map((a) => a.trim())
.filter((a) => a);
if (this.snipeList.length != count) {
logger.info(`Loaded snipe list: ${this.snipeList.length}`);
}
}
if (this.snipeList.length != count) {
logger.info(`Loaded snipe list: ${this.snipeList.length}`);
}
}
}

43
filters/burn.filter.js Normal file
View File

@ -0,0 +1,43 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BurnFilter = void 0;
const helpers_1 = require("../helpers");
class BurnFilter {
constructor(connection) {
this.connection = connection;
this.cachedResult = undefined;
}
execute(poolKeys) {
return __awaiter(this, void 0, void 0, function* () {
if (this.cachedResult) {
return this.cachedResult;
}
try {
const amount = yield this.connection.getTokenSupply(poolKeys.lpMint, this.connection.commitment);
const burned = amount.value.uiAmount === 0;
const result = { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" };
if (result.ok) {
this.cachedResult = result;
}
return result;
}
catch (e) {
if (e.code == -32602) {
return { ok: true };
}
helpers_1.logger.error({ mint: poolKeys.baseMint }, `Failed to check if LP is burned`);
}
return { ok: false, message: "Failed to check if LP is burned" };
});
}
}
exports.BurnFilter = BurnFilter;

View File

@ -1,24 +1,36 @@
import { Filter, FilterResult } from './pool-filters';
import { Connection } from '@solana/web3.js';
import { LiquidityStateV4 } from '@raydium-io/raydium-sdk';
import { logger } from '../helpers';
import { Filter, FilterResult } from "./pool-filters";
import { Connection } from "@solana/web3.js";
import { LiquidityPoolKeysV4 } from "@raydium-io/raydium-sdk";
import { logger } from "../helpers";
export class BurnFilter implements Filter {
constructor(private readonly connection: Connection) {}
private cachedResult: FilterResult | undefined = undefined;
async execute(poolState: LiquidityStateV4): Promise<FilterResult> {
try {
const amount = await this.connection.getTokenSupply(poolState.lpMint, this.connection.commitment);
const burned = amount.value.uiAmount === 0;
return { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" };
} catch (e: any) {
if (e.code == -32602) {
return { ok: true };
}
constructor(private readonly connection: Connection) {}
logger.error({ mint: poolState.baseMint }, `Failed to check if LP is burned`);
}
async execute(poolKeys: LiquidityPoolKeysV4): Promise<FilterResult> {
if (this.cachedResult) {
return this.cachedResult;
}
return { ok: false, message: 'Failed to check if LP is burned' };
}
try {
const amount = await this.connection.getTokenSupply(poolKeys.lpMint, this.connection.commitment);
const burned = amount.value.uiAmount === 0;
const result = { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" };
if (result.ok) {
this.cachedResult = result;
}
return result;
} catch (e: any) {
if (e.code == -32602) {
return { ok: true };
}
logger.error({ mint: poolKeys.baseMint }, `Failed to check if LP is burned`);
}
return { ok: false, message: "Failed to check if LP is burned" };
}
}

21
filters/index.js Normal file
View File

@ -0,0 +1,21 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./burn.filter"), exports);
__exportStar(require("./mutable.filter"), exports);
__exportStar(require("./pool-filters"), exports);
__exportStar(require("./pool-size.filter"), exports);
__exportStar(require("./renounced.filter"), exports);

View File

@ -1,4 +1,5 @@
export * from './burn.filter';
export * from './pool-filters';
export * from './pool-size.filter';
export * from './renounced.filter';
export * from "./burn.filter";
export * from "./mutable.filter";
export * from "./pool-filters";
export * from "./pool-size.filter";
export * from "./renounced.filter";

76
filters/mutable.filter.js Normal file
View File

@ -0,0 +1,76 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MutableFilter = void 0;
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
const helpers_1 = require("../helpers");
class MutableFilter {
constructor(connection, metadataSerializer, checkMutable, checkSocials) {
this.connection = connection;
this.metadataSerializer = metadataSerializer;
this.checkMutable = checkMutable;
this.checkSocials = checkSocials;
this.errorMessage = [];
this.cachedResult = undefined;
if (this.checkMutable) {
this.errorMessage.push("mutable");
}
if (this.checkSocials) {
this.errorMessage.push("socials");
}
}
execute(poolKeys) {
return __awaiter(this, void 0, void 0, function* () {
if (this.cachedResult) {
return this.cachedResult;
}
try {
const metadataPDA = (0, raydium_sdk_1.getPdaMetadataKey)(poolKeys.baseMint);
const metadataAccount = yield this.connection.getAccountInfo(metadataPDA.publicKey, this.connection.commitment);
if (!(metadataAccount === null || metadataAccount === void 0 ? void 0 : metadataAccount.data)) {
return { ok: false, message: "Mutable -> Failed to fetch account data" };
}
const deserialize = this.metadataSerializer.deserialize(metadataAccount.data);
const mutable = !this.checkMutable || deserialize[0].isMutable;
const hasSocials = !this.checkSocials || (yield this.hasSocials(deserialize[0]));
const ok = !mutable && hasSocials;
const message = [];
if (mutable) {
message.push("metadata can be changed");
}
if (!hasSocials) {
message.push("has no socials");
}
const result = { ok: ok, message: ok ? undefined : `MutableSocials -> Token ${message.join(" and ")}` };
if (!mutable) {
this.cachedResult = result;
}
return result;
}
catch (e) {
helpers_1.logger.error({ mint: poolKeys.baseMint }, `MutableSocials -> Failed to check ${this.errorMessage.join(" and ")}`);
}
return {
ok: false,
message: `MutableSocials -> Failed to check ${this.errorMessage.join(" and ")}`,
};
});
}
hasSocials(metadata) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch(metadata.uri);
const data = yield response.json();
return Object.values((_a = data === null || data === void 0 ? void 0 : data.extensions) !== null && _a !== void 0 ? _a : {}).filter((value) => value).length > 0;
});
}
}
exports.MutableFilter = MutableFilter;

77
filters/mutable.filter.ts Normal file
View File

@ -0,0 +1,77 @@
import { Filter, FilterResult } from "./pool-filters";
import { Connection } from "@solana/web3.js";
import { LiquidityPoolKeysV4 } from "@raydium-io/raydium-sdk";
import { getPdaMetadataKey } from "@raydium-io/raydium-sdk";
import { MetadataAccountData, MetadataAccountDataArgs } from "@metaplex-foundation/mpl-token-metadata";
import { Serializer } from "@metaplex-foundation/umi/serializers";
import { logger } from "../helpers";
export class MutableFilter implements Filter {
private readonly errorMessage: string[] = [];
private cachedResult: FilterResult | undefined = undefined;
constructor(
private readonly connection: Connection,
private readonly metadataSerializer: Serializer<MetadataAccountDataArgs, MetadataAccountData>,
private readonly checkMutable: boolean,
private readonly checkSocials: boolean,
) {
if (this.checkMutable) {
this.errorMessage.push("mutable");
}
if (this.checkSocials) {
this.errorMessage.push("socials");
}
}
async execute(poolKeys: LiquidityPoolKeysV4): Promise<FilterResult> {
if (this.cachedResult) {
return this.cachedResult;
}
try {
const metadataPDA = getPdaMetadataKey(poolKeys.baseMint);
const metadataAccount = await this.connection.getAccountInfo(metadataPDA.publicKey, this.connection.commitment);
if (!metadataAccount?.data) {
return { ok: false, message: "Mutable -> Failed to fetch account data" };
}
const deserialize = this.metadataSerializer.deserialize(metadataAccount.data);
const mutable = !this.checkMutable || deserialize[0].isMutable;
const hasSocials = !this.checkSocials || (await this.hasSocials(deserialize[0]));
const ok = !mutable && hasSocials;
const message: string[] = [];
if (mutable) {
message.push("metadata can be changed");
}
if (!hasSocials) {
message.push("has no socials");
}
const result = { ok: ok, message: ok ? undefined : `MutableSocials -> Token ${message.join(" and ")}` };
if (!mutable) {
this.cachedResult = result;
}
return result;
} catch (e) {
logger.error({ mint: poolKeys.baseMint }, `MutableSocials -> Failed to check ${this.errorMessage.join(" and ")}`);
}
return {
ok: false,
message: `MutableSocials -> Failed to check ${this.errorMessage.join(" and ")}`,
};
}
private async hasSocials(metadata: MetadataAccountData) {
const response = await fetch(metadata.uri);
const data = await response.json();
return Object.values(data?.extensions ?? {}).filter((value: any) => value).length > 0;
}
}

54
filters/pool-filters.js Normal file
View File

@ -0,0 +1,54 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PoolFilters = void 0;
const mpl_token_metadata_1 = require("@metaplex-foundation/mpl-token-metadata");
const burn_filter_1 = require("./burn.filter");
const mutable_filter_1 = require("./mutable.filter");
const renounced_filter_1 = require("./renounced.filter");
const pool_size_filter_1 = require("./pool-size.filter");
const helpers_1 = require("../helpers");
class PoolFilters {
constructor(connection, args) {
this.connection = connection;
this.args = args;
this.filters = [];
if (helpers_1.CHECK_IF_BURNED) {
this.filters.push(new burn_filter_1.BurnFilter(connection));
}
if (helpers_1.CHECK_IF_MINT_IS_RENOUNCED || helpers_1.CHECK_IF_FREEZABLE) {
this.filters.push(new renounced_filter_1.RenouncedFreezeFilter(connection, helpers_1.CHECK_IF_MINT_IS_RENOUNCED, helpers_1.CHECK_IF_FREEZABLE));
}
if (helpers_1.CHECK_IF_MUTABLE || helpers_1.CHECK_IF_SOCIALS) {
this.filters.push(new mutable_filter_1.MutableFilter(connection, (0, mpl_token_metadata_1.getMetadataAccountDataSerializer)(), helpers_1.CHECK_IF_MUTABLE, helpers_1.CHECK_IF_SOCIALS));
}
if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) {
this.filters.push(new pool_size_filter_1.PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize));
}
}
execute(poolKeys) {
return __awaiter(this, void 0, void 0, function* () {
if (this.filters.length === 0) {
return true;
}
const result = yield Promise.all(this.filters.map((f) => f.execute(poolKeys)));
const pass = result.every((r) => r.ok);
if (pass) {
return true;
}
for (const filterResult of result.filter((r) => !r.ok)) {
helpers_1.logger.trace(filterResult.message);
}
return false;
});
}
}
exports.PoolFilters = PoolFilters;

View File

@ -1,61 +1,76 @@
import { Connection } from '@solana/web3.js';
import { LiquidityStateV4, Token, TokenAmount } from '@raydium-io/raydium-sdk';
import { BurnFilter } from './burn.filter';
import { RenouncedFilter } from './renounced.filter';
import { PoolSizeFilter } from './pool-size.filter';
import { CHECK_IF_BURNED, CHECK_IF_MINT_IS_RENOUNCED, logger } from '../helpers';
import { Connection } from "@solana/web3.js";
import { LiquidityPoolKeysV4, Token, TokenAmount } from "@raydium-io/raydium-sdk";
import { getMetadataAccountDataSerializer } from "@metaplex-foundation/mpl-token-metadata";
import { BurnFilter } from "./burn.filter";
import { MutableFilter } from "./mutable.filter";
import { RenouncedFreezeFilter } from "./renounced.filter";
import { PoolSizeFilter } from "./pool-size.filter";
import {
CHECK_IF_BURNED,
CHECK_IF_FREEZABLE,
CHECK_IF_MINT_IS_RENOUNCED,
CHECK_IF_MUTABLE,
CHECK_IF_SOCIALS,
logger,
} from "../helpers";
export interface Filter {
execute(poolState: LiquidityStateV4): Promise<FilterResult>;
execute(poolKeysV4: LiquidityPoolKeysV4): Promise<FilterResult>;
}
export interface FilterResult {
ok: boolean;
message?: string;
ok: boolean;
message?: string;
}
export interface PoolFilterArgs {
minPoolSize: TokenAmount;
maxPoolSize: TokenAmount;
quoteToken: Token;
minPoolSize: TokenAmount;
maxPoolSize: TokenAmount;
quoteToken: Token;
}
export class PoolFilters {
private readonly filters: Filter[] = [];
private readonly filters: Filter[] = [];
constructor(
readonly connection: Connection,
readonly args: PoolFilterArgs,
) {
if (CHECK_IF_BURNED) {
this.filters.push(new BurnFilter(connection));
}
constructor(
readonly connection: Connection,
readonly args: PoolFilterArgs,
) {
if (CHECK_IF_BURNED) {
this.filters.push(new BurnFilter(connection));
}
if (CHECK_IF_MINT_IS_RENOUNCED) {
this.filters.push(new RenouncedFilter(connection));
}
if (CHECK_IF_MINT_IS_RENOUNCED || CHECK_IF_FREEZABLE) {
this.filters.push(new RenouncedFreezeFilter(connection, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_FREEZABLE));
}
if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) {
this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize));
}
}
if (CHECK_IF_MUTABLE || CHECK_IF_SOCIALS) {
this.filters.push(
new MutableFilter(connection, getMetadataAccountDataSerializer(), CHECK_IF_MUTABLE, CHECK_IF_SOCIALS),
);
}
public async execute(poolState: LiquidityStateV4): Promise<boolean> {
if (this.filters.length === 0) {
return true;
}
if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) {
this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize));
}
}
const result = await Promise.all(this.filters.map((f) => f.execute(poolState)));
const pass = result.every((r) => r.ok);
public async execute(poolKeys: LiquidityPoolKeysV4): Promise<boolean> {
if (this.filters.length === 0) {
return true;
}
if (pass) {
return true;
}
const result = await Promise.all(this.filters.map((f) => f.execute(poolKeys)));
const pass = result.every((r) => r.ok);
for (const filterResult of result.filter((r) => !r.ok)) {
logger.info(filterResult.message);
}
if (pass) {
return true;
}
return false;
}
for (const filterResult of result.filter((r) => !r.ok)) {
logger.trace(filterResult.message);
}
return false;
}
}

View File

@ -0,0 +1,50 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PoolSizeFilter = void 0;
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
const helpers_1 = require("../helpers");
class PoolSizeFilter {
constructor(connection, quoteToken, minPoolSize, maxPoolSize) {
this.connection = connection;
this.quoteToken = quoteToken;
this.minPoolSize = minPoolSize;
this.maxPoolSize = maxPoolSize;
}
execute(poolKeys) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
try {
const response = yield this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment);
const poolSize = new raydium_sdk_1.TokenAmount(this.quoteToken, response.value.amount, true);
let inRange = true;
if (!((_a = this.maxPoolSize) === null || _a === void 0 ? void 0 : _a.isZero())) {
inRange = poolSize.raw.lte(this.maxPoolSize.raw);
if (!inRange) {
return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` };
}
}
if (!((_b = this.minPoolSize) === null || _b === void 0 ? void 0 : _b.isZero())) {
inRange = poolSize.raw.gte(this.minPoolSize.raw);
if (!inRange) {
return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` };
}
}
return { ok: inRange };
}
catch (error) {
helpers_1.logger.error({ mint: poolKeys.baseMint }, `Failed to check pool size`);
}
return { ok: false, message: "PoolSize -> Failed to check pool size" };
});
}
}
exports.PoolSizeFilter = PoolSizeFilter;

View File

@ -1,43 +1,43 @@
import { Filter, FilterResult } from './pool-filters';
import { LiquidityStateV4, Token, TokenAmount } from '@raydium-io/raydium-sdk';
import { Connection } from '@solana/web3.js';
import { logger } from '../helpers';
import { Filter, FilterResult } from "./pool-filters";
import { LiquidityPoolKeysV4, Token, TokenAmount } from "@raydium-io/raydium-sdk";
import { Connection } from "@solana/web3.js";
import { logger } from "../helpers";
export class PoolSizeFilter implements Filter {
constructor(
private readonly connection: Connection,
private readonly quoteToken: Token,
private readonly minPoolSize: TokenAmount,
private readonly maxPoolSize: TokenAmount,
) {}
constructor(
private readonly connection: Connection,
private readonly quoteToken: Token,
private readonly minPoolSize: TokenAmount,
private readonly maxPoolSize: TokenAmount,
) {}
async execute(poolState: LiquidityStateV4): Promise<FilterResult> {
try {
const response = await this.connection.getTokenAccountBalance(poolState.quoteVault, this.connection.commitment);
const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true);
let inRange = true;
async execute(poolKeys: LiquidityPoolKeysV4): Promise<FilterResult> {
try {
const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment);
const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true);
let inRange = true;
if (!this.maxPoolSize?.isZero()) {
inRange = poolSize.raw.lte(this.maxPoolSize.raw);
if (!this.maxPoolSize?.isZero()) {
inRange = poolSize.raw.lte(this.maxPoolSize.raw);
if (!inRange) {
return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` };
}
}
if (!inRange) {
return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` };
}
}
if (!this.minPoolSize?.isZero()) {
inRange = poolSize.raw.gte(this.minPoolSize.raw);
if (!this.minPoolSize?.isZero()) {
inRange = poolSize.raw.gte(this.minPoolSize.raw);
if (!inRange) {
return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` };
}
}
if (!inRange) {
return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` };
}
}
return { ok: inRange };
} catch (error) {
logger.error({ mint: poolState.baseMint }, `Failed to check pool size`);
}
return { ok: inRange };
} catch (error) {
logger.error({ mint: poolKeys.baseMint }, `Failed to check pool size`);
}
return { ok: false, message: 'PoolSize -> Failed to check pool size' };
}
return { ok: false, message: "PoolSize -> Failed to check pool size" };
}
}

View File

@ -0,0 +1,69 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenouncedFreezeFilter = void 0;
const spl_token_1 = require("@solana/spl-token");
const helpers_1 = require("../helpers");
class RenouncedFreezeFilter {
constructor(connection, checkRenounced, checkFreezable) {
this.connection = connection;
this.checkRenounced = checkRenounced;
this.checkFreezable = checkFreezable;
this.errorMessage = [];
this.cachedResult = undefined;
if (this.checkRenounced) {
this.errorMessage.push("mint");
}
if (this.checkFreezable) {
this.errorMessage.push("freeze");
}
}
execute(poolKeys) {
return __awaiter(this, void 0, void 0, function* () {
if (this.cachedResult) {
return this.cachedResult;
}
try {
const accountInfo = yield this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment);
if (!(accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.data)) {
return { ok: false, message: "RenouncedFreeze -> Failed to fetch account data" };
}
const deserialize = spl_token_1.MintLayout.decode(accountInfo.data);
const renounced = !this.checkRenounced || deserialize.mintAuthorityOption === 0;
const freezable = !this.checkFreezable || deserialize.freezeAuthorityOption !== 0;
const ok = renounced && !freezable;
const message = [];
if (!renounced) {
message.push("mint");
}
if (freezable) {
message.push("freeze");
}
const result = {
ok: ok,
message: ok ? undefined : `RenouncedFreeze -> Creator can ${message.join(" and ")} tokens`,
};
if (result.ok) {
this.cachedResult = result;
}
return result;
}
catch (e) {
helpers_1.logger.error({ mint: poolKeys.baseMint }, `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(" and ")} tokens`);
}
return {
ok: false,
message: `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(" and ")} tokens`,
};
});
}
}
exports.RenouncedFreezeFilter = RenouncedFreezeFilter;

View File

@ -1,26 +1,72 @@
import { Filter, FilterResult } from './pool-filters';
import { MintLayout } from '@solana/spl-token';
import { Connection } from '@solana/web3.js';
import { LiquidityStateV4 } from '@raydium-io/raydium-sdk';
import { logger } from '../helpers';
import { Filter, FilterResult } from "./pool-filters";
import { MintLayout } from "@solana/spl-token";
import { Connection } from "@solana/web3.js";
import { LiquidityPoolKeysV4 } from "@raydium-io/raydium-sdk";
import { logger } from "../helpers";
export class RenouncedFilter implements Filter {
constructor(private readonly connection: Connection) {}
export class RenouncedFreezeFilter implements Filter {
private readonly errorMessage: string[] = [];
private cachedResult: FilterResult | undefined = undefined;
async execute(poolState: LiquidityStateV4): Promise<FilterResult> {
try {
const accountInfo = await this.connection.getAccountInfo(poolState.baseMint, this.connection.commitment);
if (!accountInfo?.data) {
return { ok: false, message: 'Renounced -> Failed to fetch account data' };
}
constructor(
private readonly connection: Connection,
private readonly checkRenounced: boolean,
private readonly checkFreezable: boolean,
) {
if (this.checkRenounced) {
this.errorMessage.push("mint");
}
const deserialize = MintLayout.decode(accountInfo.data);
const renounced = deserialize.mintAuthorityOption === 0;
return { ok: renounced, message: renounced ? undefined : 'Renounced -> Creator can mint more tokens' };
} catch (e) {
logger.error({ mint: poolState.baseMint }, `Failed to check if mint is renounced`);
}
if (this.checkFreezable) {
this.errorMessage.push("freeze");
}
}
return { ok: false, message: 'Renounced -> Failed to check if mint is renounced' };
}
async execute(poolKeys: LiquidityPoolKeysV4): Promise<FilterResult> {
if (this.cachedResult) {
return this.cachedResult;
}
try {
const accountInfo = await this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment);
if (!accountInfo?.data) {
return { ok: false, message: "RenouncedFreeze -> Failed to fetch account data" };
}
const deserialize = MintLayout.decode(accountInfo.data);
const renounced = !this.checkRenounced || deserialize.mintAuthorityOption === 0;
const freezable = !this.checkFreezable || deserialize.freezeAuthorityOption !== 0;
const ok = renounced && !freezable;
const message: string[] = [];
if (!renounced) {
message.push("mint");
}
if (freezable) {
message.push("freeze");
}
const result = {
ok: ok,
message: ok ? undefined : `RenouncedFreeze -> Creator can ${message.join(" and ")} tokens`,
};
if (result.ok) {
this.cachedResult = result;
}
return result;
} catch (e) {
logger.error(
{ mint: poolKeys.baseMint },
`RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(" and ")} tokens`,
);
}
return {
ok: false,
message: `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(" and ")} tokens`,
};
}
}

63
helpers/constants.js Normal file
View File

@ -0,0 +1,63 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SNIPE_LIST_REFRESH_INTERVAL = exports.USE_SNIPE_LIST = exports.MAX_POOL_SIZE = exports.MIN_POOL_SIZE = exports.CHECK_IF_BURNED = exports.CHECK_IF_FREEZABLE = exports.CHECK_IF_MINT_IS_RENOUNCED = exports.CHECK_IF_SOCIALS = exports.CHECK_IF_MUTABLE = exports.CONSECUTIVE_FILTER_MATCHES = exports.FILTER_CHECK_DURATION = exports.FILTER_CHECK_INTERVAL = exports.SKIP_SELLING_IF_LOST_MORE_THAN = exports.SELL_SLIPPAGE = exports.PRICE_CHECK_DURATION = exports.PRICE_CHECK_INTERVAL = exports.TRAILING_STOP_LOSS = exports.STOP_LOSS = exports.TAKE_PROFIT = exports.MAX_SELL_RETRIES = exports.AUTO_SELL_DELAY = exports.AUTO_SELL = exports.BUY_SLIPPAGE = exports.MAX_BUY_RETRIES = exports.QUOTE_AMOUNT = exports.QUOTE_MINT = exports.AUTO_BUY_DELAY = exports.CUSTOM_FEE = exports.TRANSACTION_EXECUTOR = exports.CACHE_NEW_MARKETS = exports.PRE_LOAD_EXISTING_MARKETS = exports.COMPUTE_UNIT_PRICE = exports.COMPUTE_UNIT_LIMIT = exports.MAX_TOKENS_AT_THE_TIME = exports.LOG_LEVEL = exports.RPC_WEBSOCKET_ENDPOINT = exports.RPC_ENDPOINT = exports.COMMITMENT_LEVEL = exports.NETWORK = exports.PRIVATE_KEY = void 0;
const dotenv_1 = __importDefault(require("dotenv"));
const logger_1 = require("./logger");
dotenv_1.default.config();
const retrieveEnvVariable = (variableName, logger) => {
const variable = process.env[variableName] || "";
if (!variable) {
logger.error(`${variableName} is not set`);
process.exit(1);
}
return variable;
};
// Wallet
exports.PRIVATE_KEY = retrieveEnvVariable("PRIVATE_KEY", logger_1.logger);
// Connection
exports.NETWORK = "mainnet-beta";
exports.COMMITMENT_LEVEL = retrieveEnvVariable("COMMITMENT_LEVEL", logger_1.logger);
exports.RPC_ENDPOINT = retrieveEnvVariable("RPC_ENDPOINT", logger_1.logger);
exports.RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable("RPC_WEBSOCKET_ENDPOINT", logger_1.logger);
// Bot
exports.LOG_LEVEL = retrieveEnvVariable("LOG_LEVEL", logger_1.logger);
exports.MAX_TOKENS_AT_THE_TIME = Number(retrieveEnvVariable("MAX_TOKENS_AT_THE_TIME", logger_1.logger));
exports.COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable("COMPUTE_UNIT_LIMIT", logger_1.logger));
exports.COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable("COMPUTE_UNIT_PRICE", logger_1.logger));
exports.PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable("PRE_LOAD_EXISTING_MARKETS", logger_1.logger) === "true";
exports.CACHE_NEW_MARKETS = retrieveEnvVariable("CACHE_NEW_MARKETS", logger_1.logger) === "true";
exports.TRANSACTION_EXECUTOR = retrieveEnvVariable("TRANSACTION_EXECUTOR", logger_1.logger);
exports.CUSTOM_FEE = retrieveEnvVariable("CUSTOM_FEE", logger_1.logger);
// Buy
exports.AUTO_BUY_DELAY = Number(retrieveEnvVariable("AUTO_BUY_DELAY", logger_1.logger));
exports.QUOTE_MINT = retrieveEnvVariable("QUOTE_MINT", logger_1.logger);
exports.QUOTE_AMOUNT = retrieveEnvVariable("QUOTE_AMOUNT", logger_1.logger);
exports.MAX_BUY_RETRIES = Number(retrieveEnvVariable("MAX_BUY_RETRIES", logger_1.logger));
exports.BUY_SLIPPAGE = Number(retrieveEnvVariable("BUY_SLIPPAGE", logger_1.logger));
// Sell
exports.AUTO_SELL = retrieveEnvVariable("AUTO_SELL", logger_1.logger) === "true";
exports.AUTO_SELL_DELAY = Number(retrieveEnvVariable("AUTO_SELL_DELAY", logger_1.logger));
exports.MAX_SELL_RETRIES = Number(retrieveEnvVariable("MAX_SELL_RETRIES", logger_1.logger));
exports.TAKE_PROFIT = Number(retrieveEnvVariable("TAKE_PROFIT", logger_1.logger));
exports.STOP_LOSS = Number(retrieveEnvVariable("STOP_LOSS", logger_1.logger));
exports.TRAILING_STOP_LOSS = retrieveEnvVariable("TRAILING_STOP_LOSS", logger_1.logger) === "true";
exports.PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable("PRICE_CHECK_INTERVAL", logger_1.logger));
exports.PRICE_CHECK_DURATION = Number(retrieveEnvVariable("PRICE_CHECK_DURATION", logger_1.logger));
exports.SELL_SLIPPAGE = Number(retrieveEnvVariable("SELL_SLIPPAGE", logger_1.logger));
exports.SKIP_SELLING_IF_LOST_MORE_THAN = Number(retrieveEnvVariable("SKIP_SELLING_IF_LOST_MORE_THAN", logger_1.logger));
// Filters
exports.FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable("FILTER_CHECK_INTERVAL", logger_1.logger));
exports.FILTER_CHECK_DURATION = Number(retrieveEnvVariable("FILTER_CHECK_DURATION", logger_1.logger));
exports.CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable("CONSECUTIVE_FILTER_MATCHES", logger_1.logger));
exports.CHECK_IF_MUTABLE = retrieveEnvVariable("CHECK_IF_MUTABLE", logger_1.logger) === "true";
exports.CHECK_IF_SOCIALS = retrieveEnvVariable("CHECK_IF_SOCIALS", logger_1.logger) === "true";
exports.CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable("CHECK_IF_MINT_IS_RENOUNCED", logger_1.logger) === "true";
exports.CHECK_IF_FREEZABLE = retrieveEnvVariable("CHECK_IF_FREEZABLE", logger_1.logger) === "true";
exports.CHECK_IF_BURNED = retrieveEnvVariable("CHECK_IF_BURNED", logger_1.logger) === "true";
exports.MIN_POOL_SIZE = retrieveEnvVariable("MIN_POOL_SIZE", logger_1.logger);
exports.MAX_POOL_SIZE = retrieveEnvVariable("MAX_POOL_SIZE", logger_1.logger);
exports.USE_SNIPE_LIST = retrieveEnvVariable("USE_SNIPE_LIST", logger_1.logger) === "true";
exports.SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable("SNIPE_LIST_REFRESH_INTERVAL", logger_1.logger));

View File

@ -1,59 +1,67 @@
import { Logger } from 'pino';
import dotenv from 'dotenv';
import { Commitment } from '@solana/web3.js';
import { logger } from './logger';
import { Logger } from "pino";
import dotenv from "dotenv";
import { Commitment } from "@solana/web3.js";
import { logger } from "./logger";
dotenv.config();
const retrieveEnvVariable = (variableName: string, logger: Logger) => {
const variable = process.env[variableName] || '';
if (!variable) {
logger.error(`${variableName} is not set`);
process.exit(1);
}
return variable;
const variable = process.env[variableName] || "";
if (!variable) {
logger.error(`${variableName} is not set`);
process.exit(1);
}
return variable;
};
// Wallet
export const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger);
export const PRIVATE_KEY = retrieveEnvVariable("PRIVATE_KEY", logger);
// Connection
export const NETWORK = 'mainnet-beta';
export const COMMITMENT_LEVEL: Commitment = retrieveEnvVariable('COMMITMENT_LEVEL', logger) as Commitment;
export const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger);
export const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable('RPC_WEBSOCKET_ENDPOINT', logger);
export const NETWORK = "mainnet-beta";
export const COMMITMENT_LEVEL: Commitment = retrieveEnvVariable("COMMITMENT_LEVEL", logger) as Commitment;
export const RPC_ENDPOINT = retrieveEnvVariable("RPC_ENDPOINT", logger);
export const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable("RPC_WEBSOCKET_ENDPOINT", logger);
// Bot
export const LOG_LEVEL = retrieveEnvVariable('LOG_LEVEL', logger);
export const ONE_TOKEN_AT_A_TIME = retrieveEnvVariable('ONE_TOKEN_AT_A_TIME', logger) === 'true';
export const COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable('COMPUTE_UNIT_LIMIT', logger));
export const COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable('COMPUTE_UNIT_PRICE', logger));
export const PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable('PRE_LOAD_EXISTING_MARKETS', logger) === 'true';
export const CACHE_NEW_MARKETS = retrieveEnvVariable('CACHE_NEW_MARKETS', logger) === 'true';
export const TRANSACTION_EXECUTOR = retrieveEnvVariable('TRANSACTION_EXECUTOR', logger);
export const WARP_FEE = retrieveEnvVariable('WARP_FEE', logger);
export const LOG_LEVEL = retrieveEnvVariable("LOG_LEVEL", logger);
export const MAX_TOKENS_AT_THE_TIME = Number(retrieveEnvVariable("MAX_TOKENS_AT_THE_TIME", logger));
export const COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable("COMPUTE_UNIT_LIMIT", logger));
export const COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable("COMPUTE_UNIT_PRICE", logger));
export const PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable("PRE_LOAD_EXISTING_MARKETS", logger) === "true";
export const CACHE_NEW_MARKETS = retrieveEnvVariable("CACHE_NEW_MARKETS", logger) === "true";
export const TRANSACTION_EXECUTOR = retrieveEnvVariable("TRANSACTION_EXECUTOR", logger);
export const CUSTOM_FEE = retrieveEnvVariable("CUSTOM_FEE", logger);
// Buy
export const AUTO_BUY_DELAY = Number(retrieveEnvVariable('AUTO_BUY_DELAY', logger));
export const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger);
export const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger);
export const MAX_BUY_RETRIES = Number(retrieveEnvVariable('MAX_BUY_RETRIES', logger));
export const BUY_SLIPPAGE = Number(retrieveEnvVariable('BUY_SLIPPAGE', logger));
export const AUTO_BUY_DELAY = Number(retrieveEnvVariable("AUTO_BUY_DELAY", logger));
export const QUOTE_MINT = retrieveEnvVariable("QUOTE_MINT", logger);
export const QUOTE_AMOUNT = retrieveEnvVariable("QUOTE_AMOUNT", logger);
export const MAX_BUY_RETRIES = Number(retrieveEnvVariable("MAX_BUY_RETRIES", logger));
export const BUY_SLIPPAGE = Number(retrieveEnvVariable("BUY_SLIPPAGE", logger));
// Sell
export const AUTO_SELL = retrieveEnvVariable('AUTO_SELL', logger) === 'true';
export const AUTO_SELL_DELAY = Number(retrieveEnvVariable('AUTO_SELL_DELAY', logger));
export const MAX_SELL_RETRIES = Number(retrieveEnvVariable('MAX_SELL_RETRIES', logger));
export const TAKE_PROFIT = Number(retrieveEnvVariable('TAKE_PROFIT', logger));
export const STOP_LOSS = Number(retrieveEnvVariable('STOP_LOSS', logger));
export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable('PRICE_CHECK_INTERVAL', logger));
export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable('PRICE_CHECK_DURATION', logger));
export const SELL_SLIPPAGE = Number(retrieveEnvVariable('SELL_SLIPPAGE', logger));
export const AUTO_SELL = retrieveEnvVariable("AUTO_SELL", logger) === "true";
export const AUTO_SELL_DELAY = Number(retrieveEnvVariable("AUTO_SELL_DELAY", logger));
export const MAX_SELL_RETRIES = Number(retrieveEnvVariable("MAX_SELL_RETRIES", logger));
export const TAKE_PROFIT = Number(retrieveEnvVariable("TAKE_PROFIT", logger));
export const STOP_LOSS = Number(retrieveEnvVariable("STOP_LOSS", logger));
export const TRAILING_STOP_LOSS = retrieveEnvVariable("TRAILING_STOP_LOSS", logger) === "true";
export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable("PRICE_CHECK_INTERVAL", logger));
export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable("PRICE_CHECK_DURATION", logger));
export const SELL_SLIPPAGE = Number(retrieveEnvVariable("SELL_SLIPPAGE", logger));
export const SKIP_SELLING_IF_LOST_MORE_THAN = Number(retrieveEnvVariable("SKIP_SELLING_IF_LOST_MORE_THAN", logger));
// Filters
export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true';
export const CHECK_IF_BURNED = retrieveEnvVariable('CHECK_IF_BURNED', logger) === 'true';
export const MIN_POOL_SIZE = retrieveEnvVariable('MIN_POOL_SIZE', logger);
export const MAX_POOL_SIZE = retrieveEnvVariable('MAX_POOL_SIZE', logger);
export const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true';
export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger));
export const FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable("FILTER_CHECK_INTERVAL", logger));
export const FILTER_CHECK_DURATION = Number(retrieveEnvVariable("FILTER_CHECK_DURATION", logger));
export const CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable("CONSECUTIVE_FILTER_MATCHES", logger));
export const CHECK_IF_MUTABLE = retrieveEnvVariable("CHECK_IF_MUTABLE", logger) === "true";
export const CHECK_IF_SOCIALS = retrieveEnvVariable("CHECK_IF_SOCIALS", logger) === "true";
export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable("CHECK_IF_MINT_IS_RENOUNCED", logger) === "true";
export const CHECK_IF_FREEZABLE = retrieveEnvVariable("CHECK_IF_FREEZABLE", logger) === "true";
export const CHECK_IF_BURNED = retrieveEnvVariable("CHECK_IF_BURNED", logger) === "true";
export const MIN_POOL_SIZE = retrieveEnvVariable("MIN_POOL_SIZE", logger);
export const MAX_POOL_SIZE = retrieveEnvVariable("MAX_POOL_SIZE", logger);
export const USE_SNIPE_LIST = retrieveEnvVariable("USE_SNIPE_LIST", logger) === "true";
export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable("SNIPE_LIST_REFRESH_INTERVAL", logger));

8
helpers/helper.cache.js Normal file

File diff suppressed because one or more lines are too long

23
helpers/index.js Normal file
View File

@ -0,0 +1,23 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./market"), exports);
__exportStar(require("./liquidity"), exports);
__exportStar(require("./logger"), exports);
__exportStar(require("./constants"), exports);
__exportStar(require("./token"), exports);
__exportStar(require("./wallet"), exports);
__exportStar(require("./promises"), exports);

View File

@ -1,7 +1,7 @@
export * from './market';
export * from './liquidity';
export * from './logger';
export * from './constants';
export * from './token';
export * from './wallet';
export * from './promises'
export * from "./market";
export * from "./liquidity";
export * from "./logger";
export * from "./constants";
export * from "./token";
export * from "./wallet";
export * from "./promises";

41
helpers/liquidity.js Normal file
View File

@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPoolKeys = void 0;
const web3_js_1 = require("@solana/web3.js");
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
function createPoolKeys(id, accountData, minimalMarketLayoutV3) {
return {
id,
baseMint: accountData.baseMint,
quoteMint: accountData.quoteMint,
lpMint: accountData.lpMint,
baseDecimals: accountData.baseDecimal.toNumber(),
quoteDecimals: accountData.quoteDecimal.toNumber(),
lpDecimals: 5,
version: 4,
programId: raydium_sdk_1.MAINNET_PROGRAM_ID.AmmV4,
authority: raydium_sdk_1.Liquidity.getAssociatedAuthority({
programId: raydium_sdk_1.MAINNET_PROGRAM_ID.AmmV4,
}).publicKey,
openOrders: accountData.openOrders,
targetOrders: accountData.targetOrders,
baseVault: accountData.baseVault,
quoteVault: accountData.quoteVault,
marketVersion: 3,
marketProgramId: accountData.marketProgramId,
marketId: accountData.marketId,
marketAuthority: raydium_sdk_1.Market.getAssociatedAuthority({
programId: accountData.marketProgramId,
marketId: accountData.marketId,
}).publicKey,
marketBaseVault: accountData.baseVault,
marketQuoteVault: accountData.quoteVault,
marketBids: minimalMarketLayoutV3.bids,
marketAsks: minimalMarketLayoutV3.asks,
marketEventQueue: minimalMarketLayoutV3.eventQueue,
withdrawQueue: accountData.withdrawQueue,
lpVault: accountData.lpVault,
lookupTableAccount: web3_js_1.PublicKey.default,
};
}
exports.createPoolKeys = createPoolKeys;

View File

@ -1,43 +1,43 @@
import { PublicKey } from '@solana/web3.js';
import { Liquidity, LiquidityPoolKeys, LiquidityStateV4, MAINNET_PROGRAM_ID, Market } from '@raydium-io/raydium-sdk';
import { MinimalMarketLayoutV3 } from './market';
import { PublicKey } from "@solana/web3.js";
import { Liquidity, LiquidityPoolKeys, LiquidityStateV4, MAINNET_PROGRAM_ID, Market } from "@raydium-io/raydium-sdk";
import { MinimalMarketLayoutV3 } from "./market";
export function createPoolKeys(
id: PublicKey,
accountData: LiquidityStateV4,
minimalMarketLayoutV3: MinimalMarketLayoutV3,
id: PublicKey,
accountData: LiquidityStateV4,
minimalMarketLayoutV3: MinimalMarketLayoutV3,
): LiquidityPoolKeys {
return {
id,
baseMint: accountData.baseMint,
quoteMint: accountData.quoteMint,
lpMint: accountData.lpMint,
baseDecimals: accountData.baseDecimal.toNumber(),
quoteDecimals: accountData.quoteDecimal.toNumber(),
lpDecimals: 5,
version: 4,
programId: MAINNET_PROGRAM_ID.AmmV4,
authority: Liquidity.getAssociatedAuthority({
programId: MAINNET_PROGRAM_ID.AmmV4,
}).publicKey,
openOrders: accountData.openOrders,
targetOrders: accountData.targetOrders,
baseVault: accountData.baseVault,
quoteVault: accountData.quoteVault,
marketVersion: 3,
marketProgramId: accountData.marketProgramId,
marketId: accountData.marketId,
marketAuthority: Market.getAssociatedAuthority({
programId: accountData.marketProgramId,
marketId: accountData.marketId,
}).publicKey,
marketBaseVault: accountData.baseVault,
marketQuoteVault: accountData.quoteVault,
marketBids: minimalMarketLayoutV3.bids,
marketAsks: minimalMarketLayoutV3.asks,
marketEventQueue: minimalMarketLayoutV3.eventQueue,
withdrawQueue: accountData.withdrawQueue,
lpVault: accountData.lpVault,
lookupTableAccount: PublicKey.default,
};
return {
id,
baseMint: accountData.baseMint,
quoteMint: accountData.quoteMint,
lpMint: accountData.lpMint,
baseDecimals: accountData.baseDecimal.toNumber(),
quoteDecimals: accountData.quoteDecimal.toNumber(),
lpDecimals: 5,
version: 4,
programId: MAINNET_PROGRAM_ID.AmmV4,
authority: Liquidity.getAssociatedAuthority({
programId: MAINNET_PROGRAM_ID.AmmV4,
}).publicKey,
openOrders: accountData.openOrders,
targetOrders: accountData.targetOrders,
baseVault: accountData.baseVault,
quoteVault: accountData.quoteVault,
marketVersion: 3,
marketProgramId: accountData.marketProgramId,
marketId: accountData.marketId,
marketAuthority: Market.getAssociatedAuthority({
programId: accountData.marketProgramId,
marketId: accountData.marketId,
}).publicKey,
marketBaseVault: accountData.baseVault,
marketQuoteVault: accountData.quoteVault,
marketBids: minimalMarketLayoutV3.bids,
marketAsks: minimalMarketLayoutV3.asks,
marketEventQueue: minimalMarketLayoutV3.eventQueue,
withdrawQueue: accountData.withdrawQueue,
lpVault: accountData.lpVault,
lookupTableAccount: PublicKey.default,
};
}

18
helpers/logger.js Normal file
View File

@ -0,0 +1,18 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
const pino_1 = __importDefault(require("pino"));
const transport = pino_1.default.transport({
target: "pino-pretty",
});
exports.logger = (0, pino_1.default)({
level: "info",
redact: ["poolKeys"],
serializers: {
error: pino_1.default.stdSerializers.err,
},
base: undefined,
}, transport);

View File

@ -1,17 +1,17 @@
import pino from 'pino';
import pino from "pino";
const transport = pino.transport({
target: 'pino-pretty',
target: "pino-pretty",
});
export const logger = pino(
{
level: 'info',
redact: ['poolKeys'],
serializers: {
error: pino.stdSerializers.err,
},
base: undefined,
},
transport,
{
level: "info",
redact: ["poolKeys"],
serializers: {
error: pino.stdSerializers.err,
},
base: undefined,
},
transport,
);

27
helpers/market.js Normal file
View File

@ -0,0 +1,27 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMinimalMarketV3 = exports.MINIMAL_MARKET_STATE_LAYOUT_V3 = void 0;
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
exports.MINIMAL_MARKET_STATE_LAYOUT_V3 = (0, raydium_sdk_1.struct)([(0, raydium_sdk_1.publicKey)("eventQueue"), (0, raydium_sdk_1.publicKey)("bids"), (0, raydium_sdk_1.publicKey)("asks")]);
function getMinimalMarketV3(connection, marketId, commitment) {
return __awaiter(this, void 0, void 0, function* () {
const marketInfo = yield connection.getAccountInfo(marketId, {
commitment,
dataSlice: {
offset: raydium_sdk_1.MARKET_STATE_LAYOUT_V3.offsetOf("eventQueue"),
length: 32 * 3,
},
});
return exports.MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo.data);
});
}
exports.getMinimalMarketV3 = getMinimalMarketV3;

View File

@ -1,22 +1,22 @@
import { Commitment, Connection, PublicKey } from '@solana/web3.js';
import { GetStructureSchema, MARKET_STATE_LAYOUT_V3, publicKey, struct } from '@raydium-io/raydium-sdk';
import { Commitment, Connection, PublicKey } from "@solana/web3.js";
import { GetStructureSchema, MARKET_STATE_LAYOUT_V3, publicKey, struct } from "@raydium-io/raydium-sdk";
export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([publicKey('eventQueue'), publicKey('bids'), publicKey('asks')]);
export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([publicKey("eventQueue"), publicKey("bids"), publicKey("asks")]);
export type MinimalMarketStateLayoutV3 = typeof MINIMAL_MARKET_STATE_LAYOUT_V3;
export type MinimalMarketLayoutV3 = GetStructureSchema<MinimalMarketStateLayoutV3>;
export async function getMinimalMarketV3(
connection: Connection,
marketId: PublicKey,
commitment?: Commitment,
connection: Connection,
marketId: PublicKey,
commitment?: Commitment,
): Promise<MinimalMarketLayoutV3> {
const marketInfo = await connection.getAccountInfo(marketId, {
commitment,
dataSlice: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'),
length: 32 * 3,
},
});
const marketInfo = await connection.getAccountInfo(marketId, {
commitment,
dataSlice: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf("eventQueue"),
length: 32 * 3,
},
});
return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data);
return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data);
}

5
helpers/promises.js Normal file
View File

@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sleep = void 0;
const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
exports.sleep = sleep;

20
helpers/token.js Normal file
View File

@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getToken = void 0;
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
const spl_token_1 = require("@solana/spl-token");
const web3_js_1 = require("@solana/web3.js");
function getToken(token) {
switch (token) {
case "WSOL": {
return raydium_sdk_1.Token.WSOL;
}
case "USDC": {
return new raydium_sdk_1.Token(spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), 6, "USDC", "USDC");
}
default: {
throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`);
}
}
}
exports.getToken = getToken;

View File

@ -1,23 +1,23 @@
import { Token } from '@raydium-io/raydium-sdk';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
import { PublicKey } from '@solana/web3.js';
import { Token } from "@raydium-io/raydium-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { PublicKey } from "@solana/web3.js";
export function getToken(token: string) {
switch (token) {
case 'WSOL': {
return Token.WSOL;
}
case 'USDC': {
return new Token(
TOKEN_PROGRAM_ID,
new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
6,
'USDC',
'USDC',
);
}
default: {
throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`);
}
}
switch (token) {
case "WSOL": {
return Token.WSOL;
}
case "USDC": {
return new Token(
TOKEN_PROGRAM_ID,
new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
6,
"USDC",
"USDC",
);
}
default: {
throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`);
}
}
}

25
helpers/wallet.js Normal file
View File

@ -0,0 +1,25 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWallet = void 0;
const web3_js_1 = require("@solana/web3.js");
const bs58_1 = __importDefault(require("bs58"));
const bip39_1 = require("bip39");
const ed25519_hd_key_1 = require("ed25519-hd-key");
function getWallet(wallet) {
// most likely someone pasted the private key in binary format
if (wallet.startsWith("[")) {
return web3_js_1.Keypair.fromSecretKey(JSON.parse(wallet));
}
// most likely someone pasted mnemonic
if (wallet.split(" ").length > 1) {
const seed = (0, bip39_1.mnemonicToSeedSync)(wallet, "");
const path = `m/44'/501'/0'/0'`; // we assume it's first path
return web3_js_1.Keypair.fromSeed((0, ed25519_hd_key_1.derivePath)(path, seed.toString("hex")).key);
}
// most likely someone pasted base58 encoded private key
return web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(wallet));
}
exports.getWallet = getWallet;

View File

@ -1,21 +1,21 @@
import { Keypair } from '@solana/web3.js';
import bs58 from 'bs58';
import { mnemonicToSeedSync } from 'bip39';
import { derivePath } from 'ed25519-hd-key';
import { Keypair } from "@solana/web3.js";
import bs58 from "bs58";
import { mnemonicToSeedSync } from "bip39";
import { derivePath } from "ed25519-hd-key";
export function getWallet(wallet: string): Keypair {
// most likely someone pasted the private key in binary format
if (wallet.startsWith('[')) {
return Keypair.fromSecretKey(JSON.parse(wallet));
}
// most likely someone pasted the private key in binary format
if (wallet.startsWith("[")) {
return Keypair.fromSecretKey(JSON.parse(wallet));
}
// most likely someone pasted mnemonic
if (wallet.split(' ').length > 1) {
const seed = mnemonicToSeedSync(wallet, '');
const path = `m/44'/501'/0'/0'`; // we assume it's first path
return Keypair.fromSeed(derivePath(path, seed.toString('hex')).key);
}
// most likely someone pasted mnemonic
if (wallet.split(" ").length > 1) {
const seed = mnemonicToSeedSync(wallet, "");
const path = `m/44'/501'/0'/0'`; // we assume it's first path
return Keypair.fromSeed(derivePath(path, seed.toString("hex")).key);
}
// most likely someone pasted base58 encoded private key
return Keypair.fromSecretKey(bs58.decode(wallet));
// most likely someone pasted base58 encoded private key
return Keypair.fromSecretKey(bs58.decode(wallet));
}

189
index.js Normal file
View File

@ -0,0 +1,189 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const cache_1 = require("./cache");
const listeners_1 = require("./listeners");
const web3_js_1 = require("@solana/web3.js");
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
const spl_token_1 = require("@solana/spl-token");
const bot_1 = require("./bot");
const transactions_1 = require("./transactions");
const helpers_1 = require("./helpers");
const package_json_1 = require("./package.json");
const warp_transaction_executor_1 = require("./transactions/warp-transaction-executor");
const jito_rpc_transaction_executor_1 = require("./transactions/jito-rpc-transaction-executor");
const connection = new web3_js_1.Connection(helpers_1.RPC_ENDPOINT, {
wsEndpoint: helpers_1.RPC_WEBSOCKET_ENDPOINT,
commitment: helpers_1.COMMITMENT_LEVEL,
});
function printDetails(wallet, quoteToken, bot) {
helpers_1.logger.info(`
.. :-===++++-
.-==+++++++- =+++++++++-
..:::--===+=.=: .+++++++++++:=+++++++++:
.==+++++++++++++++=:+++: .+++++++++++.=++++++++-.
.-+++++++++++++++=:=++++- .+++++++++=:.=+++++-::-.
-:+++++++++++++=:+++++++- .++++++++-:- =+++++=-:
-:++++++=++++=:++++=++++= .++++++++++- =+++++:
-:++++-:=++=:++++=:-+++++:+++++====--:::::::.
::=+-:::==:=+++=::-:--::::::::::---------::.
::-: .::::::::. --------:::..
:- .:.-:::.
WARP DRIVE ACTIVATED 🚀🐟
Made with ❤️ by humans.
Version: ${package_json_1.version}
`);
const botConfig = bot.config;
helpers_1.logger.info('------- CONFIGURATION START -------');
helpers_1.logger.info(`Wallet: ${wallet.publicKey.toString()}`);
helpers_1.logger.info('- Bot -');
helpers_1.logger.info(`Using transaction executor: ${helpers_1.TRANSACTION_EXECUTOR}`);
if (bot.isWarp || bot.isJito) {
helpers_1.logger.info(`${helpers_1.TRANSACTION_EXECUTOR} fee: ${helpers_1.CUSTOM_FEE}`);
}
else {
helpers_1.logger.info(`Compute Unit limit: ${botConfig.unitLimit}`);
helpers_1.logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`);
}
helpers_1.logger.info(`Max tokens at the time: ${botConfig.maxTokensAtTheTime}`);
helpers_1.logger.info(`Pre load existing markets: ${helpers_1.PRE_LOAD_EXISTING_MARKETS}`);
helpers_1.logger.info(`Cache new markets: ${helpers_1.CACHE_NEW_MARKETS}`);
helpers_1.logger.info(`Log level: ${helpers_1.LOG_LEVEL}`);
helpers_1.logger.info('- Buy -');
helpers_1.logger.info(`Buy amount: ${botConfig.quoteAmount.toFixed()} ${botConfig.quoteToken.name}`);
helpers_1.logger.info(`Auto buy delay: ${botConfig.autoBuyDelay} ms`);
helpers_1.logger.info(`Max buy retries: ${botConfig.maxBuyRetries}`);
helpers_1.logger.info(`Buy amount (${quoteToken.symbol}): ${botConfig.quoteAmount.toFixed()}`);
helpers_1.logger.info(`Buy slippage: ${botConfig.buySlippage}%`);
helpers_1.logger.info('- Sell -');
helpers_1.logger.info(`Auto sell: ${helpers_1.AUTO_SELL}`);
helpers_1.logger.info(`Auto sell delay: ${botConfig.autoSellDelay} ms`);
helpers_1.logger.info(`Max sell retries: ${botConfig.maxSellRetries}`);
helpers_1.logger.info(`Sell slippage: ${botConfig.sellSlippage}%`);
helpers_1.logger.info(`Price check interval: ${botConfig.priceCheckInterval} ms`);
helpers_1.logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`);
helpers_1.logger.info(`Take profit: ${botConfig.takeProfit}%`);
helpers_1.logger.info(`Stop loss: ${botConfig.stopLoss}%`);
helpers_1.logger.info(`Trailing stop loss: ${botConfig.trailingStopLoss}`);
helpers_1.logger.info(`Skip selling if lost more than: ${botConfig.skipSellingIfLostMoreThan}%`);
helpers_1.logger.info('- Snipe list -');
helpers_1.logger.info(`Snipe list: ${botConfig.useSnipeList}`);
helpers_1.logger.info(`Snipe list refresh interval: ${helpers_1.SNIPE_LIST_REFRESH_INTERVAL} ms`);
if (botConfig.useSnipeList) {
helpers_1.logger.info('- Filters -');
helpers_1.logger.info(`Filters are disabled when snipe list is on`);
}
else {
helpers_1.logger.info('- Filters -');
helpers_1.logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`);
helpers_1.logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`);
helpers_1.logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount}`);
helpers_1.logger.info(`Check renounced: ${helpers_1.CHECK_IF_MINT_IS_RENOUNCED}`);
helpers_1.logger.info(`Check freezable: ${helpers_1.CHECK_IF_FREEZABLE}`);
helpers_1.logger.info(`Check burned: ${helpers_1.CHECK_IF_BURNED}`);
helpers_1.logger.info(`Check mutable: ${helpers_1.CHECK_IF_MUTABLE}`);
helpers_1.logger.info(`Check socials: ${helpers_1.CHECK_IF_SOCIALS}`);
helpers_1.logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`);
helpers_1.logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`);
}
helpers_1.logger.info('------- CONFIGURATION END -------');
helpers_1.logger.info('Bot is running! Press CTRL + C to stop it.');
}
const runListener = () => __awaiter(void 0, void 0, void 0, function* () {
helpers_1.logger.level = helpers_1.LOG_LEVEL;
helpers_1.logger.info('Bot is starting...');
const marketCache = new cache_1.MarketCache(connection);
const poolCache = new cache_1.PoolCache();
let txExecutor;
switch (helpers_1.TRANSACTION_EXECUTOR) {
case 'warp': {
txExecutor = new warp_transaction_executor_1.WarpTransactionExecutor(helpers_1.CUSTOM_FEE);
break;
}
case 'jito': {
txExecutor = new jito_rpc_transaction_executor_1.JitoTransactionExecutor(helpers_1.CUSTOM_FEE, connection);
break;
}
default: {
txExecutor = new transactions_1.DefaultTransactionExecutor(connection);
break;
}
}
const wallet = (0, helpers_1.getWallet)(helpers_1.PRIVATE_KEY.trim());
const quoteToken = (0, helpers_1.getToken)(helpers_1.QUOTE_MINT);
const botConfig = {
wallet,
quoteAta: (0, spl_token_1.getAssociatedTokenAddressSync)(quoteToken.mint, wallet.publicKey),
minPoolSize: new raydium_sdk_1.TokenAmount(quoteToken, helpers_1.MIN_POOL_SIZE, false),
maxPoolSize: new raydium_sdk_1.TokenAmount(quoteToken, helpers_1.MAX_POOL_SIZE, false),
quoteToken,
quoteAmount: new raydium_sdk_1.TokenAmount(quoteToken, helpers_1.QUOTE_AMOUNT, false),
maxTokensAtTheTime: helpers_1.MAX_TOKENS_AT_THE_TIME,
useSnipeList: helpers_1.USE_SNIPE_LIST,
autoSell: helpers_1.AUTO_SELL,
autoSellDelay: helpers_1.AUTO_SELL_DELAY,
maxSellRetries: helpers_1.MAX_SELL_RETRIES,
autoBuyDelay: helpers_1.AUTO_BUY_DELAY,
maxBuyRetries: helpers_1.MAX_BUY_RETRIES,
unitLimit: helpers_1.COMPUTE_UNIT_LIMIT,
unitPrice: helpers_1.COMPUTE_UNIT_PRICE,
takeProfit: helpers_1.TAKE_PROFIT,
stopLoss: helpers_1.STOP_LOSS,
trailingStopLoss: helpers_1.TRAILING_STOP_LOSS,
skipSellingIfLostMoreThan: helpers_1.SKIP_SELLING_IF_LOST_MORE_THAN,
buySlippage: helpers_1.BUY_SLIPPAGE,
sellSlippage: helpers_1.SELL_SLIPPAGE,
priceCheckInterval: helpers_1.PRICE_CHECK_INTERVAL,
priceCheckDuration: helpers_1.PRICE_CHECK_DURATION,
filterCheckInterval: helpers_1.FILTER_CHECK_INTERVAL,
filterCheckDuration: helpers_1.FILTER_CHECK_DURATION,
consecutiveMatchCount: helpers_1.CONSECUTIVE_FILTER_MATCHES,
};
const bot = new bot_1.Bot(connection, marketCache, poolCache, txExecutor, botConfig);
const valid = yield bot.validate();
if (!valid) {
helpers_1.logger.info('Bot is exiting...');
process.exit(1);
}
if (helpers_1.PRE_LOAD_EXISTING_MARKETS) {
yield marketCache.init({ quoteToken });
}
const runTimestamp = Math.floor(new Date().getTime() / 1000);
const listeners = new listeners_1.Listeners(connection);
yield listeners.start({
walletPublicKey: wallet.publicKey,
quoteToken,
autoSell: helpers_1.AUTO_SELL,
cacheNewMarkets: helpers_1.CACHE_NEW_MARKETS,
});
listeners.on('market', (updatedAccountInfo) => {
const marketState = raydium_sdk_1.MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data);
marketCache.save(updatedAccountInfo.accountId.toString(), marketState);
});
listeners.on('pool', (updatedAccountInfo) => __awaiter(void 0, void 0, void 0, function* () {
const poolState = raydium_sdk_1.LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data);
const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
const exists = yield poolCache.get(poolState.baseMint.toString());
if (!exists && poolOpenTime > runTimestamp) {
poolCache.save(updatedAccountInfo.accountId.toString(), poolState);
yield bot.buy(updatedAccountInfo.accountId, poolState);
}
}));
listeners.on('wallet', (updatedAccountInfo) => __awaiter(void 0, void 0, void 0, function* () {
const accountData = spl_token_1.AccountLayout.decode(updatedAccountInfo.accountInfo.data);
if (accountData.mint.equals(quoteToken.mint)) {
return;
}
yield bot.sell(updatedAccountInfo.accountId, accountData);
}));
printDetails(wallet, quoteToken, bot);
});
runListener();

View File

@ -14,15 +14,12 @@ import {
RPC_WEBSOCKET_ENDPOINT,
PRE_LOAD_EXISTING_MARKETS,
LOG_LEVEL,
CHECK_IF_MINT_IS_RENOUNCED,
CHECK_IF_BURNED,
QUOTE_MINT,
MAX_POOL_SIZE,
MIN_POOL_SIZE,
QUOTE_AMOUNT,
PRIVATE_KEY,
USE_SNIPE_LIST,
ONE_TOKEN_AT_A_TIME,
AUTO_SELL_DELAY,
MAX_SELL_RETRIES,
AUTO_SELL,
@ -39,10 +36,22 @@ import {
PRICE_CHECK_INTERVAL,
SNIPE_LIST_REFRESH_INTERVAL,
TRANSACTION_EXECUTOR,
WARP_FEE,
CUSTOM_FEE,
FILTER_CHECK_INTERVAL,
FILTER_CHECK_DURATION,
CONSECUTIVE_FILTER_MATCHES,
MAX_TOKENS_AT_THE_TIME,
CHECK_IF_MINT_IS_RENOUNCED,
CHECK_IF_FREEZABLE,
CHECK_IF_BURNED,
CHECK_IF_MUTABLE,
CHECK_IF_SOCIALS,
TRAILING_STOP_LOSS,
SKIP_SELLING_IF_LOST_MORE_THAN,
} from './helpers';
import { version } from './package.json';
import { WarpTransactionExecutor } from './transactions/warp-transaction-executor';
import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor';
const connection = new Connection(RPC_ENDPOINT, {
wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
@ -74,17 +83,16 @@ function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) {
logger.info(`Wallet: ${wallet.publicKey.toString()}`);
logger.info('- Bot -');
logger.info(`Using transaction executor: ${TRANSACTION_EXECUTOR}`);
logger.info(`Using warp: ${bot.isWarp}`);
if (bot.isWarp) {
logger.info(`Warp fee: ${WARP_FEE}`);
}
else {
if (bot.isWarp || bot.isJito) {
logger.info(`${TRANSACTION_EXECUTOR} fee: ${CUSTOM_FEE}`);
} else {
logger.info(`Compute Unit limit: ${botConfig.unitLimit}`);
logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`);
}
logger.info(`Single token at the time: ${botConfig.oneTokenAtATime}`);
logger.info(`Max tokens at the time: ${botConfig.maxTokensAtTheTime}`);
logger.info(`Pre load existing markets: ${PRE_LOAD_EXISTING_MARKETS}`);
logger.info(`Cache new markets: ${CACHE_NEW_MARKETS}`);
logger.info(`Log level: ${LOG_LEVEL}`);
@ -105,14 +113,29 @@ function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) {
logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`);
logger.info(`Take profit: ${botConfig.takeProfit}%`);
logger.info(`Stop loss: ${botConfig.stopLoss}%`);
logger.info(`Trailing stop loss: ${botConfig.trailingStopLoss}`);
logger.info(`Skip selling if lost more than: ${botConfig.skipSellingIfLostMoreThan}%`);
logger.info('- Filters -');
logger.info('- Snipe list -');
logger.info(`Snipe list: ${botConfig.useSnipeList}`);
logger.info(`Snipe list refresh interval: ${SNIPE_LIST_REFRESH_INTERVAL} ms`);
logger.info(`Check renounced: ${botConfig.checkRenounced}`);
logger.info(`Check burned: ${botConfig.checkBurned}`);
logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`);
logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`);
if (botConfig.useSnipeList) {
logger.info('- Filters -');
logger.info(`Filters are disabled when snipe list is on`);
} else {
logger.info('- Filters -');
logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`);
logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`);
logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount}`);
logger.info(`Check renounced: ${CHECK_IF_MINT_IS_RENOUNCED}`);
logger.info(`Check freezable: ${CHECK_IF_FREEZABLE}`);
logger.info(`Check burned: ${CHECK_IF_BURNED}`);
logger.info(`Check mutable: ${CHECK_IF_MUTABLE}`);
logger.info(`Check socials: ${CHECK_IF_SOCIALS}`);
logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`);
logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`);
}
logger.info('------- CONFIGURATION END -------');
@ -129,7 +152,11 @@ const runListener = async () => {
switch (TRANSACTION_EXECUTOR) {
case 'warp': {
txExecutor = new WarpTransactionExecutor(WARP_FEE);
txExecutor = new WarpTransactionExecutor(CUSTOM_FEE);
break;
}
case 'jito': {
txExecutor = new JitoTransactionExecutor(CUSTOM_FEE, connection);
break;
}
default: {
@ -143,14 +170,13 @@ const runListener = async () => {
const botConfig = <BotConfig>{
wallet,
quoteAta: getAssociatedTokenAddressSync(quoteToken.mint, wallet.publicKey),
checkRenounced: CHECK_IF_MINT_IS_RENOUNCED,
checkBurned: CHECK_IF_BURNED,
minPoolSize: new TokenAmount(quoteToken, MIN_POOL_SIZE, false),
maxPoolSize: new TokenAmount(quoteToken, MAX_POOL_SIZE, false),
quoteToken,
quoteAmount: new TokenAmount(quoteToken, QUOTE_AMOUNT, false),
oneTokenAtATime: ONE_TOKEN_AT_A_TIME,
maxTokensAtTheTime: MAX_TOKENS_AT_THE_TIME,
useSnipeList: USE_SNIPE_LIST,
autoSell: AUTO_SELL,
autoSellDelay: AUTO_SELL_DELAY,
maxSellRetries: MAX_SELL_RETRIES,
autoBuyDelay: AUTO_BUY_DELAY,
@ -159,10 +185,15 @@ const runListener = async () => {
unitPrice: COMPUTE_UNIT_PRICE,
takeProfit: TAKE_PROFIT,
stopLoss: STOP_LOSS,
trailingStopLoss: TRAILING_STOP_LOSS,
skipSellingIfLostMoreThan: SKIP_SELLING_IF_LOST_MORE_THAN,
buySlippage: BUY_SLIPPAGE,
sellSlippage: SELL_SLIPPAGE,
priceCheckInterval: PRICE_CHECK_INTERVAL,
priceCheckDuration: PRICE_CHECK_DURATION,
filterCheckInterval: FILTER_CHECK_INTERVAL,
filterCheckDuration: FILTER_CHECK_DURATION,
consecutiveMatchCount: CONSECUTIVE_FILTER_MATCHES,
};
const bot = new Bot(connection, marketCache, poolCache, txExecutor, botConfig);

17
listeners/index.js Normal file
View File

@ -0,0 +1,17 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./listeners"), exports);

View File

@ -1 +1 @@
export * from './listeners';
export * from "./listeners";

109
listeners/listeners.js Normal file
View File

@ -0,0 +1,109 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Listeners = void 0;
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
const bs58_1 = __importDefault(require("bs58"));
const spl_token_1 = require("@solana/spl-token");
const events_1 = require("events");
class Listeners extends events_1.EventEmitter {
constructor(connection) {
super();
this.connection = connection;
this.subscriptions = [];
}
start(config) {
return __awaiter(this, void 0, void 0, function* () {
if (config.cacheNewMarkets) {
const openBookSubscription = yield this.subscribeToOpenBookMarkets(config);
this.subscriptions.push(openBookSubscription);
}
const raydiumSubscription = yield this.subscribeToRaydiumPools(config);
this.subscriptions.push(raydiumSubscription);
if (config.autoSell) {
const walletSubscription = yield this.subscribeToWalletChanges(config);
this.subscriptions.push(walletSubscription);
}
});
}
subscribeToOpenBookMarkets(config) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.onProgramAccountChange(raydium_sdk_1.MAINNET_PROGRAM_ID.OPENBOOK_MARKET, (updatedAccountInfo) => __awaiter(this, void 0, void 0, function* () {
this.emit("market", updatedAccountInfo);
}), this.connection.commitment, [
{ dataSize: raydium_sdk_1.MARKET_STATE_LAYOUT_V3.span },
{
memcmp: {
offset: raydium_sdk_1.MARKET_STATE_LAYOUT_V3.offsetOf("quoteMint"),
bytes: config.quoteToken.mint.toBase58(),
},
},
]);
});
}
subscribeToRaydiumPools(config) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.onProgramAccountChange(raydium_sdk_1.MAINNET_PROGRAM_ID.AmmV4, (updatedAccountInfo) => __awaiter(this, void 0, void 0, function* () {
this.emit("pool", updatedAccountInfo);
}), this.connection.commitment, [
{ dataSize: raydium_sdk_1.LIQUIDITY_STATE_LAYOUT_V4.span },
{
memcmp: {
offset: raydium_sdk_1.LIQUIDITY_STATE_LAYOUT_V4.offsetOf("quoteMint"),
bytes: config.quoteToken.mint.toBase58(),
},
},
{
memcmp: {
offset: raydium_sdk_1.LIQUIDITY_STATE_LAYOUT_V4.offsetOf("marketProgramId"),
bytes: raydium_sdk_1.MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(),
},
},
{
memcmp: {
offset: raydium_sdk_1.LIQUIDITY_STATE_LAYOUT_V4.offsetOf("status"),
bytes: bs58_1.default.encode([6, 0, 0, 0, 0, 0, 0, 0]),
},
},
]);
});
}
subscribeToWalletChanges(config) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.onProgramAccountChange(spl_token_1.TOKEN_PROGRAM_ID, (updatedAccountInfo) => __awaiter(this, void 0, void 0, function* () {
this.emit("wallet", updatedAccountInfo);
}), this.connection.commitment, [
{
dataSize: 165,
},
{
memcmp: {
offset: 32,
bytes: config.walletPublicKey.toBase58(),
},
},
]);
});
}
stop() {
return __awaiter(this, void 0, void 0, function* () {
for (let i = this.subscriptions.length; i >= 0; --i) {
const subscription = this.subscriptions[i];
yield this.connection.removeAccountChangeListener(subscription);
this.subscriptions.splice(i, 1);
}
});
}
}
exports.Listeners = Listeners;

View File

@ -1,112 +1,112 @@
import { LIQUIDITY_STATE_LAYOUT_V4, MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk';
import bs58 from 'bs58';
import { Connection, PublicKey } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
import { EventEmitter } from 'events';
import { LIQUIDITY_STATE_LAYOUT_V4, MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from "@raydium-io/raydium-sdk";
import bs58 from "bs58";
import { Connection, PublicKey } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { EventEmitter } from "events";
export class Listeners extends EventEmitter {
private subscriptions: number[] = [];
private subscriptions: number[] = [];
constructor(private readonly connection: Connection) {
super();
}
constructor(private readonly connection: Connection) {
super();
}
public async start(config: {
walletPublicKey: PublicKey;
quoteToken: Token;
autoSell: boolean;
cacheNewMarkets: boolean;
}) {
if (config.cacheNewMarkets) {
const openBookSubscription = await this.subscribeToOpenBookMarkets(config);
this.subscriptions.push(openBookSubscription);
}
public async start(config: {
walletPublicKey: PublicKey;
quoteToken: Token;
autoSell: boolean;
cacheNewMarkets: boolean;
}) {
if (config.cacheNewMarkets) {
const openBookSubscription = await this.subscribeToOpenBookMarkets(config);
this.subscriptions.push(openBookSubscription);
}
const raydiumSubscription = await this.subscribeToRaydiumPools(config);
this.subscriptions.push(raydiumSubscription);
const raydiumSubscription = await this.subscribeToRaydiumPools(config);
this.subscriptions.push(raydiumSubscription);
if (config.autoSell) {
const walletSubscription = await this.subscribeToWalletChanges(config);
this.subscriptions.push(walletSubscription);
}
}
if (config.autoSell) {
const walletSubscription = await this.subscribeToWalletChanges(config);
this.subscriptions.push(walletSubscription);
}
}
private async subscribeToOpenBookMarkets(config: { quoteToken: Token }) {
return this.connection.onProgramAccountChange(
MAINNET_PROGRAM_ID.OPENBOOK_MARKET,
async (updatedAccountInfo) => {
this.emit('market', updatedAccountInfo);
},
this.connection.commitment,
[
{ dataSize: MARKET_STATE_LAYOUT_V3.span },
{
memcmp: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
bytes: config.quoteToken.mint.toBase58(),
},
},
],
);
}
private async subscribeToOpenBookMarkets(config: { quoteToken: Token }) {
return this.connection.onProgramAccountChange(
MAINNET_PROGRAM_ID.OPENBOOK_MARKET,
async (updatedAccountInfo) => {
this.emit("market", updatedAccountInfo);
},
this.connection.commitment,
[
{ dataSize: MARKET_STATE_LAYOUT_V3.span },
{
memcmp: {
offset: MARKET_STATE_LAYOUT_V3.offsetOf("quoteMint"),
bytes: config.quoteToken.mint.toBase58(),
},
},
],
);
}
private async subscribeToRaydiumPools(config: { quoteToken: Token }) {
return this.connection.onProgramAccountChange(
MAINNET_PROGRAM_ID.AmmV4,
async (updatedAccountInfo) => {
this.emit('pool', updatedAccountInfo);
},
this.connection.commitment,
[
{ dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
{
memcmp: {
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
bytes: config.quoteToken.mint.toBase58(),
},
},
{
memcmp: {
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
bytes: MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(),
},
},
{
memcmp: {
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
},
},
],
);
}
private async subscribeToRaydiumPools(config: { quoteToken: Token }) {
return this.connection.onProgramAccountChange(
MAINNET_PROGRAM_ID.AmmV4,
async (updatedAccountInfo) => {
this.emit("pool", updatedAccountInfo);
},
this.connection.commitment,
[
{ dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
{
memcmp: {
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf("quoteMint"),
bytes: config.quoteToken.mint.toBase58(),
},
},
{
memcmp: {
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf("marketProgramId"),
bytes: MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(),
},
},
{
memcmp: {
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf("status"),
bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
},
},
],
);
}
private async subscribeToWalletChanges(config: { walletPublicKey: PublicKey }) {
return this.connection.onProgramAccountChange(
TOKEN_PROGRAM_ID,
async (updatedAccountInfo) => {
this.emit('wallet', updatedAccountInfo);
},
this.connection.commitment,
[
{
dataSize: 165,
},
{
memcmp: {
offset: 32,
bytes: config.walletPublicKey.toBase58(),
},
},
],
);
}
private async subscribeToWalletChanges(config: { walletPublicKey: PublicKey }) {
return this.connection.onProgramAccountChange(
TOKEN_PROGRAM_ID,
async (updatedAccountInfo) => {
this.emit("wallet", updatedAccountInfo);
},
this.connection.commitment,
[
{
dataSize: 165,
},
{
memcmp: {
offset: 32,
bytes: config.walletPublicKey.toBase58(),
},
},
],
);
}
public async stop() {
for (let i = this.subscriptions.length; i >= 0; --i) {
const subscription = this.subscriptions[i];
await this.connection.removeAccountChangeListener(subscription);
this.subscriptions.splice(i, 1);
}
}
public async stop() {
for (let i = this.subscriptions.length; i >= 0; --i) {
const subscription = this.subscriptions[i];
await this.connection.removeAccountChangeListener(subscription);
this.subscriptions.splice(i, 1);
}
}
}

496
package-lock.json generated
View File

@ -1,13 +1,14 @@
{
"name": "warp-solana-bot",
"version": "2.0.0",
"version": "2.0.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "warp-solana-bot",
"version": "2.0.0",
"version": "2.0.2",
"dependencies": {
"@metaplex-foundation/mpl-token-metadata": "^3.2.1",
"@raydium-io/raydium-sdk": "^1.3.1-beta.47",
"@solana/spl-token": "^0.4.0",
"@solana/web3.js": "^1.89.1",
@ -23,7 +24,8 @@
"npm": "^10.5.2",
"pino": "^8.18.0",
"pino-pretty": "^10.3.1",
"pino-std-serializers": "^6.2.2"
"pino-std-serializers": "^6.2.2",
"request": "^2.88.2"
},
"devDependencies": {
"@types/bn.js": "^5.1.5",
@ -75,6 +77,88 @@
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@metaplex-foundation/mpl-token-metadata": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/mpl-token-metadata/-/mpl-token-metadata-3.2.1.tgz",
"integrity": "sha512-26W1NhQwDWmLOg/pBRYut7x/vEs/5kFS2sWVEY5/X0f2jJOLhnd4NaZQcq+5u+XZsXvm1jq2AtrRGPNK43oqWQ==",
"dependencies": {
"@metaplex-foundation/mpl-toolbox": "^0.9.4"
},
"peerDependencies": {
"@metaplex-foundation/umi": ">= 0.8.2 < 1"
}
},
"node_modules/@metaplex-foundation/mpl-toolbox": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/mpl-toolbox/-/mpl-toolbox-0.9.4.tgz",
"integrity": "sha512-fd6JxfoLbj/MM8FG2x91KYVy1U6AjBQw4qjt7+Da3trzQaWnSaYHDcYRG/53xqfvZ9qofY1T2t53GXPlD87lnQ==",
"peerDependencies": {
"@metaplex-foundation/umi": ">= 0.8.2 < 1"
}
},
"node_modules/@metaplex-foundation/umi": {
"version": "0.9.1",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi/-/umi-0.9.1.tgz",
"integrity": "sha512-IhHoOvp4vfO/++YL+78+iVuLM53+FDwUOZDYgH6lx0jYXyQ27BeaieeR5i+q3A9dz4KxQo5Nzc5aCA1109QGCQ==",
"peer": true,
"dependencies": {
"@metaplex-foundation/umi-options": "^0.8.9",
"@metaplex-foundation/umi-public-keys": "^0.8.9",
"@metaplex-foundation/umi-serializers": "^0.9.0"
}
},
"node_modules/@metaplex-foundation/umi-options": {
"version": "0.8.9",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi-options/-/umi-options-0.8.9.tgz",
"integrity": "sha512-jSQ61sZMPSAk/TXn8v8fPqtz3x8d0/blVZXLLbpVbo2/T5XobiI6/MfmlUosAjAUaQl6bHRF8aIIqZEFkJiy4A==",
"peer": true
},
"node_modules/@metaplex-foundation/umi-public-keys": {
"version": "0.8.9",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi-public-keys/-/umi-public-keys-0.8.9.tgz",
"integrity": "sha512-CxMzN7dgVGOq9OcNCJe2casKUpJ3RmTVoOvDFyeoTQuK+vkZ1YSSahbqC1iGuHEtKTLSjtWjKvUU6O7zWFTw3Q==",
"peer": true,
"dependencies": {
"@metaplex-foundation/umi-serializers-encodings": "^0.8.9"
}
},
"node_modules/@metaplex-foundation/umi-serializers": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi-serializers/-/umi-serializers-0.9.0.tgz",
"integrity": "sha512-hAOW9Djl4w4ioKeR4erDZl5IG4iJdP0xA19ZomdaCbMhYAAmG/FEs5khh0uT2mq53/MnzWcXSUPoO8WBN4Q+Vg==",
"peer": true,
"dependencies": {
"@metaplex-foundation/umi-options": "^0.8.9",
"@metaplex-foundation/umi-public-keys": "^0.8.9",
"@metaplex-foundation/umi-serializers-core": "^0.8.9",
"@metaplex-foundation/umi-serializers-encodings": "^0.8.9",
"@metaplex-foundation/umi-serializers-numbers": "^0.8.9"
}
},
"node_modules/@metaplex-foundation/umi-serializers-core": {
"version": "0.8.9",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi-serializers-core/-/umi-serializers-core-0.8.9.tgz",
"integrity": "sha512-WT82tkiYJ0Qmscp7uTj1Hz6aWQPETwaKLAENAUN5DeWghkuBKtuxyBKVvEOuoXerJSdhiAk0e8DWA4cxcTTQ/w==",
"peer": true
},
"node_modules/@metaplex-foundation/umi-serializers-encodings": {
"version": "0.8.9",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi-serializers-encodings/-/umi-serializers-encodings-0.8.9.tgz",
"integrity": "sha512-N3VWLDTJ0bzzMKcJDL08U3FaqRmwlN79FyE4BHj6bbAaJ9LEHjDQ9RJijZyWqTm0jE7I750fU7Ow5EZL38Xi6Q==",
"peer": true,
"dependencies": {
"@metaplex-foundation/umi-serializers-core": "^0.8.9"
}
},
"node_modules/@metaplex-foundation/umi-serializers-numbers": {
"version": "0.8.9",
"resolved": "https://registry.npmjs.org/@metaplex-foundation/umi-serializers-numbers/-/umi-serializers-numbers-0.8.9.tgz",
"integrity": "sha512-NtBf1fnVNQJHFQjLFzRu2i9GGnigb9hOm/Gfrk628d0q0tRJB7BOM3bs5C61VAs7kJs4yd+pDNVAERJkknQ7Lg==",
"peer": true,
"dependencies": {
"@metaplex-foundation/umi-serializers-core": "^0.8.9"
}
},
"node_modules/@noble/curves": {
"version": "1.3.0",
"license": "MIT",
@ -373,11 +457,45 @@
"node": ">= 8.0.0"
}
},
"node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
"json-schema-traverse": "^0.4.1",
"uri-js": "^4.2.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/arg": {
"version": "4.1.3",
"dev": true,
"license": "MIT"
},
"node_modules/asn1": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": "~2.1.0"
}
},
"node_modules/assert-plus": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",
"integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/async-mutex": {
"version": "0.5.0",
"license": "MIT",
@ -396,6 +514,21 @@
"node": ">=8.0.0"
}
},
"node_modules/aws-sign2": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
"integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==",
"license": "Apache-2.0",
"engines": {
"node": "*"
}
},
"node_modules/aws4": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==",
"license": "MIT"
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
@ -428,6 +561,21 @@
],
"license": "MIT"
},
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
"license": "BSD-3-Clause",
"dependencies": {
"tweetnacl": "^0.14.3"
}
},
"node_modules/bcrypt-pbkdf/node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
},
"node_modules/big.js": {
"version": "6.2.1",
"license": "MIT",
@ -539,6 +687,12 @@
"node": ">=6.14.2"
}
},
"node_modules/caseless": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
"integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==",
"license": "Apache-2.0"
},
"node_modules/cipher-base": {
"version": "1.0.4",
"license": "MIT",
@ -565,6 +719,12 @@
"version": "2.20.3",
"license": "MIT"
},
"node_modules/core-util-is": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==",
"license": "MIT"
},
"node_modules/create-hash": {
"version": "1.2.0",
"license": "MIT",
@ -593,6 +753,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/dashdash": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",
"integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==",
"license": "MIT",
"dependencies": {
"assert-plus": "^1.0.0"
},
"engines": {
"node": ">=0.10"
}
},
"node_modules/dateformat": {
"version": "4.6.3",
"license": "MIT",
@ -643,6 +815,16 @@
"url": "https://github.com/motdotla/dotenv?sponsor=1"
}
},
"node_modules/ecc-jsbn": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
"integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==",
"license": "MIT",
"dependencies": {
"jsbn": "~0.1.0",
"safer-buffer": "^2.1.0"
}
},
"node_modules/ed25519-hd-key": {
"version": "1.3.0",
"license": "MIT",
@ -687,6 +869,21 @@
"node": ">=0.8.x"
}
},
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
"node_modules/extsprintf": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz",
"integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==",
"engines": [
"node >=0.6.0"
],
"license": "MIT"
},
"node_modules/eyes": {
"version": "0.1.8",
"engines": {
@ -697,6 +894,18 @@
"version": "3.0.1",
"license": "MIT"
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/fast-json-stable-stringify": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
"license": "MIT"
},
"node_modules/fast-redact": {
"version": "3.2.0",
"license": "MIT",
@ -744,6 +953,15 @@
}
}
},
"node_modules/forever-agent": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz",
"integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==",
"license": "Apache-2.0",
"engines": {
"node": "*"
}
},
"node_modules/form-data": {
"version": "4.0.0",
"license": "MIT",
@ -756,6 +974,38 @@
"node": ">= 6"
}
},
"node_modules/getpass": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
"integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==",
"license": "MIT",
"dependencies": {
"assert-plus": "^1.0.0"
}
},
"node_modules/har-schema": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
"integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==",
"license": "ISC",
"engines": {
"node": ">=4"
}
},
"node_modules/har-validator": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz",
"integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==",
"deprecated": "this library is no longer supported",
"license": "MIT",
"dependencies": {
"ajv": "^6.12.3",
"har-schema": "^2.0.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/hash-base": {
"version": "3.1.0",
"license": "MIT",
@ -784,6 +1034,21 @@
"version": "5.0.0",
"license": "MIT"
},
"node_modules/http-signature": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz",
"integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==",
"license": "MIT",
"dependencies": {
"assert-plus": "^1.0.0",
"jsprim": "^1.2.2",
"sshpk": "^1.7.0"
},
"engines": {
"node": ">=0.8",
"npm": ">=1.3.7"
}
},
"node_modules/humanize-ms": {
"version": "1.2.1",
"license": "MIT",
@ -819,6 +1084,12 @@
"version": "2.0.4",
"license": "ISC"
},
"node_modules/is-typedarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
"integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==",
"license": "MIT"
},
"node_modules/isomorphic-ws": {
"version": "4.0.1",
"license": "MIT",
@ -826,6 +1097,12 @@
"ws": "*"
}
},
"node_modules/isstream": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz",
"integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==",
"license": "MIT"
},
"node_modules/jayson": {
"version": "4.1.0",
"license": "MIT",
@ -857,6 +1134,24 @@
"node": ">=10"
}
},
"node_modules/jsbn": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
"integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==",
"license": "MIT"
},
"node_modules/json-schema": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
"integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
"license": "(AFL-2.1 OR BSD-3-Clause)"
},
"node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
"integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
"license": "MIT"
},
"node_modules/json-stringify-safe": {
"version": "5.0.1",
"license": "ISC"
@ -882,6 +1177,21 @@
"node": "*"
}
},
"node_modules/jsprim": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
"integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==",
"license": "MIT",
"dependencies": {
"assert-plus": "1.0.0",
"extsprintf": "1.3.0",
"json-schema": "0.4.0",
"verror": "1.10.0"
},
"engines": {
"node": ">=0.6.0"
}
},
"node_modules/lodash": {
"version": "4.17.21",
"license": "MIT"
@ -3522,6 +3832,15 @@
"inBundle": true,
"license": "ISC"
},
"node_modules/oauth-sign": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
"integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==",
"license": "Apache-2.0",
"engines": {
"node": "*"
}
},
"node_modules/on-exit-leak-free": {
"version": "2.1.0",
"license": "MIT"
@ -3533,6 +3852,12 @@
"wrappy": "1"
}
},
"node_modules/performance-now": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
"license": "MIT"
},
"node_modules/pino": {
"version": "8.18.0",
"license": "MIT",
@ -3617,6 +3942,12 @@
"version": "1.1.0",
"license": "MIT"
},
"node_modules/psl": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz",
"integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==",
"license": "MIT"
},
"node_modules/pump": {
"version": "3.0.0",
"license": "MIT",
@ -3625,6 +3956,24 @@
"once": "^1.3.1"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/qs": {
"version": "6.5.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",
"integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.6"
}
},
"node_modules/quick-format-unescaped": {
"version": "4.0.4",
"license": "MIT"
@ -3654,6 +4003,62 @@
"version": "0.14.1",
"license": "MIT"
},
"node_modules/request": {
"version": "2.88.2",
"resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz",
"integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==",
"deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142",
"license": "Apache-2.0",
"dependencies": {
"aws-sign2": "~0.7.0",
"aws4": "^1.8.0",
"caseless": "~0.12.0",
"combined-stream": "~1.0.6",
"extend": "~3.0.2",
"forever-agent": "~0.6.1",
"form-data": "~2.3.2",
"har-validator": "~5.1.3",
"http-signature": "~1.2.0",
"is-typedarray": "~1.0.0",
"isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.19",
"oauth-sign": "~0.9.0",
"performance-now": "^2.1.0",
"qs": "~6.5.2",
"safe-buffer": "^5.1.2",
"tough-cookie": "~2.5.0",
"tunnel-agent": "^0.6.0",
"uuid": "^3.3.2"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/request/node_modules/form-data": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
"integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.6",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 0.12"
}
},
"node_modules/request/node_modules/uuid": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
"deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.",
"license": "MIT",
"bin": {
"uuid": "bin/uuid"
}
},
"node_modules/ripemd160": {
"version": "2.0.2",
"license": "MIT",
@ -3724,6 +4129,12 @@
"node": ">=10"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/secure-json-parse": {
"version": "2.7.0",
"license": "BSD-3-Clause"
@ -3753,6 +4164,37 @@
"node": ">= 10.x"
}
},
"node_modules/sshpk": {
"version": "1.18.0",
"resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz",
"integrity": "sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==",
"license": "MIT",
"dependencies": {
"asn1": "~0.2.3",
"assert-plus": "^1.0.0",
"bcrypt-pbkdf": "^1.0.0",
"dashdash": "^1.12.0",
"ecc-jsbn": "~0.1.1",
"getpass": "^0.1.1",
"jsbn": "~0.1.0",
"safer-buffer": "^2.0.2",
"tweetnacl": "~0.14.0"
},
"bin": {
"sshpk-conv": "bin/sshpk-conv",
"sshpk-sign": "bin/sshpk-sign",
"sshpk-verify": "bin/sshpk-verify"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/sshpk/node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
},
"node_modules/string_decoder": {
"version": "1.3.0",
"license": "MIT",
@ -3792,6 +4234,19 @@
"version": "2.0.0",
"license": "MIT"
},
"node_modules/tough-cookie": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
"integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==",
"license": "BSD-3-Clause",
"dependencies": {
"psl": "^1.1.28",
"punycode": "^2.1.1"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"license": "MIT"
@ -3842,6 +4297,18 @@
"version": "2.6.2",
"license": "0BSD"
},
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
"integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
},
"engines": {
"node": "*"
}
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"license": "Unlicense"
@ -3858,6 +4325,15 @@
"node": ">=14.17"
}
},
"node_modules/uri-js": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
"license": "BSD-2-Clause",
"dependencies": {
"punycode": "^2.1.0"
}
},
"node_modules/utf-8-validate": {
"version": "5.0.10",
"hasInstallScript": true,
@ -3886,6 +4362,20 @@
"dev": true,
"license": "MIT"
},
"node_modules/verror": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",
"integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==",
"engines": [
"node >=0.6.0"
],
"license": "MIT",
"dependencies": {
"assert-plus": "^1.0.0",
"core-util-is": "1.0.2",
"extsprintf": "^1.2.0"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"license": "BSD-2-Clause"

View File

@ -2,12 +2,14 @@
"name": "warp-solana-bot",
"author": "Filip Dundjer",
"homepage": "https://warp.id",
"version": "2.0.0",
"version": "2.0.2",
"scripts": {
"start": "ts-node index.ts",
"tsc": "tsc --noEmit"
"start": "npm run cache | node index.js",
"tsc": "tsc --noEmit",
"cache": "node helpers/helper.cache.js"
},
"dependencies": {
"@metaplex-foundation/mpl-token-metadata": "^3.2.1",
"@raydium-io/raydium-sdk": "^1.3.1-beta.47",
"@solana/spl-token": "^0.4.0",
"@solana/web3.js": "^1.89.1",
@ -23,7 +25,8 @@
"npm": "^10.5.2",
"pino": "^8.18.0",
"pino-pretty": "^10.3.1",
"pino-std-serializers": "^6.2.2"
"pino-std-serializers": "^6.2.2",
"request": "^2.88.2"
},
"devDependencies": {
"@types/bn.js": "^5.1.5",

View File

@ -0,0 +1,44 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultTransactionExecutor = void 0;
const helpers_1 = require("../helpers");
class DefaultTransactionExecutor {
constructor(connection) {
this.connection = connection;
}
executeAndConfirm(transaction, payer, latestBlockhash) {
return __awaiter(this, void 0, void 0, function* () {
helpers_1.logger.debug("Executing transaction...");
const signature = yield this.execute(transaction);
helpers_1.logger.debug({ signature }, "Confirming transaction...");
return this.confirm(signature, latestBlockhash);
});
}
execute(transaction) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.sendRawTransaction(transaction.serialize(), {
preflightCommitment: this.connection.commitment,
});
});
}
confirm(signature, latestBlockhash) {
return __awaiter(this, void 0, void 0, function* () {
const confirmation = yield this.connection.confirmTransaction({
signature,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
}, this.connection.commitment);
return { confirmed: !confirmation.value.err, signature };
});
}
}
exports.DefaultTransactionExecutor = DefaultTransactionExecutor;

View File

@ -1,44 +1,44 @@
import {
BlockhashWithExpiryBlockHeight,
Connection,
Keypair,
Transaction,
VersionedTransaction,
} from '@solana/web3.js';
import { TransactionExecutor } from './transaction-executor.interface';
import { logger } from '../helpers';
BlockhashWithExpiryBlockHeight,
Connection,
Keypair,
Transaction,
VersionedTransaction,
} from "@solana/web3.js";
import { TransactionExecutor } from "./transaction-executor.interface";
import { logger } from "../helpers";
export class DefaultTransactionExecutor implements TransactionExecutor {
constructor(private readonly connection: Connection) {}
constructor(private readonly connection: Connection) {}
public async executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockhash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string }> {
logger.debug('Executing transaction...');
const signature = await this.execute(transaction);
public async executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockhash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string; error?: string }> {
logger.debug("Executing transaction...");
const signature = await this.execute(transaction);
logger.debug({ signature }, 'Confirming transaction...');
return this.confirm(signature, latestBlockhash);
}
logger.debug({ signature }, "Confirming transaction...");
return this.confirm(signature, latestBlockhash);
}
private async execute(transaction: Transaction | VersionedTransaction) {
return this.connection.sendRawTransaction(transaction.serialize(), {
preflightCommitment: this.connection.commitment,
});
}
private async execute(transaction: Transaction | VersionedTransaction) {
return this.connection.sendRawTransaction(transaction.serialize(), {
preflightCommitment: this.connection.commitment,
});
}
private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) {
const confirmation = await this.connection.confirmTransaction(
{
signature,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
},
this.connection.commitment,
);
private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) {
const confirmation = await this.connection.confirmTransaction(
{
signature,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
},
this.connection.commitment,
);
return { confirmed: !confirmation.value.err, signature };
}
return { confirmed: !confirmation.value.err, signature };
}
}

18
transactions/index.js Normal file
View File

@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./default-transaction-executor"), exports);
__exportStar(require("./transaction-executor.interface"), exports);

View File

@ -1,2 +1,2 @@
export * from './default-transaction-executor';
export * from './transaction-executor.interface';
export * from "./default-transaction-executor";
export * from "./transaction-executor.interface";

View File

@ -0,0 +1,139 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JitoTransactionExecutor = void 0;
const web3_js_1 = require("@solana/web3.js");
const helpers_1 = require("../helpers");
const axios_1 = __importStar(require("axios"));
const bs58_1 = __importDefault(require("bs58"));
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
class JitoTransactionExecutor {
constructor(jitoFee, connection) {
this.jitoFee = jitoFee;
this.connection = connection;
// https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/bundles/gettipaccounts
this.jitpTipAccounts = [
"Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY",
"DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL",
"96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5",
"3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT",
"HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe",
"ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49",
"ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt",
"DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh",
];
this.JitoFeeWallet = this.getRandomValidatorKey();
}
getRandomValidatorKey() {
const randomValidator = this.jitpTipAccounts[Math.floor(Math.random() * this.jitpTipAccounts.length)];
return new web3_js_1.PublicKey(randomValidator);
}
executeAndConfirm(transaction, payer, latestBlockhash) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
helpers_1.logger.debug("Starting Jito transaction execution...");
this.JitoFeeWallet = this.getRandomValidatorKey(); // Update wallet key each execution
helpers_1.logger.trace(`Selected Jito fee wallet: ${this.JitoFeeWallet.toBase58()}`);
try {
const fee = new raydium_sdk_1.CurrencyAmount(raydium_sdk_1.Currency.SOL, this.jitoFee, false).raw.toNumber();
helpers_1.logger.trace(`Calculated fee: ${fee} lamports`);
const jitTipTxFeeMessage = new web3_js_1.TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
web3_js_1.SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: this.JitoFeeWallet,
lamports: fee,
}),
],
}).compileToV0Message();
const jitoFeeTx = new web3_js_1.VersionedTransaction(jitTipTxFeeMessage);
jitoFeeTx.sign([payer]);
const jitoTxsignature = bs58_1.default.encode(jitoFeeTx.signatures[0]);
// Serialize the transactions once here
const serializedjitoFeeTx = bs58_1.default.encode(jitoFeeTx.serialize());
const serializedTransaction = bs58_1.default.encode(transaction.serialize());
const serializedTransactions = [serializedjitoFeeTx, serializedTransaction];
// https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/url
const endpoints = [
"https://mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://amsterdam.mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://frankfurt.mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles",
];
const requests = endpoints.map((url) => axios_1.default.post(url, {
jsonrpc: "2.0",
id: 1,
method: "sendBundle",
params: [serializedTransactions],
}));
helpers_1.logger.trace("Sending transactions to endpoints...");
const results = yield Promise.all(requests.map((p) => p.catch((e) => e)));
const successfulResults = results.filter((result) => !(result instanceof Error));
if (successfulResults.length > 0) {
helpers_1.logger.trace(`At least one successful response`);
helpers_1.logger.debug(`Confirming jito transaction...`);
return yield this.confirm(jitoTxsignature, latestBlockhash);
}
else {
helpers_1.logger.debug(`No successful responses received for jito`);
}
return { confirmed: false };
}
catch (error) {
if (error instanceof axios_1.AxiosError) {
helpers_1.logger.trace({ error: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data }, "Failed to execute jito transaction");
}
helpers_1.logger.error("Error during transaction execution", error);
return { confirmed: false };
}
});
}
confirm(signature, latestBlockhash) {
return __awaiter(this, void 0, void 0, function* () {
const confirmation = yield this.connection.confirmTransaction({
signature,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
}, this.connection.commitment);
return { confirmed: !confirmation.value.err, signature };
});
}
}
exports.JitoTransactionExecutor = JitoTransactionExecutor;

View File

@ -0,0 +1,131 @@
import {
BlockhashWithExpiryBlockHeight,
Keypair,
PublicKey,
SystemProgram,
Connection,
TransactionMessage,
VersionedTransaction,
} from "@solana/web3.js";
import { TransactionExecutor } from "./transaction-executor.interface";
import { logger } from "../helpers";
import axios, { AxiosError } from "axios";
import bs58 from "bs58";
import { Currency, CurrencyAmount } from "@raydium-io/raydium-sdk";
export class JitoTransactionExecutor implements TransactionExecutor {
// https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/bundles/gettipaccounts
private jitpTipAccounts = [
"Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY",
"DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL",
"96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5",
"3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT",
"HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe",
"ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49",
"ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt",
"DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh",
];
private JitoFeeWallet: PublicKey;
constructor(
private readonly jitoFee: string,
private readonly connection: Connection,
) {
this.JitoFeeWallet = this.getRandomValidatorKey();
}
private getRandomValidatorKey(): PublicKey {
const randomValidator = this.jitpTipAccounts[Math.floor(Math.random() * this.jitpTipAccounts.length)];
return new PublicKey(randomValidator);
}
public async executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockhash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string; error?: string }> {
logger.debug("Starting Jito transaction execution...");
this.JitoFeeWallet = this.getRandomValidatorKey(); // Update wallet key each execution
logger.trace(`Selected Jito fee wallet: ${this.JitoFeeWallet.toBase58()}`);
try {
const fee = new CurrencyAmount(Currency.SOL, this.jitoFee, false).raw.toNumber();
logger.trace(`Calculated fee: ${fee} lamports`);
const jitTipTxFeeMessage = new TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: this.JitoFeeWallet,
lamports: fee,
}),
],
}).compileToV0Message();
const jitoFeeTx = new VersionedTransaction(jitTipTxFeeMessage);
jitoFeeTx.sign([payer]);
const jitoTxsignature = bs58.encode(jitoFeeTx.signatures[0]);
// Serialize the transactions once here
const serializedjitoFeeTx = bs58.encode(jitoFeeTx.serialize());
const serializedTransaction = bs58.encode(transaction.serialize());
const serializedTransactions = [serializedjitoFeeTx, serializedTransaction];
// https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/url
const endpoints = [
"https://mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://amsterdam.mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://frankfurt.mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles",
"https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles",
];
const requests = endpoints.map((url) =>
axios.post(url, {
jsonrpc: "2.0",
id: 1,
method: "sendBundle",
params: [serializedTransactions],
}),
);
logger.trace("Sending transactions to endpoints...");
const results = await Promise.all(requests.map((p) => p.catch((e) => e)));
const successfulResults = results.filter((result) => !(result instanceof Error));
if (successfulResults.length > 0) {
logger.trace(`At least one successful response`);
logger.debug(`Confirming jito transaction...`);
return await this.confirm(jitoTxsignature, latestBlockhash);
} else {
logger.debug(`No successful responses received for jito`);
}
return { confirmed: false };
} catch (error) {
if (error instanceof AxiosError) {
logger.trace({ error: error.response?.data }, "Failed to execute jito transaction");
}
logger.error("Error during transaction execution", error);
return { confirmed: false };
}
}
private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) {
const confirmation = await this.connection.confirmTransaction(
{
signature,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
},
this.connection.commitment,
);
return { confirmed: !confirmation.value.err, signature };
}
}

View File

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@ -1,9 +1,9 @@
import { BlockhashWithExpiryBlockHeight, Keypair, MessageV0, Signer, VersionedTransaction } from '@solana/web3.js';
import { BlockhashWithExpiryBlockHeight, Keypair, VersionedTransaction } from "@solana/web3.js";
export interface TransactionExecutor {
executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockHash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string }>;
executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockHash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string; error?: string }>;
}

View File

@ -0,0 +1,85 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WarpTransactionExecutor = void 0;
const web3_js_1 = require("@solana/web3.js");
const helpers_1 = require("../helpers");
const axios_1 = __importStar(require("axios"));
const bs58_1 = __importDefault(require("bs58"));
const raydium_sdk_1 = require("@raydium-io/raydium-sdk");
class WarpTransactionExecutor {
constructor(warpFee) {
this.warpFee = warpFee;
this.warpFeeWallet = new web3_js_1.PublicKey("WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS");
}
executeAndConfirm(transaction, payer, latestBlockhash) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
helpers_1.logger.debug("Executing transaction...");
try {
const fee = new raydium_sdk_1.CurrencyAmount(raydium_sdk_1.Currency.SOL, this.warpFee, false).raw.toNumber();
const warpFeeMessage = new web3_js_1.TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
web3_js_1.SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: this.warpFeeWallet,
lamports: fee,
}),
],
}).compileToV0Message();
const warpFeeTx = new web3_js_1.VersionedTransaction(warpFeeMessage);
warpFeeTx.sign([payer]);
const response = yield axios_1.default.post("https://tx.warp.id/transaction/execute", {
transactions: [bs58_1.default.encode(warpFeeTx.serialize()), bs58_1.default.encode(transaction.serialize())],
latestBlockhash,
}, {
timeout: 100000,
});
return response.data;
}
catch (error) {
if (error instanceof axios_1.AxiosError) {
helpers_1.logger.trace({ error: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data }, "Failed to execute warp transaction");
}
}
return { confirmed: false };
});
}
}
exports.WarpTransactionExecutor = WarpTransactionExecutor;

View File

@ -1,64 +1,64 @@
import {
BlockhashWithExpiryBlockHeight,
Keypair,
PublicKey,
SystemProgram,
TransactionMessage,
VersionedTransaction,
} from '@solana/web3.js';
import { TransactionExecutor } from './transaction-executor.interface';
import { logger } from '../helpers';
import axios, { AxiosError } from 'axios';
import bs58 from 'bs58';
import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk';
BlockhashWithExpiryBlockHeight,
Keypair,
PublicKey,
SystemProgram,
TransactionMessage,
VersionedTransaction,
} from "@solana/web3.js";
import { TransactionExecutor } from "./transaction-executor.interface";
import { logger } from "../helpers";
import axios, { AxiosError } from "axios";
import bs58 from "bs58";
import { Currency, CurrencyAmount } from "@raydium-io/raydium-sdk";
export class WarpTransactionExecutor implements TransactionExecutor {
private readonly warpFeeWallet = new PublicKey('WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS');
private readonly warpFeeWallet = new PublicKey("WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS");
constructor(private readonly warpFee: string) {}
constructor(private readonly warpFee: string) {}
public async executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockhash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string }> {
logger.debug('Executing transaction...');
public async executeAndConfirm(
transaction: VersionedTransaction,
payer: Keypair,
latestBlockhash: BlockhashWithExpiryBlockHeight,
): Promise<{ confirmed: boolean; signature?: string; error?: string }> {
logger.debug("Executing transaction...");
try {
const fee = new CurrencyAmount(Currency.SOL, this.warpFee, false).raw.toNumber();
const warpFeeMessage = new TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: this.warpFeeWallet,
lamports: fee,
}),
],
}).compileToV0Message();
try {
const fee = new CurrencyAmount(Currency.SOL, this.warpFee, false).raw.toNumber();
const warpFeeMessage = new TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: [
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: this.warpFeeWallet,
lamports: fee,
}),
],
}).compileToV0Message();
const warpFeeTx = new VersionedTransaction(warpFeeMessage);
warpFeeTx.sign([payer]);
const warpFeeTx = new VersionedTransaction(warpFeeMessage);
warpFeeTx.sign([payer]);
const response = await axios.post<{ confirmed: boolean; signature: string }>(
'https://tx.warp.id/transaction/execute',
{
transactions: [bs58.encode(warpFeeTx.serialize()), bs58.encode(transaction.serialize())],
latestBlockhash,
},
{
timeout: 100000,
},
);
const response = await axios.post<{ confirmed: boolean; signature: string; error?: string }>(
"https://tx.warp.id/transaction/execute",
{
transactions: [bs58.encode(warpFeeTx.serialize()), bs58.encode(transaction.serialize())],
latestBlockhash,
},
{
timeout: 100000,
},
);
return response.data;
} catch (error) {
if (error instanceof AxiosError) {
logger.trace({ error: error.response?.data }, 'Failed to execute warp transaction');
}
}
return response.data;
} catch (error) {
if (error instanceof AxiosError) {
logger.trace({ error: error.response?.data }, "Failed to execute warp transaction");
}
}
return { confirmed: false };
}
return { confirmed: false };
}
}