My transactions are dropping semi frequently. I believe it is due to me not setting the compute units. How would I go about finding the # of compute units to use? I see in solana web3.js they have the getSimulationComputeUnits function to get this.
1 Answer
Here's a little sample script that airdrops some tokens, simulates a transaction, and extracts the compute units -- you'll need to replace the compute unit limit with the one from the simulation when you create the final transaction.
from solana.rpc.api import Client
from solders.keypair import Keypair
from solana.transaction import Transaction
from solana.rpc.commitment import Confirmed
from solders.compute_budget import (
set_compute_unit_limit,
set_compute_unit_price,
)
from solders.system_program import TransferParams, transfer
# Setup stuff
LAMPORT_PER_SOL = 1000000000
client: Client = Client("http://localhost:8899", Confirmed)
sender = Keypair()
receiver = Keypair()
airdrop = client.request_airdrop(sender.pubkey(), 1 * LAMPORT_PER_SOL)
airdrop_signature = airdrop.value
client.confirm_transaction(airdrop_signature)
# Setup the transaction
transaction = Transaction()
transaction.fee_payer = sender.pubkey()
transaction.recent_blockhash = client.get_latest_blockhash().value.blockhash
# Set the max limit, since we don't know how much it'll take
transaction.add(set_compute_unit_limit(1_400_000))
transaction.add(set_compute_unit_price(3))
transaction.add(transfer(TransferParams(
from_pubkey=sender.pubkey(),
to_pubkey=receiver.pubkey(),
lamports=1_000_000)
))
# Get the units consumed from simulation
resp = client.simulate_transaction(transaction, sig_verify=False)
print(resp.value.units_consumed)