Пример #1
0
    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)
Пример #2
0
    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, network_id=None):
        resp.status = falcon.HTTP_200

        # TODO make caching more generic for custom resources

        cache_key = '{}-{}'.format(req.method, req.url)
        console_handler = logging.StreamHandler()
        console_handler.setLevel('INFO')
        logger = logging.getLogger('yee')
        logger.setLevel('INFO')
        logger.addHandler(console_handler)
        # logger.info(cache_key)

        response = self.cache_region.get(cache_key, self.cache_expiration_time)

        if response is NO_VALUE:
            substrate01 = SubstrateInterface(SHARDS_TABLE['shard.0'])
            substrate02 = SubstrateInterface(SHARDS_TABLE['shard.1'])
            substrate03 = SubstrateInterface(SHARDS_TABLE['shard.2'])
            substrate04 = SubstrateInterface(SHARDS_TABLE['shard.3'])

            shard01 = substrate01.get_block_header(None)
            shard01['finalizedNum'] = substrate01.get_block_number(
                substrate01.get_chain_finalised_head())
            shard02 = substrate02.get_block_header(None)
            shard02['finalizedNum'] = substrate02.get_block_number(
                substrate02.get_chain_finalised_head())
            shard03 = substrate03.get_block_header(None)
            shard03['finalizedNum'] = substrate03.get_block_number(
                substrate03.get_chain_finalised_head())
            shard04 = substrate04.get_block_header(None)
            shard04['finalizedNum'] = substrate04.get_block_number(
                substrate04.get_chain_finalised_head())
            response = self.get_jsonapi_response(data={
                'type': 'FinalizedHeadList',
                'attributes': {
                    'shard01': shard01,
                    'shard02': shard02,
                    'shard03': shard03,
                    'shard04': shard04
                }
            }, )

            self.cache_region.set(cache_key, response)
            resp.set_header('X-Cache', 'MISS')
        else:
            resp.set_header('X-Cache', 'HIT')

        resp.media = response
Пример #4
0
    def setUpClass(cls):

        cls.substrate = SubstrateInterface(url='dummy', ss58_format=42, type_registry_preset='kusama')
        metadata_decoder = MetadataDecoder(ScaleBytes(metadata_v12_hex))
        metadata_decoder.decode()
        cls.substrate.get_block_metadata = MagicMock(return_value=metadata_decoder)

        def mocked_request(method, params):
            if method == 'chain_getRuntimeVersion':
                return {
                    "jsonrpc": "2.0",
                    "result": {"specVersion": 2023},
                    "id": 1
                }
            elif method == 'chain_getHeader':
                return {
                    "jsonrpc": "2.0",
                    "result": {
                        "digest": {
                            "logs": [
                            ]
                        },
                        "extrinsicsRoot": "0xa94148d938c7b7976abf4272dca95724d7a74da2f3649ec0bd53dc3daaedda44",
                        "number": "0x4abaaa",
                        "parentHash": "0xe1781813275653a970b4260298b3858b36d38e072256dad674f7c786a0cae236",
                        "stateRoot": "0xb6aa468385c82d15b343a676b3488d9f141ac100fc548bb8a546f27a7241c44a"
                    },
                    "id": 1
                }

        cls.substrate.rpc_request = MagicMock(side_effect=mocked_request)

        cls.empty_substrate = SubstrateInterface(url='dummy', ss58_format=42, type_registry_preset='kusama')

        def mocked_request(method, params):

            return {'jsonrpc': '2.0', 'result': None, 'id': 1}

        cls.empty_substrate.rpc_request = MagicMock(side_effect=mocked_request)

        cls.error_substrate = SubstrateInterface(url='dummy', ss58_format=42, type_registry_preset='kusama')

        def mocked_request(method, params):
            return {'jsonrpc': '2.0', 'error': {
                'code': -32602, 'message': 'Generic error message'
            }, 'id': 1}

        cls.error_substrate.rpc_request = MagicMock(side_effect=mocked_request)
Пример #5
0
    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
Пример #6
0
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})")
Пример #7
0
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))
Пример #8
0
    def setUpClass(cls):
        cls.env = SubstrateTestEnv.create_europa(port=39944)
        cls.env.start_node()
        substrate=SubstrateInterface(url=cls.env.url(), type_registry_preset=cls.env.typ(), type_registry=cls.env.types())

        cls.subscriber = SubstrateSubscriber(substrate)
        cls.substrate = substrate
Пример #9
0
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
    }
Пример #10
0
    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'}
Пример #11
0
    def setUpClass(cls):
        logging.info("init deplay")

        cls.env = SubstrateTestEnv.create_europa(port=39944)
        cls.env.start_node()
        cls.substrate = SubstrateInterface(url=cls.env.url(),
                                           type_registry_preset=cls.env.typ(),
                                           type_registry=cls.env.types())

        cls.contract_metadata = ContractMetadata.create_from_file(
            metadata_file=os.path.join(os.path.dirname(__file__), 'constracts',
                                       'ink', 'erc20.json'),
            substrate=cls.substrate)

        cls.erc20 = ERC20.create_from_contracts(
            substrate=cls.substrate,
            contract_file=os.path.join(os.path.dirname(__file__), 'constracts',
                                       'ink', 'erc20.wasm'),
            metadata_file=os.path.join(os.path.dirname(__file__), 'constracts',
                                       'ink', 'erc20.json'))
        cls.alice = Keypair.create_from_uri('//Alice')
        cls.bob = Keypair.create_from_uri('//Bob')

        cls.erc20.instantiate_with_code(cls.alice, 1000000 * (10**15))

        cls.observer = ERC20Observer.create_from_address(
            substrate=cls.substrate,
            contract_address=cls.erc20.contract_address,
            metadata_file=os.path.join(os.path.dirname(__file__), 'constracts',
                                       'ink', 'erc20.json'))
def with_custom_type_registry(custom_type_registry):

    substrate = SubstrateInterface(url=URL,
                                   # address_type=42, 
                                   type_registry_preset='default', 
                                   type_registry=custom_type_registry)
    return substrate
Пример #13
0
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))
Пример #14
0
def main():
    # use [europa](https://github.com/patractlabs/europa) as test node endpoint, notice `type_registry` should set correctly.
    substrate=SubstrateInterface(url='ws://127.0.0.1:9944', type_registry_preset="default", type_registry={'types': {'LookupSource': 'MultiAddress'}})
    # load deployer key
    alice = Keypair.create_from_uri('//Alice')
    bob = Keypair.create_from_uri('//Bob')

    factory = ContractFactory.create_from_file(
        substrate=substrate, 
        code_file=os.path.join(os.path.dirname(__file__), 'contract', 'erc20.wasm'),
        metadata_file=os.path.join(os.path.dirname(__file__), 'contract', 'erc20.json')
    )

    auto_api = factory.new(alice, 1000000 * (10 ** 15), endowment=10**15, gas_limit=1000000000000)

    # api will auto generate caller for contract from metadata
    # this api is for test
    api = ContractAPI(auto_api.contract_address, factory.metadata, substrate)
    alice_balance_old = api.balance_of(bob, alice.ss58_address) # bob is the keypair for `//Bob`

    res = api.transfer(alice, bob.ss58_address, 100000, gas_limit=20000000000)
    print(f'transfer res {res.error_message}')
    print(res.is_success)

    alice_balance = api.balance_of(bob, alice.ss58_address)
    print(f'transfer alice_balance from {alice_balance_old} to {alice_balance}')

    bob_balance = api.balance_of(bob, bob.ss58_address)
    print(f'transfer bob_balance {bob_balance}')
Пример #15
0
    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
Пример #16
0
    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}
Пример #17
0
    def _get_node_interface(self, endpoint: str) -> SubstrateInterface:
        """Get an instance of SubstrateInterface, a specialized class in
        interfacing with a Substrate node that deals with SCALE encoding/decoding,
        metadata parsing, type registry management and versioning of types.

        May raise (most common):
        - RemoteError: from RequestException, problems requesting the url.
        - FileNotFound: via `load_type_registry_preset()` if it doesn't exist
        a preset file for the given `type_registry_preset` argument.
        - ValueError and TypeError: invalid constructor arguments.
        """
        si_attributes = self.chain.substrate_interface_attributes()
        try:
            node_interface = SubstrateInterface(
                url=endpoint,
                type_registry_preset=si_attributes.type_registry_preset,
                use_remote_preset=True,
            )
        except (requests.exceptions.RequestException, WebSocketException, SubstrateRequestException) as e:  # noqa: E501
            message = (
                f'{self.chain} could not connect to node at endpoint: {endpoint}. '
                f'Connection error: {str(e)}.'
            )
            log.error(message)
            raise RemoteError(message) from e
        except (FileNotFoundError, ValueError, TypeError) as e:
            message = (
                f'{self.chain} could not connect to node at endpoint: {endpoint}. '
                f'Unexpected error during SubstrateInterface instantiation: {str(e)}.'
            )
            log.error(message)
            raise RemoteError('Invalid SubstrateInterface instantiation') from e

        return node_interface
    def setUpClass(cls):

        metadata_decoder = MetadataDecoder(ScaleBytes(metadata_v10_hex))
        metadata_decoder.decode()

        cls.substrate = SubstrateInterface(url='dummy', address_type=2, type_registry_preset='kusama')
        cls.substrate.get_block_metadata = MagicMock(return_value=metadata_decoder)
Пример #19
0
    def test_env_canvas(self):
        # init api
        substrate = SubstrateInterface(url=self.env.url(),
                                       type_registry_preset=self.env.typ(),
                                       type_registry=self.env.types())

        alice = Keypair.create_from_uri('//Alice')
        bob = Keypair.create_from_uri('//Bob')

        # erc20 api
        erc20 = ERC20.create_from_contracts(
            substrate=substrate,
            contract_file=os.path.join(os.path.dirname(__file__), 'constracts',
                                       'ink', 'erc20.wasm'),
            metadata_file=os.path.join(os.path.dirname(__file__), 'constracts',
                                       'ink', 'erc20.json'))

        # deplay a erc20 contract
        erc20.instantiate_with_code(alice, 1000000 * (10**15))

        erc20.transfer_from(alice,
                            from_acc=alice.ss58_address,
                            to_acc=bob.ss58_address,
                            amt=10000)

        erc20.transfer(alice, bob.ss58_address, 10000)
Пример #20
0
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 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 setUpClass(cls):

        cls.kusama_substrate = SubstrateInterface(
            url=settings.KUSAMA_NODE_URL,
            ss58_format=2,
            type_registry_preset='kusama')

        orig_rpc_request = cls.kusama_substrate.rpc_request

        def mocked_request(method, params):
            if method == 'state_getKeysPaged':
                if params[
                        3] == '0x2e8047826d028f5cc092f5e694860efbd4f74ee1535424cdf3626a175867db62':

                    if params[2] == params[0]:
                        return {
                            'jsonrpc':
                            '2.0',
                            'result': [
                                '0x9c5d795d0297be56027a4b2464e333979c5d795d0297be56027a4b2464e3339700000a9c44f24e314127af63ae55b864a28d7aee',
                                '0x9c5d795d0297be56027a4b2464e333979c5d795d0297be56027a4b2464e3339700002f21194993a750972574e2d82ce8c95078a6',
                                '0x9c5d795d0297be56027a4b2464e333979c5d795d0297be56027a4b2464e333970000a940f973ccf435ae9c040c253e1c043c5fb2',
                                '0x9c5d795d0297be56027a4b2464e333979c5d795d0297be56027a4b2464e3339700010b75619f666c3f172f0d1c7fa86d02adcf9c'
                            ],
                            'id':
                            8
                        }
                    else:
                        return {'jsonrpc': '2.0', 'result': [], 'id': 8}
            return orig_rpc_request(method, params)

        cls.kusama_substrate.rpc_request = MagicMock(
            side_effect=mocked_request)
Пример #23
0
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
    }
Пример #24
0
    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)
Пример #25
0
    def setUpClass(cls):
        cls.polkadot_substrate = SubstrateInterface(
            url=settings.POLKADOT_NODE_URL,
            ss58_format=0,
            type_registry_preset='polkadot',
            type_registry={'types': {
                'TestType': 'u8'
            }})

        cls.kusama_substrate = SubstrateInterface(
            url=settings.KUSAMA_NODE_URL,
            ss58_format=2,
            type_registry_preset='kusama',
            type_registry={'types': {
                'TestType': 'u16'
            }})
Пример #26
0
    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 on_get(self, req, resp):

        sequencer_task = Status.get_status(self.session, 'SEQUENCER_TASK_ID')
        integrity_head = Status.get_status(self.session, 'INTEGRITY_HEAD')
        sequencer_head = self.session.query(func.max(BlockTotal.id)).one()[0]
        best_block = Block.query(self.session).filter_by(
            id=self.session.query(func.max(Block.id)).one()[0]).first()

        if best_block:
            best_block_datetime = best_block.datetime.replace(tzinfo=pytz.UTC).timestamp() * 1000
            best_block_nr = best_block.id
        else:
            best_block_datetime = None
            best_block_nr = None

        substrate = SubstrateInterface(SUBSTRATE_RPC_URL)
        chain_head_block_id = substrate.get_block_number(substrate.get_chain_head())
        chain_finalized_block_id = substrate.get_block_number(substrate.get_chain_finalised_head())

        resp.media = {
            'best_block_datetime': best_block_datetime,
            'best_block_nr': best_block_nr,
            'sequencer_task': sequencer_task.value,
            'sequencer_head': sequencer_head,
            'integrity_head': int(integrity_head.value),
            'chain_head_block_id': chain_head_block_id,
            'chain_finalized_block_id': chain_finalized_block_id
        }
Пример #28
0
def main():
    # use [europa](https://github.com/patractlabs/europa) as test node endpoint, notice `type_registry` should set correctly.
    substrate = SubstrateInterface(
        url='ws://127.0.0.1:9944',
        type_registry_preset="default",
        type_registry={'types': {
            'LookupSource': 'MultiAddress'
        }})
    # load deployer key
    alice = Keypair.create_from_uri('//Alice')
    bob = Keypair.create_from_uri('//Bob')

    # 1. load a contract from WASM file and metadata.json file (Those files is complied by [ink!](https://github.com/paritytech/ink))
    # in this example, we use `ink/example/erc20` contract as example.
    factory = ContractFactory.create_from_file(
        substrate=substrate,
        code_file=os.path.join(os.path.dirname(__file__), 'contract',
                               'erc20.wasm'),
        metadata_file=os.path.join(os.path.dirname(__file__), 'contract',
                                   'erc20.json'))

    # this api is `ContractAPI`
    api = factory.new(alice,
                      1000000 * (10**15),
                      endowment=10**15,
                      gas_limit=1000000000000)
    print(api.contract_address)  # contract_address is the deployed contract
Пример #29
0
    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'}
Пример #30
0
    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)