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 serialize_item(self, item): substrate = SubstrateInterface(SUBSTRATE_RPC_URL) data = item.serialize() storage_call = RuntimeStorage.query(self.session).filter_by( module_id='system', name='Account', ).order_by(RuntimeStorage.spec_version.desc()).first() print(storage_call) account = substrate.get_storage( block_hash=None, module='System', function='Account', params=item.id, return_scale_type=storage_call.type_value, hasher=storage_call.type_hasher, metadata_version=SUBSTRATE_METADATA_VERSION ) print('----------------') print(account) data['attributes']['free_balance'] = account['data']['free'] data['attributes']['reserved_balance'] = account['data']['reserved'] data['attributes']['nonce'] = account['nonce'] return data
def on_get(self, req, resp): substrate = SubstrateInterface(SUBSTRATE_RPC_URL) # Get extrinsics json_block = substrate.get_chain_block(req.params.get('block_hash')) if not json_block: resp.status = falcon.HTTP_404 else: extrinsics = json_block['block']['extrinsics'] # Get metadata metadata_decoder = substrate.get_block_metadata( json_block['block']['header']['parentHash']) #result = [{'runtime': substrate.get_block_runtime_version(req.params.get('block_hash')), 'metadata': metadata_result.get_data_dict()}] result = [] for extrinsic in extrinsics: if int(json_block['block']['header']['number'], 16) == 61181: extrinsics_decoder = ExtrinsicsBlock61181Decoder( ScaleBytes(extrinsic), metadata=metadata_decoder) else: extrinsics_decoder = ExtrinsicsDecoder( ScaleBytes(extrinsic), metadata=metadata_decoder) result.append(extrinsics_decoder.decode()) resp.status = falcon.HTTP_201 resp.media = result
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 __init__(self, config: 'Munch' = None, network: str = None, chain_endpoint: str = None): r""" Initializes a subtensor chain interface. Args: config (:obj:`Munch`, `optional`): metagraph.Metagraph.config() network (default='akira', type=str) The subtensor network flag. The likely choices are: -- akira (testing network) -- kusanagi (main network) If this option is set it overloads subtensor.chain_endpoint with an entry point node from that network. chain_endpoint (default=None, type=str) The subtensor endpoint flag. If set, overrides the --network flag. """ if config == None: config = Subtensor.default_config() config.subtensor.network = network if network != None else config.subtensor.network config.subtensor.chain_endpoint = chain_endpoint if chain_endpoint != None else config.subtensor.chain_endpoint Subtensor.check_config(config) self.config = copy.deepcopy(config) chain_endpoint = "ws://subtensor.rawatech.com:9944" if not chain_endpoint else "ws://" + chain_endpoint # chain_endpoint = "ws://feynman.kusanagi.bittensor.com:9944" if not chain_endpoint else "ws://" + chain_endpoint self.substrate = SubstrateInterface( ss58_format=42, type_registry_preset='substrate-node-template', type_registry=self.custom_type_registry, url=chain_endpoint)
def cmd_list(args, config): substrate = SubstrateInterface(url=get_config(args, config, 'rpcurl'), type_registry_preset=get_type_preset( get_config(args, config, 'network'))) active_era = substrate.query(module='Staking', storage_function='ActiveEra') active_era = active_era.value['index'] depth = get_config(args, config, 'deptheras') depth = int(depth) if depth is not None else 84 start = active_era - depth end = active_era eras_payment_info = get_eras_payment_info_filtered( substrate, start, end, accounts=get_included_accounts(args, config), only_unclaimed=args.only_unclaimed) eras_payment_info = OrderedDict( sorted(eras_payment_info.items(), reverse=True)) for era_index, era in eras_payment_info.items(): print(f"Era: {era_index}") for accountId in era: msg = "claimed" if era[accountId]['claimed'] else "unclaimed" formatted_amount = format_balance_to_symbol( substrate, era[accountId]['amount'], substrate.token_decimals) print(f"\t {accountId} => {formatted_amount} ({msg})")
def _get_last_block(self, node_interface: SubstrateInterface) -> BlockNumber: """Return the chain height. """ log.debug(f'{self.chain} querying last block', url=node_interface.url) try: last_block = node_interface.get_block_number( block_hash=node_interface.get_chain_head(), ) except ( requests.exceptions.RequestException, SubstrateRequestException, # TODO: remove TypeError once py-susbtrate-interface `get_block_number` # handles a None response. Keep ValueError just in case `get_chain_head` # returns None. # https://github.com/polkascan/py-substrate-interface/issues/68 TypeError, ValueError, ) as e: message = ( f'{self.chain} failed to request last block ' f'at endpoint: {node_interface.url} due to: {str(e)}.' ) log.error(message) raise RemoteError(message) from e log.debug(f'{self.chain} last block', last_block=last_block) return BlockNumber(last_block)
def _get_last_block(self, node_interface: SubstrateInterface) -> BlockNumber: """Return the chain height. May raise: - RemoteError if there is an error """ log.debug(f'{self.chain} querying last block', url=node_interface.url) try: last_block = node_interface.get_block_number( block_hash=node_interface.get_chain_head(), ) if last_block is None: # For some reason a node can rarely return None as last block raise SubstrateRequestException( f'{self.chain} node failed to request last block. Returned None', ) except ( requests.exceptions.RequestException, SubstrateRequestException, WebSocketException, ValueError, ) as e: message = ( f'{self.chain} failed to request last block ' f'at endpoint: {node_interface.url} due to: {str(e)}.' ) log.error(message) raise RemoteError(message) from e log.debug(f'{self.chain} last block', last_block=last_block) return BlockNumber(last_block)
def on_get(self, req, resp): substrate = SubstrateInterface(SUBSTRATE_RPC_URL) resp.status = falcon.HTTP_200 current_era = substrate.get_storage( block_hash= "0x519fc882113d886615ad5c7a93f8319640270ab8a09546798f7f8d973a99b017", module="Staking", function="CurrentEra", return_scale_type='BlockNumber') # Retrieve validator for new session from storage validators = substrate.get_storage( block_hash= "0x519fc882113d886615ad5c7a93f8319640270ab8a09546798f7f8d973a99b017", module="Session", function="Validators", return_scale_type='Vec<AccountId>') or [] # for validator in validators: # storage_bytes = substrate.get_storage("0x904871d0e6284c0555134fa187891580979a2fc426a4f8873a8d15d8cca6020f", # "Balances", "FreeBalance", validator.replace('0x', '')) # #print(validator.replace('0x', '')) # # if storage_bytes: # obj = ScaleDecoder.get_decoder_class('Balance', ScaleBytes(storage_bytes)) # nominators.append(obj.decode()) resp.media = {'validators': validators, 'current_era': current_era}
def balance_snapshot(self, account_id=None, block_start=1, block_end=None, block_ids=None): if account_id: accounts = [account_id] else: accounts = [account.id for account in Account.query(self.session)] harvester = PolkascanHarvesterService( db_session=self.session, type_registry=TYPE_REGISTRY, type_registry_file=TYPE_REGISTRY_FILE ) if block_ids: block_range = block_ids else: if block_end is None: # Set block end to chaintip substrate = SubstrateInterface(url=SUBSTRATE_RPC_URL, runtime_config=RuntimeConfiguration()) block_end = substrate.get_block_number(substrate.get_chain_finalised_head()) block_range = range(block_start, block_end + 1) for block_id in block_range: for account in accounts: harvester.create_balance_snapshot(block_id, account) self.session.commit() return { 'message': 'Snapshop created', 'account_id': account_id, 'block_start': block_start, 'block_end': block_end, 'block_ids': block_ids }
def start_init(self): if self.init: print('start_init task is running : '.format(self.init)) return {'result': 'waiting init task completed! '} n = Block.query(self.session).filter_by(bid=1).count() if n >= 4: print(' init task is completed! count().n: {} '.format(n)) return {'result': ' init task is completed! '} self.init = True print("start_init") for shard in SHARDS_TABLE: substrate_url = SHARDS_TABLE[shard] substrate = SubstrateInterface(substrate_url) start_block_hash = substrate.get_block_hash(3) print('== start_init substrate_url {} ==start_block_hash-{}'.format( substrate_url, start_block_hash)) end_block_hash = None accumulate_block_recursive.delay(start_block_hash, end_block_hash, substrate_url) return { 'result': 'start_init job started', 'SHARDS_TABLE': SHARDS_TABLE, 'init_task_id': self.request.id }
def on_post(self, req, resp): msg = "TODO" if req.media.get('account_id'): account = Account.query(self.session).filter(Account.id == req.media.get('account_id')).first() if account: substrate = SubstrateInterface(SUBSTRATE_RPC_URL) balance = substrate.get_storage( block_hash=None, module='Balances', function='FreeBalance', params=account.id, return_scale_type='Balance', hasher='Blake2_256') or 0 account.balance = balance self.session.commit() resp.media = { 'status': 'success', 'data': { 'message': msg } } else: resp.status = falcon.HTTP_404 resp.media = {'result': 'Account not found'}
def on_get(self, req, resp): substrate = SubstrateInterface( url=SUBSTRATE_RPC_URL, runtime_config=RuntimeConfiguration(), type_registry_preset=settings.TYPE_REGISTRY ) # Get extrinsics json_block = substrate.get_chain_block(req.params.get('block_hash')) if not json_block: resp.status = falcon.HTTP_404 else: extrinsics = json_block['block']['extrinsics'] # Get metadata metadata_decoder = substrate.get_block_metadata(json_block['block']['header']['parentHash']) #result = [{'runtime': substrate.get_block_runtime_version(req.params.get('block_hash')), 'metadata': metadata_result.get_data_dict()}] result = [] for extrinsic in extrinsics: extrinsics_decoder = ExtrinsicsDecoder(ScaleBytes(extrinsic), metadata=metadata_decoder) result.append(extrinsics_decoder.decode()) resp.status = falcon.HTTP_201 resp.media = result
def check_healthy(): for shard in SHARDS_TABLE: substrate_url = SHARDS_TABLE[shard] substrate = SubstrateInterface(substrate_url) block = substrate.get_block_number(None) print('== shard--{} ===substrate_url###{}==block=={} '.format( shard, substrate_url, block))
def register(domain, name, ip_addr, info, key): substrate = SubstrateInterface(url="http://127.0.0.1:9933", ss58_format=42, type_registry_preset='polkadot', type_registry={ "types": { "Certificate": { "type": "struct", "type_mapping": [["version_number", "i32"], ["owner_id", "AccountId"], ["name", "Vec<u8>"], ["info", "Vec<u8>"], ["key", "Vec<u8>"], ["ip_addr", "Vec<u8>"], ["domain", "Vec<u8>"]] } } }) keypair = Keypair.create_from_uri('//Alice') call = substrate.compose_call(call_module='SiipModule', call_function='register_certificate', call_params={ 'name': name, 'domain': domain, 'ip_addr': ip_addr, 'info': info, 'key': key, }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) return substrate.submit_extrinsic(extrinsic)
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') cls.substrate_v13 = 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')) cls.metadata_v13_obj = cls.substrate_v13.runtime_config.create_scale_object( 'MetadataVersioned', data=ScaleBytes(cls.metadata_fixture_dict['V13'])) cls.metadata_v13_obj.decode() cls.substrate_v13.init_runtime() cls.substrate_v13.metadata_decoder = cls.metadata_v13_obj # Create new keypair mnemonic = Keypair.generate_mnemonic() cls.keypair = Keypair.create_from_mnemonic(mnemonic)
def on_post(self, req, resp): block_hash = None if req.media.get('block_id'): substrate = SubstrateInterface( url=SUBSTRATE_RPC_URL, runtime_config=RuntimeConfiguration(), type_registry_preset=settings.TYPE_REGISTRY) block_hash = substrate.get_block_hash(req.media.get('block_id')) elif req.media.get('block_hash'): block_hash = req.media.get('block_hash') else: resp.status = falcon.HTTP_BAD_REQUEST resp.media = { 'errors': ['Either block_hash or block_id should be supplied'] } if block_hash: print('Processing {} ...'.format(block_hash)) harvester = PolkascanHarvesterService( db_session=self.session, type_registry=TYPE_REGISTRY, type_registry_file=TYPE_REGISTRY_FILE + '-mst') block = Block.query( self.session).filter(Block.hash == block_hash).first() if block: resp.status = falcon.HTTP_200 resp.media = { 'result': 'already exists', 'parentHash': block.parent_hash } else: amount = req.media.get('amount', 1) for nr in range(0, amount): try: block = harvester.add_block(block_hash) except BlockAlreadyAdded as e: print('Skipping {}'.format(block_hash)) block_hash = block.parent_hash if block.id == 0: break self.session.commit() resp.status = falcon.HTTP_201 resp.media = { 'result': 'added', 'parentHash': block.parent_hash } else: resp.status = falcon.HTTP_404 resp.media = {'result': 'Block not found'}
def setUpClass(cls): cls.kusama_substrate = SubstrateInterface( url=settings.KUSAMA_NODE_URL, address_type=2, type_registry_preset='kusama') cls.polkadot_substrate = SubstrateInterface( url=settings.POLKADOT_NODE_URL, address_type=0, type_registry_preset='polkadot')
def on_get(self, req, resp): if 'block_hash' in req.params: substrate = SubstrateInterface(SUBSTRATE_RPC_URL) metadata = substrate.get_block_metadata(req.params.get('block_hash')) resp.status = falcon.HTTP_200 resp.media = metadata.value else: resp.status = falcon.HTTP_BAD_REQUEST
def get_fee_info(signed_extrinsic): substrate = SubstrateInterface( url=settings.NODE_URL, address_type=2, type_registry_preset="kusama", ) fee_info = substrate.rpc_request( "payment_queryInfo", [signed_extrinsic], ).get("result") return fee_info
def accumulation_hook(self, db_session): if self.extrinsic.success: vote_account_id = self.extrinsic.address stash_account_id = self.extrinsic.address # TODO refactor when new runtime aware substrateinterface # TODO make substrateinterface part of processor over websockets # Get balance of stash_account substrate = SubstrateInterface(SUBSTRATE_RPC_URL) storage_call = RuntimeStorage.query(db_session).filter_by( module_id='balances', name='FreeBalance', ).order_by(RuntimeStorage.spec_version.desc()).first() stash = substrate.get_storage( block_hash=self.block.hash, module='Balances', function='FreeBalance', params=stash_account_id, return_scale_type=storage_call.type_value, hasher=storage_call.type_hasher) vote_audit = DemocracyVoteAudit( block_id=self.extrinsic.block_id, extrinsic_idx=self.extrinsic.extrinsic_idx, type_id=DEMOCRACY_VOTE_AUDIT_TYPE_NORMAL, data={ 'vote_account_id': vote_account_id, 'stash_account_id': stash_account_id, 'stash': stash }) # Process parameters for param in self.extrinsic.params: if param.get('name') == 'ref_index': vote_audit.democracy_referendum_id = param.get('value') if param.get('name') == 'vote': vote_audit.data['vote_raw'] = param.get('value') vote_audit.data['vote_yes'] = bool( vote_audit.data['vote_raw']) vote_audit.data['vote_no'] = not bool( vote_audit.data['vote_raw']) # Determine conviction and weight of vote vote_audit.data['conviction'] = vote_audit.data[ 'vote_raw'] & Conviction.CONVICTION_MASK vote_audit.data['vote_yes_weighted'] = int( vote_audit.data['vote_yes']) * vote_audit.data['stash'] vote_audit.data['vote_no_weighted'] = int( vote_audit.data['vote_no']) * vote_audit.data['stash'] vote_audit.save(db_session)
def serialize_item(self, item): address = bech32.encode(HRP, bytes().fromhex(item.id)) substrate = SubstrateInterface( SUBSTRATE_RPC_URL, metadata_version=SUBSTRATE_METADATA_VERSION) data = item.serialize() data['attributes']['free_balance'] = int( substrate.get_Balance(address), 16) data['attributes']['nonce'] = int(substrate.get_Nonce(address), 16) return data
def create_MnemonicKey(self): substrate = SubstrateInterface(url=self.url, address_type=42, type_registry_preset='polkadot') # keypair=Keypair.create_from_seed("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a") #alice账号 file_name = open('account_info.csv', encoding='utf-8') csv_lines = csv.reader(file_name) data = [] for row in csv_lines: if csv_lines.line_num == 1: continue else: data.append(row) print("data", data) for info in data: print("info", info) account = info[0] keypair = Keypair.create_from_mnemonic(self.seed_secret) # keypair = Keypair.create_from_mnemonic(info[1]) amount = info[1] print("type", type(amount)) call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ # 接收方 'dest': account, 'value': Decimal(amount) * 10**10 }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) try: result = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print(result) print("Extrinsic '{}' sent and included in block '{}'".format( result['extrinsic_hash'], result['block_hash'])) except SubstrateRequestException as e: print(e) with open("faild_info.txt", "a") as f: f.write(account + "\n") time.sleep(5)
class ReloadTypeRegistryTestCase(unittest.TestCase): def setUp(self) -> None: self.substrate = SubstrateInterface(url='dummy', ss58_format=42, type_registry_preset='test') def test_initial_correct_type_local(self): decoding_class = self.substrate.runtime_config.type_registry['types'][ 'blocknumber'] self.assertEqual( self.substrate.runtime_config.get_decoder_class('u64'), decoding_class) def test_reloading_use_remote_preset(self): # Intentionally overwrite type in local preset u32_cls = self.substrate.runtime_config.get_decoder_class('u32') u64_cls = self.substrate.runtime_config.get_decoder_class('u64') self.substrate.runtime_config.type_registry['types'][ 'blocknumber'] = u32_cls self.assertEqual( u32_cls, self.substrate.runtime_config.get_decoder_class('BlockNumber')) # Reload type registry self.substrate.reload_type_registry() self.assertEqual( u64_cls, self.substrate.runtime_config.get_decoder_class('BlockNumber')) def test_reloading_use_local_preset(self): # Intentionally overwrite type in local preset u32_cls = self.substrate.runtime_config.get_decoder_class('u32') u64_cls = self.substrate.runtime_config.get_decoder_class('u64') self.substrate.runtime_config.type_registry['types'][ 'blocknumber'] = u32_cls self.assertEqual( u32_cls, self.substrate.runtime_config.get_decoder_class('BlockNumber')) # Reload type registry self.substrate.reload_type_registry(use_remote_preset=False) self.assertEqual( u64_cls, self.substrate.runtime_config.get_decoder_class('BlockNumber'))
def main(): url = "http://" + sys.argv[1] substrate = SubstrateInterface(url=url, type_registry_preset='default') balance_info = substrate.get_runtime_state(module='System', storage_function='Account', params=[sys.argv[2] ]).get('result') if balance_info: print("\n\nCurrent free balance: {}".format( balance_info.get('data').get('free', 0) / 10**12))
def result_handler(result): if result.get("method", "") == "chain_newHead": number = result['params']['result']['number'] substrate_connection = SubstrateInterface(url=rpc_url) block_hash = substrate_connection.get_block_hash(number) block_events = substrate_connection.get_runtime_events( block_hash=block_hash).get('result') print(int(number, 16), block_hash) for block_event in block_events: module_id = block_event['module_id'] event_id = block_event['event_id'] if module_id == "Staking" and event_id == "EraPayout": print(f"{module_id}.{event_id}") publisher.publish(topic_path, b' ')
def serialize_item(self, item): substrate = SubstrateInterface( SUBSTRATE_RPC_URL, metadata_version=SUBSTRATE_METADATA_VERSION) return { 'type': 'account', 'id': item.address, 'attributes': { 'id': item.id, 'address': item.address, 'balance': int(substrate.get_Balance(item.address), 16), 'shard_num': item.shard_num } }
def on_get(self, req, resp): if 'block_hash' in req.params: substrate = SubstrateInterface( url=settings.SUBSTRATE_RPC_URL, runtime_config=RuntimeConfiguration(), type_registry_preset=settings.TYPE_REGISTRY ) metadata = substrate.get_block_metadata(req.params.get('block_hash')) resp.status = falcon.HTTP_200 resp.media = metadata.value else: resp.status = falcon.HTTP_BAD_REQUEST
def __init__(self, db_session, type_registry='default', type_registry_file=None): self.db_session = db_session if type_registry_file: custom_type_registry = load_type_registry_file(type_registry_file) else: custom_type_registry = None self.substrate = SubstrateInterface( url=settings.SUBSTRATE_RPC_URL, type_registry=custom_type_registry, type_registry_preset=type_registry ) self.metadata_store = {}
def get_extrinsic_events(extrinsic_time_point): substrate = SubstrateInterface( url=settings.NODE_URL, address_type=2, type_registry_preset="kusama", ) extrinsic_events = [] block_hash = substrate.get_block_hash(extrinsic_time_point[0]) block_events = substrate.get_runtime_events(block_hash).get("result") for event in block_events: if event["extrinsic_idx"] == extrinsic_time_point[1]: # Todo, only get required event data # Perhaps just event_id and params? extrinsic_events.append(event) return extrinsic_events