├── .env.copy ├── .gitignore ├── .prettierrc ├── LICENSE.md ├── README.md ├── bot.ts ├── cache ├── index.ts ├── market.cache.ts ├── pool.cache.ts └── snipe-list.cache.ts ├── filters ├── burn.filter.ts ├── index.ts ├── mutable.filter.ts ├── pool-filters.ts ├── pool-size.filter.ts └── renounced.filter.ts ├── helpers ├── constants.ts ├── index.ts ├── liquidity.ts ├── logger.ts ├── market.ts ├── promises.ts ├── token.ts └── wallet.ts ├── index.ts ├── listeners ├── index.ts └── listeners.ts ├── package-lock.json ├── package.json ├── readme ├── output.png └── wsol.png ├── snipe-list.txt ├── transactions ├── default-transaction-executor.ts ├── index.ts ├── jito-rpc-transaction-executor.ts ├── transaction-executor.interface.ts └── warp-transaction-executor.ts └── tsconfig.json /.env.copy: -------------------------------------------------------------------------------- 1 | # Wallet 2 | PRIVATE_KEY= 3 | 4 | # Connection 5 | RPC_ENDPOINT=https://api.mainnet-beta.solana.com 6 | RPC_WEBSOCKET_ENDPOINT=wss://api.mainnet-beta.solana.com 7 | COMMITMENT_LEVEL=confirmed 8 | 9 | # Bot 10 | LOG_LEVEL=trace 11 | MAX_TOKENS_AT_THE_TIME=1 12 | PRE_LOAD_EXISTING_MARKETS=false 13 | CACHE_NEW_MARKETS=false 14 | # default or warp or jito 15 | TRANSACTION_EXECUTOR=default 16 | # if using default executor, fee below will be applied 17 | COMPUTE_UNIT_LIMIT=101337 18 | COMPUTE_UNIT_PRICE=421197 19 | # if using warp or jito executor, fee below will be applied 20 | CUSTOM_FEE=0.006 21 | 22 | # Buy 23 | QUOTE_MINT=WSOL 24 | QUOTE_AMOUNT=0.001 25 | AUTO_BUY_DELAY=0 26 | MAX_BUY_RETRIES=10 27 | BUY_SLIPPAGE=20 28 | 29 | # Sell 30 | AUTO_SELL=true 31 | MAX_SELL_RETRIES=10 32 | AUTO_SELL_DELAY=0 33 | PRICE_CHECK_INTERVAL=2000 34 | PRICE_CHECK_DURATION=600000 35 | TAKE_PROFIT=40 36 | STOP_LOSS=20 37 | TRAILING_STOP_LOSS=true 38 | SKIP_SELLING_IF_LOST_MORE_THAN=90 39 | SELL_SLIPPAGE=20 40 | 41 | # Filters 42 | USE_SNIPE_LIST=false 43 | SNIPE_LIST_REFRESH_INTERVAL=30000 44 | FILTER_CHECK_DURATION=60000 45 | FILTER_CHECK_INTERVAL=2000 46 | CONSECUTIVE_FILTER_MATCHES=3 47 | CHECK_IF_MUTABLE=false 48 | CHECK_IF_SOCIALS=true 49 | CHECK_IF_MINT_IS_RENOUNCED=true 50 | CHECK_IF_FREEZABLE=false 51 | CHECK_IF_BURNED=true 52 | MIN_POOL_SIZE=5 53 | MAX_POOL_SIZE=50 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # PNPM 126 | pnpm-lock.yaml 127 | 128 | # yarn v2 129 | .yarn/cache 130 | .yarn/unplugged 131 | .yarn/build-state.yml 132 | .yarn/install-state.gz 133 | .pnp.* 134 | 135 | # JetBrains 136 | .idea 137 | 138 | # Visual Studio Code 139 | *.code-workspace 140 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "printWidth": 120 5 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solana Trading Bot (Beta) 2 | 3 | The Solana Trading Bot is a software tool designed to automate the buying and selling of tokens on the Solana blockchain. 4 | It is configured to execute trades based on predefined parameters and strategies set by the user. 5 | 6 | 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. 7 | 8 | ## Setup 9 | 10 | To run the script you need to: 11 | 12 | - Create a new empty Solana wallet 13 | - Transfer some SOL to it. 14 | - Convert some SOL to USDC or WSOL. 15 | - You need USDC or WSOL depending on the configuration set below. 16 | - Configure the script by updating `.env.copy` file (remove the .copy from the file name when done). 17 | - Check [Configuration](#configuration) section bellow 18 | - Install dependencies by typing: `npm install` 19 | - Run the script by typing: `npm run start` in terminal 20 | 21 | You should see the following output: 22 | ![output](readme/output.png) 23 | 24 | ### Configuration 25 | 26 | #### Wallet 27 | 28 | - `PRIVATE_KEY` - Your wallet's private key. 29 | 30 | #### Connection 31 | 32 | - `RPC_ENDPOINT` - HTTPS RPC endpoint for interacting with the Solana network. 33 | - `RPC_WEBSOCKET_ENDPOINT` - WebSocket RPC endpoint for real-time updates from the Solana network. 34 | - `COMMITMENT_LEVEL`- The commitment level of transactions (e.g., "finalized" for the highest level of security). 35 | 36 | #### Bot 37 | 38 | - `LOG_LEVEL` - Set logging level, e.g., `info`, `debug`, `trace`, etc. 39 | - `MAX_TOKENS_AT_A_TIME` - Set to `1` to process buying one token at a time. 40 | - `COMPUTE_UNIT_LIMIT` - Compute limit used to calculate fees. 41 | - `COMPUTE_UNIT_PRICE` - Compute price used to calculate fees. 42 | - `PRE_LOAD_EXISTING_MARKETS` - Bot will load all existing markets in memory on start. 43 | - This option should not be used with public RPC. 44 | - `CACHE_NEW_MARKETS` - Set to `true` to cache new markets. 45 | - This option should not be used with public RPC. 46 | - `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions, or set it to jito to use JSON-RPC jito executer 47 | - For more details checkout [warp](#warp-transactions-beta) section 48 | - `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` 49 | - Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above 50 | - On top of this fee, minimal solana network fee will be applied 51 | 52 | #### Buy 53 | 54 | - `QUOTE_MINT` - Which pools to snipe, USDC or WSOL. 55 | - `QUOTE_AMOUNT` - Amount used to buy each new token. 56 | - `AUTO_BUY_DELAY` - Delay in milliseconds before buying a token. 57 | - `MAX_BUY_RETRIES` - Maximum number of retries for buying a token. 58 | - `BUY_SLIPPAGE` - Slippage % 59 | 60 | #### Sell 61 | 62 | - `AUTO_SELL` - Set to `true` to enable automatic selling of tokens. 63 | - If you want to manually sell bought tokens, disable this option. 64 | - `MAX_SELL_RETRIES` - Maximum number of retries for selling a token. 65 | - `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token. 66 | - `PRICE_CHECK_INTERVAL` - Interval in milliseconds for checking the take profit and stop loss conditions. 67 | - Set to zero to disable take profit and stop loss. 68 | - `PRICE_CHECK_DURATION` - Time in milliseconds to wait for stop loss/take profit conditions. 69 | - If you don't reach profit or loss bot will auto sell after this time. 70 | - Set to zero to disable take profit and stop loss. 71 | - `TAKE_PROFIT` - Percentage profit at which to take profit. 72 | - Take profit is calculated based on quote mint. 73 | - `STOP_LOSS` - Percentage loss at which to stop the loss. 74 | - Stop loss is calculated based on quote mint. 75 | - `TRAILING_STOP_LOSS` - Set to `true` to use trailing stop loss. 76 | - `SKIP_SELLING_IF_LOST_MORE_THAN` - If token loses more than X% of value, bot will not try to sell 77 | - 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. 78 | - `SELL_SLIPPAGE` - Slippage %. 79 | 80 | #### Snipe list 81 | 82 | - `USE_SNIPE_LIST` - Set to `true` to enable buying only tokens listed in `snipe-list.txt`. 83 | - Pool must not exist before the bot starts. 84 | - If token can be traded before bot starts nothing will happen. Bot will not buy the token. 85 | - `SNIPE_LIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the snipe list. 86 | - You can update snipe list while bot is running. It will pickup the new changes each time it does refresh. 87 | 88 | Note: When using snipe list filters below will be disabled. 89 | 90 | #### Filters 91 | 92 | - `FILTER_CHECK_INTERVAL` - Interval in milliseconds for checking if pool match the filters. 93 | - Set to zero to disable filters. 94 | - `FILTER_CHECK_DURATION` - Time in milliseconds to wait for pool to match the filters. 95 | - If pool doesn't match the filter buy will not happen. 96 | - Set to zero to disable filters. 97 | - `CONSECUTIVE_FILTER_MATCHES` - How many times in a row pool needs to match the filters. 98 | - 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 99 | - `CHECK_IF_MUTABLE` - Set to `true` to buy tokens only if their metadata are not mutable. 100 | - `CHECK_IF_SOCIALS` - Set to `true` to buy tokens only if they have at least 1 social. 101 | - `CHECK_IF_MINT_IS_RENOUNCED` - Set to `true` to buy tokens only if their mint is renounced. 102 | - `CHECK_IF_FREEZABLE` - Set to `true` to buy tokens only if they are not freezable. 103 | - `CHECK_IF_BURNED` - Set to `true` to buy tokens only if their liquidity pool is burned. 104 | - `MIN_POOL_SIZE` - Bot will buy only if the pool size is greater than or equal the specified amount. 105 | - Set `0` to disable. 106 | - `MAX_POOL_SIZE` - Bot will buy only if the pool size is less than or equal the specified amount. 107 | - Set `0` to disable. 108 | 109 | ## Warp transactions (beta) 110 | 111 | In case you experience a lot of failed transactions or transaction performance is too slow, you can try using `warp` for executing transactions. 112 | Warp is hosted service that executes transactions using integrations with third party providers. 113 | 114 | Using warp for transactions supports the team behind this project. 115 | 116 | ### Security 117 | 118 | When using warp, transaction is sent to the hosted service. 119 | **Payload that is being sent will NOT contain your wallet private key**. Fee transaction is signed on your machine. 120 | Each request is processed by hosted service and sent to third party provider. 121 | **We don't store your transactions, nor we store your private key.** 122 | 123 | Note: Warp transactions are disabled by default. 124 | 125 | ### Fees 126 | 127 | When using warp for transactions, fee is distributed between developers of warp and third party providers. 128 | In case TX fails, no fee will be taken from your account. 129 | 130 | ## Common issues 131 | 132 | If you have an error which is not listed here, please create a new issue in this repository. 133 | To collect more information on an issue, please change `LOG_LEVEL` to `debug`. 134 | 135 | ### Unsupported RPC node 136 | 137 | - If you see following error in your log file: 138 | `Error: 410 Gone: {"jsonrpc":"2.0","error":{"code": 410, "message":"The RPC call or parameters have been disabled."}, "id": "986f3599-b2b7-47c4-b951-074c19842bad" }` 139 | it means your RPC node doesn't support methods needed to execute script. 140 | - FIX: Change your RPC node. You can use Helius or Quicknode. 141 | 142 | ### No token account 143 | 144 | - If you see following error in your log file: 145 | `Error: No SOL token account found in wallet: ` 146 | it means that wallet you provided doesn't have USDC/WSOL token account. 147 | - FIX: Go to dex and swap some SOL to USDC/WSOL. For example when you swap sol to wsol you should see it in wallet as shown below: 148 | 149 | ![wsol](readme/wsol.png) 150 | 151 | ## Contact 152 | 153 | [![](https://img.shields.io/discord/1201826085655023616?color=5865F2&logo=Discord&style=flat-square)](https://discord.gg/xYUETCA2aP) 154 | 155 | - If you want to leave a tip, you can send it to the following address: 156 | `7gm6BPQrSBaTAYaJheuRevBNXcmKsgbkfBCVSjBnt9aP` 157 | 158 | - If you need custom features or assistance, feel free to contact the admin team on discord for dedicated support. 159 | 160 | ## Disclaimer 161 | 162 | The Solana Trading Bot is provided as is, for learning purposes. 163 | Trading cryptocurrencies and tokens involves risk, and past performance is not indicative of future results. 164 | The use of this bot is at your own risk, and we are not responsible for any losses incurred while using the bot. 165 | -------------------------------------------------------------------------------- /bot.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ComputeBudgetProgram, 3 | Connection, 4 | Keypair, 5 | PublicKey, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { 10 | createAssociatedTokenAccountIdempotentInstruction, 11 | createCloseAccountInstruction, 12 | getAccount, 13 | getAssociatedTokenAddress, 14 | RawAccount, 15 | TOKEN_PROGRAM_ID, 16 | } from '@solana/spl-token'; 17 | import { Liquidity, LiquidityPoolKeysV4, LiquidityStateV4, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 18 | import { MarketCache, PoolCache, SnipeListCache } from './cache'; 19 | import { PoolFilters } from './filters'; 20 | import { TransactionExecutor } from './transactions'; 21 | import { createPoolKeys, logger, NETWORK, sleep } from './helpers'; 22 | import { Semaphore } from 'async-mutex'; 23 | import BN from 'bn.js'; 24 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 25 | import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; 26 | 27 | export interface BotConfig { 28 | wallet: Keypair; 29 | minPoolSize: TokenAmount; 30 | maxPoolSize: TokenAmount; 31 | quoteToken: Token; 32 | quoteAmount: TokenAmount; 33 | quoteAta: PublicKey; 34 | maxTokensAtTheTime: number; 35 | useSnipeList: boolean; 36 | autoSell: boolean; 37 | autoBuyDelay: number; 38 | autoSellDelay: number; 39 | maxBuyRetries: number; 40 | maxSellRetries: number; 41 | unitLimit: number; 42 | unitPrice: number; 43 | takeProfit: number; 44 | stopLoss: number; 45 | trailingStopLoss: boolean; 46 | skipSellingIfLostMoreThan: number; 47 | buySlippage: number; 48 | sellSlippage: number; 49 | priceCheckInterval: number; 50 | priceCheckDuration: number; 51 | filterCheckInterval: number; 52 | filterCheckDuration: number; 53 | consecutiveMatchCount: number; 54 | } 55 | 56 | export class Bot { 57 | // snipe list 58 | private readonly snipeListCache?: SnipeListCache; 59 | 60 | private readonly semaphore: Semaphore; 61 | private sellExecutionCount = 0; 62 | private readonly stopLoss = new Map(); 63 | public readonly isWarp: boolean = false; 64 | public readonly isJito: boolean = false; 65 | 66 | constructor( 67 | private readonly connection: Connection, 68 | private readonly marketStorage: MarketCache, 69 | private readonly poolStorage: PoolCache, 70 | private readonly txExecutor: TransactionExecutor, 71 | readonly config: BotConfig, 72 | ) { 73 | this.isWarp = txExecutor instanceof WarpTransactionExecutor; 74 | this.isJito = txExecutor instanceof JitoTransactionExecutor; 75 | this.semaphore = new Semaphore(config.maxTokensAtTheTime); 76 | 77 | if (this.config.useSnipeList) { 78 | this.snipeListCache = new SnipeListCache(); 79 | this.snipeListCache.init(); 80 | } 81 | } 82 | 83 | async validate() { 84 | try { 85 | await getAccount(this.connection, this.config.quoteAta, this.connection.commitment); 86 | } catch (error) { 87 | logger.error( 88 | `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`, 89 | ); 90 | return false; 91 | } 92 | 93 | return true; 94 | } 95 | 96 | public async buy(accountId: PublicKey, poolState: LiquidityStateV4) { 97 | logger.trace({ mint: poolState.baseMint }, `Processing new pool...`); 98 | 99 | if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) { 100 | logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`); 101 | return; 102 | } 103 | 104 | if (this.config.autoBuyDelay > 0) { 105 | logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`); 106 | await sleep(this.config.autoBuyDelay); 107 | } 108 | 109 | const numberOfActionsBeingProcessed = 110 | this.config.maxTokensAtTheTime - this.semaphore.getValue() + this.sellExecutionCount; 111 | if (this.semaphore.isLocked() || numberOfActionsBeingProcessed >= this.config.maxTokensAtTheTime) { 112 | logger.debug( 113 | { mint: poolState.baseMint.toString() }, 114 | `Skipping buy because max tokens to process at the same time is ${this.config.maxTokensAtTheTime} and currently ${numberOfActionsBeingProcessed} tokens is being processed`, 115 | ); 116 | return; 117 | } 118 | 119 | await this.semaphore.acquire(); 120 | 121 | try { 122 | const [market, mintAta] = await Promise.all([ 123 | this.marketStorage.get(poolState.marketId.toString()), 124 | getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), 125 | ]); 126 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); 127 | 128 | if (!this.config.useSnipeList) { 129 | const match = await this.filterMatch(poolKeys); 130 | 131 | if (!match) { 132 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`); 133 | return; 134 | } 135 | } 136 | 137 | for (let i = 0; i < this.config.maxBuyRetries; i++) { 138 | try { 139 | logger.info( 140 | { mint: poolState.baseMint.toString() }, 141 | `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`, 142 | ); 143 | const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals); 144 | const result = await this.swap( 145 | poolKeys, 146 | this.config.quoteAta, 147 | mintAta, 148 | this.config.quoteToken, 149 | tokenOut, 150 | this.config.quoteAmount, 151 | this.config.buySlippage, 152 | this.config.wallet, 153 | 'buy', 154 | ); 155 | 156 | if (result.confirmed) { 157 | logger.info( 158 | { 159 | mint: poolState.baseMint.toString(), 160 | signature: result.signature, 161 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 162 | }, 163 | `Confirmed buy tx`, 164 | ); 165 | 166 | break; 167 | } 168 | 169 | logger.info( 170 | { 171 | mint: poolState.baseMint.toString(), 172 | signature: result.signature, 173 | error: result.error, 174 | }, 175 | `Error confirming buy tx`, 176 | ); 177 | } catch (error) { 178 | logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`); 179 | } 180 | } 181 | } catch (error) { 182 | logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`); 183 | } finally { 184 | this.semaphore.release(); 185 | } 186 | } 187 | 188 | public async sell(accountId: PublicKey, rawAccount: RawAccount) { 189 | this.sellExecutionCount++; 190 | 191 | try { 192 | logger.trace({ mint: rawAccount.mint }, `Processing new token...`); 193 | 194 | const poolData = await this.poolStorage.get(rawAccount.mint.toString()); 195 | 196 | if (!poolData) { 197 | logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`); 198 | return; 199 | } 200 | 201 | const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber()); 202 | const tokenAmountIn = new TokenAmount(tokenIn, rawAccount.amount, true); 203 | 204 | if (tokenAmountIn.isZero()) { 205 | logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`); 206 | return; 207 | } 208 | 209 | if (this.config.autoSellDelay > 0) { 210 | logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`); 211 | await sleep(this.config.autoSellDelay); 212 | } 213 | 214 | const market = await this.marketStorage.get(poolData.state.marketId.toString()); 215 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market); 216 | 217 | for (let i = 0; i < this.config.maxSellRetries; i++) { 218 | try { 219 | const shouldSell = await this.waitForSellSignal(tokenAmountIn, poolKeys); 220 | 221 | if (!shouldSell) { 222 | return; 223 | } 224 | 225 | logger.info( 226 | { mint: rawAccount.mint }, 227 | `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`, 228 | ); 229 | 230 | const result = await this.swap( 231 | poolKeys, 232 | accountId, 233 | this.config.quoteAta, 234 | tokenIn, 235 | this.config.quoteToken, 236 | tokenAmountIn, 237 | this.config.sellSlippage, 238 | this.config.wallet, 239 | 'sell', 240 | ); 241 | 242 | if (result.confirmed) { 243 | logger.info( 244 | { 245 | dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`, 246 | mint: rawAccount.mint.toString(), 247 | signature: result.signature, 248 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 249 | }, 250 | `Confirmed sell tx`, 251 | ); 252 | break; 253 | } 254 | 255 | logger.info( 256 | { 257 | mint: rawAccount.mint.toString(), 258 | signature: result.signature, 259 | error: result.error, 260 | }, 261 | `Error confirming sell tx`, 262 | ); 263 | } catch (error) { 264 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`); 265 | } 266 | } 267 | } catch (error) { 268 | logger.error({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`); 269 | } finally { 270 | this.sellExecutionCount--; 271 | } 272 | } 273 | 274 | // noinspection JSUnusedLocalSymbols 275 | private async swap( 276 | poolKeys: LiquidityPoolKeysV4, 277 | ataIn: PublicKey, 278 | ataOut: PublicKey, 279 | tokenIn: Token, 280 | tokenOut: Token, 281 | amountIn: TokenAmount, 282 | slippage: number, 283 | wallet: Keypair, 284 | direction: 'buy' | 'sell', 285 | ) { 286 | const slippagePercent = new Percent(slippage, 100); 287 | const poolInfo = await Liquidity.fetchInfo({ 288 | connection: this.connection, 289 | poolKeys, 290 | }); 291 | 292 | const computedAmountOut = Liquidity.computeAmountOut({ 293 | poolKeys, 294 | poolInfo, 295 | amountIn, 296 | currencyOut: tokenOut, 297 | slippage: slippagePercent, 298 | }); 299 | 300 | const latestBlockhash = await this.connection.getLatestBlockhash(); 301 | const { innerTransaction } = Liquidity.makeSwapFixedInInstruction( 302 | { 303 | poolKeys: poolKeys, 304 | userKeys: { 305 | tokenAccountIn: ataIn, 306 | tokenAccountOut: ataOut, 307 | owner: wallet.publicKey, 308 | }, 309 | amountIn: amountIn.raw, 310 | minAmountOut: computedAmountOut.minAmountOut.raw, 311 | }, 312 | poolKeys.version, 313 | ); 314 | 315 | const messageV0 = new TransactionMessage({ 316 | payerKey: wallet.publicKey, 317 | recentBlockhash: latestBlockhash.blockhash, 318 | instructions: [ 319 | ...(this.isWarp || this.isJito 320 | ? [] 321 | : [ 322 | ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }), 323 | ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }), 324 | ]), 325 | ...(direction === 'buy' 326 | ? [ 327 | createAssociatedTokenAccountIdempotentInstruction( 328 | wallet.publicKey, 329 | ataOut, 330 | wallet.publicKey, 331 | tokenOut.mint, 332 | ), 333 | ] 334 | : []), 335 | ...innerTransaction.instructions, 336 | ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []), 337 | ], 338 | }).compileToV0Message(); 339 | 340 | const transaction = new VersionedTransaction(messageV0); 341 | transaction.sign([wallet, ...innerTransaction.signers]); 342 | 343 | return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash); 344 | } 345 | 346 | private async filterMatch(poolKeys: LiquidityPoolKeysV4) { 347 | if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) { 348 | return true; 349 | } 350 | 351 | const filters = new PoolFilters(this.connection, { 352 | quoteToken: this.config.quoteToken, 353 | minPoolSize: this.config.minPoolSize, 354 | maxPoolSize: this.config.maxPoolSize, 355 | }); 356 | 357 | const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval; 358 | let timesChecked = 0; 359 | let matchCount = 0; 360 | 361 | do { 362 | try { 363 | const shouldBuy = await filters.execute(poolKeys); 364 | 365 | if (shouldBuy) { 366 | matchCount++; 367 | 368 | if (this.config.consecutiveMatchCount <= matchCount) { 369 | logger.debug( 370 | { mint: poolKeys.baseMint.toString() }, 371 | `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`, 372 | ); 373 | return true; 374 | } 375 | } else { 376 | matchCount = 0; 377 | } 378 | 379 | await sleep(this.config.filterCheckInterval); 380 | } finally { 381 | timesChecked++; 382 | } 383 | } while (timesChecked < timesToCheck); 384 | 385 | return false; 386 | } 387 | 388 | private async waitForSellSignal(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) { 389 | if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) { 390 | return true; 391 | } 392 | 393 | const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval; 394 | const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100)); 395 | const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true); 396 | const takeProfit = this.config.quoteAmount.add(profitAmount); 397 | let stopLoss: TokenAmount; 398 | 399 | if (!this.stopLoss.get(poolKeys.baseMint.toString())) { 400 | const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100)); 401 | const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true); 402 | stopLoss = this.config.quoteAmount.subtract(lossAmount); 403 | 404 | this.stopLoss.set(poolKeys.baseMint.toString(), stopLoss); 405 | } else { 406 | stopLoss = this.stopLoss.get(poolKeys.baseMint.toString())!; 407 | } 408 | 409 | const slippage = new Percent(this.config.sellSlippage, 100); 410 | let timesChecked = 0; 411 | 412 | do { 413 | try { 414 | const poolInfo = await Liquidity.fetchInfo({ 415 | connection: this.connection, 416 | poolKeys, 417 | }); 418 | 419 | const amountOut = Liquidity.computeAmountOut({ 420 | poolKeys, 421 | poolInfo, 422 | amountIn: amountIn, 423 | currencyOut: this.config.quoteToken, 424 | slippage, 425 | }).amountOut as TokenAmount; 426 | 427 | if (this.config.trailingStopLoss) { 428 | const trailingLossFraction = amountOut.mul(this.config.stopLoss).numerator.div(new BN(100)); 429 | const trailingLossAmount = new TokenAmount(this.config.quoteToken, trailingLossFraction, true); 430 | const trailingStopLoss = amountOut.subtract(trailingLossAmount); 431 | 432 | if (trailingStopLoss.gt(stopLoss)) { 433 | logger.trace( 434 | { mint: poolKeys.baseMint.toString() }, 435 | `Updating trailing stop loss from ${stopLoss.toFixed()} to ${trailingStopLoss.toFixed()}`, 436 | ); 437 | this.stopLoss.set(poolKeys.baseMint.toString(), trailingStopLoss); 438 | stopLoss = trailingStopLoss; 439 | } 440 | } 441 | 442 | if (this.config.skipSellingIfLostMoreThan > 0) { 443 | const stopSellingFraction = this.config.quoteAmount 444 | .mul(this.config.skipSellingIfLostMoreThan) 445 | .numerator.div(new BN(100)); 446 | 447 | const stopSellingAmount = new TokenAmount(this.config.quoteToken, stopSellingFraction, true); 448 | 449 | if (amountOut.lt(stopSellingAmount)) { 450 | logger.debug( 451 | { mint: poolKeys.baseMint.toString() }, 452 | `Token dropped more than ${this.config.skipSellingIfLostMoreThan}%, sell stopped. Initial: ${this.config.quoteAmount.toFixed()} | Current: ${amountOut.toFixed()}`, 453 | ); 454 | this.stopLoss.delete(poolKeys.baseMint.toString()); 455 | return false; 456 | } 457 | } 458 | 459 | logger.debug( 460 | { mint: poolKeys.baseMint.toString() }, 461 | `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`, 462 | ); 463 | 464 | if (amountOut.lt(stopLoss)) { 465 | this.stopLoss.delete(poolKeys.baseMint.toString()); 466 | break; 467 | } 468 | 469 | if (amountOut.gt(takeProfit)) { 470 | this.stopLoss.delete(poolKeys.baseMint.toString()); 471 | break; 472 | } 473 | 474 | await sleep(this.config.priceCheckInterval); 475 | } catch (e) { 476 | logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); 477 | } finally { 478 | timesChecked++; 479 | } 480 | } while (timesChecked < timesToCheck); 481 | 482 | return true; 483 | } 484 | } 485 | -------------------------------------------------------------------------------- /cache/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market.cache'; 2 | export * from './pool.cache'; 3 | export * from './snipe-list.cache'; 4 | -------------------------------------------------------------------------------- /cache/market.cache.ts: -------------------------------------------------------------------------------- 1 | import { Connection, PublicKey } from '@solana/web3.js'; 2 | import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers'; 3 | import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 4 | 5 | export class MarketCache { 6 | private readonly keys: Map = new Map(); 7 | constructor(private readonly connection: Connection) {} 8 | 9 | async init(config: { quoteToken: Token }) { 10 | logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`); 11 | 12 | const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, { 13 | commitment: this.connection.commitment, 14 | dataSlice: { 15 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 16 | length: MINIMAL_MARKET_STATE_LAYOUT_V3.span, 17 | }, 18 | filters: [ 19 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 20 | { 21 | memcmp: { 22 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 23 | bytes: config.quoteToken.mint.toBase58(), 24 | }, 25 | }, 26 | ], 27 | }); 28 | 29 | for (const account of accounts) { 30 | const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data); 31 | this.keys.set(account.pubkey.toString(), market); 32 | } 33 | 34 | logger.debug({}, `Cached ${this.keys.size} markets`); 35 | } 36 | 37 | public save(marketId: string, keys: MinimalMarketLayoutV3) { 38 | if (!this.keys.has(marketId)) { 39 | logger.trace({}, `Caching new market: ${marketId}`); 40 | this.keys.set(marketId, keys); 41 | } 42 | } 43 | 44 | public async get(marketId: string): Promise { 45 | if (this.keys.has(marketId)) { 46 | return this.keys.get(marketId)!; 47 | } 48 | 49 | logger.trace({}, `Fetching new market keys for ${marketId}`); 50 | const market = await this.fetch(marketId); 51 | this.keys.set(marketId, market); 52 | return market; 53 | } 54 | 55 | private fetch(marketId: string): Promise { 56 | return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /cache/pool.cache.ts: -------------------------------------------------------------------------------- 1 | import { LiquidityStateV4 } from '@raydium-io/raydium-sdk'; 2 | import { logger } from '../helpers'; 3 | 4 | export class PoolCache { 5 | private readonly keys: Map = new Map< 6 | string, 7 | { id: string; state: LiquidityStateV4 } 8 | >(); 9 | 10 | public save(id: string, state: LiquidityStateV4) { 11 | if (!this.keys.has(state.baseMint.toString())) { 12 | logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`); 13 | this.keys.set(state.baseMint.toString(), { id, state }); 14 | } 15 | } 16 | 17 | public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4 }> { 18 | return this.keys.get(mint)!; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /cache/snipe-list.cache.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { logger, SNIPE_LIST_REFRESH_INTERVAL } from '../helpers'; 4 | 5 | export class SnipeListCache { 6 | private snipeList: string[] = []; 7 | private fileLocation = path.join(__dirname, '../snipe-list.txt'); 8 | 9 | constructor() { 10 | setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL); 11 | } 12 | 13 | public init() { 14 | this.loadSnipeList(); 15 | } 16 | 17 | public isInList(mint: string) { 18 | return this.snipeList.includes(mint); 19 | } 20 | 21 | private loadSnipeList() { 22 | logger.trace(`Refreshing snipe list...`); 23 | 24 | const count = this.snipeList.length; 25 | const data = fs.readFileSync(this.fileLocation, 'utf-8'); 26 | this.snipeList = data 27 | .split('\n') 28 | .map((a) => a.trim()) 29 | .filter((a) => a); 30 | 31 | if (this.snipeList.length != count) { 32 | logger.info(`Loaded snipe list: ${this.snipeList.length}`); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /filters/burn.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { logger } from '../helpers'; 5 | 6 | export class BurnFilter implements Filter { 7 | private cachedResult: FilterResult | undefined = undefined; 8 | 9 | constructor(private readonly connection: Connection) {} 10 | 11 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 12 | if (this.cachedResult) { 13 | return this.cachedResult; 14 | } 15 | 16 | try { 17 | const amount = await this.connection.getTokenSupply(poolKeys.lpMint, this.connection.commitment); 18 | const burned = amount.value.uiAmount === 0; 19 | const result = { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" }; 20 | 21 | if (result.ok) { 22 | this.cachedResult = result; 23 | } 24 | 25 | return result; 26 | } catch (e: any) { 27 | if (e.code == -32602) { 28 | return { ok: true }; 29 | } 30 | 31 | logger.error({ mint: poolKeys.baseMint }, `Failed to check if LP is burned`); 32 | } 33 | 34 | return { ok: false, message: 'Failed to check if LP is burned' }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /filters/index.ts: -------------------------------------------------------------------------------- 1 | export * from './burn.filter'; 2 | export * from './mutable.filter'; 3 | export * from './pool-filters'; 4 | export * from './pool-size.filter'; 5 | export * from './renounced.filter'; 6 | -------------------------------------------------------------------------------- /filters/mutable.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { getPdaMetadataKey } from '@raydium-io/raydium-sdk'; 5 | import { MetadataAccountData, MetadataAccountDataArgs } from '@metaplex-foundation/mpl-token-metadata'; 6 | import { Serializer } from '@metaplex-foundation/umi/serializers'; 7 | import { logger } from '../helpers'; 8 | 9 | export class MutableFilter implements Filter { 10 | private readonly errorMessage: string[] = []; 11 | private cachedResult: FilterResult | undefined = undefined; 12 | 13 | constructor( 14 | private readonly connection: Connection, 15 | private readonly metadataSerializer: Serializer, 16 | private readonly checkMutable: boolean, 17 | private readonly checkSocials: boolean, 18 | ) { 19 | if (this.checkMutable) { 20 | this.errorMessage.push('mutable'); 21 | } 22 | 23 | if (this.checkSocials) { 24 | this.errorMessage.push('socials'); 25 | } 26 | } 27 | 28 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 29 | if (this.cachedResult) { 30 | return this.cachedResult; 31 | } 32 | 33 | try { 34 | const metadataPDA = getPdaMetadataKey(poolKeys.baseMint); 35 | const metadataAccount = await this.connection.getAccountInfo(metadataPDA.publicKey, this.connection.commitment); 36 | 37 | if (!metadataAccount?.data) { 38 | return { ok: false, message: 'Mutable -> Failed to fetch account data' }; 39 | } 40 | 41 | const deserialize = this.metadataSerializer.deserialize(metadataAccount.data); 42 | const mutable = !this.checkMutable || deserialize[0].isMutable; 43 | const hasSocials = !this.checkSocials || (await this.hasSocials(deserialize[0])); 44 | const ok = !mutable && hasSocials; 45 | const message: string[] = []; 46 | 47 | if (mutable) { 48 | message.push('metadata can be changed'); 49 | } 50 | 51 | if (!hasSocials) { 52 | message.push('has no socials'); 53 | } 54 | 55 | const result = { ok: ok, message: ok ? undefined : `MutableSocials -> Token ${message.join(' and ')}` }; 56 | 57 | if (!mutable) { 58 | this.cachedResult = result; 59 | } 60 | 61 | return result; 62 | } catch (e) { 63 | logger.error({ mint: poolKeys.baseMint }, `MutableSocials -> Failed to check ${this.errorMessage.join(' and ')}`); 64 | } 65 | 66 | return { 67 | ok: false, 68 | message: `MutableSocials -> Failed to check ${this.errorMessage.join(' and ')}`, 69 | }; 70 | } 71 | 72 | private async hasSocials(metadata: MetadataAccountData) { 73 | const response = await fetch(metadata.uri); 74 | const data = await response.json(); 75 | return Object.values(data?.extensions ?? {}).filter((value: any) => value).length > 0; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /filters/pool-filters.ts: -------------------------------------------------------------------------------- 1 | import { Connection } from '@solana/web3.js'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { getMetadataAccountDataSerializer } from '@metaplex-foundation/mpl-token-metadata'; 4 | import { BurnFilter } from './burn.filter'; 5 | import { MutableFilter } from './mutable.filter'; 6 | import { RenouncedFreezeFilter } from './renounced.filter'; 7 | import { PoolSizeFilter } from './pool-size.filter'; 8 | import { CHECK_IF_BURNED, CHECK_IF_FREEZABLE, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_MUTABLE, CHECK_IF_SOCIALS, logger } from '../helpers'; 9 | 10 | export interface Filter { 11 | execute(poolKeysV4: LiquidityPoolKeysV4): Promise; 12 | } 13 | 14 | export interface FilterResult { 15 | ok: boolean; 16 | message?: string; 17 | } 18 | 19 | export interface PoolFilterArgs { 20 | minPoolSize: TokenAmount; 21 | maxPoolSize: TokenAmount; 22 | quoteToken: Token; 23 | } 24 | 25 | export class PoolFilters { 26 | private readonly filters: Filter[] = []; 27 | 28 | constructor( 29 | readonly connection: Connection, 30 | readonly args: PoolFilterArgs, 31 | ) { 32 | if (CHECK_IF_BURNED) { 33 | this.filters.push(new BurnFilter(connection)); 34 | } 35 | 36 | if (CHECK_IF_MINT_IS_RENOUNCED || CHECK_IF_FREEZABLE) { 37 | this.filters.push(new RenouncedFreezeFilter(connection, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_FREEZABLE)); 38 | } 39 | 40 | if (CHECK_IF_MUTABLE || CHECK_IF_SOCIALS) { 41 | this.filters.push(new MutableFilter(connection, getMetadataAccountDataSerializer(), CHECK_IF_MUTABLE, CHECK_IF_SOCIALS)); 42 | } 43 | 44 | if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) { 45 | this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize)); 46 | } 47 | } 48 | 49 | public async execute(poolKeys: LiquidityPoolKeysV4): Promise { 50 | if (this.filters.length === 0) { 51 | return true; 52 | } 53 | 54 | const result = await Promise.all(this.filters.map((f) => f.execute(poolKeys))); 55 | const pass = result.every((r) => r.ok); 56 | 57 | if (pass) { 58 | return true; 59 | } 60 | 61 | for (const filterResult of result.filter((r) => !r.ok)) { 62 | logger.trace(filterResult.message); 63 | } 64 | 65 | return false; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /filters/pool-size.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { Connection } from '@solana/web3.js'; 4 | import { logger } from '../helpers'; 5 | 6 | export class PoolSizeFilter implements Filter { 7 | constructor( 8 | private readonly connection: Connection, 9 | private readonly quoteToken: Token, 10 | private readonly minPoolSize: TokenAmount, 11 | private readonly maxPoolSize: TokenAmount, 12 | ) {} 13 | 14 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 15 | try { 16 | const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment); 17 | const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true); 18 | let inRange = true; 19 | 20 | if (!this.maxPoolSize?.isZero()) { 21 | inRange = poolSize.raw.lte(this.maxPoolSize.raw); 22 | 23 | if (!inRange) { 24 | return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` }; 25 | } 26 | } 27 | 28 | if (!this.minPoolSize?.isZero()) { 29 | inRange = poolSize.raw.gte(this.minPoolSize.raw); 30 | 31 | if (!inRange) { 32 | return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` }; 33 | } 34 | } 35 | 36 | return { ok: inRange }; 37 | } catch (error) { 38 | logger.error({ mint: poolKeys.baseMint }, `Failed to check pool size`); 39 | } 40 | 41 | return { ok: false, message: 'PoolSize -> Failed to check pool size' }; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /filters/renounced.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { MintLayout } from '@solana/spl-token'; 3 | import { Connection } from '@solana/web3.js'; 4 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 5 | import { logger } from '../helpers'; 6 | 7 | export class RenouncedFreezeFilter implements Filter { 8 | private readonly errorMessage: string[] = []; 9 | private cachedResult: FilterResult | undefined = undefined; 10 | 11 | constructor( 12 | private readonly connection: Connection, 13 | private readonly checkRenounced: boolean, 14 | private readonly checkFreezable: boolean, 15 | ) { 16 | if (this.checkRenounced) { 17 | this.errorMessage.push('mint'); 18 | } 19 | 20 | if (this.checkFreezable) { 21 | this.errorMessage.push('freeze'); 22 | } 23 | } 24 | 25 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 26 | if (this.cachedResult) { 27 | return this.cachedResult; 28 | } 29 | 30 | try { 31 | const accountInfo = await this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment); 32 | if (!accountInfo?.data) { 33 | return { ok: false, message: 'RenouncedFreeze -> Failed to fetch account data' }; 34 | } 35 | 36 | const deserialize = MintLayout.decode(accountInfo.data); 37 | const renounced = !this.checkRenounced || deserialize.mintAuthorityOption === 0; 38 | const freezable = !this.checkFreezable || deserialize.freezeAuthorityOption !== 0; 39 | const ok = renounced && !freezable; 40 | const message: string[] = []; 41 | 42 | if (!renounced) { 43 | message.push('mint'); 44 | } 45 | 46 | if (freezable) { 47 | message.push('freeze'); 48 | } 49 | 50 | const result = { 51 | ok: ok, 52 | message: ok ? undefined : `RenouncedFreeze -> Creator can ${message.join(' and ')} tokens`, 53 | }; 54 | 55 | if (result.ok) { 56 | this.cachedResult = result; 57 | } 58 | 59 | return result; 60 | } catch (e) { 61 | logger.error( 62 | { mint: poolKeys.baseMint }, 63 | `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(' and ')} tokens`, 64 | ); 65 | } 66 | 67 | return { 68 | ok: false, 69 | message: `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(' and ')} tokens`, 70 | }; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /helpers/constants.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from 'pino'; 2 | import dotenv from 'dotenv'; 3 | import { Commitment } from '@solana/web3.js'; 4 | import { logger } from './logger'; 5 | 6 | dotenv.config(); 7 | 8 | const retrieveEnvVariable = (variableName: string, logger: Logger) => { 9 | const variable = process.env[variableName] || ''; 10 | if (!variable) { 11 | logger.error(`${variableName} is not set`); 12 | process.exit(1); 13 | } 14 | return variable; 15 | }; 16 | 17 | // Wallet 18 | export const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger); 19 | 20 | // Connection 21 | export const NETWORK = 'mainnet-beta'; 22 | export const COMMITMENT_LEVEL: Commitment = retrieveEnvVariable('COMMITMENT_LEVEL', logger) as Commitment; 23 | export const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger); 24 | export const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable('RPC_WEBSOCKET_ENDPOINT', logger); 25 | 26 | // Bot 27 | export const LOG_LEVEL = retrieveEnvVariable('LOG_LEVEL', logger); 28 | export const MAX_TOKENS_AT_THE_TIME = Number(retrieveEnvVariable('MAX_TOKENS_AT_THE_TIME', logger)); 29 | export const COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable('COMPUTE_UNIT_LIMIT', logger)); 30 | export const COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable('COMPUTE_UNIT_PRICE', logger)); 31 | export const PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable('PRE_LOAD_EXISTING_MARKETS', logger) === 'true'; 32 | export const CACHE_NEW_MARKETS = retrieveEnvVariable('CACHE_NEW_MARKETS', logger) === 'true'; 33 | export const TRANSACTION_EXECUTOR = retrieveEnvVariable('TRANSACTION_EXECUTOR', logger); 34 | export const CUSTOM_FEE = retrieveEnvVariable('CUSTOM_FEE', logger); 35 | 36 | // Buy 37 | export const AUTO_BUY_DELAY = Number(retrieveEnvVariable('AUTO_BUY_DELAY', logger)); 38 | export const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger); 39 | export const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger); 40 | export const MAX_BUY_RETRIES = Number(retrieveEnvVariable('MAX_BUY_RETRIES', logger)); 41 | export const BUY_SLIPPAGE = Number(retrieveEnvVariable('BUY_SLIPPAGE', logger)); 42 | 43 | // Sell 44 | export const AUTO_SELL = retrieveEnvVariable('AUTO_SELL', logger) === 'true'; 45 | export const AUTO_SELL_DELAY = Number(retrieveEnvVariable('AUTO_SELL_DELAY', logger)); 46 | export const MAX_SELL_RETRIES = Number(retrieveEnvVariable('MAX_SELL_RETRIES', logger)); 47 | export const TAKE_PROFIT = Number(retrieveEnvVariable('TAKE_PROFIT', logger)); 48 | export const STOP_LOSS = Number(retrieveEnvVariable('STOP_LOSS', logger)); 49 | export const TRAILING_STOP_LOSS = retrieveEnvVariable('TRAILING_STOP_LOSS', logger) === 'true'; 50 | export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable('PRICE_CHECK_INTERVAL', logger)); 51 | export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable('PRICE_CHECK_DURATION', logger)); 52 | export const SELL_SLIPPAGE = Number(retrieveEnvVariable('SELL_SLIPPAGE', logger)); 53 | export const SKIP_SELLING_IF_LOST_MORE_THAN = Number(retrieveEnvVariable('SKIP_SELLING_IF_LOST_MORE_THAN', logger)); 54 | 55 | // Filters 56 | export const FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable('FILTER_CHECK_INTERVAL', logger)); 57 | export const FILTER_CHECK_DURATION = Number(retrieveEnvVariable('FILTER_CHECK_DURATION', logger)); 58 | export const CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable('CONSECUTIVE_FILTER_MATCHES', logger)); 59 | export const CHECK_IF_MUTABLE = retrieveEnvVariable('CHECK_IF_MUTABLE', logger) === 'true'; 60 | export const CHECK_IF_SOCIALS = retrieveEnvVariable('CHECK_IF_SOCIALS', logger) === 'true'; 61 | export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true'; 62 | export const CHECK_IF_FREEZABLE = retrieveEnvVariable('CHECK_IF_FREEZABLE', logger) === 'true'; 63 | export const CHECK_IF_BURNED = retrieveEnvVariable('CHECK_IF_BURNED', logger) === 'true'; 64 | export const MIN_POOL_SIZE = retrieveEnvVariable('MIN_POOL_SIZE', logger); 65 | export const MAX_POOL_SIZE = retrieveEnvVariable('MAX_POOL_SIZE', logger); 66 | export const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true'; 67 | export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger)); 68 | -------------------------------------------------------------------------------- /helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market'; 2 | export * from './liquidity'; 3 | export * from './logger'; 4 | export * from './constants'; 5 | export * from './token'; 6 | export * from './wallet'; 7 | export * from './promises' 8 | -------------------------------------------------------------------------------- /helpers/liquidity.ts: -------------------------------------------------------------------------------- 1 | import { PublicKey } from '@solana/web3.js'; 2 | import { Liquidity, LiquidityPoolKeys, LiquidityStateV4, MAINNET_PROGRAM_ID, Market } from '@raydium-io/raydium-sdk'; 3 | import { MinimalMarketLayoutV3 } from './market'; 4 | 5 | export function createPoolKeys( 6 | id: PublicKey, 7 | accountData: LiquidityStateV4, 8 | minimalMarketLayoutV3: MinimalMarketLayoutV3, 9 | ): LiquidityPoolKeys { 10 | return { 11 | id, 12 | baseMint: accountData.baseMint, 13 | quoteMint: accountData.quoteMint, 14 | lpMint: accountData.lpMint, 15 | baseDecimals: accountData.baseDecimal.toNumber(), 16 | quoteDecimals: accountData.quoteDecimal.toNumber(), 17 | lpDecimals: 5, 18 | version: 4, 19 | programId: MAINNET_PROGRAM_ID.AmmV4, 20 | authority: Liquidity.getAssociatedAuthority({ 21 | programId: MAINNET_PROGRAM_ID.AmmV4, 22 | }).publicKey, 23 | openOrders: accountData.openOrders, 24 | targetOrders: accountData.targetOrders, 25 | baseVault: accountData.baseVault, 26 | quoteVault: accountData.quoteVault, 27 | marketVersion: 3, 28 | marketProgramId: accountData.marketProgramId, 29 | marketId: accountData.marketId, 30 | marketAuthority: Market.getAssociatedAuthority({ 31 | programId: accountData.marketProgramId, 32 | marketId: accountData.marketId, 33 | }).publicKey, 34 | marketBaseVault: accountData.baseVault, 35 | marketQuoteVault: accountData.quoteVault, 36 | marketBids: minimalMarketLayoutV3.bids, 37 | marketAsks: minimalMarketLayoutV3.asks, 38 | marketEventQueue: minimalMarketLayoutV3.eventQueue, 39 | withdrawQueue: accountData.withdrawQueue, 40 | lpVault: accountData.lpVault, 41 | lookupTableAccount: PublicKey.default, 42 | }; 43 | } 44 | -------------------------------------------------------------------------------- /helpers/logger.ts: -------------------------------------------------------------------------------- 1 | import pino from 'pino'; 2 | 3 | const transport = pino.transport({ 4 | target: 'pino-pretty', 5 | }); 6 | 7 | export const logger = pino( 8 | { 9 | level: 'info', 10 | redact: ['poolKeys'], 11 | serializers: { 12 | error: pino.stdSerializers.err, 13 | }, 14 | base: undefined, 15 | }, 16 | transport, 17 | ); 18 | -------------------------------------------------------------------------------- /helpers/market.ts: -------------------------------------------------------------------------------- 1 | import { Commitment, Connection, PublicKey } from '@solana/web3.js'; 2 | import { GetStructureSchema, MARKET_STATE_LAYOUT_V3, publicKey, struct } from '@raydium-io/raydium-sdk'; 3 | 4 | export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([publicKey('eventQueue'), publicKey('bids'), publicKey('asks')]); 5 | export type MinimalMarketStateLayoutV3 = typeof MINIMAL_MARKET_STATE_LAYOUT_V3; 6 | export type MinimalMarketLayoutV3 = GetStructureSchema; 7 | 8 | export async function getMinimalMarketV3( 9 | connection: Connection, 10 | marketId: PublicKey, 11 | commitment?: Commitment, 12 | ): Promise { 13 | const marketInfo = await connection.getAccountInfo(marketId, { 14 | commitment, 15 | dataSlice: { 16 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 17 | length: 32 * 3, 18 | }, 19 | }); 20 | 21 | return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data); 22 | } 23 | -------------------------------------------------------------------------------- /helpers/promises.ts: -------------------------------------------------------------------------------- 1 | export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); 2 | -------------------------------------------------------------------------------- /helpers/token.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '@raydium-io/raydium-sdk'; 2 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; 3 | import { PublicKey } from '@solana/web3.js'; 4 | 5 | export function getToken(token: string) { 6 | switch (token) { 7 | case 'WSOL': { 8 | return Token.WSOL; 9 | } 10 | case 'USDC': { 11 | return new Token( 12 | TOKEN_PROGRAM_ID, 13 | new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), 14 | 6, 15 | 'USDC', 16 | 'USDC', 17 | ); 18 | } 19 | default: { 20 | throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /helpers/wallet.ts: -------------------------------------------------------------------------------- 1 | import { Keypair } from '@solana/web3.js'; 2 | import bs58 from 'bs58'; 3 | import { mnemonicToSeedSync } from 'bip39'; 4 | import { derivePath } from 'ed25519-hd-key'; 5 | 6 | export function getWallet(wallet: string): Keypair { 7 | // most likely someone pasted the private key in binary format 8 | if (wallet.startsWith('[')) { 9 | return Keypair.fromSecretKey(JSON.parse(wallet)); 10 | } 11 | 12 | // most likely someone pasted mnemonic 13 | if (wallet.split(' ').length > 1) { 14 | const seed = mnemonicToSeedSync(wallet, ''); 15 | const path = `m/44'/501'/0'/0'`; // we assume it's first path 16 | return Keypair.fromSeed(derivePath(path, seed.toString('hex')).key); 17 | } 18 | 19 | // most likely someone pasted base58 encoded private key 20 | return Keypair.fromSecretKey(bs58.decode(wallet)); 21 | } 22 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { MarketCache, PoolCache } from './cache'; 2 | import { Listeners } from './listeners'; 3 | import { Connection, KeyedAccountInfo, Keypair } from '@solana/web3.js'; 4 | import { LIQUIDITY_STATE_LAYOUT_V4, MARKET_STATE_LAYOUT_V3, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 5 | import { AccountLayout, getAssociatedTokenAddressSync } from '@solana/spl-token'; 6 | import { Bot, BotConfig } from './bot'; 7 | import { DefaultTransactionExecutor, TransactionExecutor } from './transactions'; 8 | import { 9 | getToken, 10 | getWallet, 11 | logger, 12 | COMMITMENT_LEVEL, 13 | RPC_ENDPOINT, 14 | RPC_WEBSOCKET_ENDPOINT, 15 | PRE_LOAD_EXISTING_MARKETS, 16 | LOG_LEVEL, 17 | QUOTE_MINT, 18 | MAX_POOL_SIZE, 19 | MIN_POOL_SIZE, 20 | QUOTE_AMOUNT, 21 | PRIVATE_KEY, 22 | USE_SNIPE_LIST, 23 | AUTO_SELL_DELAY, 24 | MAX_SELL_RETRIES, 25 | AUTO_SELL, 26 | MAX_BUY_RETRIES, 27 | AUTO_BUY_DELAY, 28 | COMPUTE_UNIT_LIMIT, 29 | COMPUTE_UNIT_PRICE, 30 | CACHE_NEW_MARKETS, 31 | TAKE_PROFIT, 32 | STOP_LOSS, 33 | BUY_SLIPPAGE, 34 | SELL_SLIPPAGE, 35 | PRICE_CHECK_DURATION, 36 | PRICE_CHECK_INTERVAL, 37 | SNIPE_LIST_REFRESH_INTERVAL, 38 | TRANSACTION_EXECUTOR, 39 | CUSTOM_FEE, 40 | FILTER_CHECK_INTERVAL, 41 | FILTER_CHECK_DURATION, 42 | CONSECUTIVE_FILTER_MATCHES, 43 | MAX_TOKENS_AT_THE_TIME, 44 | CHECK_IF_MINT_IS_RENOUNCED, 45 | CHECK_IF_FREEZABLE, 46 | CHECK_IF_BURNED, 47 | CHECK_IF_MUTABLE, 48 | CHECK_IF_SOCIALS, 49 | TRAILING_STOP_LOSS, 50 | SKIP_SELLING_IF_LOST_MORE_THAN, 51 | } from './helpers'; 52 | import { version } from './package.json'; 53 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 54 | import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; 55 | 56 | const connection = new Connection(RPC_ENDPOINT, { 57 | wsEndpoint: RPC_WEBSOCKET_ENDPOINT, 58 | commitment: COMMITMENT_LEVEL, 59 | }); 60 | 61 | function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) { 62 | logger.info(` 63 | .. :-===++++- 64 | .-==+++++++- =+++++++++- 65 | ..:::--===+=.=: .+++++++++++:=+++++++++: 66 | .==+++++++++++++++=:+++: .+++++++++++.=++++++++-. 67 | .-+++++++++++++++=:=++++- .+++++++++=:.=+++++-::-. 68 | -:+++++++++++++=:+++++++- .++++++++-:- =+++++=-: 69 | -:++++++=++++=:++++=++++= .++++++++++- =+++++: 70 | -:++++-:=++=:++++=:-+++++:+++++====--:::::::. 71 | ::=+-:::==:=+++=::-:--::::::::::---------::. 72 | ::-: .::::::::. --------:::.. 73 | :- .:.-:::. 74 | 75 | WARP DRIVE ACTIVATED 🚀🐟 76 | Made with ❤️ by humans. 77 | Version: ${version} 78 | `); 79 | 80 | const botConfig = bot.config; 81 | 82 | logger.info('------- CONFIGURATION START -------'); 83 | logger.info(`Wallet: ${wallet.publicKey.toString()}`); 84 | 85 | logger.info('- Bot -'); 86 | logger.info(`Using transaction executor: ${TRANSACTION_EXECUTOR}`); 87 | 88 | if (bot.isWarp || bot.isJito) { 89 | logger.info(`${TRANSACTION_EXECUTOR} fee: ${CUSTOM_FEE}`); 90 | } else { 91 | logger.info(`Compute Unit limit: ${botConfig.unitLimit}`); 92 | logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`); 93 | } 94 | 95 | logger.info(`Max tokens at the time: ${botConfig.maxTokensAtTheTime}`); 96 | logger.info(`Pre load existing markets: ${PRE_LOAD_EXISTING_MARKETS}`); 97 | logger.info(`Cache new markets: ${CACHE_NEW_MARKETS}`); 98 | logger.info(`Log level: ${LOG_LEVEL}`); 99 | 100 | logger.info('- Buy -'); 101 | logger.info(`Buy amount: ${botConfig.quoteAmount.toFixed()} ${botConfig.quoteToken.name}`); 102 | logger.info(`Auto buy delay: ${botConfig.autoBuyDelay} ms`); 103 | logger.info(`Max buy retries: ${botConfig.maxBuyRetries}`); 104 | logger.info(`Buy amount (${quoteToken.symbol}): ${botConfig.quoteAmount.toFixed()}`); 105 | logger.info(`Buy slippage: ${botConfig.buySlippage}%`); 106 | 107 | logger.info('- Sell -'); 108 | logger.info(`Auto sell: ${AUTO_SELL}`); 109 | logger.info(`Auto sell delay: ${botConfig.autoSellDelay} ms`); 110 | logger.info(`Max sell retries: ${botConfig.maxSellRetries}`); 111 | logger.info(`Sell slippage: ${botConfig.sellSlippage}%`); 112 | logger.info(`Price check interval: ${botConfig.priceCheckInterval} ms`); 113 | logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`); 114 | logger.info(`Take profit: ${botConfig.takeProfit}%`); 115 | logger.info(`Stop loss: ${botConfig.stopLoss}%`); 116 | logger.info(`Trailing stop loss: ${botConfig.trailingStopLoss}`); 117 | logger.info(`Skip selling if lost more than: ${botConfig.skipSellingIfLostMoreThan}%`); 118 | 119 | logger.info('- Snipe list -'); 120 | logger.info(`Snipe list: ${botConfig.useSnipeList}`); 121 | logger.info(`Snipe list refresh interval: ${SNIPE_LIST_REFRESH_INTERVAL} ms`); 122 | 123 | if (botConfig.useSnipeList) { 124 | logger.info('- Filters -'); 125 | logger.info(`Filters are disabled when snipe list is on`); 126 | } else { 127 | logger.info('- Filters -'); 128 | logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`); 129 | logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`); 130 | logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount}`); 131 | logger.info(`Check renounced: ${CHECK_IF_MINT_IS_RENOUNCED}`); 132 | logger.info(`Check freezable: ${CHECK_IF_FREEZABLE}`); 133 | logger.info(`Check burned: ${CHECK_IF_BURNED}`); 134 | logger.info(`Check mutable: ${CHECK_IF_MUTABLE}`); 135 | logger.info(`Check socials: ${CHECK_IF_SOCIALS}`); 136 | logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`); 137 | logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`); 138 | } 139 | 140 | logger.info('------- CONFIGURATION END -------'); 141 | 142 | logger.info('Bot is running! Press CTRL + C to stop it.'); 143 | } 144 | 145 | const runListener = async () => { 146 | logger.level = LOG_LEVEL; 147 | logger.info('Bot is starting...'); 148 | 149 | const marketCache = new MarketCache(connection); 150 | const poolCache = new PoolCache(); 151 | let txExecutor: TransactionExecutor; 152 | 153 | switch (TRANSACTION_EXECUTOR) { 154 | case 'warp': { 155 | txExecutor = new WarpTransactionExecutor(CUSTOM_FEE); 156 | break; 157 | } 158 | case 'jito': { 159 | txExecutor = new JitoTransactionExecutor(CUSTOM_FEE, connection); 160 | break; 161 | } 162 | default: { 163 | txExecutor = new DefaultTransactionExecutor(connection); 164 | break; 165 | } 166 | } 167 | 168 | const wallet = getWallet(PRIVATE_KEY.trim()); 169 | const quoteToken = getToken(QUOTE_MINT); 170 | const botConfig = { 171 | wallet, 172 | quoteAta: getAssociatedTokenAddressSync(quoteToken.mint, wallet.publicKey), 173 | minPoolSize: new TokenAmount(quoteToken, MIN_POOL_SIZE, false), 174 | maxPoolSize: new TokenAmount(quoteToken, MAX_POOL_SIZE, false), 175 | quoteToken, 176 | quoteAmount: new TokenAmount(quoteToken, QUOTE_AMOUNT, false), 177 | maxTokensAtTheTime: MAX_TOKENS_AT_THE_TIME, 178 | useSnipeList: USE_SNIPE_LIST, 179 | autoSell: AUTO_SELL, 180 | autoSellDelay: AUTO_SELL_DELAY, 181 | maxSellRetries: MAX_SELL_RETRIES, 182 | autoBuyDelay: AUTO_BUY_DELAY, 183 | maxBuyRetries: MAX_BUY_RETRIES, 184 | unitLimit: COMPUTE_UNIT_LIMIT, 185 | unitPrice: COMPUTE_UNIT_PRICE, 186 | takeProfit: TAKE_PROFIT, 187 | stopLoss: STOP_LOSS, 188 | trailingStopLoss: TRAILING_STOP_LOSS, 189 | skipSellingIfLostMoreThan: SKIP_SELLING_IF_LOST_MORE_THAN, 190 | buySlippage: BUY_SLIPPAGE, 191 | sellSlippage: SELL_SLIPPAGE, 192 | priceCheckInterval: PRICE_CHECK_INTERVAL, 193 | priceCheckDuration: PRICE_CHECK_DURATION, 194 | filterCheckInterval: FILTER_CHECK_INTERVAL, 195 | filterCheckDuration: FILTER_CHECK_DURATION, 196 | consecutiveMatchCount: CONSECUTIVE_FILTER_MATCHES, 197 | }; 198 | 199 | const bot = new Bot(connection, marketCache, poolCache, txExecutor, botConfig); 200 | const valid = await bot.validate(); 201 | 202 | if (!valid) { 203 | logger.info('Bot is exiting...'); 204 | process.exit(1); 205 | } 206 | 207 | if (PRE_LOAD_EXISTING_MARKETS) { 208 | await marketCache.init({ quoteToken }); 209 | } 210 | 211 | const runTimestamp = Math.floor(new Date().getTime() / 1000); 212 | const listeners = new Listeners(connection); 213 | await listeners.start({ 214 | walletPublicKey: wallet.publicKey, 215 | quoteToken, 216 | autoSell: AUTO_SELL, 217 | cacheNewMarkets: CACHE_NEW_MARKETS, 218 | }); 219 | 220 | listeners.on('market', (updatedAccountInfo: KeyedAccountInfo) => { 221 | const marketState = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data); 222 | marketCache.save(updatedAccountInfo.accountId.toString(), marketState); 223 | }); 224 | 225 | listeners.on('pool', async (updatedAccountInfo: KeyedAccountInfo) => { 226 | const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data); 227 | const poolOpenTime = parseInt(poolState.poolOpenTime.toString()); 228 | const exists = await poolCache.get(poolState.baseMint.toString()); 229 | 230 | if (!exists && poolOpenTime > runTimestamp) { 231 | poolCache.save(updatedAccountInfo.accountId.toString(), poolState); 232 | await bot.buy(updatedAccountInfo.accountId, poolState); 233 | } 234 | }); 235 | 236 | listeners.on('wallet', async (updatedAccountInfo: KeyedAccountInfo) => { 237 | const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo.data); 238 | 239 | if (accountData.mint.equals(quoteToken.mint)) { 240 | return; 241 | } 242 | 243 | await bot.sell(updatedAccountInfo.accountId, accountData); 244 | }); 245 | 246 | printDetails(wallet, quoteToken, bot); 247 | }; 248 | 249 | runListener(); 250 | -------------------------------------------------------------------------------- /listeners/index.ts: -------------------------------------------------------------------------------- 1 | export * from './listeners'; 2 | -------------------------------------------------------------------------------- /listeners/listeners.ts: -------------------------------------------------------------------------------- 1 | import { LIQUIDITY_STATE_LAYOUT_V4, MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 2 | import bs58 from 'bs58'; 3 | import { Connection, PublicKey } from '@solana/web3.js'; 4 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; 5 | import { EventEmitter } from 'events'; 6 | 7 | export class Listeners extends EventEmitter { 8 | private subscriptions: number[] = []; 9 | 10 | constructor(private readonly connection: Connection) { 11 | super(); 12 | } 13 | 14 | public async start(config: { 15 | walletPublicKey: PublicKey; 16 | quoteToken: Token; 17 | autoSell: boolean; 18 | cacheNewMarkets: boolean; 19 | }) { 20 | if (config.cacheNewMarkets) { 21 | const openBookSubscription = await this.subscribeToOpenBookMarkets(config); 22 | this.subscriptions.push(openBookSubscription); 23 | } 24 | 25 | const raydiumSubscription = await this.subscribeToRaydiumPools(config); 26 | this.subscriptions.push(raydiumSubscription); 27 | 28 | if (config.autoSell) { 29 | const walletSubscription = await this.subscribeToWalletChanges(config); 30 | this.subscriptions.push(walletSubscription); 31 | } 32 | } 33 | 34 | private async subscribeToOpenBookMarkets(config: { quoteToken: Token }) { 35 | return this.connection.onProgramAccountChange( 36 | MAINNET_PROGRAM_ID.OPENBOOK_MARKET, 37 | async (updatedAccountInfo) => { 38 | this.emit('market', updatedAccountInfo); 39 | }, 40 | this.connection.commitment, 41 | [ 42 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 43 | { 44 | memcmp: { 45 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 46 | bytes: config.quoteToken.mint.toBase58(), 47 | }, 48 | }, 49 | ], 50 | ); 51 | } 52 | 53 | private async subscribeToRaydiumPools(config: { quoteToken: Token }) { 54 | return this.connection.onProgramAccountChange( 55 | MAINNET_PROGRAM_ID.AmmV4, 56 | async (updatedAccountInfo) => { 57 | this.emit('pool', updatedAccountInfo); 58 | }, 59 | this.connection.commitment, 60 | [ 61 | { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span }, 62 | { 63 | memcmp: { 64 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'), 65 | bytes: config.quoteToken.mint.toBase58(), 66 | }, 67 | }, 68 | { 69 | memcmp: { 70 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'), 71 | bytes: MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(), 72 | }, 73 | }, 74 | { 75 | memcmp: { 76 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'), 77 | bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]), 78 | }, 79 | }, 80 | ], 81 | ); 82 | } 83 | 84 | private async subscribeToWalletChanges(config: { walletPublicKey: PublicKey }) { 85 | return this.connection.onProgramAccountChange( 86 | TOKEN_PROGRAM_ID, 87 | async (updatedAccountInfo) => { 88 | this.emit('wallet', updatedAccountInfo); 89 | }, 90 | this.connection.commitment, 91 | [ 92 | { 93 | dataSize: 165, 94 | }, 95 | { 96 | memcmp: { 97 | offset: 32, 98 | bytes: config.walletPublicKey.toBase58(), 99 | }, 100 | }, 101 | ], 102 | ); 103 | } 104 | 105 | public async stop() { 106 | for (let i = this.subscriptions.length; i >= 0; --i) { 107 | const subscription = this.subscriptions[i]; 108 | await this.connection.removeAccountChangeListener(subscription); 109 | this.subscriptions.splice(i, 1); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "warp-solana-bot", 3 | "author": "Filip Dundjer", 4 | "homepage": "https://warp.id", 5 | "version": "2.0.2", 6 | "scripts": { 7 | "start": "ts-node index.ts", 8 | "tsc": "tsc --noEmit" 9 | }, 10 | "dependencies": { 11 | "@metaplex-foundation/mpl-token-metadata": "^3.2.1", 12 | "@raydium-io/raydium-sdk": "^1.3.1-beta.47", 13 | "@solana/spl-token": "^0.4.0", 14 | "@solana/web3.js": "^1.89.1", 15 | "async-mutex": "^0.5.0", 16 | "axios": "^1.6.8", 17 | "bigint-buffer": "^1.1.5", 18 | "bip39": "^3.1.0", 19 | "bn.js": "^5.2.1", 20 | "bs58": "^5.0.0", 21 | "dotenv": "^16.4.1", 22 | "ed25519-hd-key": "^1.3.0", 23 | "i": "^0.3.7", 24 | "npm": "^10.5.2", 25 | "pino": "^8.18.0", 26 | "pino-pretty": "^10.3.1", 27 | "pino-std-serializers": "^6.2.2" 28 | }, 29 | "devDependencies": { 30 | "@types/bn.js": "^5.1.5", 31 | "prettier": "^3.2.4", 32 | "ts-node": "^10.9.2", 33 | "typescript": "^5.3.3" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /readme/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdundjer/solana-sniper-bot/04e5ca7d27dffd19423ad509210eaff922a0c22c/readme/output.png -------------------------------------------------------------------------------- /readme/wsol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdundjer/solana-sniper-bot/04e5ca7d27dffd19423ad509210eaff922a0c22c/readme/wsol.png -------------------------------------------------------------------------------- /snipe-list.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdundjer/solana-sniper-bot/04e5ca7d27dffd19423ad509210eaff922a0c22c/snipe-list.txt -------------------------------------------------------------------------------- /transactions/default-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Connection, 4 | Keypair, 5 | Transaction, 6 | VersionedTransaction, 7 | } from '@solana/web3.js'; 8 | import { TransactionExecutor } from './transaction-executor.interface'; 9 | import { logger } from '../helpers'; 10 | 11 | export class DefaultTransactionExecutor implements TransactionExecutor { 12 | constructor(private readonly connection: Connection) {} 13 | 14 | public async executeAndConfirm( 15 | transaction: VersionedTransaction, 16 | payer: Keypair, 17 | latestBlockhash: BlockhashWithExpiryBlockHeight, 18 | ): Promise<{ confirmed: boolean; signature?: string, error?: string }> { 19 | logger.debug('Executing transaction...'); 20 | const signature = await this.execute(transaction); 21 | 22 | logger.debug({ signature }, 'Confirming transaction...'); 23 | return this.confirm(signature, latestBlockhash); 24 | } 25 | 26 | private async execute(transaction: Transaction | VersionedTransaction) { 27 | return this.connection.sendRawTransaction(transaction.serialize(), { 28 | preflightCommitment: this.connection.commitment, 29 | }); 30 | } 31 | 32 | private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { 33 | const confirmation = await this.connection.confirmTransaction( 34 | { 35 | signature, 36 | lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, 37 | blockhash: latestBlockhash.blockhash, 38 | }, 39 | this.connection.commitment, 40 | ); 41 | 42 | return { confirmed: !confirmation.value.err, signature }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /transactions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './default-transaction-executor'; 2 | export * from './transaction-executor.interface'; 3 | -------------------------------------------------------------------------------- /transactions/jito-rpc-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Keypair, 4 | PublicKey, 5 | SystemProgram, 6 | Connection, 7 | TransactionMessage, 8 | VersionedTransaction, 9 | } from '@solana/web3.js'; 10 | import { TransactionExecutor } from './transaction-executor.interface'; 11 | import { logger } from '../helpers'; 12 | import axios, { AxiosError } from 'axios'; 13 | import bs58 from 'bs58'; 14 | import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; 15 | 16 | export class JitoTransactionExecutor implements TransactionExecutor { 17 | // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/bundles/gettipaccounts 18 | private jitpTipAccounts = [ 19 | 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY', 20 | 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL', 21 | '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5', 22 | '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT', 23 | 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe', 24 | 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49', 25 | 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt', 26 | 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh', 27 | ]; 28 | 29 | private JitoFeeWallet: PublicKey; 30 | 31 | constructor( 32 | private readonly jitoFee: string, 33 | private readonly connection: Connection, 34 | ) { 35 | this.JitoFeeWallet = this.getRandomValidatorKey(); 36 | } 37 | 38 | private getRandomValidatorKey(): PublicKey { 39 | const randomValidator = this.jitpTipAccounts[Math.floor(Math.random() * this.jitpTipAccounts.length)]; 40 | return new PublicKey(randomValidator); 41 | } 42 | 43 | public async executeAndConfirm( 44 | transaction: VersionedTransaction, 45 | payer: Keypair, 46 | latestBlockhash: BlockhashWithExpiryBlockHeight, 47 | ): Promise<{ confirmed: boolean; signature?: string; error?: string }> { 48 | logger.debug('Starting Jito transaction execution...'); 49 | this.JitoFeeWallet = this.getRandomValidatorKey(); // Update wallet key each execution 50 | logger.trace(`Selected Jito fee wallet: ${this.JitoFeeWallet.toBase58()}`); 51 | 52 | try { 53 | const fee = new CurrencyAmount(Currency.SOL, this.jitoFee, false).raw.toNumber(); 54 | logger.trace(`Calculated fee: ${fee} lamports`); 55 | 56 | const jitTipTxFeeMessage = new TransactionMessage({ 57 | payerKey: payer.publicKey, 58 | recentBlockhash: latestBlockhash.blockhash, 59 | instructions: [ 60 | SystemProgram.transfer({ 61 | fromPubkey: payer.publicKey, 62 | toPubkey: this.JitoFeeWallet, 63 | lamports: fee, 64 | }), 65 | ], 66 | }).compileToV0Message(); 67 | 68 | const jitoFeeTx = new VersionedTransaction(jitTipTxFeeMessage); 69 | jitoFeeTx.sign([payer]); 70 | 71 | const jitoTxsignature = bs58.encode(jitoFeeTx.signatures[0]); 72 | 73 | // Serialize the transactions once here 74 | const serializedjitoFeeTx = bs58.encode(jitoFeeTx.serialize()); 75 | const serializedTransaction = bs58.encode(transaction.serialize()); 76 | const serializedTransactions = [serializedjitoFeeTx, serializedTransaction]; 77 | 78 | // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/url 79 | const endpoints = [ 80 | 'https://mainnet.block-engine.jito.wtf/api/v1/bundles', 81 | 'https://amsterdam.mainnet.block-engine.jito.wtf/api/v1/bundles', 82 | 'https://frankfurt.mainnet.block-engine.jito.wtf/api/v1/bundles', 83 | 'https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles', 84 | 'https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles', 85 | ]; 86 | 87 | const requests = endpoints.map((url) => 88 | axios.post(url, { 89 | jsonrpc: '2.0', 90 | id: 1, 91 | method: 'sendBundle', 92 | params: [serializedTransactions], 93 | }), 94 | ); 95 | 96 | logger.trace('Sending transactions to endpoints...'); 97 | const results = await Promise.all(requests.map((p) => p.catch((e) => e))); 98 | 99 | const successfulResults = results.filter((result) => !(result instanceof Error)); 100 | 101 | if (successfulResults.length > 0) { 102 | logger.trace(`At least one successful response`); 103 | logger.debug(`Confirming jito transaction...`); 104 | return await this.confirm(jitoTxsignature, latestBlockhash); 105 | } else { 106 | logger.debug(`No successful responses received for jito`); 107 | } 108 | 109 | return { confirmed: false }; 110 | } catch (error) { 111 | if (error instanceof AxiosError) { 112 | logger.trace({ error: error.response?.data }, 'Failed to execute jito transaction'); 113 | } 114 | logger.error('Error during transaction execution', error); 115 | return { confirmed: false }; 116 | } 117 | } 118 | 119 | private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { 120 | const confirmation = await this.connection.confirmTransaction( 121 | { 122 | signature, 123 | lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, 124 | blockhash: latestBlockhash.blockhash, 125 | }, 126 | this.connection.commitment, 127 | ); 128 | 129 | return { confirmed: !confirmation.value.err, signature }; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /transactions/transaction-executor.interface.ts: -------------------------------------------------------------------------------- 1 | import { BlockhashWithExpiryBlockHeight, Keypair, VersionedTransaction } from '@solana/web3.js'; 2 | 3 | export interface TransactionExecutor { 4 | executeAndConfirm( 5 | transaction: VersionedTransaction, 6 | payer: Keypair, 7 | latestBlockHash: BlockhashWithExpiryBlockHeight, 8 | ): Promise<{ confirmed: boolean; signature?: string, error?: string }>; 9 | } 10 | -------------------------------------------------------------------------------- /transactions/warp-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Keypair, 4 | PublicKey, 5 | SystemProgram, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { TransactionExecutor } from './transaction-executor.interface'; 10 | import { logger } from '../helpers'; 11 | import axios, { AxiosError } from 'axios'; 12 | import bs58 from 'bs58'; 13 | import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; 14 | 15 | export class WarpTransactionExecutor implements TransactionExecutor { 16 | private readonly warpFeeWallet = new PublicKey('WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS'); 17 | 18 | constructor(private readonly warpFee: string) {} 19 | 20 | public async executeAndConfirm( 21 | transaction: VersionedTransaction, 22 | payer: Keypair, 23 | latestBlockhash: BlockhashWithExpiryBlockHeight, 24 | ): Promise<{ confirmed: boolean; signature?: string; error?: string }> { 25 | logger.debug('Executing transaction...'); 26 | 27 | try { 28 | const fee = new CurrencyAmount(Currency.SOL, this.warpFee, false).raw.toNumber(); 29 | const warpFeeMessage = new TransactionMessage({ 30 | payerKey: payer.publicKey, 31 | recentBlockhash: latestBlockhash.blockhash, 32 | instructions: [ 33 | SystemProgram.transfer({ 34 | fromPubkey: payer.publicKey, 35 | toPubkey: this.warpFeeWallet, 36 | lamports: fee, 37 | }), 38 | ], 39 | }).compileToV0Message(); 40 | 41 | const warpFeeTx = new VersionedTransaction(warpFeeMessage); 42 | warpFeeTx.sign([payer]); 43 | 44 | const response = await axios.post<{ confirmed: boolean; signature: string; error?: string }>( 45 | 'https://tx.warp.id/transaction/execute', 46 | { 47 | transactions: [bs58.encode(warpFeeTx.serialize()), bs58.encode(transaction.serialize())], 48 | latestBlockhash, 49 | }, 50 | { 51 | timeout: 100000, 52 | }, 53 | ); 54 | 55 | return response.data; 56 | } catch (error) { 57 | if (error instanceof AxiosError) { 58 | logger.trace({ error: error.response?.data }, 'Failed to execute warp transaction'); 59 | } 60 | } 61 | 62 | return { confirmed: false }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": true, /* Enable all strict type-checking options. */ 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | --------------------------------------------------------------------------------