├── .github └── workflows │ ├── publish.yml │ └── python-app.yml ├── .gitignore ├── LICENSE ├── README.md ├── basic_bundle.py ├── basic_txn.py ├── example.py ├── jito_py_rpc ├── __init__.py └── jito_jsonrpc_sdk.py ├── setup.py └── tests └── test_jito_json_rpc_sdk.py /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python Package 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-latest 11 | environment: PyPi 12 | permissions: 13 | id-token: write # IMPORTANT: this permission is mandatory for trusted publishing 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Set up Python 18 | uses: actions/setup-python@v4 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install build 25 | - name: Build package 26 | run: python -m build 27 | - name: Publish package 28 | uses: pypa/gh-action-pypi-publish@v1.12.4 29 | with: 30 | password: ${{ secrets.PYPITOKEN }} 31 | -------------------------------------------------------------------------------- /.github/workflows/python-app.yml: -------------------------------------------------------------------------------- 1 | name: Python application 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: ['3.8', '3.9', '3.10', '3.11', '3.12'] 11 | 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v2 15 | 16 | - name: Set up Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install pytest responses 25 | pip install -e . 26 | 27 | #- name: Run tests 28 | # env: 29 | # JITO_TESTNET_URL: https://dallas.testnet.block-engine.jito.wtf/api/v1 30 | # run: pytest ./tests/test_jito_json_rpc_sdk.py 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | sdk/__pycache__/* 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # Virtual environment 30 | .env/ 31 | .venv/ 32 | env/ 33 | venv/ 34 | ENV/ 35 | env.bak/ 36 | venv.bak/ 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .nox/ 52 | .coverage 53 | .coverage.* 54 | .cache 55 | nosetests.xml 56 | coverage.xml 57 | *.cover 58 | *.py,cover 59 | .hypothesis/ 60 | .pytest_cache/ 61 | cover/ 62 | 63 | # Translations 64 | *.mo 65 | *.pot 66 | 67 | # Django stuff: 68 | *.log 69 | local_settings.py 70 | db.sqlite3 71 | db.sqlite3-journal 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | docs/_static/ 83 | docs/_templates/ 84 | 85 | # PyBuilder 86 | target/ 87 | 88 | # Jupyter Notebook 89 | .ipynb_checkpoints 90 | 91 | # IPython 92 | profile_default/ 93 | ipython_config.py 94 | 95 | # pyenv 96 | .python-version 97 | 98 | # celery beat schedule file 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | spyderproject 114 | spyderworkspace 115 | 116 | # VS Code 117 | .vscode/ 118 | history/ 119 | 120 | # PyCharm 121 | .idea/ 122 | *.iml 123 | *.iws 124 | *.ipr 125 | out/ 126 | 127 | # mypy 128 | .mypy_cache/ 129 | .dmypy.json 130 | dmypy.json 131 | 132 | # Pyre type checker 133 | .pyre/ 134 | 135 | # Pycharm 136 | .idea/ 137 | *.iml 138 | *.iws 139 | *.ipr 140 | out/ 141 | 142 | # MacOS specific files 143 | .DS_Store 144 | 145 | # Windows specific files 146 | Thumbs.db 147 | ehthumbs.db 148 | Desktop.ini 149 | $RECYCLE.BIN/ 150 | 151 | # Anaconda environments 152 | .envs/ 153 | .conda/ 154 | 155 | # Miscellaneous 156 | *.swp 157 | *~ 158 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2025 Jito Labs 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jito-sdk-python 2 | 3 | [![Discord](https://img.shields.io/discord/938287290806042626?label=Discord&logo=discord&style=flat&color=7289DA)](https://discord.gg/WeAMhmaZ) 4 | ![Python](https://img.shields.io/badge/Python-3.8%2B-blue?logo=python) 5 | [![PyPI](https://img.shields.io/pypi/v/jito-py-rpc?label=PyPI&logo=python)](https://pypi.org/project/jito-py-rpc/) 6 | [![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://pypi.org/project/jito-py-rpc/) 7 | 8 | The Jito JSON-RPC Python SDK provides an interface for interacting with Jito's enhanced Solana infrastructure. This SDK supports methods for managing bundles and transactions, offering improved performance and additional features while interacting with the Block Engine. 9 | 10 | ## Features 11 | 12 | ### Bundles 13 | - `get_inflight_bundle_statuses`: Retrieve the status of in-flight bundles. 14 | - `get_bundle_statuses`: Fetch the statuses of submitted bundles. 15 | - `get_tip_accounts`: Get accounts eligible for tips. 16 | - `send_bundle`: Submit bundles to the Jito Block Engine. 17 | 18 | ### Transactions 19 | - `send_transaction`: Submit transactions with enhanced priority and speed. 20 | 21 | ## Installation 22 | 23 | ### Prerequisites 24 | 25 | This project requires Python 3.8 or higher. If you haven't installed Python yet, follow these steps: 26 | 27 | 1. **Install Python**: 28 | Download and install Python from [python.org](https://www.python.org/downloads/) 29 | 30 | 2. Verify the installation: 31 | ```bash 32 | python --version 33 | ``` 34 | 35 | 3. (Optional but recommended) Set up a virtual environment: 36 | ```bash 37 | python -m venv jito-env 38 | source jito-env/bin/activate # On Windows use `jito-env\Scripts\activate` 39 | ``` 40 | 41 | ### Installing jito-sdk-python 42 | 43 | Install the SDK using pip: 44 | 45 | ```bash 46 | pip install jito-py-rpc 47 | ``` 48 | 49 | ## Usage Examples 50 | 51 | ### Basic Transaction Example 52 | 53 | 54 | To run the basic transaction example: 55 | 56 | 1. Ensure your environment is set up in `basic_txn.py`: 57 | 58 | ```python 59 | # Load the sender's keypair 60 | wallet_path = "/path/to/wallet.json" 61 | 62 | # Set up receiver pubkey 63 | receiver = Pubkey.from_string("YOUR_RECEIVER_KEY") 64 | ``` 65 | 66 | 2. Run the example: 67 | ```bash 68 | python basic_txn.py 69 | ``` 70 | 71 | ### Basic Bundle Example 72 | 73 | To run the basic bundle example: 74 | 75 | 1. Ensure your environment is set up in `basic_bundle.py`: 76 | 77 | ```python 78 | # Load the sender's keypair 79 | wallet_path = "/path/to/wallet.json" 80 | 81 | # Set up receiver pubkey 82 | receiver = Pubkey.from_string("YOUR_RECEIVER_KEY") 83 | ``` 84 | 85 | 2. Run the example: 86 | ```bash 87 | python basic_bundle.py 88 | ``` 89 | 90 | ## Contributing 91 | 92 | Contributions are welcome! Please feel free to submit a Pull Request. 93 | 94 | ## Support 95 | 96 | For support, please join our [Discord community](https://discord.gg/jTSmEzaR). 97 | -------------------------------------------------------------------------------- /basic_bundle.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | import base64 4 | import os 5 | import sys 6 | from solana.rpc.async_api import AsyncClient 7 | from solders.keypair import Keypair 8 | from solders.pubkey import Pubkey 9 | from solders.system_program import TransferParams, transfer 10 | from solders.transaction import Transaction 11 | from solders.message import Message 12 | from solders.instruction import Instruction 13 | from solders.hash import Hash 14 | from jito_py_rpc import JitoJsonRpcSDK 15 | 16 | async def check_bundle_status(sdk: JitoJsonRpcSDK, bundle_id: str, max_attempts: int = 30, delay: float = 2.0): 17 | for attempt in range(max_attempts): 18 | response = sdk.get_inflight_bundle_statuses([bundle_id]) 19 | 20 | if not response['success']: 21 | print(f"Error checking bundle status: {response.get('error', 'Unknown error')}") 22 | await asyncio.sleep(delay) 23 | continue 24 | 25 | print(f"Raw response (Attempt {attempt + 1}/{max_attempts}):") 26 | print(json.dumps(response, indent=2)) 27 | 28 | if 'result' not in response['data']: 29 | print(f"Unexpected response structure. 'result' not found in response data.") 30 | await asyncio.sleep(delay) 31 | continue 32 | 33 | result = response['data']['result'] 34 | if 'value' not in result or not result['value']: 35 | print(f"Bundle {bundle_id} not found in response") 36 | await asyncio.sleep(delay) 37 | continue 38 | 39 | bundle_status = result['value'][0] 40 | status = bundle_status.get('status') 41 | print(f"Attempt {attempt + 1}/{max_attempts}: Bundle status - {status}") 42 | 43 | if status == 'Landed': 44 | print(f"Bundle {bundle_id} has landed on-chain! Performing additional confirmation...") 45 | final_status = await confirm_landed_bundle(sdk, bundle_id) 46 | return final_status 47 | elif status == 'Failed': 48 | print(f"Bundle {bundle_id} has failed.") 49 | return status 50 | elif status == 'Invalid': 51 | if attempt < 5: # Check a few more times before giving up on Invalid(usually on start) 52 | print(f"Bundle {bundle_id} is currently invalid. Checking again...") 53 | else: 54 | print(f"Bundle {bundle_id} is invalid (not in system or outside 5-minute window).") 55 | return status 56 | elif status == 'Pending': 57 | print(f"Bundle {bundle_id} is still pending. Checking again in {delay} seconds...") 58 | else: 59 | print(f"Unknown status '{status}' for bundle {bundle_id}") 60 | 61 | await asyncio.sleep(delay) 62 | 63 | print(f"Max attempts reached. Final status of bundle {bundle_id}: {status}") 64 | return status 65 | 66 | async def confirm_landed_bundle(sdk: JitoJsonRpcSDK, bundle_id: str, max_attempts: int = 60, delay: float = 2.0): 67 | for attempt in range(max_attempts): 68 | response = sdk.get_bundle_statuses([bundle_id]) 69 | 70 | if not response['success']: 71 | print(f"Error confirming bundle status: {response.get('error', 'Unknown error')}") 72 | await asyncio.sleep(delay) 73 | 74 | print(f"Confirmation attempt {attempt + 1}/{max_attempts}:") 75 | print(json.dumps(response, indent=2)) 76 | 77 | if 'result' not in response['data']: 78 | print(f"Unexpected response structure. 'result' not found in response data.") 79 | await asyncio.sleep(delay) 80 | 81 | result = response['data']['result'] 82 | if 'value' not in result or not result['value']: 83 | print(f"Bundle {bundle_id} not found in confirmation response") 84 | await asyncio.sleep(delay) 85 | 86 | bundle_status = result['value'][0] 87 | if bundle_status['bundle_id'] != bundle_id: 88 | print(f"Unexpected bundle ID in response: {bundle_status['bundle_id']}") 89 | await asyncio.sleep(delay) 90 | 91 | status = bundle_status.get('confirmation_status') 92 | 93 | if status == 'finalized': 94 | print(f"Bundle {bundle_id} has been finalized on-chain!") 95 | # Extract transaction ID and construct Solscan link 96 | if 'transactions' in bundle_status and bundle_status['transactions']: 97 | tx_id = bundle_status['transactions'][0] 98 | solscan_link = f"https://solscan.io/tx/{tx_id}" 99 | print(f"Transaction details: {solscan_link}") 100 | else: 101 | print("Transaction ID not found in the response.") 102 | return 'Finalized' 103 | elif status == 'confirmed': 104 | print(f"Bundle {bundle_id} is confirmed but not yet finalized. Checking again...") 105 | elif status == 'processed': 106 | print(f"Bundle {bundle_id} is processed but not yet confirmed. Checking again...") 107 | else: 108 | print(f"Unexpected status '{status}' during confirmation for bundle {bundle_id}") 109 | 110 | # Check for errors 111 | err = bundle_status.get('err', {}).get('Ok') 112 | if err is not None: 113 | print(f"Error in bundle {bundle_id}: {err}") 114 | return 'Failed' 115 | 116 | await asyncio.sleep(delay) 117 | 118 | print(f"Max confirmation attempts reached. Unable to confirm finalization of bundle {bundle_id}") 119 | return 'Landed' 120 | async def basic_bundle(): 121 | # Initialize connection to Solana testnet 122 | solana_client = AsyncClient("https://api.mainnet-beta.solana.com") 123 | 124 | # Read wallet from local path 125 | wallet_path = "/path/to/wallet.json" 126 | with open(wallet_path, 'r') as file: 127 | wallet_keypair_data = json.load(file) 128 | wallet_keypair = Keypair.from_bytes(bytes(wallet_keypair_data)) 129 | 130 | # Initialize JitoJsonRpcSDK 131 | jito_client = JitoJsonRpcSDK(url="https://mainnet.block-engine.jito.wtf/api/v1") 132 | 133 | #Example using UUID 134 | #jito_client = JitoJsonRpcSDK(url="https://mainnet.block-engine.jito.wtf/api/v1", uuid_var="YOUR_UUID" ) 135 | 136 | # Set up transaction parameters 137 | receiver = Pubkey.from_string("YOUR_RECIEVER_KEY") 138 | jito_tip_account = Pubkey.from_string(jito_client.get_random_tip_account()) 139 | jito_tip_amount = 1000 # lamports (increase if there exists larger volume) 140 | transfer_amount = 1000 # lamports 141 | 142 | # Memo program ID 143 | memo_program_id = Pubkey.from_string("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") 144 | 145 | # Create instructions 146 | transfer_ix = transfer(TransferParams( 147 | from_pubkey=wallet_keypair.pubkey(), 148 | to_pubkey=receiver, 149 | lamports=transfer_amount 150 | )) 151 | 152 | tip_ix = transfer(TransferParams( 153 | from_pubkey=wallet_keypair.pubkey(), 154 | to_pubkey=jito_tip_account, 155 | lamports=jito_tip_amount 156 | )) 157 | 158 | memo_ix = Instruction( 159 | program_id=memo_program_id, 160 | accounts=[], 161 | data=bytes("Let's Jito!", "utf-8") 162 | ) 163 | 164 | # Get recent blockhash 165 | recent_blockhash = await solana_client.get_latest_blockhash() 166 | 167 | # Create the transaction 168 | message = Message.new_with_blockhash( 169 | [transfer_ix, tip_ix, memo_ix], 170 | wallet_keypair.pubkey(), 171 | recent_blockhash.value.blockhash 172 | ) 173 | transaction = Transaction.new_unsigned(message) 174 | 175 | # Sign the transaction 176 | transaction.sign([wallet_keypair], recent_blockhash.value.blockhash) 177 | 178 | # Serialize and base58 encode the entire signed transaction 179 | serialized_transaction = base64.b64encode(bytes(transaction)).decode('ascii') 180 | 181 | try: 182 | # Prepare the bundle request 183 | bundle_request = [serialized_transaction] 184 | print(f"Sending bundle request: {json.dumps(bundle_request, indent=2)}") 185 | 186 | # Send the bundle using sendBundle method 187 | result = jito_client.send_bundle(bundle_request) 188 | print('Raw API response:', json.dumps(result, indent=2)) 189 | 190 | if result['success']: 191 | bundle_id = result['data']['result'] 192 | print(f"Bundle sent successfully. Bundle ID: {bundle_id}") 193 | 194 | # Check the status of the bundle 195 | final_status = await check_bundle_status(jito_client, bundle_id, max_attempts=30, delay=2.0) 196 | 197 | if final_status == 'Finalized': 198 | print("Bundle has been confirmed and finalized on-chain.") 199 | elif final_status == 'Landed': 200 | print("Bundle has landed on-chain but could not be confirmed as finalized within the timeout period.") 201 | else: 202 | print(f"Bundle did not land on-chain. Final status: {final_status}") 203 | else: 204 | print(f"Failed to send bundle: {result.get('error', 'Unknown error')}") 205 | 206 | except Exception as error: 207 | print('Error sending or confirming bundle:', str(error)) 208 | 209 | # Close the Solana client session 210 | await solana_client.close() 211 | 212 | async def confirm_bundle(jito_client, bundle_id, timeout_seconds=60): 213 | start_time = asyncio.get_event_loop().time() 214 | 215 | while asyncio.get_event_loop().time() - start_time < timeout_seconds: 216 | try: 217 | status = jito_client.get_bundle_statuses([[bundle_id]]) 218 | print('Bundle status:', status) 219 | 220 | if status['success'] and bundle_id in status['data']['result']: 221 | bundle_status = status['data']['result'][bundle_id] 222 | if bundle_status['status'] == 'finalized': 223 | print('Bundle has been finalized on the blockchain.') 224 | return bundle_status 225 | elif bundle_status['status'] == 'confirmed': 226 | print('Bundle has been confirmed but not yet finalized.') 227 | elif bundle_status['status'] == 'processed': 228 | print('Bundle has been processed but not yet confirmed.') 229 | elif bundle_status['status'] == 'failed': 230 | raise Exception(f"Bundle failed: {bundle_status.get('error')}") 231 | else: 232 | print(f"Unknown bundle status: {bundle_status['status']}") 233 | except Exception as error: 234 | print('Error checking bundle status:', str(error)) 235 | 236 | # Wait for a short time before checking again 237 | await asyncio.sleep(2) 238 | 239 | print(f"Bundle {bundle_id} has not finalized within {timeout_seconds}s, but it may still be in progress.") 240 | return jito_client.get_bundle_statuses([bundle_id]) 241 | 242 | if __name__ == "__main__": 243 | asyncio.run(basic_bundle()) -------------------------------------------------------------------------------- /basic_txn.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import json 4 | import asyncio 5 | import base64 6 | from solders.keypair import Keypair 7 | from solders.pubkey import Pubkey 8 | from solders.system_program import TransferParams, transfer 9 | from solders.instruction import Instruction 10 | from solders.transaction import Transaction 11 | from solders.compute_budget import set_compute_unit_limit, set_compute_unit_price 12 | from solders.transaction_status import TransactionConfirmationStatus 13 | from solders.signature import Signature 14 | from solana.rpc.async_api import AsyncClient 15 | from solana.exceptions import SolanaRpcException 16 | from jito_py_rpc import JitoJsonRpcSDK 17 | 18 | async def check_transaction_status(client: AsyncClient, signature_str: str): 19 | print("Checking transaction status...") 20 | max_attempts = 60 # 60 seconds 21 | attempt = 0 22 | 23 | signature = Signature.from_string(signature_str) 24 | 25 | while attempt < max_attempts: 26 | try: 27 | response = await client.get_signature_statuses([signature]) 28 | 29 | if response.value[0] is not None: 30 | status = response.value[0] 31 | slot = status.slot 32 | confirmations = status.confirmations 33 | err = status.err 34 | confirmation_status = status.confirmation_status 35 | 36 | print(f"Slot: {slot}") 37 | print(f"Confirmations: {confirmations}") 38 | print(f"Confirmation status: {confirmation_status}") 39 | 40 | if err: 41 | print(f"Transaction failed with error: {err}") 42 | return False 43 | elif confirmation_status == TransactionConfirmationStatus.Finalized: 44 | print("Transaction is finalized.") 45 | return True 46 | elif confirmation_status == TransactionConfirmationStatus.Confirmed: 47 | print("Transaction is confirmed but not yet finalized.") 48 | elif confirmation_status == TransactionConfirmationStatus.Processed: 49 | print("Transaction is processed but not yet confirmed or finalized.") 50 | else: 51 | print("Transaction status not available yet.") 52 | 53 | await asyncio.sleep(1) 54 | attempt += 1 55 | except Exception as e: 56 | print(f"Error checking transaction status: {e}") 57 | await asyncio.sleep(1) 58 | attempt += 1 59 | 60 | print(f"Transaction not finalized after {max_attempts} attempts.") 61 | return False 62 | 63 | async def send_transaction_with_priority_fee(sdk, solana_client, sender, receiver, amount, jito_tip_amount, priority_fee, compute_unit_limit=100_000): 64 | try: 65 | recent_blockhash = await solana_client.get_latest_blockhash() 66 | 67 | # Transfer to the known receiver 68 | transfer_ix = transfer(TransferParams(from_pubkey=sender.pubkey(), to_pubkey=receiver, lamports=amount)) 69 | 70 | # Jito tip transfer 71 | jito_tip_account = Pubkey.from_string(sdk.get_random_tip_account()) 72 | jito_tip_ix = transfer(TransferParams(from_pubkey=sender.pubkey(), to_pubkey=jito_tip_account, lamports=jito_tip_amount)) 73 | 74 | # Priority Fee 75 | priority_fee_ix = set_compute_unit_price(priority_fee) 76 | 77 | transaction = Transaction.new_signed_with_payer( 78 | [priority_fee_ix, transfer_ix, jito_tip_ix], 79 | sender.pubkey(), 80 | [sender], 81 | recent_blockhash.value.blockhash 82 | ) 83 | 84 | #serialized_transaction = base58.b58encode(bytes(transaction)).decode('ascii') 85 | serialized_transaction = base64.b64encode(bytes(transaction)).decode('ascii') 86 | 87 | print(f"Sending transaction with priority fee: {priority_fee} micro-lamports per compute unit") 88 | print(f"Transfer amount: {amount} lamports to {receiver}") 89 | print(f"Jito tip amount: {jito_tip_amount} lamports to {jito_tip_account}") 90 | print(f"Serialized transaction: {serialized_transaction}") 91 | 92 | response = sdk.send_txn(params=serialized_transaction, bundleOnly=False) 93 | 94 | if response['success']: 95 | print(f"Full Jito SDK response: {response}") 96 | signature_str = response['data']['result'] 97 | print(f"Transaction signature: {signature_str}") 98 | 99 | finalized = await check_transaction_status(solana_client, signature_str) 100 | 101 | if finalized: 102 | print("Transaction has been finalized.") 103 | solscan_url = f"https://solscan.io/tx/{signature_str}" 104 | print(f"View transaction details on Solscan: {solscan_url}") 105 | else: 106 | print("Transaction was not finalized within the expected time.") 107 | 108 | return signature_str 109 | else: 110 | print(f"Error sending transaction: {response['error']}") 111 | return None 112 | 113 | except Exception as e: 114 | print(f"Exception occurred: {str(e)}") 115 | return None 116 | 117 | async def main(): 118 | solana_client = AsyncClient("https://api.mainnet-beta.solana.com") 119 | sdk = JitoJsonRpcSDK(url="https://mainnet.block-engine.jito.wtf/api/v1") 120 | wallet_path = "/path/to/wallet.json" 121 | 122 | with open(wallet_path, 'r') as file: 123 | private_key = json.load(file) 124 | sender = Keypair.from_bytes(bytes(private_key)) 125 | 126 | receiver = Pubkey.from_string("YOUR_RECIEVER_KEY") 127 | 128 | print(f"Sender public key: {sender.pubkey()}") 129 | print(f"Receiver public key: {receiver}") 130 | 131 | priority_fee = 1000 # Lamport for priority fee (increase if there exists larger volume) 132 | amount = 1000 # Lamports to transfer to receiver 133 | jito_tip_amount = 1000 # Lamports for Jito tip (increase if there exists larger volume) 134 | 135 | signature = await send_transaction_with_priority_fee(sdk, solana_client, sender, receiver, amount, jito_tip_amount, priority_fee) 136 | 137 | if signature: 138 | print(f"Transaction process completed. Signature: {signature}") 139 | 140 | await solana_client.close() 141 | 142 | asyncio.run(main()) -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from jito_py_rpc import JitoJsonRpcSDK 2 | 3 | 4 | def main(): 5 | # Initialize the SDK 6 | # mainnet 7 | #BLOCK_ENG_URL = "https://mainnet.block-engine.jito.wtf:443/api/v1" 8 | 9 | # testnet 10 | BLOCK_ENG_URL = "https://dallas.testnet.block-engine.jito.wtf/api/v1" 11 | sdk = JitoJsonRpcSDK(BLOCK_ENG_URL) 12 | 13 | # If you are using authentication which is not needed unless you request rate limit increase 14 | #UUID_ENV = "JITO_UUID" 15 | #sdk = JitoJsonRpcSDK(BLOCK_ENG_URL, UUID_ENV) 16 | 17 | result = sdk.get_tip_accounts() 18 | print(result) 19 | 20 | params = [ 21 | "4VbvoRYXFaXzDBUYfMXP1irhMZ9XRE6F1keS8GbYzKxgdpEasZtRv6GXxbygPp3yBVeSR4wN9JEauSTnVTKjuq3ktM3JpMebYpdGxZWUttJv9N2DzxBm4vhySdq2hbu1LQX7WxS2xsHG6vNwVCjP33Z2ZLP7S5dZujcan1Xq5Z2HibbbK3M3LD59QVuczyK44Fe3k27kVQ43oRH5L7KgpUS1vBoqTd9ZTzC32H62WPHJeLrQiNkmSB668FivXBAfMg13Svgiu9E", 22 | "6HZu11s3SDBz5ytDj1tyBuoeUnwa1wPoKvq6ffivmfhTGahe3xvGpizJkofHCeDn1UgPN8sLABueKE326aGLXkn5yQyrrpuRF9q1TPZqqBMzcDvoJS1khPBprxnXcxNhMUbV78cS2R8LrCU29wjYk5b4JpVtF23ys4ZBZoNZKmPekAW9odcPVXb9HoMnWvx8xwqd7GsVB56R343vAX6HGUMoiB1WgR9jznG655WiXQTff5gPsCP3QJFTXC7iYEYtrcA3dUeZ3q4YK9ipdYZsgAS9H46i9dhDP2Zx3" 23 | ] 24 | result = sdk.send_bundle(params) 25 | print(result) 26 | 27 | params = ["892b79ed49138bfb3aa5441f0df6e06ef34f9ee8f3976c15b323605bae0cf51d"] 28 | result = sdk.get_bundle_statuses(params) 29 | print(result) 30 | 31 | params = [ 32 | "4hXTCkRzt9WyecNzV1XPgCDfGAZzQKNxLXgynz5QDuWWPSAZBZSHptvWRL3BjCvzUXRdKvHL2b7yGrRQcWyaqsaBCncVG7BFggS8w9snUts67BSh3EqKpXLUm5UMHfD7ZBe9GhARjbNQMLJ1QD3Spr6oMTBU6EhdB4RD8CP2xUxr2u3d6fos36PD98XS6oX8TQjLpsMwncs5DAMiD4nNnR8NBfyghGCWvCVifVwvA8B8TJxE1aiyiv2L429BCWfyzAme5sZW8rDb14NeCQHhZbtNqfXhcp2tAnaAT" 33 | ] 34 | result = sdk.send_txn(params) 35 | print(result) 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /jito_py_rpc/__init__.py: -------------------------------------------------------------------------------- 1 | from .jito_jsonrpc_sdk import JitoJsonRpcSDK 2 | 3 | __version__ = '0.1.4' 4 | __all__ = ['JitoJsonRpcSDK'] 5 | -------------------------------------------------------------------------------- /jito_py_rpc/jito_jsonrpc_sdk.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | import json 4 | import random 5 | 6 | # Jito JSON RPC SDK 7 | # Bindings for https://github.com/jito-labs/mev-protos/blob/master/json_rpc/http.md 8 | class JitoJsonRpcSDK: 9 | # Initialize a block engine URL 10 | def __init__(self, url, uuid_var=None): 11 | self.url = url 12 | if uuid_var == None: 13 | self.uuid_var = None 14 | else: 15 | self.uuid_var = self.__get_uuid(uuid_var) 16 | 17 | def __get_uuid(self, uuid_var): 18 | return os.getenv(uuid_var) 19 | 20 | # Send a request to the Block engine url using the JSON RPC methods 21 | def __send_request(self, endpoint, method, params=None): 22 | if endpoint == None: 23 | return "Error: Please enter a valid endpoint." 24 | 25 | if self.uuid_var == None: 26 | headers = { 27 | 'Content-Type': 'application/json', 28 | "accept": "application/json" 29 | } 30 | else: 31 | headers = { 32 | 'Content-Type': 'application/json', 33 | "accept": "application/json", 34 | "x-jito-auth": self.uuid_var 35 | } 36 | # Only add encoding parameter for sendBundle and sendTransaction methods 37 | if method in ["sendBundle", "sendTransaction"]: 38 | data = { 39 | "id": 1, 40 | "jsonrpc": "2.0", 41 | "method": method, 42 | "params": [params, {"encoding": "base64"}] 43 | } 44 | else: 45 | data = { 46 | "id": 1, 47 | "jsonrpc": "2.0", 48 | "method": method, 49 | "params": [params] 50 | } 51 | 52 | print(data) 53 | try: 54 | resp = requests.post(self.url + endpoint, headers=headers, json=data) 55 | resp.raise_for_status() 56 | return {"success": True, "data": resp.json()} 57 | except requests.exceptions.HTTPError as errh: 58 | return {"success": False, "error": f"HTTP Error: {errh}"} 59 | except requests.exceptions.ConnectionError as errc: 60 | return {"success": False, "error": f"Error Connecting: {errc}"} 61 | except requests.exceptions.Timeout as errt: 62 | return {"success": False, "error": f"Timeout Error: {errt}"} 63 | except requests.exceptions.InvalidHeader as err: 64 | return {"success": False, "error": f"Invalid Header error: {err}"} 65 | except requests.exceptions.InvalidURL as err: 66 | return {"success": False, "error": f"InvalidURL error: {err}"} 67 | except requests.exceptions.RequestException as err: 68 | return {"success": False, "error": f"An error occurred: {err}"} 69 | 70 | #Bundle Endpoint 71 | def get_tip_accounts(self, params=None): 72 | if self.uuid_var == None: 73 | return self.__send_request(endpoint="/bundles", method="getTipAccounts") 74 | else: 75 | return self.__send_request(endpoint="/bundles?uuid=" + self.uuid_var, method="getTipAccounts") 76 | 77 | def get_random_tip_account(self): 78 | response = self.get_tip_accounts() 79 | if not response['success']: 80 | print(f"Error getting tip accounts: {response.get('error', 'Unknown error')}") 81 | return None 82 | 83 | tip_accounts = response['data']['result'] 84 | if not tip_accounts: 85 | print("No tip accounts found.") 86 | return None 87 | 88 | random_account = random.choice(tip_accounts) 89 | return random_account 90 | 91 | 92 | def get_bundle_statuses(self, bundle_uuids): 93 | endpoint = "/bundles" 94 | if self.uuid_var is not None: 95 | endpoint += f"?uuid={self.uuid_var}" 96 | 97 | # Ensure bundle_uuids is a list 98 | if not isinstance(bundle_uuids, list): 99 | bundle_uuids = [bundle_uuids] 100 | 101 | # Correct format for the request 102 | params = bundle_uuids 103 | 104 | return self.__send_request(endpoint=endpoint, method="getBundleStatuses", params=params) 105 | 106 | def send_bundle(self, params=None): 107 | if self.uuid_var == None: 108 | return self.__send_request(endpoint="/bundles",method="sendBundle", params=params) 109 | else: 110 | return self.__send_request(endpoint="/bundles?uuid=" + self.uuid_var, method="sendBundle", params=params) 111 | 112 | def get_inflight_bundle_statuses(self, bundle_uuids): 113 | endpoint = "/bundles" 114 | if self.uuid_var is not None: 115 | endpoint += f"?uuid={self.uuid_var}" 116 | 117 | # Ensure bundle_uuids is a list 118 | if not isinstance(bundle_uuids, list): 119 | bundle_uuids = [bundle_uuids] 120 | 121 | # Correct format for the request 122 | params = bundle_uuids 123 | 124 | return self.__send_request(endpoint=endpoint, method="getInflightBundleStatuses", params=params) 125 | 126 | # Transaction Endpoint 127 | def send_txn(self, params=None, bundleOnly=False): 128 | ep = "/transactions" 129 | query_params = [] 130 | 131 | if bundleOnly: 132 | query_params.append("bundleOnly=true") 133 | 134 | if self.uuid_var is not None: 135 | query_params.append(f"uuid={self.uuid_var}") 136 | 137 | if query_params: 138 | ep += "?" + "&".join(query_params) 139 | 140 | return self.__send_request(endpoint=ep, method="sendTransaction", params=params) 141 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from pathlib import Path 3 | 4 | this_directory = Path(__file__).parent 5 | long_description = (this_directory / "README.md").read_text() 6 | 7 | setup( 8 | name='jito_py_rpc', 9 | version='0.1.4', # Bump version 10 | packages=find_packages(), 11 | install_requires=[ 12 | "requests", 13 | ], 14 | long_description=long_description, 15 | long_description_content_type='text/markdown', 16 | author='Jito Labs', 17 | author_email='marshall@jito.wtf', 18 | url='https://github.com/jito-labs/jito-py-rpc', 19 | classifiers=[ 20 | 'Development Status :: 3 - Alpha', 21 | 'Intended Audience :: Developers', 22 | 'Programming Language :: Python :: 3', 23 | 'Programming Language :: Python :: 3.8', 24 | 'Programming Language :: Python :: 3.9', 25 | 'Programming Language :: Python :: 3.10', 26 | 'Programming Language :: Python :: 3.11', 27 | 'Programming Language :: Python :: 3.12', 28 | ], 29 | python_requires='>=3.8', 30 | ) 31 | -------------------------------------------------------------------------------- /tests/test_jito_json_rpc_sdk.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import requests_mock 3 | from jito_jsonrpc_sdk import JitoJsonRpcSDK 4 | 5 | @pytest.fixture 6 | def sdk(): 7 | return JitoJsonRpcSDK(url="https://dallas.testnet.block-engine.jito.wtf/api/v1", uuid_var="TEST_UUID") 8 | 9 | def test_get_tip_accounts(sdk, requests_mock): 10 | requests_mock.post("https://dallas.testnet.block-engine.jito.wtf/api/v1", json={"status_code": 200}, status_code=200) 11 | result = sdk.get_tip_accounts() 12 | if result is None: 13 | print("there be nothing here from this call") 14 | 15 | print(result) 16 | assert result.status_code == 200 17 | #assert result['data']['result'] == "success" 18 | 19 | def test_get_bundle_statuses(sdk, requests_mock): 20 | requests_mock.post("https://dallas.testnet.block-engine.jito.wtf/api/v1/bundles", json={"result": {"value": []}}, status_code=200) 21 | result = sdk.get_bundle_statuses(params={"bundleId": "123"}) 22 | assert result['status_code'] == 200 23 | #assert result['data']['result']['value'] == [] 24 | 25 | def test_send_bundle(sdk, requests_mock): 26 | requests_mock.post("https://dallas.testnet.block-engine.jito.wtf/api/v1/bundles", json={"result": "bundle_sent"}, status_code=200) 27 | result = sdk.send_bundle(params={"bundleData": "data"}) 28 | assert result['status_code'] == 200 29 | #assert result['data']['result'] == "bundle_sent" 30 | 31 | def test_send_txn(sdk, requests_mock): 32 | requests_mock.post("https://dallas.testnet.block-engine.jito.wtf/api/v1/transactions", json={"result": "txn_sent"}, status_code=200) 33 | result = sdk.send_txn(params={"txnData": "data"}) 34 | assert result['status_code'] == 200 35 | #assert result['data']['result'] == "txn_sent" --------------------------------------------------------------------------------