Skip to content

Commit fc7d892

Browse files
authored
Merge pull request #76 from peaqnetwork/feat/1208539891229773_typo
Fix typo
2 parents 9cdcba1 + b423388 commit fc7d892

File tree

7 files changed

+269
-5
lines changed

7 files changed

+269
-5
lines changed

ETH/did/did.sol.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
"type": "bytes"
5353
}
5454
],
55-
"name": "RemoveAttribte",
55+
"name": "RemoveAttribute",
5656
"type": "event"
5757
},
5858
{

tests/bridge_did_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def test_bridge_did(self):
111111
block_idx = self._eth_remove_attribute(contract, eth_kp_src, eth_src, KEY)
112112
self.assertRaises(ValueError, contract.functions.readAttribute(eth_src, KEY).call)
113113

114-
event = contract.events.RemoveAttribte.create_filter(fromBlock=block_idx, toBlock=block_idx)
114+
event = contract.events.RemoveAttribute.create_filter(fromBlock=block_idx, toBlock=block_idx)
115115
events = event.get_all_entries()
116116
self.assertEqual(f"{events[0]['args']['did_account']}", f"{eth_src}")
117117
self.assertEqual(f"0x{events[0]['args']['name'].hex()}", f"{KEY}")

tests/reward_distribution_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
'max': 90 * 10 ** 9,
3333
},
3434
'peaq-dev': {
35-
'min': 20 * 10 ** 9,
35+
'min': 1 * 10 ** 9,
3636
'max': 90 * 10 ** 9,
3737
}
3838
}
@@ -268,7 +268,7 @@ def test_transaction_fee_reward_v2(self):
268268
self._check_transaction_fee_reward_from_sender(block_number)
269269
self._check_transaction_fee_reward_from_collator(block_number)
270270

271-
def test_transaction_fee_reward(self):
271+
def test_transaction_fee_reward_with_tip(self):
272272
# Execute
273273
receipt = transfer_with_tip(
274274
self._substrate, self._kp_bob, self._kp_eve.ss58_address,

tests/token_economy_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ def test_constants(self):
211211
@pytest.mark.skipif(TestUtils.is_local_new_chain() is True, reason='Dont need to test on the new chain')
212212
def test_block_reward(self):
213213
block_reward = {
214-
'peaq-dev-fork': int(3.805175038 * 10 ** 18),
214+
'peaq-dev-fork': int(1.902587519 * 10 ** 18),
215215
'krest-network-fork': int(3.805175038 * 10 ** 18),
216216
'peaq-network-fork': int(27.96803653 * 10 ** 18),
217217
}

tools/check_reward_v1.py

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
import sys
2+
sys.path.append('./')
3+
4+
5+
from substrateinterface import SubstrateInterface
6+
from peaq.utils import get_block_height, get_block_hash
7+
import argparse
8+
from collections import Counter
9+
from tools.utils import get_all_events
10+
from peaq.utils import get_account_balance
11+
import pprint
12+
pp = pprint.PrettyPrinter(indent=4)
13+
14+
15+
POT_ADDR = '5EYCAe5cKPAoFh2HnQQvpKqRYZGqBpaA87u4Zzw89qPE58is'
16+
ALLOW_ERROR_PERCENTAGE = 1e-6
17+
18+
19+
def get_current_collator(substrate, num=80):
20+
now_block_height = get_block_height(substrate)
21+
collators = []
22+
for i in range(num):
23+
print(f'get author in block height: {now_block_height - i}')
24+
block_hash = get_block_hash(substrate, now_block_height - i)
25+
block_info = substrate.get_block(block_hash, include_author=True)
26+
collators.append(block_info['author'])
27+
return Counter(collators)
28+
29+
30+
def get_session_validator(substrate):
31+
session_info = substrate.query(
32+
module='Session',
33+
storage_function='Validators',
34+
params=[],
35+
)
36+
return set(session_info.value)
37+
38+
39+
# Only for the token economy V1
40+
# flake8: noqa: C901
41+
if __name__ == '__main__':
42+
parser = argparse.ArgumentParser(description='Get storage and constants from a Substrate chain')
43+
parser.add_argument('-r', '--runtime', type=str, required=True, help='Your runtime websocket endpoint')
44+
parser.add_argument('-n', '--num', type=int, default=5, help='Number of blocks to check')
45+
parser.add_argument('-p', '--percentage', type=int, required=True, help='Collator Delegator rate')
46+
parser.add_argument('-c', '--coefficient', type=int, required=True, help='Collator/Delegator coefficient')
47+
48+
args = parser.parse_args()
49+
50+
if args.percentage < 0 or args.percentage > 100:
51+
raise ValueError(f'Percentage should be between 0 and 100, but got {args.percentage}')
52+
53+
substrate = SubstrateInterface(
54+
url=args.runtime,
55+
)
56+
57+
target_block_num = args.num
58+
now_block_height = get_block_height(substrate)
59+
now_block_hash = get_block_hash(substrate, now_block_height)
60+
if now_block_height < target_block_num:
61+
raise ValueError(f'Block height is {now_block_height}, less than target block number {target_block_num}')
62+
63+
# get collator/delegator issuance number
64+
total_reward = substrate.query(
65+
module='InflationManager',
66+
storage_function='BlockRewards',
67+
params=[],
68+
)
69+
collator_delegator_issuance = total_reward.value * args.percentage / 100
70+
71+
for block_height in range(now_block_height - target_block_num, now_block_height):
72+
print(f'Block height: {block_height}')
73+
# get block data
74+
block_hash = get_block_hash(substrate, block_height)
75+
previous_block_hash = get_block_hash(substrate, block_height - 1)
76+
block_author = substrate.get_block(block_hash, include_author=True)['author']
77+
print(f'block hash: {block_hash}, previous block hash: {previous_block_hash} block author: {block_author}')
78+
79+
pot = get_account_balance(substrate, POT_ADDR, previous_block_hash)
80+
81+
# Get staking info
82+
staking_info = {}
83+
info = substrate.query(
84+
module='ParachainStaking',
85+
storage_function='CandidatePool',
86+
params=[block_author],
87+
block_hash=previous_block_hash,
88+
)
89+
staking_info[block_author] = info.value
90+
staking_info[block_author]['delegators'] = {
91+
delegator['owner']: delegator['amount']
92+
for delegator in info.value['delegators']
93+
}
94+
print(f'staking info: {staking_info}')
95+
96+
# get block reward
97+
result = get_all_events(
98+
substrate,
99+
block_hash,
100+
'ParachainStaking', 'Rewarded')
101+
reward_info = {
102+
event.value['attributes'][0]: event.value['attributes'][1]
103+
for event in result
104+
}
105+
print(f'Block height: {block_height}, block author: {block_author}, reward info: {reward_info}, staking info: {staking_info}, pot: {pot}')
106+
107+
# Check total
108+
total_reward = sum(reward_info.values())
109+
# Note float comparing
110+
if float(abs(total_reward - pot)) / pot > ALLOW_ERROR_PERCENTAGE:
111+
raise ValueError(f'Total reward is not equal to collator/delegator issuance {collator_delegator_issuance}, got {total_reward}')
112+
113+
denominator = args.coefficient * \
114+
staking_info[block_author]['stake'] + \
115+
sum(staking_info[block_author]['delegators'].values())
116+
# Calculate the collator reward
117+
real_collator_reward = reward_info[block_author]
118+
target_collator_reward = collator_delegator_issuance * \
119+
float(args.coefficient) * staking_info[block_author]['stake'] / denominator
120+
if float(abs(real_collator_reward - target_collator_reward)) / target_collator_reward > ALLOW_ERROR_PERCENTAGE:
121+
raise ValueError(f'Collator reward is not equal to target reward {target_collator_reward}, got {real_collator_reward}')
122+
# Calculate the delegator reward
123+
for addr, value in reward_info.items():
124+
if addr == block_author:
125+
continue
126+
real_delegator_reward = value
127+
target_delegator_reward = collator_delegator_issuance * \
128+
float(staking_info[block_author]['delegators'][addr]) / denominator
129+
if float(abs(real_delegator_reward - target_delegator_reward)) / target_delegator_reward > ALLOW_ERROR_PERCENTAGE:
130+
raise ValueError(f'Delegator reward is not equal to target reward {target_delegator_reward}, got {real_delegator_reward}')
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import sys
2+
sys.path.append('./')
3+
import time
4+
5+
from substrateinterface import SubstrateInterface, Keypair
6+
from peaq.sudo_extrinsic import funds
7+
from peaq.utils import ExtrinsicBatch
8+
from tools.utils import get_collators
9+
from tools.constants import KP_GLOBAL_SUDO, BLOCK_GENERATE_TIME
10+
from tools.runtime_upgrade import wait_until_block_height
11+
import argparse
12+
13+
14+
def fund_delegators(substrate: SubstrateInterface, delegators: list, amount: int, batch_num: int = 500):
15+
delegators = [kp.ss58_address for kp in delegators]
16+
for i in range(0, len(delegators), batch_num):
17+
print(f'Funding {i} / {len(delegators)}')
18+
funds(substrate, KP_GLOBAL_SUDO, delegators[i:i + batch_num], amount)
19+
print(f'Funded {i} / {len(delegators)}')
20+
21+
22+
def generate_delegators(number: int):
23+
return [Keypair.create_from_mnemonic(Keypair.generate_mnemonic()) for _ in range(number)]
24+
25+
26+
def get_collator_stake(substrate: SubstrateInterface, validator: str) -> int:
27+
key = Keypair(ss58_address=validator)
28+
collator_info = get_collators(substrate, key)
29+
return int(collator_info['stake'].value)
30+
31+
32+
def delegate_join_delegators(substrate: SubstrateInterface, delegators: list, collator_addr: str, collator_stake: int):
33+
for i, kp in enumerate(delegators):
34+
batch = ExtrinsicBatch(substrate, kp)
35+
batch.compose_call(
36+
'ParachainStaking',
37+
'join_delegators',
38+
{
39+
'collator': collator_addr,
40+
'amount': collator_stake
41+
}
42+
)
43+
batch.execute()
44+
45+
46+
def delegate_delegators(substrate: SubstrateInterface, delegators: list, collator_addr: str, collator_stake: int):
47+
for i, kp in enumerate(delegators):
48+
batch = ExtrinsicBatch(substrate, kp)
49+
batch.compose_call(
50+
'ParachainStaking',
51+
'delegate_another_candidate',
52+
{
53+
'collator': collator_addr,
54+
'amount': collator_stake
55+
}
56+
)
57+
batch.execute()
58+
59+
60+
def get_validators_info(substrate):
61+
validators = substrate.query('Session', 'Validators', [])
62+
return [validator.value for validator in validators]
63+
64+
65+
def main():
66+
parser = argparse.ArgumentParser(description='Setup the delegator')
67+
parser.add_argument('--number', type=int, required=True, help='Number of collators one delegator want to delegate')
68+
parser.add_argument('--url', type=str, required=True, help='websocket URL')
69+
70+
args = parser.parse_args()
71+
substrate = SubstrateInterface(url=args.url)
72+
73+
print('Wait until block height 1')
74+
wait_until_block_height(substrate, 1)
75+
validators = get_validators_info(substrate)
76+
if len(validators) == 0:
77+
print('No validators found')
78+
return
79+
if len(validators) < args.number:
80+
print(f'Number of validators {len(validators)} is less than {args.number}')
81+
return
82+
83+
print(f'Number of validators are {len(validators)}')
84+
# Get default staking number
85+
total_collator_stake = sum(get_collator_stake(substrate, validator) for validator in validators[:args.number])
86+
fund_value = total_collator_stake * 3
87+
if fund_value < 2 * 10 ** 18:
88+
fund_value = 2 * 10 ** 18
89+
print(f'Collator stake {total_collator_stake} is less than {fund_value}, so we will fund it with {fund_value}')
90+
91+
# Fund the delegators
92+
kps = generate_delegators(1)
93+
fund_delegators(substrate, kps, fund_value)
94+
time.sleep(BLOCK_GENERATE_TIME)
95+
96+
# Delegate the first
97+
delegate_join_delegators(substrate, kps, validators[0], get_collator_stake(substrate, validators[0]))
98+
if args.number == 1:
99+
return
100+
print('Wait for one session')
101+
time.sleep(6 * 10)
102+
103+
# Delegate
104+
validators = validators[1:]
105+
for idx, validator in enumerate(validators[:args.number]):
106+
print(F'Setup delegators for {validator} start, {idx} / {len(validators)}')
107+
delegate_delegators(
108+
substrate,
109+
kps,
110+
validator,
111+
get_collator_stake(substrate, validator))
112+
print(f'Setup delegators for {validator} successfully, {idx} / {len(validators)}')
113+
114+
while True:
115+
pending_tx = substrate.retrieve_pending_extrinsics()
116+
if len(pending_tx) < 5:
117+
print(f'The pending transactions are {len(pending_tx)}, we can continue')
118+
break
119+
else:
120+
print(f'Waiting for {len(pending_tx)} pending transactions')
121+
print('Wait for one session')
122+
time.sleep(6 * 10)
123+
124+
125+
if __name__ == '__main__':
126+
main()

tools/utils.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,14 @@ def get_event(substrate, block_hash, pallet, event_name):
420420
return None
421421

422422

423+
def get_all_events(substrate, block_hash, pallet, event_name):
424+
return [
425+
event['event']
426+
for event in substrate.get_events(block_hash)
427+
if event.value['module_id'] == pallet and event.value['event_id'] == event_name
428+
]
429+
430+
423431
def batch_fund(batch, kp_or_addr, amount):
424432
addr = kp_or_addr
425433
if isinstance(kp_or_addr, Keypair):

0 commit comments

Comments
 (0)