|
| 1 | +"""Example exercise: find the validators with the 3 lowest commission rates on |
| 2 | +Autonity Piccadilly Testnet and delegate 100 NTN to each. |
| 3 | +""" |
| 4 | + |
| 5 | +import os |
| 6 | +from typing import cast |
| 7 | + |
| 8 | +from autonity import networks |
| 9 | +from autonity.factories import Autonity |
| 10 | +from autonity.contracts.autonity import ValidatorState |
| 11 | +from web3 import Web3 |
| 12 | +from web3.middleware import Middleware, SignAndSendRawMiddlewareBuilder |
| 13 | + |
| 14 | + |
| 15 | +# Use the RPC provider pre-configured for the Autonity Piccadilly Testnet |
| 16 | +w3 = Web3(networks.piccadilly.http_provider) |
| 17 | + |
| 18 | +# Load account and set it as the default sender |
| 19 | +account = w3.eth.account.from_key(os.environ["PRIVATE_KEY"]) |
| 20 | +w3.eth.default_account = account.address |
| 21 | + |
| 22 | +# Also set it as the default signer |
| 23 | +signer_middleware = cast(Middleware, SignAndSendRawMiddlewareBuilder.build(account)) |
| 24 | +w3.middleware_onion.add(signer_middleware) |
| 25 | + |
| 26 | +# Create binding around the Autonity contract |
| 27 | +autonity = Autonity(w3) |
| 28 | + |
| 29 | +# Get the addresses of all registered validators |
| 30 | +validator_addresses = autonity.get_validators() |
| 31 | + |
| 32 | +# Get validator data as instances of `autonity.contracts.autonity.Validator` |
| 33 | +validators = [autonity.get_validator(address) for address in validator_addresses] |
| 34 | + |
| 35 | +# Only consider active validators |
| 36 | +active_validators = [ |
| 37 | + validator for validator in validators if validator.state is ValidatorState.ACTIVE |
| 38 | +] |
| 39 | + |
| 40 | +# Identify the targets by sorting validators by commission rate and taking the first 3 |
| 41 | +target_validators = sorted( |
| 42 | + active_validators, key=lambda validator: validator.commission_rate |
| 43 | +)[:3] |
| 44 | + |
| 45 | +# Convert 100 NTN to ton (the equivalent of wei) |
| 46 | +amount = 100 * (10 ** autonity.decimals()) |
| 47 | + |
| 48 | +for validator in target_validators: |
| 49 | + # Delegate stake to the target validator |
| 50 | + print(validator.node_address, validator.commission_rate) |
| 51 | + tx = autonity.bond(validator.node_address, amount).transact() |
| 52 | + receipt = w3.eth.wait_for_transaction_receipt(tx) |
| 53 | + |
| 54 | + # Make sure a new bonding request has been created by inspecting the event |
| 55 | + logs = autonity.NewBondingRequest().process_receipt(receipt) |
| 56 | + print(logs[0].args) |
0 commit comments