0

I am using Python Substrate Interface (https://github.com/polkascan/py-substrate-interface) to interact with the substrate node.

I need to execute Pallet::Balances::force_transfer function, this function can only be run with the root/sudo account. How I can achieve this please.

1 Answer 1

1

You need to have the Sudo pallet deployed, which is often the case in development networks.
Then you can wrap the call in Sudo::sudo and sign it with the sudo key.

Example of Alice being sudo and stealing funds from Bob via sudo force_transfer;
You can try this code on a substrate --dev node to see it working.

from substrateinterface import SubstrateInterface, Keypair
from substrateinterface.exceptions import SubstrateRequestException

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

# Derive the Alice and Bob accounts
alice = Keypair.create_from_uri('//Alice')
bob = Keypair.create_from_uri('//Bob')

# Query the sudo key
sudo_key = substrate.query(
    module='Sudo',
    storage_function='Key',
)

print("Sudo key: {}".format(sudo_key.value))
if sudo_key.value == alice.ss58_address:
    print("Alice is the sudo key")
else:
    raise Exception("Unknown or no sudo key")

# Alice steals funds from Bob via sudo force_transfer:
call = substrate.compose_call(
    call_module='Balances',
    call_function='force_transfer',
    call_params={
        'source': bob.ss58_address,
        'dest': alice.ss58_address,
        'value': 100000000000000000000,
    }
)
# Wrap it in sudo.
call = substrate.compose_call(
    call_module='Sudo',
    call_function='sudo',
    call_params={
        'call': call.value,
    }
)

# Signed by Alice
extrinsic = substrate.create_signed_extrinsic(call=call, keypair=alice)

try:
    receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)
    print("Extrinsic '{}' sent and included in block '{}'".format(receipt.extrinsic_hash, receipt.block_hash))

except SubstrateRequestException as e:
    print("Failed to send: {}".format(e))
5
  • Thanks @oliver for the help. What if Alice is not a sudo user? Commented Nov 8, 2022 at 13:58
  • 1
    Then you need to use a different mnemonic instead of //Alice. Development chains use Alice, that's why I used it in the example. Commented Nov 8, 2022 at 14:05
  • Thank you very much for the help and your time, What if I wanted to do two transaction with pallet::balances::force_transfer from two diffirent source account, wraps in pallet:utlity::batch and than perform these transaction as a sudo. Can we use a double wraper here? Commented Nov 8, 2022 at 15:27
  • It should be enough to wrap the batch in a sudo since batch propagates the origin. Commented Nov 9, 2022 at 12:26
  • any example of how to do same in rust? :) Commented May 17, 2023 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.