Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Version 2.0 #403

Draft
wants to merge 6 commits into
base: v2.0
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 5 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,16 @@ older or runtimes under development the `ss58_format` (default 42) and other pro

### Balance information of an account
```python
result = substrate.query('System', 'Account', ['F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T'])
result = substrate.runtime.pallet('System').storage('Account').get('F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T')
print(result.value['data']['free']) # 635278638077956496
```
### Create balance transfer extrinsic

```python
call = substrate.compose_call(
call_module='Balances',
call_function='transfer',
call_params={
'dest': '5E9oDs9PjpsBbxXxRE9uMaZZhnBAV38n2ouLB28oecBDdeQo',
'value': 1 * 10**12
}
)

keypair = Keypair.create_from_uri('//Alice')
extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair)

receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)
receipt = substrate.runtime.pallet("Balances").call("transfer_keep_alive").create_extrinsic(
dest='5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
value=1 * 10**15
).sign_and_submit(keypair=keypair, era={'period': 64}, wait_for_inclusion=True)

print(f"Extrinsic '{receipt.extrinsic_hash}' sent and included in block '{receipt.block_hash}'")
```
Expand Down
1 change: 1 addition & 0 deletions examples/assets/flipper-v4.contract

Large diffs are not rendered by default.

69 changes: 69 additions & 0 deletions examples/async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Polkascan Substrate Interface Library
#
# Copyright 2018-2023 Stichting Polkascan (Polkascan Foundation).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import asyncio

from substrateinterface import SubstrateInterface

async def main():

uri = "ws://localhost:9944"

# old non async example
substrate = SubstrateInterface(uri)
print(substrate.rpc_request('system_name', []))

async with SubstrateInterface(uri, use_async=True) as substrate:

async def storage_result_handler(message, update_nr, subscription_id):
for change_storage_key, change_data in message['params']['result']['changes']:
# TODO decode storage key and data
print(f'{change_storage_key}: {change_data}')
# subscription will end when result_handler return a result
# Example usage, keep for 10 updates; will likely end with 10 blocks because of event subscription
if update_nr > 10:
return {'message': 'Task finished', 'subscription_id': subscription_id}

payloads = [
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload(
"state_subscribeStorage",
# storage keys: System.Account Alice, Bob; System.Events
[[
'0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d',
'0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48',
'0x26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7']],
result_handler=storage_result_handler
),
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
substrate.create_request_payload('system_name') ,
]
responses = await substrate.send_rpc_requests(payloads)

for payload in responses:
print(payload.response)


if __name__ == "__main__":
asyncio.run(main())

26 changes: 10 additions & 16 deletions examples/balance_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,23 @@
# logging.basicConfig(level=logging.DEBUG)

substrate = SubstrateInterface(
url="ws://127.0.0.1:9944"
url="ws://127.0.0.1:9944",

)
result = substrate.runtime.api("Core").call("version").execute()
block_hash = substrate.runtime.pallet("System").storage("BlockHash").get(3358739)


keypair = Keypair.create_from_uri('//Alice')
# borrow_rate = substrate.query("Loans", "BorrowRate", [101], block_hash="0x24155c44e47572496091f4a0216155dc6e503150a1f10881c90d3484bbeea7e3")

call = substrate.compose_call(
call_module='Balances',
call_function='transfer',
call_params={
'dest': '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
'value': 1 * 10**15
}
)
receipt = substrate.runtime.pallet("Balances").call("transfer_keep_alive").create_extrinsic(
dest='5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
value=1 * 10**15
).sign_and_submit(keypair=keypair, era={'period': 64}, wait_for_inclusion=True)

extrinsic = substrate.create_signed_extrinsic(
call=call,
keypair=keypair,
era={'period': 64}
)

try:
receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)

print('Extrinsic "{}" included in block "{}"'.format(
receipt.extrinsic_hash, receipt.block_hash
))
Expand Down
2 changes: 1 addition & 1 deletion examples/batch_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

balance_call = substrate.compose_call(
call_module='Balances',
call_function='transfer',
call_function='transfer_keep_alive',
call_params={
'dest': '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
'value': 1 * 10**15
Expand Down
17 changes: 15 additions & 2 deletions examples/create_and_exec_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,33 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json

import os

from scalecodec.types import PortableRegistry, PortableType, Vec
from substrateinterface.contracts import ContractCode, ContractInstance
from substrateinterface import SubstrateInterface, Keypair

# Enable for debugging purposes
import logging
logging.basicConfig(level=logging.DEBUG)

substrate = SubstrateInterface(url='wss://rococo-contracts-rpc.polkadot.io')
with open(os.path.join(os.path.dirname(__file__), 'assets', 'flipper-v4.contract'), 'r') as file:
metadata_dict = json.load(file)

registry = PortableRegistry.new()
registry.deserialize(metadata_dict)


# substrate = SubstrateInterface(url='wss://rococo-contracts-rpc.polkadot.io')
# keypair = Keypair.create_from_mnemonic("image panda soap apart model autumn table they modify mushroom praise remind")
keypair = Keypair.create_from_uri('//Alice')
substrate = SubstrateInterface(url='ws://127.0.0.1:9944')
contract_address = "5DYXHYiH5jPj8orDw5HSFJhmATe8NtmbguG3vs53v8RgSHTW"

# Check if contract is on chain
contract_info = substrate.query("Contracts", "ContractInfoOf", [contract_address])
contract_info = substrate.runtime.pallet("Contracts").storage("ContractInfoOf").get(contract_address)

if contract_info.value:

Expand All @@ -42,6 +53,8 @@
)
else:

code = substrate.contract.bundle()

# Upload WASM code
code = ContractCode.create_from_contract_files(
metadata_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper-v4.json'),
Expand Down
2 changes: 1 addition & 1 deletion examples/extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

substrate = SubstrateInterface(url="wss://rpc.polkadot.io")

substrate.register_extension(SubstrateNodeExtension(max_block_range=100))
substrate.extensions.register(SubstrateNodeExtension(max_block_range=100))

# Search for block number corresponding a specific datetime
block_datetime = datetime(2022, 12, 31, 0, 0, 0)
Expand Down
2 changes: 1 addition & 1 deletion examples/fee_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

call = substrate.compose_call(
call_module='Balances',
call_function='transfer',
call_function='transfer_keep_alive',
call_params={
'dest': '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
'value': 1 * 10**15
Expand Down
18 changes: 6 additions & 12 deletions examples/multisig.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,21 @@
logging.basicConfig(level=logging.DEBUG)

substrate = SubstrateInterface(url="ws://127.0.0.1:9944")

keypair_alice = Keypair.create_from_uri('//Alice', ss58_format=substrate.ss58_format)
keypair_bob = Keypair.create_from_uri('//Bob', ss58_format=substrate.ss58_format)
keypair_charlie = Keypair.create_from_uri('//Charlie', ss58_format=substrate.ss58_format)
keypair_alice = substrate.keyring.create_from_uri('//Alice')
keypair_bob = substrate.keyring.create_from_uri('//Bob')
keypair_charlie = substrate.keyring.create_from_uri('//Charlie')

# Generate multi-sig account from signatories and threshold
multisig_account = substrate.generate_multisig_account(
signatories=[
keypair_alice.ss58_address,
keypair_bob.ss58_address,
keypair_charlie.ss58_address
],
threshold=2
signatories=[keypair_alice, keypair_bob, keypair_charlie], threshold=2
)

call = substrate.compose_call(
call_module='Balances',
call_function='transfer',
call_function='transfer_keep_alive',
call_params={
'dest': keypair_alice.ss58_address,
'value': 3 * 10 ** 3
'value': 4 * 10 ** 3
}
)

Expand Down
4 changes: 3 additions & 1 deletion examples/storage_subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from substrateinterface import SubstrateInterface

import logging
logging.basicConfig(level=logging.DEBUG)

def subscription_handler(storage_key, updated_obj, update_nr, subscription_id):
print(f"Update for {storage_key}: {updated_obj.value}")


substrate = SubstrateInterface(url="ws://127.0.0.1:9944")


# Accounts to track
storage_keys = [
substrate.create_storage_key(
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ eth_utils>=1.3.0,<3
pycryptodome>=3.11.0,<4
PyNaCl>=1.0.1,<2

scalecodec>=1.2.6,<1.3
scalecodec>=2.0.0a1,<3
py-sr25519-bindings>=0.2.0,<1
py-ed25519-zebra-bindings>=1.0,<2
py-bip39-bindings>=0.1.9,<1
Expand Down
Loading