def _create_account_args( self, owner: PublicKey, skip_confirmation: bool, balance_needed: int, ) -> Tuple[PublicKey, Transaction, Account, Account, TxOpts]: new_account = Account() # Allocate memory for the account # Construct transaction txn = Transaction() txn.add( sp.create_account( sp.CreateAccountParams( from_pubkey=self.payer.public_key(), new_account_pubkey=new_account.public_key(), lamports=balance_needed, space=ACCOUNT_LAYOUT.sizeof(), program_id=self.program_id, ))) txn.add( spl_token.initialize_account( spl_token.InitializeAccountParams( account=new_account.public_key(), mint=self.pubkey, owner=owner, program_id=self.program_id))) return ( new_account.public_key(), txn, self.payer, new_account, TxOpts(skip_preflight=True, skip_confirmation=skip_confirmation), )
async def create_stake(client: AsyncClient, payer: Keypair, stake: Keypair, authority: PublicKey, lamports: int): print(f"Creating stake {stake.public_key}") resp = await client.get_minimum_balance_for_rent_exemption(STAKE_LEN) txn = Transaction() txn.add( sys.create_account( sys.CreateAccountParams( from_pubkey=payer.public_key, new_account_pubkey=stake.public_key, lamports=resp['result'] + lamports, space=STAKE_LEN, program_id=STAKE_PROGRAM_ID, ))) txn.add( st.initialize( st.InitializeParams(stake=stake.public_key, authorized=Authorized( staker=authority, withdrawer=authority, ), lockup=Lockup( unix_timestamp=0, epoch=0, custodian=sys.SYS_PROGRAM_ID, )))) await client.send_transaction(txn, payer, stake, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed))
async def set_authority( self, account: PublicKey, current_authority: Union[Account, PublicKey], authority_type: spl_token.AuthorityType, new_authority: Optional[PublicKey] = None, multi_signers: Optional[List[Account]] = None, opts: TxOpts = TxOpts(), ) -> RPCResponse: """Assign a new authority to the account. :param account: Public key of the token account. :param current_authority: Current authority of the account. :param authority_type: Type of authority to set. :param new_authority: (optional) New authority of the account. :param multi_signers: (optional) Signing accounts if `owner` is a multiSig. :param opts: (optional) Transaction options. """ txn, payer, signers, opts = self._set_authority_args( account, current_authority, authority_type, new_authority, multi_signers, opts) return await self._conn.send_transaction(txn, payer, *signers, opts=opts)
async def create_vote(client: AsyncClient, payer: Keypair, vote: Keypair, node: Keypair, voter: PublicKey, withdrawer: PublicKey, commission: int): print(f"Creating vote account {vote.public_key}") resp = await client.get_minimum_balance_for_rent_exemption(VOTE_STATE_LEN) txn = Transaction() txn.add( sys.create_account( sys.CreateAccountParams( from_pubkey=payer.public_key, new_account_pubkey=vote.public_key, lamports=resp['result'], space=VOTE_STATE_LEN, program_id=VOTE_PROGRAM_ID, ))) txn.add( initialize( InitializeParams( vote=vote.public_key, rent_sysvar=SYSVAR_RENT_PUBKEY, clock_sysvar=SYSVAR_CLOCK_PUBKEY, node=node.public_key, authorized_voter=voter, authorized_withdrawer=withdrawer, commission=commission, ))) await client.send_transaction(txn, payer, vote, node, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed))
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))
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 _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
async def test_mint_to_checked( async_stubbed_sender, async_stubbed_sender_token_account_pk, test_token, ): # pylint: disable=redefined-outer-name """Test mint token checked and get balance.""" expected_amount = 1000 mint_amount = 700 expected_decimals = 6 mint_resp = await test_token.mint_to_checked( dest=async_stubbed_sender_token_account_pk, mint_authority=async_stubbed_sender, amount=mint_amount, decimals=expected_decimals, multi_signers=None, opts=TxOpts(skip_confirmation=False), ) assert_valid_response(mint_resp) resp = await test_token.get_balance(async_stubbed_sender_token_account_pk) balance_info = resp["result"]["value"] assert balance_info["amount"] == str(expected_amount) assert balance_info["decimals"] == expected_decimals assert balance_info["uiAmount"] == 0.001
def mint(self,payer:Keypair,mintAuthority:str=None,owner:str=None,amount=1): """ :param pubkey: :param program_id: :param payer: :return: """ mintAuthority=payer.public_key if mintAuthority is None else PublicKey(mintAuthority) owner=payer.public_key if owner is None else PublicKey(owner) tk=Token(self.api,mintAuthority,program_id=TOKEN_PROGRAM_ID,payer=payer) token=tk.create_mint(self.api, mint_authority=mintAuthority, freeze_authority=mintAuthority, decimals=0, program_id=TOKEN_PROGRAM_ID, payer=payer, skip_confirmation=False) mint_info=token.get_mint_info() if amount>0: token.create_associated_token_account(owner=owner) tx_opts=TxOpts(skip_confirmation=False,max_retries=3) tk.mint_to(owner,mint_authority=mintAuthority,amount=amount,opts=tx_opts) return mint_info
def cancel_order(self, owner: Account, order: t.Order, opts: TxOpts = TxOpts()) -> RPCResponse: txn = Transaction().add( self.make_cancel_order_instruction(owner.public_key(), order)) return self._conn.send_transaction(txn, owner, opts=opts)
async def transfer_checked( self, source: PublicKey, dest: PublicKey, owner: PublicKey, amount: int, decimals: int, multi_signers: Optional[List[Keypair]], opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Transfer tokens to another account, asserting the token mint and decimals. Args: source: Public key of account to transfer tokens from. dest: Public key of account to transfer tokens to. owner: Owner of the source account. amount: Number of tokens to transfer. decimals: Number of decimals in transfer amount. multi_signers: (optional) Signing accounts if `owner` is a multiSig. opts: (optional) Transaction options. recent_blockhash: (optional) a prefetched Blockhash for the transaction. """ txn, signers, opts = self._transfer_checked_args( source, dest, owner, amount, decimals, multi_signers, opts) return await self._conn.send_transaction( txn, *signers, opts=opts, recent_blockhash=recent_blockhash)
async def mint_to( self, dest: PublicKey, mint_authority: Union[Keypair, PublicKey], amount: int, multi_signers: Optional[List[Keypair]] = None, opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Mint new tokens. Args: dest: Public key of the account to mint to. mint_authority: Public key of the minting authority. amount: Amount to mint. multi_signers: (optional) Signing accounts if `owner` is a multisig. opts: (optional) Transaction options. recent_blockhash: (optional) a prefetched Blockhash for the transaction. If skip confirmation is set to `False`, this method will block for at most 30 seconds or until the transaction is confirmed. """ txn, signers, opts = self._mint_to_args(dest, mint_authority, amount, multi_signers, opts) return await self._conn.send_transaction( txn, *signers, opts=opts, recent_blockhash=recent_blockhash)
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
async def create_multisig( self, m: int, multi_signers: List[PublicKey], opts: TxOpts = TxOpts(skip_preflight=True, skip_confirmation=False), recent_blockhash: Optional[Blockhash] = None, ) -> PublicKey: # pylint: disable=invalid-name """Create and initialize a new multisig. Args: m: Number of required signatures. multi_signers: Full set of signers. opts: (optional) Transaction options. recent_blockhash: (optional) a prefetched Blockhash for the transaction. Returns: Public key of the new multisig account. """ balance_needed = await AsyncToken.get_min_balance_rent_for_exempt_for_multisig( self._conn) txn, payer, multisig = self._create_multisig_args( m, multi_signers, balance_needed) await self._conn.send_transaction(txn, payer, multisig, opts=opts, recent_blockhash=recent_blockhash) return multisig.public_key
async def set_authority( self, account: PublicKey, current_authority: Union[Keypair, PublicKey], authority_type: spl_token.AuthorityType, new_authority: Optional[PublicKey] = None, multi_signers: Optional[List[Keypair]] = None, opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Assign a new authority to the account. Args: account: Public key of the token account. current_authority: Current authority of the account. authority_type: Type of authority to set. new_authority: (optional) New authority of the account. multi_signers: (optional) Signing accounts if `owner` is a multiSig. opts: (optional) Transaction options. recent_blockhash: (optional) a prefetched Blockhash for the transaction. """ txn, payer, signers, opts = self._set_authority_args( account, current_authority, authority_type, new_authority, multi_signers, opts) return await self._conn.send_transaction( txn, payer, *signers, opts=opts, recent_blockhash=recent_blockhash)
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 _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 _approve_args( self, source: PublicKey, delegate: PublicKey, owner: Union[Keypair, PublicKey], amount: int, 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.approve( spl_token.ApproveParams( program_id=self.program_id, source=source, delegate=delegate, owner=owner_pubkey, amount=amount, signers=[signer.public_key for signer in signers], ) ) ) return txn, self.payer, signers, opts
async def create_mint(client: AsyncClient, payer: Keypair, mint: Keypair, mint_authority: PublicKey): mint_balance = await AsyncToken.get_min_balance_rent_for_exempt_for_mint( client) print(f"Creating pool token mint {mint.public_key}") txn = Transaction() txn.add( sys.create_account( sys.CreateAccountParams( from_pubkey=payer.public_key, new_account_pubkey=mint.public_key, lamports=mint_balance, space=MINT_LAYOUT.sizeof(), program_id=TOKEN_PROGRAM_ID, ))) txn.add( spl_token.initialize_mint( spl_token.InitializeMintParams( program_id=TOKEN_PROGRAM_ID, mint=mint.public_key, decimals=9, mint_authority=mint_authority, freeze_authority=None, ))) await client.send_transaction(txn, payer, mint, opts=TxOpts(skip_confirmation=False, preflight_commitment=Confirmed))
async def mint_to_checked( self, dest: PublicKey, mint_authority: PublicKey, amount: int, decimals: int, multi_signers: Optional[List[Keypair]] = None, opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Mint new tokens, asserting the token mint and decimals. Args: dest: Public key of the account to mint to. mint_authority: Public key of the minting authority. amount: Amount to mint. decimals: Number of decimals in amount to mint. multi_signers: (optional) Signing accounts if `owner` is a multiSig. opts: (optional) Transaction options. recent_blockhash (optional): A prefetched blockhash for the transaction. """ txn, signers, opts = self._mint_to_checked_args( dest, mint_authority, amount, decimals, multi_signers, opts) return await self._conn.send_transaction( txn, *signers, opts=opts, recent_blockhash=recent_blockhash)
async def approve_checked( self, source: PublicKey, delegate: PublicKey, owner: PublicKey, amount: int, decimals: int, multi_signers: Optional[List[Keypair]] = None, opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Grant a third-party permission to transfer up the specified number of tokens from an account. This method also asserts the token mint and decimals. Args: source: Public key of the source account. delegate: Account authorized to perform a transfer tokens from the source account. owner: Owner of the source account. amount: Maximum number of tokens the delegate may transfer. decimals: Number of decimals in approve amount. multi_signers: (optional) Signing accounts if `owner` is a multisig. opts: (optional) Transaction options. recent_blockhash (optional): A prefetched blockhash for the transaction. """ txn, payer, signers, opts = self._approve_checked_args( source, delegate, owner, amount, decimals, multi_signers, opts) return await self._conn.send_transaction( txn, payer, *signers, opts=opts, recent_blockhash=recent_blockhash)
def close_account( self, account: PublicKey, dest: PublicKey, authority: Union[Keypair, PublicKey], multi_signers: Optional[List[Keypair]] = None, opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Remove approval for the transfer of any remaining tokens. Args: account: Account to close. dest: Account to receive the remaining balance of the closed account. authority: Authority which is allowed to close the account. multi_signers: (optional) Signing accounts if `owner` is a multiSig. opts: (optional) Transaction options. recent_blockhash: (optional) a prefetched Blockhash for the transaction. """ txn, signers, opts = self._close_account_args(account, dest, authority, multi_signers) return self._conn.send_transaction(txn, *signers, opts=opts, recent_blockhash=recent_blockhash)
def test_no_airdrop(self): from_owner = self.create_sol_account() mint_amount = 1000_000_000_000 from_spl_token_acc = self.create_token_account(from_owner.public_key(), mint_amount) to_neon_acc = self.create_eth_account().address sleep(15) self.assertEqual(self.wrapper.get_balance(from_spl_token_acc), mint_amount) self.assertEqual(self.wrapper.get_balance(to_neon_acc), 0) trx = Transaction() trx.add( self.create_account_instruction(to_neon_acc, from_owner.public_key())) trx.add( self.wrapper.create_neon_erc20_account_instruction( from_owner.public_key(), to_neon_acc)) # No input liquidity opts = TxOpts(skip_preflight=True, skip_confirmation=False) print(self.solana_client.send_transaction(trx, from_owner, opts=opts)) sleep(15) eth_balance = proxy.eth.get_balance(to_neon_acc) print("NEON balance is: ", eth_balance) self.assertEqual(eth_balance, 0)
async def burn_checked( self, account: PublicKey, owner: PublicKey, amount: int, decimals: int, multi_signers: Optional[List[Keypair]] = None, opts: TxOpts = TxOpts(), recent_blockhash: Optional[Blockhash] = None, ) -> RPCResponse: """Burn tokens, asserting the token mint and decimals. Args: account: Account to burn tokens from. owner: Owner of the account. amount: Amount to burn. decimals: Number of decimals in amount to burn. multi_signers: (optional) Signing accounts if `owner` is a multisig. opts: (optional) Transaction options. recent_blockhash: (optional) a prefetched Blockhash for the transaction. """ txn, signers, opts = self._burn_checked_args(account, owner, amount, decimals, multi_signers, opts) return await self._conn.send_transaction( txn, *signers, opts=opts, recent_blockhash=recent_blockhash)
def cancel_order(self, client_id): """ :return: a dict contains tx_hash and id """ self.open_acc = self.market.find_open_orders_accounts_for_owner( self.payer.public_key())[0].address return self.market.cancel_order_by_client_id( self.payer, PublicKey(self.open_acc), client_id, TxOpts(skip_preflight=True))
def create_mint( conn: Client, payer: Account, mint_authority: PublicKey, decimals: int, program_id: PublicKey, freeze_authority: Optional[PublicKey] = None, skip_confirmation: bool = False, ) -> Token: """Create and initialize a token. :param conn: RPC connection to a solana cluster. :param payer: Fee payer for transaction. :param mint_authority: Account or multisig that will control minting. :param decimals: Location of the decimal place. :param program_id: SPL Token program account. :param freeze_authority: (optional) Account or multisig that can freeze token accounts. :param skip_confirmation: (optional) Option to skip transaction confirmation. :return: Token object for the newly minted token. If skip confirmation is set to `False`, this method will block for at most 30 seconds or until the transaction is confirmed. """ mint_account = Account() token = Token(conn, mint_account.public_key(), program_id, payer) # Allocate memory for the account balance_needed = Token.get_min_balance_rent_for_exempt_for_mint(conn) # Construct transaction txn = Transaction() txn.add( sp.create_account( sp.CreateAccountParams( from_pubkey=payer.public_key(), new_account_pubkey=mint_account.public_key(), lamports=balance_needed, space=MINT_LAYOUT.sizeof(), program_id=program_id, ) ) ) txn.add( spl_token.initialize_mint( spl_token.InitializeMintParams( program_id=program_id, mint=mint_account.public_key(), decimals=decimals, mint_authority=mint_authority, freeze_authority=freeze_authority, ) ) ) # Send the two instructions conn.send_transaction( txn, payer, mint_account, opts=TxOpts(skip_confirmation=skip_confirmation, skip_preflight=True) ) return token
def cancel_order_by_client_id( self, owner: Account, open_orders_account: PublicKey, client_id: int, opts: TxOpts = TxOpts()) -> RPCResponse: txs = Transaction().add( self.make_cancel_order_by_client_id_instruction( owner, open_orders_account, client_id)) return self._conn.send_transaction(txs, owner, opts=opts)
def _buy_func(self, price, client_id): self.market.place_order(payer=PublicKey(self.base), owner=self.payer, side=Side.BUY, order_type=OrderType.LIMIT, limit_price=price, max_quantity=abs(self.amount), client_id=client_id, opts=TxOpts(skip_preflight=True)) print( f'Client ID: {client_id}; Price {price}; Amount: {self.amount}; Open: BUY' )
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)