def sol_instr_partial_call_or_continue(self, storage_account, step_count, evm_instruction): return TransactionInstruction( program_id=self.loader.loader_id, data=bytearray.fromhex("0D") + self.collateral_pool_index_buf + step_count.to_bytes(8, byteorder='little') + evm_instruction, keys=[ AccountMeta(pubkey=storage_account, is_signer=False, is_writable=True), # System instructions account: AccountMeta(pubkey=PublicKey(SYSVAR_INSTRUCTION_PUBKEY), is_signer=False, is_writable=False), # Operator address: AccountMeta(pubkey=self.acc.public_key(), is_signer=True, is_writable=True), # Collateral pool address: AccountMeta(pubkey=self.collateral_pool_address, is_signer=False, is_writable=True), # Operator's NEON token account: AccountMeta(pubkey=get_associated_token_address(self.acc.public_key(), ETH_TOKEN_MINT_ID), is_signer=False, is_writable=True), # User's NEON token account: AccountMeta(pubkey=self.caller_token, is_signer=False, is_writable=True), # System program account: AccountMeta(pubkey=PublicKey(SYS_PROGRAM_ID), is_signer=False, is_writable=False), AccountMeta(pubkey=self.reId, is_signer=False, is_writable=True), AccountMeta(pubkey=self.re_code, is_signer=False, is_writable=True), AccountMeta(pubkey=self.caller, is_signer=False, is_writable=True), AccountMeta(pubkey=self.caller_token, is_signer=False, is_writable=True), AccountMeta(pubkey=self.loader.loader_id, is_signer=False, is_writable=False), AccountMeta(pubkey=ETH_TOKEN_MINT_ID, is_signer=False, is_writable=False), AccountMeta(pubkey=TOKEN_PROGRAM_ID, is_signer=False, is_writable=False), ])
def decode_allocate_with_seed( instruction: TransactionInstruction) -> AllocateWithSeedParams: """Decode an allocate with seed system instruction and retrieve the instruction params. Args: instruction: The instruction to decode. Example: >>> from solana.publickey import PublicKey >>> allocator, base, program_id = PublicKey(1), PublicKey(2), PublicKey(3) >>> instruction = allocate( ... AllocateWithSeedParams( ... account_pubkey=allocator, ... base_pubkey=base, ... seed={"length": 4, "chars": "gqln"}, ... space=65537, ... program_id=program_id ... ) ... ) >>> decode_allocate_with_seed(instruction) AllocateWithSeedParams(account_pubkey=11111111111111111111111111111112, base_pubkey=11111111111111111111111111111113, seed=Container(length=4, chars=u'gqln'), space=65537, program_id=11111111111111111111111111111114) Returns: The decoded instruction params. """ # pylint: disable=line-too-long # noqa: E501 parsed_data = __parse_and_validate_instruction( instruction, 1, InstructionType.ALLOCATE_WITH_SEED) return AllocateWithSeedParams( account_pubkey=instruction.keys[0].pubkey, base_pubkey=PublicKey(parsed_data.args.base), seed=parsed_data.args.seed, space=parsed_data.args.space, program_id=PublicKey(parsed_data.args.program_id), )
def test_token(stubbed_sender, freeze_authority, test_http_client) -> Token: """Test create mint.""" resp = test_http_client.request_airdrop(stubbed_sender.public_key, AIRDROP_AMOUNT) test_http_client.confirm_transaction(resp["result"]) expected_decimals = 6 token_client = Token.create_mint( test_http_client, stubbed_sender, stubbed_sender.public_key, expected_decimals, TOKEN_PROGRAM_ID, freeze_authority.public_key, ) assert token_client.pubkey assert token_client.program_id == TOKEN_PROGRAM_ID assert token_client.payer.public_key == stubbed_sender.public_key resp = test_http_client.get_account_info(token_client.pubkey) assert_valid_response(resp) assert resp["result"]["value"]["owner"] == str(TOKEN_PROGRAM_ID) mint_data = layouts.MINT_LAYOUT.parse( decode_byte_string(resp["result"]["value"]["data"][0])) assert mint_data.is_initialized assert mint_data.decimals == expected_decimals assert mint_data.supply == 0 assert PublicKey(mint_data.mint_authority) == stubbed_sender.public_key assert PublicKey(mint_data.freeze_authority) == freeze_authority.public_key return token_client
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 test_set_authority(): """Test set authority.""" account, new_authority, current_authority = PublicKey(0), PublicKey( 1), PublicKey(2) params = spl_token.SetAuthorityParams( program_id=TOKEN_PROGRAM_ID, account=account, authority=spl_token.AuthorityType.FreezeAccount, new_authority=new_authority, current_authority=current_authority, ) instruction = spl_token.set_authority(params) assert spl_token.decode_set_authority(instruction) == params multisig_params = spl_token.SetAuthorityParams( program_id=TOKEN_PROGRAM_ID, account=account, authority=spl_token.AuthorityType.FreezeAccount, current_authority=current_authority, signers=[PublicKey(i) for i in range(3, 10)], ) instruction = spl_token.set_authority(multisig_params) decoded_params = spl_token.decode_set_authority(instruction) assert not decoded_params.new_authority assert decoded_params == multisig_params
def test_is_on_curve(): """Test on curve verify.""" on_curve = PublicKey("4fwsi7ei2vDcUByZWXV3YmMEyLwBnLamiuDzUrEKADnm") assert PublicKey._is_on_curve(pubkey_bytes=bytes(on_curve)) # pylint: disable=protected-access off_curve = PublicKey("12rqwuEgBYiGhBrDJStCiqEtzQpTTiZbh7teNVLuYcFA") assert not PublicKey._is_on_curve(pubkey_bytes=bytes(off_curve)) # pylint: disable=protected-access
def _create_mint_info(self, info: RPCResponse) -> MintInfo: if not info: raise ValueError("Failed to find mint account") owner = info["result"]["value"]["owner"] if owner != str(self.program_id): raise AttributeError(f"Invalid mint owner: {owner}") bytes_data = decode_byte_string(info["result"]["value"]["data"][0]) if len(bytes_data) != MINT_LAYOUT.sizeof(): raise ValueError("Invalid mint size") decoded_data = MINT_LAYOUT.parse(bytes_data) decimals = decoded_data.decimals if decoded_data.mint_authority_option == 0: mint_authority = None else: mint_authority = PublicKey(decoded_data.mint_authority) supply = decoded_data.supply is_initialized = decoded_data.is_initialized != 0 if decoded_data.freeze_authority_option == 0: freeze_authority = None else: freeze_authority = PublicKey(decoded_data.freeze_authority) return MintInfo(mint_authority, supply, decimals, is_initialized, freeze_authority)
def test_approve2(stubbed_reciever, stubbed_sender): """Test approve2.""" mint = PublicKey(0) params = spl_token.Approve2Params( program_id=TOKEN_PROGRAM_ID, source=stubbed_sender.public_key(), mint=mint, delegate=stubbed_reciever, owner=stubbed_sender.public_key(), amount=123, decimals=6, ) instruction = spl_token.approve2(params) assert spl_token.decode_approve2(instruction) == params multisig_params = spl_token.Approve2Params( program_id=TOKEN_PROGRAM_ID, source=stubbed_sender.public_key(), mint=mint, delegate=stubbed_reciever, owner=stubbed_sender.public_key(), signers=[PublicKey(i + 1) for i in range(3)], amount=123, decimals=6, ) instruction = spl_token.approve2(multisig_params) assert spl_token.decode_approve2(instruction) == multisig_params
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 make_resize_instruction(self, account, code_account_old, code_account_new, seed) -> TransactionInstruction: return TransactionInstruction( program_id=EVM_LOADER_ID, data=bytearray.fromhex("11") + bytes(seed), # 17- ResizeStorageAccount keys=[ AccountMeta(pubkey=PublicKey(account), is_signer=False, is_writable=True), (AccountMeta( pubkey=code_account_old, is_signer=False, is_writable=True) if code_account_old else AccountMeta( pubkey=PublicKey("11111111111111111111111111111111"), is_signer=False, is_writable=False)), AccountMeta(pubkey=code_account_new, is_signer=False, is_writable=True), AccountMeta(pubkey=self.operator_account, is_signer=True, is_writable=False) ], )
def msg_deployed(self, message): print('msg_deployed method of the solana spl token') if self.contract.state != 'WAITING_FOR_DEPLOYMENT': take_off_blocking(self.contract.network.name) return else: conn = SolanaInt(self.contract.network.name).connect() key = Keypair.from_secret_key(bytes(SOLANA_KEYPAIR[0:32])) token_address = PublicKey(self.solana_contract.address) tok_int = Token(conn, token_address, TOKEN_PROGRAM_ID, key) holders = self.contract.tokenholder_set.all() if holders: print('transfering premint tokens') for th in holders: holder_addr = PublicKey(th.address) try: associated_address = tok_int.create_associated_token_account(holder_addr) print(f'created associated account {associated_address}') except RPCException: print('associated token account already created') associated_address = get_associated_token_address(holder_addr, tok_int.pubkey) response = tok_int.mint_to(associated_address, key, int(th.amount)) print(f'tx_hash = {response["result"]}') print('transferring of mint authority started') owner = PublicKey(self.admin_address) address = self.solana_contract.address tok_int.set_authority(address, key.public_key, 0, owner) print('successfully transferred mint authority') self.initialized({})
async def test_token(alt_stubbed_sender, test_http_client_async) -> AsyncToken: """Test create mint.""" resp = await test_http_client_async.request_airdrop(alt_stubbed_sender.public_key(), AIRDROP_AMOUNT) confirmed = await aconfirm_transaction(test_http_client_async, resp["result"]) assert_valid_response(confirmed) expected_decimals = 6 expected_freeze_authority = Account() token_client = await AsyncToken.create_mint( test_http_client_async, alt_stubbed_sender, alt_stubbed_sender.public_key(), expected_decimals, TOKEN_PROGRAM_ID, expected_freeze_authority.public_key(), ) assert token_client.pubkey assert token_client.program_id == TOKEN_PROGRAM_ID assert token_client.payer.public_key() == alt_stubbed_sender.public_key() resp = await test_http_client_async.get_account_info(token_client.pubkey) assert_valid_response(resp) assert resp["result"]["value"]["owner"] == str(TOKEN_PROGRAM_ID) mint_data = layouts.MINT_LAYOUT.parse(decode_byte_string(resp["result"]["value"]["data"][0])) assert mint_data.is_initialized assert mint_data.decimals == expected_decimals assert mint_data.supply == 0 assert PublicKey(mint_data.mint_authority) == alt_stubbed_sender.public_key() assert PublicKey(mint_data.freeze_authority) == expected_freeze_authority.public_key() return token_client
def test_burn2(stubbed_reciever): """Test burn2.""" mint, owner = PublicKey(0), PublicKey(1) params = spl_token.Burn2Params( program_id=TOKEN_PROGRAM_ID, mint=mint, account=stubbed_reciever, owner=owner, amount=123, decimals=6, ) instruction = spl_token.burn2(params) assert spl_token.decode_burn2(instruction) == params multisig_params = spl_token.Burn2Params( program_id=TOKEN_PROGRAM_ID, mint=mint, account=stubbed_reciever, owner=owner, signers=[PublicKey(i) for i in range(3, 10)], amount=123, decimals=6, ) instruction = spl_token.burn2(multisig_params) assert spl_token.decode_burn2(instruction) == multisig_params
def test_transfer_checked(stubbed_receiver, stubbed_sender): """Test transfer_checked.""" mint = PublicKey(0) params = spl_token.TransferCheckedParams( program_id=TOKEN_PROGRAM_ID, source=stubbed_sender.public_key, mint=mint, dest=stubbed_receiver, owner=stubbed_sender.public_key, amount=123, decimals=6, ) instruction = spl_token.transfer_checked(params) assert spl_token.decode_transfer_checked(instruction) == params multisig_params = spl_token.TransferCheckedParams( program_id=TOKEN_PROGRAM_ID, source=stubbed_sender.public_key, mint=mint, dest=stubbed_receiver, owner=stubbed_sender.public_key, signers=[PublicKey(i + 1) for i in range(3)], amount=123, decimals=6, ) instruction = spl_token.transfer_checked(multisig_params) assert spl_token.decode_transfer_checked(instruction) == multisig_params
def test_find_program_address(): """Test create associated_token_address.""" program_id = PublicKey("BPFLoader1111111111111111111111111111111111") program_address, nonce = PublicKey.find_program_address([bytes()], program_id) assert program_address == PublicKey.create_program_address( [bytes(), helpers.to_uint8_bytes(nonce)], program_id)
def test_mint_to2(stubbed_reciever): """Test mint_to2.""" mint, mint_authority = PublicKey(0), PublicKey(1) params = spl_token.MintTo2Params( program_id=TOKEN_PROGRAM_ID, mint=mint, dest=stubbed_reciever, mint_authority=mint_authority, amount=123, decimals=6, ) instruction = spl_token.mint_to2(params) assert spl_token.decode_mint_to2(instruction) == params multisig_params = spl_token.MintTo2Params( program_id=TOKEN_PROGRAM_ID, mint=mint, dest=stubbed_reciever, mint_authority=mint_authority, signers=[PublicKey(i) for i in range(3, 10)], amount=123, decimals=6, ) instruction = spl_token.mint_to2(multisig_params) assert spl_token.decode_mint_to2(instruction) == multisig_params
def test_create_with_seed(): """Test create with seed""" default_public_key = PublicKey("11111111111111111111111111111111") derived_key = PublicKey.create_with_seed(default_public_key, "limber chicken: 4/45", default_public_key) assert derived_key == PublicKey( "9h1HyLCW5dZnBVap8C5egQ9Z6pHyjsh5MNy83iPqqRuq")
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 test_cancel_order_by_client_id(): """Test cancel order by client id.""" params = inlib.CancelOrderByClientIDParams(market=PublicKey(0), request_queue=PublicKey(1), owner=PublicKey(2), open_orders=PublicKey(3), client_id=1) instruction = inlib.cancel_order_by_client_id(params) assert inlib.decode_cancel_order_by_client_id(instruction) == params
def test_consume_events(): params = inlib.ConsumeEventsParams( market=PublicKey(0), event_queue=PublicKey(1), open_orders_accounts=[PublicKey(i + 2) for i in range(8)], limit=1, ) instruction = inlib.consume_events(params) assert inlib.decode_consume_events(instruction) == params
async def test_new_associated_account(test_token): # pylint: disable=redefined-outer-name """Test creating a new associated token account.""" new_acct = PublicKey(0) token_account_pubkey = await test_token.create_associated_token_account(new_acct) expected_token_account_key, _ = new_acct.find_program_address( seeds=[bytes(new_acct), bytes(TOKEN_PROGRAM_ID), bytes(test_token.pubkey)], program_id=ASSOCIATED_TOKEN_PROGRAM_ID, ) assert token_account_pubkey == expected_token_account_key
def get_accounts(self, ether): (sol_address, _) = self.loader.ether2program(ether) info = client.get_account_info(sol_address, commitment=Confirmed)['result']['value'] data = base64.b64decode(info['data'][0]) acc_info = ACCOUNT_INFO_LAYOUT.parse(data) code_address = PublicKey(acc_info.code_account) alternate_token = get_associated_token_address(PublicKey(sol_address), ETH_TOKEN_MINT_ID) return (sol_address, alternate_token, code_address)
class Canceller: readonly_accs = [ PublicKey(EVM_LOADER_ID), PublicKey(ETH_TOKEN_MINT_ID), PublicKey(TOKEN_PROGRAM_ID), PublicKey(SYSVAR_CLOCK_PUBKEY), PublicKey(SYSVAR_INSTRUCTION_PUBKEY), PublicKey(KECCAK_PROGRAM), PublicKey(SYSVAR_RENT_PUBKEY), PublicKey(INCINERATOR_PUBKEY), PublicKey(SYS_PROGRAM_ID), ] def __init__(self): # Initialize user account self.signer = get_solana_accounts()[0] self.solana = SolanaInteractor(SOLANA_URL) self.waiter = None self._operator = self.signer.public_key() self.operator_token = get_associated_token_address( PublicKey(self._operator), ETH_TOKEN_MINT_ID) self.builder = NeonInstruction(self._operator) def unlock_accounts(self, blocked_storages): tx_list = [] for storage, tx_accounts in blocked_storages.items(): (neon_tx, blocked_accounts) = tx_accounts if blocked_accounts is None: self.error( f"Empty blocked accounts for the Neon tx {neon_tx}.") else: keys = [] for acc in blocked_accounts: is_writable = False if PublicKey( acc) in self.readonly_accs else True keys.append( AccountMeta(pubkey=acc, is_signer=False, is_writable=is_writable)) self.builder.init_eth_trx(neon_tx.tx, None, self.operator_token) self.builder.init_iterative(storage, None, 0) tx = self.builder.make_cancel_transaction(keys) tx_list.append(tx) if not len(tx_list): return self.debug(f"Send Cancel: {len(tx_list)}") try: SolTxListSender(self, tx_list, f'CancelWithNonce({len(tx_list)})').send() except Exception as err: err_tb = "".join(traceback.format_tb(err.__traceback__)) self.warning( 'Exception on submitting transaction. ' + f'Type(err): {type(err)}, Error: {err}, Traceback: {err_tb}')
def _create_account_info(self, info: RPCResponse) -> AccountInfo: if not info: raise ValueError("Invalid account owner") if info["result"]["value"]["owner"] != str(self.program_id): raise AttributeError("Invalid account owner") bytes_data = decode_byte_string(info["result"]["value"]["data"][0]) if len(bytes_data) != ACCOUNT_LAYOUT.sizeof(): raise ValueError("Invalid account size") decoded_data = ACCOUNT_LAYOUT.parse(bytes_data) mint = PublicKey(decoded_data.mint) owner = PublicKey(decoded_data.owner) amount = decoded_data.amount if decoded_data.delegate_option == 0: delegate = None delegated_amount = 0 else: delegate = PublicKey(decoded_data.delegate) delegated_amount = decoded_data.delegated_amount is_initialized = decoded_data.state != 0 is_frozen = decoded_data.state == 2 if decoded_data.is_native_option == 1: rent_exempt_reserve = decoded_data.is_native is_native = True else: rent_exempt_reserve = None is_native = False if decoded_data.close_authority_option == 0: close_authority = None else: close_authority = PublicKey(decoded_data.owner) if mint != self.pubkey: raise AttributeError(f"Invalid account mint: {decoded_data.mint} != {self.pubkey}") return AccountInfo( mint, owner, amount, delegate, delegated_amount, is_initialized, is_frozen, is_native, rent_exempt_reserve, close_authority, )
def test_initialize_account(stubbed_sender): """Test initialize account.""" new_account, token_mint = PublicKey(0), PublicKey(1) params = spl_token.InitializeAccountParams( program_id=TOKEN_PROGRAM_ID, account=new_account, mint=token_mint, owner=stubbed_sender.public_key(), ) instruction = spl_token.initialize_account(params) assert spl_token.decode_initialize_account(instruction) == params
def __init__(self, upper: float, lower: float, amount: float, grid: int, pair: str, base: str, quote: str, owner: str, private: str): """ :params upper: price up :params lower: price down :params amount: amount of the order :params grid: amount of grid :params pair: dexlab trading pair address :params base: youur base coin address for trading :params quote: your quote coin address for trading :params owner: your solana wallet address :params private: your private key for pay the transaction gas """ self.upper = upper self.lower = lower self.amount = amount self.grid = grid self.pair = pair self.base = base self.quote = quote self.owner = owner self.key = base58.b58decode(private) self.payer = Account(self.key[:32]) self.client = Client('', '') self.cc = conn('https://api.mainnet-beta.solana.com/') self.market = Market.load( self.cc, PublicKey(self.pair), program_id=PublicKey( '9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin')) try: self.open_acc = self.market.find_open_orders_accounts_for_owner( self.payer.public_key())[0].address except: self.open_acc = '' self.base_decimal = self.market.state.base_spl_token_decimals() self.quote_decimal = self.market.state.quote_spl_token_decimals() print(f'Initialize...\n\n' f'----parameters----\n\n' f'upper: {self.upper}\n' f'lower: {self.lower}\n' f'amount: {self.amount}\n' f'grid: {self.grid}\n' f'base decimal: {self.base_decimal}\n' f'quote decimal: {self.quote_decimal}\n' f'pair: {self.pair}\n' f'base: {self.base}\n' f'quote: {self.quote}\n' f'owner: {self.owner}\n' f'open orders account: {self.open_acc}\n' f'key: {self.key[:32]}\n\n' f'----start----\n')
def test_initialize_multisig(): """Test initialize multisig.""" new_multisig = PublicKey(0) signers = [PublicKey(i + 1) for i in range(3)] params = spl_token.InitializeMultisigParams( program_id=TOKEN_PROGRAM_ID, multisig=new_multisig, signers=signers, m=len(signers), ) instruction = spl_token.initialize_multisig(params) assert spl_token.decode_initialize_multisig(instruction) == params
def decode_initialize_mint(instruction: TransactionInstruction) -> InitializeMintParams: """Decode an initialize mint token instruction and retrieve the instruction params.""" parsed_data = __parse_and_validate_instruction(instruction, 2, InstructionType.InitializeMint) return InitializeMintParams( decimals=parsed_data.args.decimals, program_id=instruction.program_id, mint=instruction.keys[0].pubkey, mint_authority=PublicKey(parsed_data.args.mint_authority), freeze_authority=PublicKey(parsed_data.args.freeze_authority) if parsed_data.args.freeze_authority_option else None, )
def test_invalid_pubkeys(): """Test invalid public keys.""" with pytest.raises(ValueError): PublicKey([ 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]) with pytest.raises(ValueError): PublicKey( "0x300000000000000000000000000000000000000000000000000000000000000000000" ) with pytest.raises(ValueError): PublicKey( "0x300000000000000000000000000000000000000000000000000000000000000" ) with pytest.raises(ValueError): PublicKey( "135693854574979916511997248057056142015550763280047535983739356259273198796800000" ) with pytest.raises(ValueError): PublicKey("12345")
def test_set_operations() -> None: """Tests that a publickey is now hashable with the appropriate set operations.""" public_key_primary = PublicKey("11111111111111111111111111111111") public_key_secondary = PublicKey( "CiDwVBFgWV9E5MvXWoLgnEgn2hK7rJikbvfWavzAQz3") public_key_duplicate = PublicKey( "CiDwVBFgWV9E5MvXWoLgnEgn2hK7rJikbvfWavzAQz3") public_key_set = { public_key_primary, public_key_secondary, public_key_duplicate } assert public_key_primary.__hash__() != public_key_secondary.__hash__() assert public_key_secondary.__hash__() == public_key_duplicate.__hash__() assert len(public_key_set) == 2