def test_calculate(self): rewards = [] ratios = [0.25, 0.05, 0.3, 0.15, 0.25] total_reward = 1000 for i, ratio in enumerate(ratios, start=1): rl0 = RewardLog( address="addr" + str(i), type="D", staking_balance=total_reward * ratio, current_balance=0, ) rl0.ratio = ratio rl0.ratio4 = ratio rewards.append(rl0) rewards.append(RewardLog("addrdummy", "D", 0, 0).skip("skipped for testing", 4)) phaseMapping = CalculatePhaseMapping() new_rewards = phaseMapping.calculate(rewards, {"addr2": "addr1"}) # filter out skipped records new_rewards = list(rl for rl in new_rewards if not rl.skipped) # check new ratios sum up to 1 # old and new reward amount is the same ratio_sum = sum(rl.ratio5 for rl in new_rewards) # payment address for address2 is address1 payment_address_set = set(rl.paymentaddress for rl in new_rewards) self.assertEqual(4, len(payment_address_set)) self.assertAlmostEqual(1.0, ratio_sum, delta=ALMOST_ZERO) # ratio of records having payment address addr1 must be 0.30 (0.25+0.05) self.assertAlmostEqual( 0.30, sum( rl.ratio for rl in list( filter( lambda rl: rl.paymentaddress == "addr1", filter(lambda rl: not rl.skipped, new_rewards), ) ) ), delta=ALMOST_ZERO, )
def test_process_payouts(self): logger.debug("") # Console formatting factory = ProviderFactory(provider='prpc') parser = BakingYamlConfParser(self.baking_config, None, None, None, None, block_api=factory, api_base_url=None) parser.parse() parser.process() cfg_dict = parser.get_conf_obj() baking_cfg = BakingConf(cfg_dict) srvc_fee_calc = ServiceFeeCalculator( baking_cfg.get_full_supporters_set(), baking_cfg.get_specials_map(), baking_cfg.get_service_fee()) rules_model = RulesModel(baking_cfg.get_excluded_set_tob(), baking_cfg.get_excluded_set_toe(), baking_cfg.get_excluded_set_tof(), baking_cfg.get_dest_map()) payment_calc = PhasedPaymentCalculator( baking_cfg.get_founders_map(), baking_cfg.get_owners_map(), srvc_fee_calc, baking_cfg.get_min_delegation_amount() * MUTEZ, rules_model) rewardApi = factory.newRewardApi( default_network_config_map[CURRENT_TESTNET], baking_cfg.get_baking_address(), "") # Simulate logic in payment_producer reward_logs = [] attempts = 0 exiting = False while not exiting and attempts < 2: attempts += 1 try: # Reward data # Fetch cycle 90 of delphinet for tz1gtHbmBF3TSebsgJfJPvUB2e9x8EDeNm6V reward_model = rewardApi.get_rewards_for_cycle_map( PAYOUT_CYCLE) # Calculate rewards - payment_producer.py reward_logs, total_amount = payment_calc.calculate( reward_model) # Check total reward amount matches sums of records self.assertTrue( total_amount, sum([rl.amount for rl in reward_logs if rl.payable])) exiting = True except ApiProviderException as e: logger.error( "{:s} error at payment producer loop: '{:s}', will try again." .format("RPC", str(e))) sleep(5) # # The next 3 phases happen in payment_consumer.py # # Merge payments to same address phaseMerge = CalculatePhaseMerge() reward_logs = phaseMerge.calculate(reward_logs) # Handle remapping of payment to alternate address phaseMapping = CalculatePhaseMapping() reward_logs = phaseMapping.calculate(reward_logs, baking_cfg.get_dest_map()) # Filter zero-balance addresses based on config phaseZeroBalance = CalculatePhaseZeroBalance() reward_logs = phaseZeroBalance.calculate( reward_logs, baking_cfg.get_reactivate_zeroed()) # Filter out non-payable items reward_logs = [pi for pi in reward_logs if pi.payable] reward_logs.sort(key=cmp_to_key(cmp_by_type_balance)) # TRD Calculated Results # tz1V9SpwXaGFiYdDfGJtWjA61EumAH3DwSyT type: D, stake bal: 62657.83, cur bal: 62657.83, ratio: 0.327420, fee_ratio: 0.000000, amount: 0.000000, fee_amount: 0.000000, fee_rate: 0.00, payable: N, skipped: Y, at-phase: 1, desc: Excluded by configuration, pay_addr: tz1V9SpwXaGFiYdDfGJtWjA61EumAH3DwSyT # tz1YTMY7Zewx6AMM2h9eCwc8TyXJ5wgn9ace type: D, stake bal: 55646.70, cur bal: 55646.70, ratio: 0.432340, fee_ratio: 0.000000, amount: 102.988160, fee_amount: 0.000000, fee_rate: 0.00, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1YTMY7Zewx6AMM2h9eCwc8TyXJ5wgn9ace # tz1T5woJN3r7SV5v2HGDyA5kurhbD9Y8ZKHZ type: D, stake bal: 25689.88, cur bal: 25689.88, ratio: 0.179635, fee_ratio: 0.019959, amount: 42.791010, fee_amount: 4.754557, fee_rate: 0.10, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1T5woJN3r7SV5v2HGDyA5kurhbD9Y8ZKHZ # tz1fgX6oRWQb4HYHUT6eRjW8diNFrqjEfgq7 type: D, stake bal: 24916.33, cur bal: 24916.33, ratio: 0.193584, fee_ratio: 0.000000, amount: 46.113902, fee_amount: 0.000000, fee_rate: 0.00, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1fgX6oRWQb4HYHUT6eRjW8diNFrqjEfgq7 # tz1RRzfechTs3gWdM58y6xLeByta3JWaPqwP type: D, stake bal: 6725.43, cur bal: 6725.43, ratio: 0.047027, fee_ratio: 0.005225, amount: 11.202382, fee_amount: 1.244709, fee_rate: 0.10, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1RMmSzPSWPSSaKU193Voh4PosWSZx1C7Hs # tz1L1XQWKxG38wk1Ain1foGaEZj8zeposcbk type: D, stake bal: 981.64, cur bal: 981.64, ratio: 0.007627, fee_ratio: 0.000000, amount: 1.816762, fee_amount: 0.000000, fee_rate: 0.00, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1L1XQWKxG38wk1Ain1foGaEZj8zeposcbk # tz1L1XQWKxG38wk1Ain1foGaEZj8zeposcbk type: O, stake bal: 14750.53, cur bal: 0.00, ratio: 0.114602, fee_ratio: 0.000000, amount: 27.299548, fee_amount: 0.000000, fee_rate: 0.00, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1L1XQWKxG38wk1Ain1foGaEZj8zeposcbk # tz1fgX6oRWQb4HYHUT6eRjW8diNFrqjEfgq7 type: F, stake bal: 0.00, cur bal: 0.00, ratio: 0.006296, fee_ratio: 0.000000, amount: 1.499816, fee_amount: 0.000000, fee_rate: 0.00, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1fgX6oRWQb4HYHUT6eRjW8diNFrqjEfgq7 # tz1YTMY7Zewx6AMM2h9eCwc8TyXJ5wgn9ace type: F, stake bal: 0.00, cur bal: 0.00, ratio: 0.018889, fee_ratio: 0.000000, amount: 4.499450, fee_amount: 0.000000, fee_rate: 0.00, payable: Y, skipped: N, at-phase: 0, desc: , pay_addr: tz1YTMY7Zewx6AMM2h9eCwc8TyXJ5wgn9ace # Final records before creating transactions # These values are known to be correct cr = {} cr["tz1T5woJN3r7SV5v2HGDyA5kurhbD9Y8ZKHZ"] = { "type": "D", "amount": 42791010, "pay_addr": "tz1T5woJN3r7SV5v2HGDyA5kurhbD9Y8ZKHZ" } cr["tz1RRzfechTs3gWdM58y6xLeByta3JWaPqwP"] = { "type": "D", "amount": 11202382, "pay_addr": "tz1RMmSzPSWPSSaKU193Voh4PosWSZx1C7Hs" } cr["tz1YTMY7Zewx6AMM2h9eCwc8TyXJ5wgn9ace"] = { "type": "M", "amount": 107487610, "pay_addr": "tz1YTMY7Zewx6AMM2h9eCwc8TyXJ5wgn9ace" } cr["tz1fgX6oRWQb4HYHUT6eRjW8diNFrqjEfgq7"] = { "type": "M", "amount": 47613718, "pay_addr": "tz1fgX6oRWQb4HYHUT6eRjW8diNFrqjEfgq7" } cr["tz1L1XQWKxG38wk1Ain1foGaEZj8zeposcbk"] = { "type": "M", "amount": 29116310, "pay_addr": "tz1L1XQWKxG38wk1Ain1foGaEZj8zeposcbk" } # Verify that TRD calculated matches known values for r in reward_logs: # We know this address should be skipped if r.address == "tz1V9SpwXaGFiYdDfGJtWjA61EumAH3DwSyT": self.assertEqual(r.skipped, 1) self.assertEqual(r.amount, 0) continue # All others we can compare normally cmp = cr[r.address] self.assertEqual(r.type, cmp["type"]) self.assertEqual(r.amount, (cmp["amount"])) self.assertEqual(r.paymentaddress, cmp["pay_addr"])
def _consume_batch(self, payment_batch): try: payment_items = payment_batch.batch if len(payment_items) == 0: logger.debug("Batch is empty, ignoring...") return True if payment_items[0].type == EXIT_PAYMENT_TYPE: logger.warn("Exit signal received. Terminating...") return False sleep(1) pymnt_cycle = payment_batch.cycle logger.info("Starting payments for cycle {}".format(pymnt_cycle)) # Filter out non-payable items payment_items = [pi for pi in payment_items if pi.payable] already_paid_items = [ pi for pi in payment_items if pi.paid.is_processed() ] payment_items = [ pi for pi in payment_items if not pi.paid.is_processed() ] # Handle remapping of payment to alternate address phaseMapping = CalculatePhaseMapping() payment_items = phaseMapping.calculate(payment_items, self.dest_map) # Merge payments to same address phaseMerge = CalculatePhaseMerge() payment_items = phaseMerge.calculate(payment_items) # Filter zero-balance addresses based on config phaseZeroBalance = CalculatePhaseZeroBalance() payment_items = phaseZeroBalance.calculate(payment_items, self.reactivate_zeroed) payment_items.sort(key=functools.cmp_to_key(cmp_by_type_balance)) batch_payer = BatchPayer( self.node_addr, self.key_name, self.client_manager, self.delegator_pays_ra_fee, self.delegator_pays_xfer_fee, self.network_config, self.plugins_manager, self.dry_run, ) # 3- do the payment ( payment_logs, total_attempts, total_payout_amount, number_future_payable_cycles, ) = batch_payer.pay(payment_items, dry_run=self.dry_run) # override batch data payment_batch.batch = payment_logs # 4- count failed payments nb_paid, nb_failed, nb_unknown = count_and_log_failed(payment_logs) # 5- create payment report file report_file = self.create_payment_report(nb_failed, payment_logs, pymnt_cycle, already_paid_items) # 5.1- modify calculations report if total_attempts > 0: self.add_transaction_fees_to_calculation_report( payment_logs, pymnt_cycle) # 6- Clean failure reports self.clean_failed_payment_reports(pymnt_cycle, nb_failed == 0) # 7- notify batch producer if nb_failed == 0: if payment_batch.producer_ref: payment_batch.producer_ref.on_success(payment_batch) else: if payment_batch.producer_ref: payment_batch.producer_ref.on_fail(payment_batch) # 8- send notification via plugins if total_attempts > 0: subject = "Reward Payouts for Cycle {:d}".format(pymnt_cycle) status = "" if nb_failed == 0 and nb_unknown == 0: status = status + "Completed Successfully!" else: status = status + "attempted" if nb_failed > 0: status = status + ", {:d} failed".format(nb_failed) if nb_unknown > 0: status = (status + ", {:d} injected but final state not known". format(nb_unknown)) subject = subject + " " + status admin_message = "The current payout account balance is expected to last for the next {:d} cycle(s)!".format( number_future_payable_cycles) # Payout notification receives cycle, rewards total, number of delegators self.plugins_manager.send_payout_notification( pymnt_cycle, total_payout_amount, (nb_paid + nb_failed + nb_unknown)) # Admin notification receives subject, message, CSV report, raw log objects self.plugins_manager.send_admin_notification( subject, admin_message, [report_file], payment_logs) # 9- publish anonymous stats if self.publish_stats and self.args and not self.dry_run: stats_dict = self.create_stats_dict( self.key_name, nb_failed, nb_unknown, pymnt_cycle, payment_logs, total_attempts, ) stats_publisher(stats_dict) else: logger.info("Anonymous statistics disabled{:s}".format( ", (Dry run)" if self.dry_run else "")) except Exception: logger.error("Error at reward payment", exc_info=True) return True
def test_batch_payer_total_payout_amount(): factory = ProviderFactory(provider="prpc") parser = BakingYamlConfParser(baking_config, None, None, None, None, block_api=factory, api_base_url=None) parser.parse() parser.process() cfg_dict = parser.get_conf_obj() baking_cfg = BakingConf(cfg_dict) srvc_fee_calc = ServiceFeeCalculator( baking_cfg.get_full_supporters_set(), baking_cfg.get_specials_map(), baking_cfg.get_service_fee(), ) rules_model = RulesModel( baking_cfg.get_excluded_set_tob(), baking_cfg.get_excluded_set_toe(), baking_cfg.get_excluded_set_tof(), baking_cfg.get_dest_map(), ) payment_calc = PhasedPaymentCalculator( baking_cfg.get_founders_map(), baking_cfg.get_owners_map(), srvc_fee_calc, baking_cfg.get_min_delegation_amount() * MUTEZ, rules_model, ) rewardApi = factory.newRewardApi( default_network_config_map[CURRENT_TESTNET], baking_cfg.get_baking_address(), "") # Simulate logic in payment_producer reward_logs = [] attempts = 0 exiting = False while not exiting and attempts < 2: attempts += 1 # Reward data # Fetch cycle 51 of granadanet for tz1gtHbmBF3TSebsgJfJPvUB2e9x8EDeNm6V reward_model = rewardApi.get_rewards_for_cycle_map( PAYOUT_CYCLE, RewardsType.ACTUAL) # Calculate rewards - payment_producer.py reward_model.computed_reward_amount = reward_model.total_reward_amount reward_logs, total_amount = payment_calc.calculate(reward_model) # Check total reward amount matches sums of records assert total_amount == sum( [rl.amount for rl in reward_logs if rl.payable]) exiting = True # Merge payments to same address phaseMerge = CalculatePhaseMerge() reward_logs = phaseMerge.calculate(reward_logs) # Handle remapping of payment to alternate address phaseMapping = CalculatePhaseMapping() reward_logs = phaseMapping.calculate(reward_logs, baking_cfg.get_dest_map()) # Filter zero-balance addresses based on config phaseZeroBalance = CalculatePhaseZeroBalance() reward_logs = phaseZeroBalance.calculate( reward_logs, baking_cfg.get_reactivate_zeroed()) # Filter out non-payable items reward_logs = [ payment_item for payment_item in reward_logs if payment_item.payable ] reward_logs.sort(key=cmp_to_key(cmp_by_type_balance)) batch_payer = BatchPayer( node_url=node_endpoint, pymnt_addr="tz1gtHbmBF3TSebsgJfJPvUB2e9x8EDeNm6V", clnt_mngr=ClientManager(node_endpoint, PRIVATE_SIGNER_URL), delegator_pays_ra_fee=True, delegator_pays_xfer_fee=True, network_config=network, plugins_manager=PluginManager(baking_cfg.get_plugins_conf(), dry_run=True), dry_run=True, ) # Fix the endpoint auto port assignment because # https://mainnet-tezos.giganode.io:8732 cannot be reached batch_payer.clnt_mngr.node_endpoint = node_endpoint # Do the payment ( payment_logs, total_attempts, total_payout_amount, number_future_payable_cycles, ) = batch_payer.pay(reward_logs, dry_run=True) assert total_attempts == 3 assert total_payout_amount == 238211030 assert (PAYMENT_ADDRESS_BALANCE // total_payout_amount) - 1 == number_future_payable_cycles
def test_batch_payer_total_payout_amount(): factory = ProviderFactory(provider="prpc") parser = BakingYamlConfParser( baking_config, None, None, None, None, block_api=factory, api_base_url=None ) parser.parse() parser.process() cfg_dict = parser.get_conf_obj() baking_cfg = BakingConf(cfg_dict) srvc_fee_calc = ServiceFeeCalculator( baking_cfg.get_full_supporters_set(), baking_cfg.get_specials_map(), baking_cfg.get_service_fee(), ) rules_model = RulesModel( baking_cfg.get_excluded_set_tob(), baking_cfg.get_excluded_set_toe(), baking_cfg.get_excluded_set_tof(), baking_cfg.get_dest_map(), ) payment_calc = PhasedPaymentCalculator( baking_cfg.get_founders_map(), baking_cfg.get_owners_map(), srvc_fee_calc, int(baking_cfg.get_min_delegation_amount() * MUTEZ_PER_TEZ), rules_model, ) rewardApi = factory.newRewardApi( default_network_config_map[CURRENT_TESTNET], baking_cfg.get_baking_address(), "" ) # Simulate logic in payment_producer reward_logs = [] attempts = 0 exiting = False while not exiting and attempts < 2: attempts += 1 # Reward data # Fetch cycle 51 of granadanet for tz1gtHbmBF3TSebsgJfJPvUB2e9x8EDeNm6V reward_model = rewardApi.get_rewards_for_cycle_map( PAYOUT_CYCLE, RewardsType.ACTUAL ) # Calculate rewards - payment_producer.py reward_model.computed_reward_amount = reward_model.total_reward_amount reward_logs, total_amount = payment_calc.calculate(reward_model) # Check total reward amount matches sums of records # diff of 1 expected due to floating point arithmetic assert ( total_amount - sum([rl.adjusted_amount for rl in reward_logs if rl.payable]) <= 1 ) exiting = True # Merge payments to same address phaseMerge = CalculatePhaseMerge() reward_logs = phaseMerge.calculate(reward_logs) # Handle remapping of payment to alternate address phaseMapping = CalculatePhaseMapping() reward_logs = phaseMapping.calculate(reward_logs, baking_cfg.get_dest_map()) # Filter zero-balance addresses based on config phaseZeroBalance = CalculatePhaseZeroBalance() reward_logs = phaseZeroBalance.calculate( reward_logs, baking_cfg.get_reactivate_zeroed() ) # Filter out non-payable items reward_logs = [payment_item for payment_item in reward_logs if payment_item.payable] reward_logs.sort(key=cmp_to_key(cmp_by_type_balance)) batch_payer = BatchPayer( node_url=node_endpoint, pymnt_addr="tz1N4UfQCahHkRShBanv9QP9TnmXNgCaqCyZ", clnt_mngr=ClientManager(node_endpoint, PRIVATE_SIGNER_URL), delegator_pays_ra_fee=True, delegator_pays_xfer_fee=True, network_config=network, plugins_manager=PluginManager(baking_cfg.get_plugins_conf(), dry_run=True), dry_run=True, ) # Do the payment ( _, total_attempts, total_payout_amount, number_future_payable_cycles, ) = batch_payer.pay(reward_logs, dry_run=True) # Payment does not have status done, paid or injected thus the total payout amount is zero assert total_payout_amount == 0 assert number_future_payable_cycles == 2 assert total_attempts == 3 # Check the adjusted amount assert reward_logs[0].adjusted_amount == 40418486 assert reward_logs[1].adjusted_amount == 10581272 assert reward_logs[2].adjusted_amount == 109732835 assert reward_logs[3].adjusted_amount == 48362127 assert reward_logs[4].adjusted_amount == 29116310