async def deposit_sol( client: AsyncClient, funder: Keypair, stake_pool_address: PublicKey, destination_token_account: PublicKey, amount: int, ): resp = await client.get_account_info(stake_pool_address, commitment=Confirmed) data = resp['result']['value']['data'] stake_pool = StakePool.decode(data[0], data[1]) (withdraw_authority, seed) = find_withdraw_authority_program_address(STAKE_POOL_PROGRAM_ID, stake_pool_address) txn = Transaction() txn.add( sp.deposit_sol( sp.DepositSolParams( program_id=STAKE_POOL_PROGRAM_ID, stake_pool=stake_pool_address, withdraw_authority=withdraw_authority, reserve_stake=stake_pool.reserve_stake, funding_account=funder.public_key, destination_pool_account=destination_token_account, manager_fee_account=stake_pool.manager_fee_account, referral_pool_account=destination_token_account, pool_mint=stake_pool.pool_mint, system_program_id=sys.SYS_PROGRAM_ID, token_program_id=stake_pool.token_program_id, amount=amount, deposit_authority=None, ) ) ) await client.send_transaction( txn, funder, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed))
def __init__(self, db: MemDB, solana: SolanaInteractor, eth_tx: EthTx, steps: int): self._db = db self.eth_tx = eth_tx self.neon_sign = '0x' + eth_tx.hash_signed().hex() self.steps = steps self.waiter = self self.solana = solana self._resource_list = OperatorResourceList(self) self.resource = None self.signer = None self.operator_key = None self.builder = None self._pending_tx = None self.eth_sender = '0x' + eth_tx.sender() self.deployed_contract = eth_tx.contract() if self.deployed_contract: self.deployed_contract = '0x' + self.deployed_contract self.to_address = eth_tx.toAddress.hex() if self.to_address: self.to_address = '0x' + self.to_address self.steps_emulated = 0 self.create_account_tx = Transaction() self.account_txs_name = '' self._resize_contract_list = [] self._create_account_list = [] self._eth_meta_list = []
async def withdraw_sol( client: AsyncClient, owner: Keypair, source_token_account: PublicKey, stake_pool_address: PublicKey, destination_system_account: PublicKey, amount: int, ): resp = await client.get_account_info(stake_pool_address, commitment=Confirmed) data = resp['result']['value']['data'] stake_pool = StakePool.decode(data[0], data[1]) (withdraw_authority, seed) = find_withdraw_authority_program_address(STAKE_POOL_PROGRAM_ID, stake_pool_address) txn = Transaction() txn.add( sp.withdraw_sol( sp.WithdrawSolParams( program_id=STAKE_POOL_PROGRAM_ID, stake_pool=stake_pool_address, withdraw_authority=withdraw_authority, source_transfer_authority=owner.public_key, source_pool_account=source_token_account, reserve_stake=stake_pool.reserve_stake, destination_system_account=destination_system_account, manager_fee_account=stake_pool.manager_fee_account, pool_mint=stake_pool.pool_mint, clock_sysvar=SYSVAR_CLOCK_PUBKEY, stake_history_sysvar=SYSVAR_STAKE_HISTORY_PUBKEY, stake_program_id=STAKE_PROGRAM_ID, token_program_id=stake_pool.token_program_id, amount=amount, sol_withdraw_authority=None, ) ) ) await client.send_transaction( txn, owner, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed))
def _create_perm_accounts(self, seed_list): tx = Transaction() stage_list = [ NeonCreatePermAccount(self._s, seed, STORAGE_SIZE) for seed in seed_list ] account_list = [s.sol_account for s in stage_list] info_list = self._s.solana.get_account_info_list(account_list) balance = self._s.solana.get_multiple_rent_exempt_balances_for_size( [STORAGE_SIZE])[0] for account, stage in zip(info_list, stage_list): if not account: stage.balance = balance stage.build() tx.add(stage.tx) elif account.lamports < balance: raise RuntimeError(f"insufficient balance") elif PublicKey(account.owner) != PublicKey(EVM_LOADER_ID): raise RuntimeError(f"wrong owner") elif account.tag not in {EMPTY_STORAGE_TAG, FINALIZED_STORAGE_TAG}: raise RuntimeError(f"not empty, not finalized") rid = self._resource.rid opkey = str(self._resource.public_key()) if len(tx.instructions): self.debug(f"Create new accounts for resource {opkey}:{rid}") SolTxListSender(self._s, [tx], NeonCreatePermAccount.NAME).send() else: self.debug(f"Use existing accounts for resource {opkey}:{rid}") return account_list
async def test_send_raw_transaction_and_get_balance(async_stubbed_sender, async_stubbed_receiver, test_http_client_async): """Test sending a raw transaction to localnet.""" # Get a recent blockhash resp = await test_http_client_async.get_recent_blockhash(Finalized) assert_valid_response(resp) recent_blockhash = resp["result"]["value"]["blockhash"] # Create transfer tx transfer lamports from stubbed sender to async_stubbed_receiver transfer_tx = Transaction(recent_blockhash=recent_blockhash).add( sp.transfer( sp.TransferParams(from_pubkey=async_stubbed_sender.public_key, to_pubkey=async_stubbed_receiver, lamports=1000))) # Sign transaction transfer_tx.sign(async_stubbed_sender) # Send raw transaction resp = await test_http_client_async.send_raw_transaction( transfer_tx.serialize()) assert_valid_response(resp) # Confirm transaction resp = await test_http_client_async.confirm_transaction(resp["result"]) # Check balances resp = await test_http_client_async.get_balance( async_stubbed_sender.public_key) assert_valid_response(resp) assert resp["result"]["value"] == 9999988000 resp = await test_http_client_async.get_balance(async_stubbed_receiver) assert_valid_response(resp) assert resp["result"]["value"] == 10000002000
def createERC20TokenAccountTrx(self, token_info) -> Transaction: trx = Transaction() trx.add( TransactionInstruction( program_id=EVM_LOADER_ID, data=bytes.fromhex('0F'), keys=[ AccountMeta(pubkey=self.operator_account, is_signer=True, is_writable=True), AccountMeta(pubkey=PublicKey(token_info["key"]), is_signer=False, is_writable=True), AccountMeta(pubkey=PublicKey(token_info["owner"]), is_signer=False, is_writable=True), AccountMeta(pubkey=PublicKey(token_info["contract"]), is_signer=False, is_writable=True), AccountMeta(pubkey=PublicKey(token_info["mint"]), is_signer=False, is_writable=True), AccountMeta(pubkey=SYS_PROGRAM_ID, is_signer=False, is_writable=False), AccountMeta(pubkey=TOKEN_PROGRAM_ID, is_signer=False, is_writable=False), AccountMeta(pubkey=SYSVAR_RENT_PUBKEY, is_signer=False, is_writable=False), ])) return trx
def liquidate(self, group: Group, margin_account: MarginAccount, prices: typing.List[TokenValue]) -> typing.Optional[str]: instruction_builders = self.prepare_instructions( group, margin_account, prices) if len(instruction_builders) == 0: return None transaction = Transaction() for builder in instruction_builders: transaction.add(builder.build()) for instruction in transaction.instructions: self.logger.debug("INSTRUCTION") self.logger.debug(" Keys:") for key in instruction.keys: self.logger.debug(" ", f"{key.pubkey}".ljust(45), f"{key.is_signer}".ljust(6), f"{key.is_writable}".ljust(6)) self.logger.debug(" Data:", " ".join(f"{x:02x}" for x in instruction.data)) self.logger.debug(" Program ID:", instruction.program_id) transaction_response = self.context.client.send_transaction( transaction, self.wallet.account) transaction_id = self.context.unwrap_transaction_id_or_raise_exception( transaction_response) return transaction_id
def transfer(params: TransferParams) -> Transaction: """Generate a Transaction that transfers lamports from one account to another. >>> from solana.publickey import PublicKey >>> sender, reciever = PublicKey(1), PublicKey(2) >>> transfer_tx = transfer( ... TransferParams(from_pubkey=sender, to_pubkey=reciever, lamports=1000) ... ) >>> type(transfer_tx) <class 'solana.transaction.Transaction'> """ layout = SYSTEM_INSTRUCTION_LAYOUTS[_TRANSFER] data = encode_data(layout, params.lamports) txn = Transaction() txn.add( TransactionInstruction( keys=[ AccountMeta(pubkey=params.from_pubkey, is_signer=True, is_writable=True), AccountMeta(pubkey=params.to_pubkey, is_signer=False, is_writable=True), ], program_id=sys_program_id(), data=data, )) return txn
def send_transaction( self, txn: Transaction, *signers: Account, opts: types.TxOpts = types.TxOpts() ) -> types.RPCResponse: """Send a transaction. :param txn: Transaction object. :param signers: Signers to sign the transaction. :param opts: (optional) Transaction options. >>> from solana.account import Account >>> from solana.system_program import TransferParams, transfer >>> from solana.transaction import Transaction >>> sender, reciever = Account(1), Account(2) >>> txn = Transaction().add(transfer(TransferParams( ... from_pubkey=sender.public_key(), to_pubkey=reciever.public_key(), lamports=1000))) >>> solana_client = Client("http://localhost:8899") >>> solana_client.send_transaction(txn, sender) # doctest: +SKIP {'jsonrpc': '2.0', 'result': '236zSA5w4NaVuLXXHK1mqiBuBxkNBu84X6cfLBh1v6zjPrLfyECz4zdedofBaZFhs4gdwzSmij9VkaSo2tR5LTgG', 'id': 12} """ try: # TODO: Cache recent blockhash blockhash_resp = self.get_recent_blockhash() if not blockhash_resp["result"]: raise RuntimeError("failed to get recent blockhash") txn.recent_blockhash = Blockhash(blockhash_resp["result"]["value"]["blockhash"]) except Exception as err: raise RuntimeError("failed to get recent blockhash") from err txn.sign(*signers) return self.send_raw_transaction(txn.serialize(), opts=opts)
def send_transaction(self, txn: Transaction, *signers: Account) -> RPCResponse: """Send a transaction. :param txn: Transaction object. :param signers: Signers to sign the transaction >>> from solana.account import Account >>> from solana.system_program import TransferParams, transfer >>> sender, reciever = Account(1), Account(2) >>> tx = transfer(TransferParams( ... from_pubkey=sender.public_key(), to_pubkey=reciever.public_key(), lamports=1000)) >>> solana_client = Client("http://localhost:8899") >>> solana_client.send_transaction(tx, sender) # doctest: +SKIP {'jsonrpc': '2.0', 'result': '236zSA5w4NaVuLXXHK1mqiBuBxkNBu84X6cfLBh1v6zjPrLfyECz4zdedofBaZFhs4gdwzSmij9VkaSo2tR5LTgG', 'id': 12} """ try: # TODO: Cache recent blockhash blockhash_resp = self.get_recent_blockhash() if not blockhash_resp["result"]: raise RuntimeError("failed to get recent blockhash") txn.recent_blockhash = Blockhash( blockhash_resp["result"]["value"]["blockhash"]) except Exception as err: raise RuntimeError("failed to get recent blockhash") from err txn.sign(*signers) wire_format = b58encode(txn.serialize()).decode("utf-8") return self._provider.make_request(RPCMethod("sendTransaction"), wire_format)
def make_combined_transaction(self, storage, steps, msg, instruction): print("make_combined_transaction") trx = Transaction() trx.add(self.sol_instr_keccak(make_keccak_instruction_data(1, len(msg), 13))) trx.add(self.sol_instr_partial_call_or_continue(storage, steps, instruction)) print(trx.__dict__) return trx
def topup(self, api_endpoint, to, amount=None, skip_confirmation=True): """ Send a small amount of native currency to the specified wallet to handle gas fees. Return a status flag of success or fail and the native transaction data. """ msg = "" try: # Connect to the api_endpoint client = Client(api_endpoint) msg += "Initialized client" # List accounts sender_account = Account(self.private_key) dest_account = PublicKey(to) msg += " | Gathered accounts" # List signers signers = [sender_account] # Start transaction tx = Transaction() # Determine the amount to send try: if amount is None: min_rent_reseponse = client.get_minimum_balance_for_rent_exemption( ACCOUNT_LAYOUT.sizeof()) lamports = min_rent_reseponse["result"] else: lamports = int(amount) msg += f" | Fetched lamports: {lamports * 1e-9} SOL" except Exception as e: msg += " | ERROR: couldn't process lamports" raise (e) # Generate transaction transfer_ix = transfer( TransferParams(from_pubkey=sender_account.public_key(), to_pubkey=dest_account, lamports=lamports)) tx = tx.add(transfer_ix) msg += f" | Transferring funds" # Send request try: response = client.send_transaction( tx, *signers, opts=types.TxOpts(skip_confirmation=skip_confirmation)) return json.dumps({ 'status': HTTPStatus.OK, 'msg': f"Successfully sent {lamports * 1e-9} SOL to {to}", 'tx': response.get('result') if skip_confirmation else response['result']['transaction']['signatures'], }) except Exception as e: msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}" raise (e) except Exception as e: return json.dumps({ 'status': HTTPStatus.BAD_REQUEST, 'msg': msg, })
def mint_to(self, api_endpoint, pool_account, dest, amount, skip_confirmation=True): msg = "" client = Client(api_endpoint) msg += "Initialized client" # Create account objects source_account = Account(self.private_key) signers = [source_account] pool = self.load_binary_option(api_endpoint, pool_account) # List non-derived accounts pool_account = PublicKey(pool_account) dest_account = PublicKey(dest) escrow_mint_account = PublicKey(pool["escrow_mint"]) mint_authority_account = source_account.public_key() payer_account = source_account.public_key() token_account = PublicKey(TOKEN_PROGRAM_ID) tx = Transaction() token_pda_address = get_associated_token_address( dest_account, escrow_mint_account) associated_token_account_ix = create_associated_token_account( payer=payer_account, owner=dest_account, mint=escrow_mint_account, ) tx = tx.add(associated_token_account_ix) mint_to_ix = mint_to( MintToParams( program_id=token_account, mint=escrow_mint_account, dest=token_pda_address, mint_authority=mint_authority_account, amount=int(amount), signers=[mint_authority_account], )) tx = tx.add(mint_to_ix) # Send request try: response = client.send_transaction( tx, *signers, opts=types.TxOpts(skip_confirmation=skip_confirmation)) return json.dumps({ 'status': HTTPStatus.OK, 'msg': msg + f" | MintTo {dest} successful", 'tx': response.get('result') if skip_confirmation else response['result']['transaction']['signatures'], }) except Exception as e: msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}" raise (e)
def create_storage_account(self, seed): storage = PublicKey(sha256(bytes(self.acc.public_key()) + bytes(seed, 'utf8') + bytes(PublicKey(EVM_LOADER))).digest()) print("Storage", storage) if getBalance(storage) == 0: trx = Transaction() trx.add(createAccountWithSeed(self.acc.public_key(), self.acc.public_key(), seed, 10**9, 128*1024, PublicKey(EVM_LOADER))) send_transaction(client, trx, self.acc) return storage
async def create_associated_token_account(client: AsyncClient, payer: Keypair, owner: PublicKey, mint: PublicKey) -> PublicKey: txn = Transaction() create_txn = spl_token.create_associated_token_account( payer=payer.public_key, owner=owner, mint=mint) txn.add(create_txn) await client.send_transaction(txn, payer, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed)) return create_txn.keys[1].pubkey
def _create_associated_token_account_args( self, owner: PublicKey, skip_confirmation: bool, ) -> Tuple[PublicKey, Transaction, Keypair, TxOpts]: # Construct transaction txn = Transaction() create_txn = spl_token.create_associated_token_account( payer=self.payer.public_key, owner=owner, mint=self.pubkey ) txn.add(create_txn) return create_txn.keys[1].pubkey, txn, self.payer, TxOpts(skip_confirmation=skip_confirmation)
async def test_send_raw_transaction_and_get_balance(alt_stubbed_sender, alt_stubbed_receiver, test_http_client_async): """Test sending a raw transaction to localnet.""" # Get a recent blockhash resp = await test_http_client_async.get_recent_blockhash() assert_valid_response(resp) recent_blockhash = resp["result"]["value"]["blockhash"] # Create transfer tx transfer lamports from stubbed sender to alt_stubbed_receiver transfer_tx = Transaction(recent_blockhash=recent_blockhash).add( sp.transfer( sp.TransferParams(from_pubkey=alt_stubbed_sender.public_key(), to_pubkey=alt_stubbed_receiver, lamports=1000))) # Sign transaction transfer_tx.sign(alt_stubbed_sender) # Send raw transaction resp = await test_http_client_async.send_raw_transaction( transfer_tx.serialize()) assert_valid_response(resp) # Confirm transaction resp = await aconfirm_transaction(test_http_client_async, resp["result"]) assert_valid_response(resp) expected_meta = { "err": None, "fee": 5000, "innerInstructions": [], "logMessages": [ "Program 11111111111111111111111111111111 invoke [1]", "Program 11111111111111111111111111111111 success", ], "postBalances": [9999988000, 1954, 1], "postTokenBalances": [], "preBalances": [9999994000, 954, 1], "preTokenBalances": [], "rewards": [], "status": { "Ok": None }, } assert resp["result"]["meta"] == expected_meta # Check balances resp = await test_http_client_async.get_balance( alt_stubbed_sender.public_key()) assert_valid_response(resp) assert resp["result"]["value"] == 9999988000 resp = await test_http_client_async.get_balance(alt_stubbed_receiver) assert_valid_response(resp) assert resp["result"]["value"] == 1954
async def decrease_validator_stake( client: AsyncClient, payer: Keypair, staker: Keypair, stake_pool_address: PublicKey, validator_vote: PublicKey, lamports: int ): resp = await client.get_account_info(stake_pool_address, commitment=Confirmed) data = resp['result']['value']['data'] stake_pool = StakePool.decode(data[0], data[1]) resp = await client.get_account_info(stake_pool.validator_list, commitment=Confirmed) data = resp['result']['value']['data'] validator_list = ValidatorList.decode(data[0], data[1]) (withdraw_authority, seed) = find_withdraw_authority_program_address(STAKE_POOL_PROGRAM_ID, stake_pool_address) validator_info = next(x for x in validator_list.validators if x.vote_account_address == validator_vote) (validator_stake, _) = find_stake_program_address( STAKE_POOL_PROGRAM_ID, validator_info.vote_account_address, stake_pool_address, ) transient_stake_seed = validator_info.transient_seed_suffix_start + 1 # bump up by one to avoid reuse (transient_stake, _) = find_transient_stake_program_address( STAKE_POOL_PROGRAM_ID, validator_info.vote_account_address, stake_pool_address, transient_stake_seed, ) txn = Transaction() txn.add( sp.decrease_validator_stake( sp.DecreaseValidatorStakeParams( program_id=STAKE_POOL_PROGRAM_ID, stake_pool=stake_pool_address, staker=staker.public_key, withdraw_authority=withdraw_authority, validator_list=stake_pool.validator_list, validator_stake=validator_stake, transient_stake=transient_stake, clock_sysvar=SYSVAR_CLOCK_PUBKEY, rent_sysvar=SYSVAR_RENT_PUBKEY, system_program_id=sys.SYS_PROGRAM_ID, stake_program_id=STAKE_PROGRAM_ID, lamports=lamports, transient_stake_seed=transient_stake_seed, ) ) ) signers = [payer, staker] if payer != staker else [payer] await client.send_transaction( txn, *signers, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed))
def create_associated_token_account(self, owner: PublicKey, payer: SolanaAccount): # Construct transaction # This part of code is based on original implementation of Token.create_associated_token_account # except that skip_preflight is set to True txn = Transaction() create_txn = spl_token.create_associated_token_account( payer=payer.public_key(), owner=owner, mint=self.token.pubkey) txn.add(create_txn) self.token._conn.send_transaction(txn, payer, opts=TxOpts(skip_preflight=True, skip_confirmation=False)) return create_txn.keys[1].pubkey
async def test_program_subscribe( test_http_client_async: AsyncClient, websocket: SolanaWsClientProtocol, program_subscribed: Tuple[PublicKey, PublicKey], ): """Test program subscription.""" program, owned = program_subscribed instruction = sp.assign( sp.AssignParams(account_pubkey=owned.public_key, program_id=program.public_key)) transaction = Transaction() transaction.add(instruction) await test_http_client_async.send_transaction(transaction, owned) main_resp = await websocket.recv() assert main_resp.result.value.pubkey == owned.public_key
def _approve_checked_args( self, source: PublicKey, delegate: PublicKey, owner: Union[Keypair, PublicKey], amount: int, decimals: int, multi_signers: Optional[List[Keypair]], opts: TxOpts, ) -> Tuple[Transaction, Keypair, List[Keypair], TxOpts]: if isinstance(owner, Keypair): owner_pubkey = owner.public_key signers = [owner] else: owner_pubkey = owner signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.approve_checked( spl_token.ApproveCheckedParams( program_id=self.program_id, source=source, mint=self.pubkey, delegate=delegate, owner=owner_pubkey, amount=amount, decimals=decimals, signers=[signer.public_key for signer in signers], ) ) ) return txn, self.payer, signers, opts
def _mint_to_checked_args( self, dest: PublicKey, mint_authority: Union[Keypair, PublicKey], amount: int, decimals: int, multi_signers: Optional[List[Keypair]], opts: TxOpts, ) -> Tuple[Transaction, List[Keypair], TxOpts]: if isinstance(mint_authority, Keypair): owner_pubkey = mint_authority.public_key signers = [mint_authority] else: owner_pubkey = mint_authority signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.mint_to_checked( spl_token.MintToCheckedParams( program_id=self.program_id, mint=self.pubkey, dest=dest, mint_authority=owner_pubkey, amount=amount, decimals=decimals, signers=[signer.public_key for signer in signers], ) ) ) return txn, signers, opts
def _burn_args( self, account: PublicKey, owner: Union[PublicKey, Keypair], amount: int, multi_signers: Optional[List[Keypair]], opts: TxOpts = TxOpts(), ) -> Tuple[Transaction, List[Keypair], TxOpts]: if isinstance(owner, Keypair): owner_pubkey = owner.public_key signers = [owner] else: owner_pubkey = owner signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.burn( spl_token.BurnParams( program_id=self.program_id, account=account, mint=self.pubkey, owner=owner_pubkey, amount=amount, signers=[signer.public_key for signer in signers], ) ) ) return txn, signers, opts
def _close_account_args( self, account: PublicKey, dest: PublicKey, authority: Union[PublicKey, Keypair], multi_signers: Optional[List[Keypair]], opts: TxOpts = TxOpts(), ) -> Tuple[Transaction, List[Keypair], TxOpts]: if isinstance(authority, Keypair): authority_pubkey = authority.public_key signers = [authority] else: authority_pubkey = authority signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.close_account( spl_token.CloseAccountParams( program_id=self.program_id, account=account, dest=dest, owner=authority_pubkey, signers=[signer.public_key for signer in signers], ) ) ) return txn, signers, opts
def _revoke_args( self, account: PublicKey, owner: Union[Keypair, PublicKey], multi_signers: Optional[List[Keypair]], opts: TxOpts = TxOpts(), ) -> Tuple[Transaction, Keypair, List[Keypair], TxOpts]: if isinstance(owner, Keypair): owner_pubkey = owner.public_key signers = [owner] else: owner_pubkey = owner signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.revoke( spl_token.RevokeParams( program_id=self.program_id, account=account, owner=owner_pubkey, signers=[signer.public_key for signer in signers], ) ) ) return txn, self.payer, signers, opts
def _set_authority_args( self, account: PublicKey, current_authority: Union[Keypair, PublicKey], authority_type: spl_token.AuthorityType, new_authority: Optional[PublicKey], multi_signers: Optional[List[Keypair]], opts: TxOpts = TxOpts(), ) -> Tuple[Transaction, Keypair, List[Keypair], TxOpts]: if isinstance(current_authority, Keypair): current_authority_pubkey = current_authority.public_key signers = [current_authority] else: current_authority_pubkey = current_authority signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.set_authority( spl_token.SetAuthorityParams( program_id=self.program_id, account=account, authority=authority_type, current_authority=current_authority_pubkey, signers=[signer.public_key for signer in signers], new_authority=new_authority, ) ) ) return txn, self.payer, signers, opts
def _transfer_args( self, source: PublicKey, dest: PublicKey, owner: Union[Keypair, PublicKey], amount: int, multi_signers: Optional[List[Keypair]], opts: TxOpts, ) -> Tuple[Transaction, List[Keypair], TxOpts]: if isinstance(owner, Keypair): owner_pubkey = owner.public_key signers = [owner] else: owner_pubkey = owner signers = multi_signers if multi_signers else [] txn = Transaction().add( spl_token.transfer( spl_token.TransferParams( program_id=self.program_id, source=source, dest=dest, owner=owner_pubkey, amount=amount, signers=[signer.public_key for signer in signers], ) ) ) return txn, signers, opts
def test_send_transaction_and_get_balance(stubbed_sender, stubbed_reciever, test_http_client): """Test sending a transaction to localnet.""" # Create transfer tx to transfer lamports from stubbed sender to stubbed_reciever transfer_tx = Transaction().add( sp.transfer( sp.TransferParams(from_pubkey=stubbed_sender.public_key(), to_pubkey=stubbed_reciever, lamports=1000))) resp = test_http_client.send_transaction(transfer_tx, stubbed_sender) assert_valid_response(resp) # Confirm transaction resp = confirm_transaction(test_http_client, resp["result"]) assert_valid_response(resp) expected_meta = { "err": None, "fee": 5000, "innerInstructions": [], "logMessages": [], "postBalances": [9999994000, 954, 1], "preBalances": [10000000000, 0, 1], "status": { "Ok": None }, } assert resp["result"]["meta"] == expected_meta # Check balances resp = test_http_client.get_balance(stubbed_sender.public_key()) assert_valid_response(resp) assert resp["result"]["value"] == 9999994000 resp = test_http_client.get_balance(stubbed_reciever) assert_valid_response(resp) assert resp["result"]["value"] == 954
async def test_send_transaction_prefetched_blockhash( async_stubbed_sender_prefetched_blockhash, async_stubbed_receiver_prefetched_blockhash, test_http_client_async): """Test sending a transaction to localnet.""" # Create transfer tx to transfer lamports from stubbed sender to async_stubbed_receiver transfer_tx = Transaction().add( sp.transfer( sp.TransferParams( from_pubkey=async_stubbed_sender_prefetched_blockhash. public_key, to_pubkey=async_stubbed_receiver_prefetched_blockhash, lamports=1000, ))) resp = await test_http_client_async.send_transaction( transfer_tx, async_stubbed_sender_prefetched_blockhash) assert_valid_response(resp) # Confirm transaction await test_http_client_async.confirm_transaction(resp["result"]) # Check balances resp = await test_http_client_async.get_balance( async_stubbed_sender_prefetched_blockhash.public_key) assert_valid_response(resp) assert resp["result"]["value"] == 9999994000 resp = await test_http_client_async.get_balance( async_stubbed_receiver_prefetched_blockhash) assert_valid_response(resp) assert resp["result"]["value"] == 10000001000
async def parse_tx(self, tx_sig: str) -> ParsedTx: tx_receipt = self._solana_client_manager.get_sol_tx_info( tx_sig, 5, "base64") self.msg(tx_receipt) encoded_data = tx_receipt["result"].get("transaction")[0] decoded_data = base64.b64decode(encoded_data) decoded_data_hex = decoded_data.hex() tx = Transaction.deserialize(bytes.fromhex(decoded_data_hex)) tx_metadata = {} # Append each parsed transaction to parsed metadata tx_instructions = [] for instruction in tx.instructions: parsed_instruction = self.anchor_parser.parse_instruction( instruction) if self.is_valid_instruction(parsed_instruction): tx_instructions.append(parsed_instruction) tx_metadata["instructions"] = tx_instructions """ For example: Embed instruction specific information in tx_metadata """ return { "tx_sig": tx_sig, "tx_metadata": tx_metadata, "result": tx_receipt["result"], }