jito-labs / jito-py-rpc

Jito Python JSON RPC SDK
14 stars 2 forks source link

Help me, I can't send a token purchase transaction using jito-sdk-python through Jupyter. #3

Open MrLux0r opened 2 weeks ago

MrLux0r commented 2 weeks ago

I can't add a tip for Jito to my transaction. Could you please help me figure out what I'm doing wrong?

async def main(): url = "https://mainnet.helius-rpc.com/?api-key=my_key" solana_client = AsyncClient(url, commitment=Confirmed) sdk = JitoJsonRpcSDK(url="https://mainnet.block-engine.jito.wtf/api/v1") wallet_path = "keypair.json"

with open(wallet_path, 'r') as file:
    private_key = json.load(file)
    sender = Keypair.from_seed(bytes(private_key))

print(f"Sender public key: {sender.pubkey()}")

jupiter = Jupiter(
    async_client=solana_client,
    keypair=sender,
)

token_mint = "T1oYbAejEESrZLtSAjumAXhzFqZGNxQ4kVN9vPUoxMv"  # Mint адрес токена, который вы хотите купить
amount_in_sol = 0.01  # Количество SOL, которое вы хотите потратить на покупку токена
LAMPORTS_PER_SOL = 1_000_000_000  # 1 SOL = 1,000,000,000 lamports
amount_in_lamports = int(amount_in_sol * LAMPORTS_PER_SOL)

# Выполнение свопа через Jupiter
transaction_data = await jupiter.swap(
    input_mint="So11111111111111111111111111111111111111112",  # WSOL
    output_mint=token_mint,
    amount=amount_in_lamports,
    slippage_bps=50,  # 0.5% slippage
    compute_unit_price_micro_lamports=1000
)

# Декодируем транзакцию от Jupiter
raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))

# Подписываем базовую транзакцию
signature = sender.sign_message(message.to_bytes_versioned(raw_transaction.message))

# 1. Получаем tip аккаунт от Jito и создаем инструкцию перевода
jito_tip_account = Pubkey.from_string(sdk.get_random_tip_account())
jito_tip_ix = transfer(
    TransferParams(from_pubkey=sender.pubkey(), to_pubkey=jito_tip_account, lamports=1000)
)

# 2. Получаем список аккаунтов и инструкций из Jupiter
account_keys = list(raw_transaction.message.account_keys)
jupiter_instructions = raw_transaction.message.instructions

# 3. Добавляем tip аккаунт если его нет
if jito_tip_account not in account_keys:
    account_keys.append(jito_tip_account)

# 4. Создаем CompiledInstruction для tip
system_program_index = account_keys.index(jito_tip_ix.program_id)
sender_index = account_keys.index(sender.pubkey())
tip_account_index = account_keys.index(jito_tip_account)

jito_tip_compiled = CompiledInstruction(
    program_id_index=system_program_index,
    accounts=bytes([sender_index, tip_account_index]),
    data=jito_tip_ix.data
)

# 5. Объединяем все инструкции
all_instructions = [
    *jupiter_instructions,  # Jupiter инструкции
    jito_tip_compiled  # Jito tip в конце
]

# 6. Создаем новое сообщение с добавленным tip
new_message = message.MessageV0(
    header=raw_transaction.message.header,
    account_keys=account_keys,
    recent_blockhash=raw_transaction.message.recent_blockhash,
    instructions=all_instructions,
    address_table_lookups=raw_transaction.message.address_table_lookups
)

# 7. Создаем финальную транзакцию
new_transaction = VersionedTransaction.populate(new_message, [signature])

print("Transaction created successfully")
print(new_transaction)

# 8. Сериализуем транзакцию
serialized_transaction = base58.b58encode(bytes(new_transaction)).decode('ascii')

response = sdk.send_txn(params=serialized_transaction, bundleOnly=True)
# response = {}

if response:
    if response['success']:
        print(f"Full Jito SDK response: {response}")
        signature_str = response['data']['result']
        print(f"Transaction signature: {signature_str}")

        finalized = await check_transaction_status(solana_client, signature_str)

        if finalized:
            print("Transaction has been finalized.")
            solscan_url = f"https://solscan.io/tx/{signature_str}"
            print(f"View transaction details on Solscan: {solscan_url}")
        else:
            print("Transaction was not finalized within the expected time.")
    else:
        print(f"Error sending transaction: {response['error']}")

await solana_client.close()
MrLux0r commented 2 weeks ago

No one helped me. I was told that I need to register my wallet, but it's unclear where and why???

I have an error in composing the instructions with tips for Jito.

MrLux0r commented 2 weeks ago

async def main(): url = "https://mainnet.helius-rpc.com/?api-key=my_key" solana_client = AsyncClient(url, commitment=Confirmed) sdk = JitoJsonRpcSDK(url="https://mainnet.block-engine.jito.wtf/api/v1") wallet_path = "keypair.json"

with open(wallet_path, 'r') as file:
    private_key = json.load(file)
    sender = Keypair.from_seed(bytes(private_key))

print(f"Sender public key: {sender.pubkey()}")

jupiter = Jupiter(
    async_client=solana_client,
    keypair=sender,
)

token_mint = "T1oYbAejEESrZLtSAjumAXhzFqZGNxQ4kVN9vPUoxMv"  # Mint адрес токена, который вы хотите купить
amount_in_sol = 0.01  # Количество SOL, которое вы хотите потратить на покупку токена
LAMPORTS_PER_SOL = 1_000_000_000  # 1 SOL = 1,000,000,000 lamports
amount_in_lamports = int(amount_in_sol * LAMPORTS_PER_SOL)

# Выполнение свопа через Jupiter
transaction_data = await jupiter.swap(
    input_mint="So11111111111111111111111111111111111111112",  # WSOL
    output_mint=token_mint,
    amount=amount_in_lamports,
    slippage_bps=50,  # 0.5% slippage
)

recent_blockhash = await solana_client.get_latest_blockhash()

versioned_tx = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))

# print("Original instructions:")
# for inst in versioned_tx.message.instructions:
#     print(f"Program ID index: {inst.program_id_index}")
#     print(f"Accounts: {inst.accounts}")
#     print(f"Data: {inst.data}")
#     print("---")

# Получаем инструкции из versioned_tx
instructions = list(versioned_tx.message.instructions)
# instructions = [
#     Instruction.decode(bytes(inst.program_id_index) + bytes(inst.data))
#     for inst in versioned_tx.message.instructions
# ]

# print(instructions)

# Создаем Jito tip инструкцию
jito_tip_account = Pubkey.from_string(sdk.get_random_tip_account())

jito_tip = transfer(
    TransferParams(
        from_pubkey=sender.pubkey(),
        to_pubkey=jito_tip_account,
        lamports=1000
    )
)

# Добавляем Jito tip к инструкциям
instructions.append(jito_tip)

msg = MessageV0.try_compile(
    payer=sender.pubkey(),
    instructions=instructions,
    address_lookup_table_accounts=[],
    recent_blockhash=recent_blockhash.value.blockhash,
)

tx = VersionedTransaction(msg, [sender])

# print(tx)

# serialized_transaction = tx.serialize()

# Отправка транзакции через Jito
serialized_transaction = base58.b58encode(bytes(tx)).decode('ascii')
response = sdk.send_txn(params=serialized_transaction, bundleOnly=True)

if response['success']:
    print(f"Full Jito SDK response: {response}")
    signature_str = response['data']['result']
    print(f"Transaction signature: {signature_str}")

    finalized = await check_transaction_status(solana_client, signature_str)

    if finalized:
        print("Transaction has been finalized.")
        solscan_url = f"https://solscan.io/tx/{signature_str}"
        print(f"View transaction details on Solscan: {solscan_url}")
    else:
        print("Transaction was not finalized within the expected time.")
else:
    print(f"Error sending transaction: {response['error']}")

await solana_client.close()

TypeError: argument 'instructions': 'CompiledInstruction' object cannot be converted to 'Instruction'
MrLux0r commented 2 weeks ago

I still cannot buy tokens using the Jito service.

MrLux0r commented 2 weeks ago

Yes, I showed my code, explained everything, and did everything they told me, including uploading the Solana wallet for the error correction, but it didn't work. I created different wallets and tried to upload them, but I got an error everywhere. Support didn't help me at all. I don't know how to buy tokens through Jito.

sebcrpt commented 1 week ago

Да, я показал свой код, все объяснил и сделал все, что мне сказал, включая загрузку кошелька Solana для исправления ошибки, но это не сработало. Я создал разные кошельки и пытался их загрузить, но везде была ошибка. Поддержка мне вообще не помогла. Я не знаю, как купить токены через Jito.

у меня была такая же проблема. я так решил. Одна транзакция от Юпитера, вторая jito tips. Собираем и отправляем бандл. только не забудь транзакцию от юпитера превратить из бейс64 в байты, а потом в бейс58 . Сорри, не умею писать по-английски))

davidco277 commented 4 days ago

I can't add a tip for Jito to my transaction. Could you please help me figure out what I'm doing wrong?

async def main(): url = "https://mainnet.helius-rpc.com/?api-key=my_key" solana_client = AsyncClient(url, commitment=Confirmed) sdk = JitoJsonRpcSDK(url="https://mainnet.block-engine.jito.wtf/api/v1") wallet_path = "keypair.json"

with open(wallet_path, 'r') as file:
    private_key = json.load(file)
    sender = Keypair.from_seed(bytes(private_key))

print(f"Sender public key: {sender.pubkey()}")

jupiter = Jupiter(
    async_client=solana_client,
    keypair=sender,
)

token_mint = "T1oYbAejEESrZLtSAjumAXhzFqZGNxQ4kVN9vPUoxMv"  # Mint адрес токена, который вы хотите купить
amount_in_sol = 0.01  # Количество SOL, которое вы хотите потратить на покупку токена
LAMPORTS_PER_SOL = 1_000_000_000  # 1 SOL = 1,000,000,000 lamports
amount_in_lamports = int(amount_in_sol * LAMPORTS_PER_SOL)

# Выполнение свопа через Jupiter
transaction_data = await jupiter.swap(
    input_mint="So11111111111111111111111111111111111111112",  # WSOL
    output_mint=token_mint,
    amount=amount_in_lamports,
    slippage_bps=50,  # 0.5% slippage
    compute_unit_price_micro_lamports=1000
)

# Декодируем транзакцию от Jupiter
raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))

# Подписываем базовую транзакцию
signature = sender.sign_message(message.to_bytes_versioned(raw_transaction.message))

# 1. Получаем tip аккаунт от Jito и создаем инструкцию перевода
jito_tip_account = Pubkey.from_string(sdk.get_random_tip_account())
jito_tip_ix = transfer(
    TransferParams(from_pubkey=sender.pubkey(), to_pubkey=jito_tip_account, lamports=1000)
)

# 2. Получаем список аккаунтов и инструкций из Jupiter
account_keys = list(raw_transaction.message.account_keys)
jupiter_instructions = raw_transaction.message.instructions

# 3. Добавляем tip аккаунт если его нет
if jito_tip_account not in account_keys:
    account_keys.append(jito_tip_account)

# 4. Создаем CompiledInstruction для tip
system_program_index = account_keys.index(jito_tip_ix.program_id)
sender_index = account_keys.index(sender.pubkey())
tip_account_index = account_keys.index(jito_tip_account)

jito_tip_compiled = CompiledInstruction(
    program_id_index=system_program_index,
    accounts=bytes([sender_index, tip_account_index]),
    data=jito_tip_ix.data
)

# 5. Объединяем все инструкции
all_instructions = [
    *jupiter_instructions,  # Jupiter инструкции
    jito_tip_compiled  # Jito tip в конце
]

# 6. Создаем новое сообщение с добавленным tip
new_message = message.MessageV0(
    header=raw_transaction.message.header,
    account_keys=account_keys,
    recent_blockhash=raw_transaction.message.recent_blockhash,
    instructions=all_instructions,
    address_table_lookups=raw_transaction.message.address_table_lookups
)

# 7. Создаем финальную транзакцию
new_transaction = VersionedTransaction.populate(new_message, [signature])

print("Transaction created successfully")
print(new_transaction)

# 8. Сериализуем транзакцию
serialized_transaction = base58.b58encode(bytes(new_transaction)).decode('ascii')

response = sdk.send_txn(params=serialized_transaction, bundleOnly=True)
# response = {}

if response:
    if response['success']:
        print(f"Full Jito SDK response: {response}")
        signature_str = response['data']['result']
        print(f"Transaction signature: {signature_str}")

        finalized = await check_transaction_status(solana_client, signature_str)

        if finalized:
            print("Transaction has been finalized.")
            solscan_url = f"https://solscan.io/tx/{signature_str}"
            print(f"View transaction details on Solscan: {solscan_url}")
        else:
            print("Transaction was not finalized within the expected time.")
    else:
        print(f"Error sending transaction: {response['error']}")

await solana_client.close()

Hello, i'm facing the exact same problem and not finding a solution anywhere. Have you figured it out yet?