async def nine_nine(ctx, arg): if (ctx.channel.type == "private"): # Forbid DM in discord await ctx.send("Hold on Capt'ain, you can't send me private messages !" ) else: substrate = SubstrateInterface( url=node_rpc, address_type=42, type_registry_preset='substrate-node-template') call = substrate.compose_call(call_module='Balances', call_function='transfer', call_params={ 'dest': arg, 'value': 100 * 10**12 }) reply = "" keypair = Keypair.create_from_mnemonic(faucet_mnemonic) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) reply = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=False) await ctx.send( ctx.author.mention + " Awesome, you just received 100 dPIRL, it has no real value it's only the testnet token :) " + reply['extrinsic_hash'] + str(ctx.channel.type))
def test_hdkd_path_gt_32_bytes(self): derivation_address = '5GR5pfZeNs1uQiSWVxZaQiZou3wdZiX894eqgvfNfHbEh7W2' derivation_path = '//PathNameLongerThan32BytesWhichShouldBeHashed' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_sign_unsupported_crypto_type(self): keypair = Keypair.create_from_private_key( ss58_address='16ADqpMa4yzfmWs3nuTSMhfZ2ckeGtvqhPWCNqECEGDcGgU2', private_key= '0x1f1995bdf3a17b60626a26cfe6f564b337d46056b7a1281b64c649d592ccda0a9cffd34d9fb01cae1fba61aeed184c817442a2186d5172416729a4b54dd4b84e', crypto_type=3) self.assertRaises(ConfigurationError, keypair.sign, "0x1234")
def get_keypair(args, config): enabled_signing_methods = config['Defaults'].keys() & {'signingseed', 'signingmnemonic', 'signinguri'} if (len(enabled_signing_methods) != 1): return None signing_method = list(enabled_signing_methods)[0] if signing_method == 'signingseed': keypair = Keypair.create_from_seed(config['Defaults'].get('signingseed')) if signing_method == 'signingmnemonic': keypair = Keypair.create_from_mnemonic(config['Defaults'].get('signingmnemonic')) if signing_method == 'signinguri': keypair = Keypair.create_from_uri(config['Defaults'].get('signinguri')) return keypair
def regenerate_hotkey(self, mnemonic: Union[list, str], use_password: bool = True, overwrite: bool = False) -> 'Wallet': """ Regenerates the hotkey from passed mnemonic, encrypts it with the user's password and save the file Args: mnemonic: (Union[list, str], optional): Key mnemonic as list of words or string space separated words. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): Will this operation overwrite the hotkey under the same path <wallet path>/<wallet name>/hotkeys/<hotkey> Returns: wallet (bittensor.Wallet): this object with newly created hotkey. """ if isinstance(mnemonic, str): mnemonic = mnemonic.split() if len(mnemonic) not in [12, 15, 18, 21, 24]: raise ValueError( "Mnemonic has invalid size. This should be 12,15,18,21 or 24 words" ) keypair = Keypair.create_from_mnemonic(" ".join(mnemonic)) display_mnemonic_msg(keypair, "hotkey") self.set_hotkey(keypair, encrypt=use_password, overwrite=overwrite) return self
def main(): url = "http://" + sys.argv[1] substrate = SubstrateInterface( url=url, type_registry_preset='default' ) keypair = Keypair.create_from_seed(sys.argv[2]) call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ 'dest': sys.argv[3], 'value': int(sys.argv[4]) * 10**12 } ) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) try: result = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=False) print("Extrinsic '{}' sent".format(result['extrinsic_hash'])) except SubstrateRequestException as e: print("Failed to send: {}".format(e))
def test_hdkd_nested_numeric_hard_path(self): derivation_address = '5Fc3qszVcAXHAmjjm61KcxqvV1kh91jpydE476NjjnJneNdP' derivation_path = '//polkadot//0' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_nested_numeric2_hard_path(self): derivation_address = '5Dr9GrefZzxfeHovyiKUXKYGKRRiTbPhfLo14iYcHKNccN9q' derivation_path = '//1//5000' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_default_to_dev_mnemonic(self): derivation_address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' derivation_path = '//Alice' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def bazaar_initiate_buy(_data): data_ = {} substrate = connect() price = _data['price'] amount = _data['amount'] seller = _data['seller'] mnemonic = _data['mnemonic'] keypair = Keypair.create_from_mnemonic(mnemonic) call = substrate.compose_call(call_module='Bazaar', call_function='initiate_buy', call_params={ 'price': price, 'amount': amount, 'seller': seller }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def test_hdkd_nested_hard_soft_path(self): derivation_address = '5CJGwWiKXSE16WJaxBdPZhWqUYkotgenLUALv7ZvqQ4TXeqf' derivation_path = '//Bob/test' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def get_substrate_address_from_public_key( chain: SubstrateChain, public_key: SubstratePublicKey, ) -> Union[KusamaAddress, PolkadotAddress]: """Return a valid address for the given Substrate chain and public key. Public key: 32 len str, leading '0x' is optional. May raise: - AttributeError: if public key is not a string. - TypeError: if ss58_format is not an int. - ValueError: if public key is not 32 bytes long or the ss58_format is not a valid int. """ if chain == SubstrateChain.KUSAMA: ss58_format = 2 elif chain == SubstrateChain.POLKADOT: ss58_format = 0 else: raise AssertionError(f'Unexpected chain: {chain}') keypair = Keypair( public_key=public_key, ss58_format=ss58_format, ) if chain == SubstrateChain.KUSAMA: return KusamaAddress(keypair.ss58_address) # else can only be polkadot return PolkadotAddress(keypair.ss58_address)
def transfer_token(token, _data): data_ = {} substrate = connect() _to = _data['to'] _amount = _data['amount'] caller = _data['caller'] mnemonic = _data['mnemonic'] keypair = Keypair.create_from_mnemonic(mnemonic) call = substrate.compose_call(call_module='Token', call_function='transfer', call_params={ 'token': token, 'to': _to, 'value': _amount }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def test_hdkd_nested_soft_hard_path(self): derivation_address = '5Cwc8tShrshDJUp1P1M21dKUTcYQpV9GcfSa4hUBNmMdV3Cx' derivation_path = '/Bob//test' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_path_eq_32_bytes(self): derivation_address = '5Ea3JZpvsBN34jiQwVrLiMh5ypaHtPSyM2DWQvLmSRioEmyk' derivation_path = '//rococo-validator-profiled-node-0' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def deserialize_keypair_from_keyfile_data( keyfile_data: bytes) -> 'bittensor.Keypair': """ Deserializes Keypair object from passed keyfile data. Args: keyfile_data ( bytest, required ): Keyfile data as bytes to be loaded. Returns: keypair (bittensor.Keypair): Keypair loaded from bytes. Raises: KeyFileError: Raised if the passed bytest cannot construct a keypair object. """ # Decode from json. keyfile_data = keyfile_data.decode() try: keyfile_dict = dict(json.loads(keyfile_data)) except: string_value = str(keyfile_data) if string_value[:2] == "0x": string_value = ss58_encode(string_value) keyfile_dict = { 'accountId': None, 'publicKey': None, 'secretPhrase': None, 'secretSeed': None, 'ss58Address': string_value } else: raise KeyFileError( 'Keypair could not be created from keyfile data: {}'.format( string_value)) if "secretSeed" in keyfile_dict and keyfile_dict['secretSeed'] != None: return Keypair.create_from_seed(keyfile_dict['secretSeed']) if "secretPhrase" in keyfile_dict and keyfile_dict['secretPhrase'] != None: return Keypair.create_from_mnemonic( mnemonic=keyfile_dict['secretPhrase']) if "ss58Address" in keyfile_dict and keyfile_dict['ss58Address'] != None: return Keypair(ss58_address=keyfile_dict['ss58Address']) else: raise KeyFileError( 'Keypair could not be created from keyfile data: {}'.format( keyfile_dict))
def fulfill(self, contract: ContractInstance, args: dict, res: int) -> None: keypair = Keypair.create_from_private_key( private_key=self.credentials["private_key"], public_key=self.credentials["public_key"], ) # Estimate gas fee predicted_gas = contract.read( keypair, "simple_callback", args={ "request_id": args["request_id"], "callback_addr": args["from"], "result": { "Numeric": res }, }, ) logger.debug( f"[[bold]{self.name}[/]] Estimating gas fee: {predicted_gas.gas_consumed}" ) # Execute call receipt = contract.exec( keypair, "simple_callback", args={ "request_id": args["request_id"], "callback_addr": args["from"], "result": { "Numeric": res }, }, gas_limit=predicted_gas.gas_consumed * 2, ) logger.info( f"[[bold]{self.name}[/]] Callback substrate receipt: {receipt}") if receipt.is_succes: # Log the callback completed events for contract_event in receipt.contract_events: logger.info( f"[[bold]{self.name}[/]] Contract callback events {contract_event.name} {contract_event.docs}: {contract_event.value}" ) else: raise Exception( f"[[bold]{self.name}[/]] Contract fulfill request {args} unsuccessful {receipt.error_message}" ) # Read back the result result = contract.read(keypair, "oracle_results", args={"request_id": args["request_id"]}) logger.info( f"[[bold]{self.name}[/]] Reading the value from contract after the callback {result}", )
def test_only_provide_public_key(self): keypair = Keypair( public_key= '0xe4359ad3e2716c539a1d663ebd0a51bdc5c98a12e663bb4c4402db47828c9446', address_type=0) self.assertEqual(keypair.ss58_address, '16ADqpMa4yzfmWs3nuTSMhfZ2ckeGtvqhPWCNqECEGDcGgU2')
def set_coldkeypub(self, keypair: 'bittensor.Keypair', encrypt: bool = False, overwrite: bool = False) -> 'bittensor.Keyfile': self._coldkeypub = Keypair(ss58_address=keypair.ss58_address) self.coldkeypub_file.set_keypair(self._coldkeypub, encrypt=encrypt, overwrite=overwrite)
def test_hdkd_soft_path(self): mnemonic = 'old leopard transfer rib spatial phone calm indicate online fire caution review' derivation_address = '5GNXbA46ma5dg19GXdiKi5JH3mnkZ8Yea3bBtZAvj7t99P9i' derivation_path = '/Alice' derived_keypair = Keypair.create_from_uri(mnemonic + derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_hard_path(self): mnemonic = 'old leopard transfer rib spatial phone calm indicate online fire caution review' derivation_address = '5FEiH8iuDUw271xbqWTWuB6WrDjv5dnCeDX1CyHubAniXDNN' derivation_path = '//Alice' derived_keypair = Keypair.create_from_uri(mnemonic + derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_create_ed25519_keypair(self): mnemonic = "old leopard transfer rib spatial phone calm indicate online fire caution review" keypair = Keypair.create_from_mnemonic(mnemonic, address_type=0, crypto_type=KeypairType.ED25519) self.assertEqual(keypair.ss58_address, "16dYRUXznyhvWHS1ktUENGfNAEjCawyDzHRtN9AdFnJRc38h")
def get_keypair(args, config): signingseed = get_config(args, config, 'signingseed') signingmnemonic = get_config(args, config, 'signingmnemonic') signinguri = get_config(args, config, 'signinguri') ss58_format = get_ss58_address_format(get_config(args, config, 'network')) if signingseed is not None: keypair = Keypair.create_from_seed(signingseed, ss58_format) elif signingmnemonic is not None: keypair = Keypair.create_from_mnemonic(signingmnemonic, ss58_format) elif signinguri is not None: keypair = Keypair.create_from_uri(signinguri, ss58_format) else: keypair = None return keypair
def test_only_provide_ss58_address(self): keypair = Keypair( ss58_address='16ADqpMa4yzfmWs3nuTSMhfZ2ckeGtvqhPWCNqECEGDcGgU2') self.assertEqual( keypair.public_key, bytes.fromhex( 'e4359ad3e2716c539a1d663ebd0a51bdc5c98a12e663bb4c4402db47828c9446' ))
def setUpClass(cls): cls.kusama_substrate = SubstrateInterface( url=settings.KUSAMA_NODE_URL, ss58_format=2, type_registry_preset='kusama') cls.polkadot_substrate = SubstrateInterface( url=settings.POLKADOT_NODE_URL, ss58_format=0, type_registry_preset='polkadot') module_path = os.path.dirname(__file__) cls.metadata_fixture_dict = load_type_registry_file( os.path.join(module_path, 'fixtures', 'metadata_hex.json')) # Create new keypair mnemonic = Keypair.generate_mnemonic() cls.keypair = Keypair.create_from_mnemonic(mnemonic)
def test_hdkd_multi_lang(self): mnemonic_path = "秘 心 姜 封 迈 走 描 朗 出 莫 人 口//0" keypair = Keypair.create_from_uri( mnemonic_path, language_code=MnemonicLanguageCode.CHINESE_SIMPLIFIED) self.assertNotEqual(keypair, None) # "é" as multibyte unicode character mnemonic_path = "nation armure tympan devancer temporel capsule ogive médecin acheter narquois abrasif brasier//0" keypair = Keypair.create_from_uri( mnemonic_path, language_code=MnemonicLanguageCode.FRENCH) self.assertNotEqual(keypair, None) # "é" as one byte unicode character: mnemonic_path = "nation armure tympan devancer temporel capsule ogive médecin acheter narquois abrasif brasier//0" keypair = Keypair.create_from_uri( mnemonic_path, language_code=MnemonicLanguageCode.FRENCH) self.assertNotEqual(keypair, None)
def test_create_ecdsa_keypair_mnemonic(self): mnemonic = "old leopard transfer rib spatial phone calm indicate online fire caution review" # m/44'/60'/0'/0/0 keypair = Keypair.create_from_mnemonic(mnemonic, crypto_type=KeypairType.ECDSA) self.assertEqual("0xc6A0d8799D596BDd5C30E9ACbe2c63F37c142e35", keypair.ss58_address)
def test_create_ecdsa_keypair_uri(self): mnemonic = "old leopard transfer rib spatial phone calm indicate online fire caution review" suri_0 = f"{mnemonic}/m/44'/60'/0'/0/0" keypair = Keypair.create_from_uri(suri_0, crypto_type=KeypairType.ECDSA) self.assertEqual("0xc6A0d8799D596BDd5C30E9ACbe2c63F37c142e35", keypair.ss58_address) suri_1 = f"{mnemonic}/m/44'/60'/0'/0/1" keypair = Keypair.create_from_uri(suri_1, crypto_type=KeypairType.ECDSA) self.assertEqual("0x571DCd75Cd50852db08951e3A173aC23e44F05c9", keypair.ss58_address)
def test_hdkd_create_uri_correct_ss58format(self): derivation_address = 'HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F' derivation_path = '//Alice' derived_keypair = Keypair.create_from_uri(derivation_path, ss58_format=2) self.assertEqual(derived_keypair.ss58_format, 2) self.assertEqual(derived_keypair.ss58_address, derivation_address)
def run(): try: substrate = SubstrateInterface( url="wss://hk.listen.io/", address_type=42, type_registry_preset='default' ) import time time.sleep(1) keypair = Keypair.create_from_mnemonic("adult hunt thank force make satisfy saddle pumpkin reject very avoid goat") # print("Created address: {}".format(keypair.ss58_address)) mnemonic = Keypair.generate_mnemonic() # 接收方随机生成 keypair1 = Keypair.create_from_mnemonic(mnemonic, 2) # 可以直接调用自己定义的模块 不需要特殊处理 call = substrate.compose_call( call_module='Listen', call_function='air_drop', call_params={ # 接收方 # 'dest': '5GnGKSCitk1QPpMNugtTGX9t6TqzDGvL5BqKzLfHNsLSrwqN', 'des': keypair1.ss58_address, # 'value': 10 * 10**14 } ) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) try: result = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print("Extrinsic '{}' sent and included in block '{}'".format(result['extrinsic_hash'], result['block_hash'])) # substrate.s except SubstrateRequestException as e: print("Failed to send: {}".format(e)) except Exception as e: print(e)