From 240ce7fc346bd97e5109576e289a86084e03ac2e Mon Sep 17 00:00:00 2001 From: Pooya Fekri Date: Mon, 27 Nov 2023 09:32:46 +0330 Subject: [PATCH 1/3] Fix usage to deleted w3 in EVMFundManager --- core/utils.py | 3 +++ faucet/faucet_manager/fund_manager.py | 10 ++++++++-- faucet/models.py | 6 +++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/core/utils.py b/core/utils.py index af4568ce..c28a4db7 100644 --- a/core/utils.py +++ b/core/utils.py @@ -146,3 +146,6 @@ def to_checksum_address(address: str): def get_transaction_receipt(self, hash): return self.w3.eth.get_transaction_receipt(hash) + + def get_balance(self, address): + self.w3.eth.get_balance(address) diff --git a/faucet/faucet_manager/fund_manager.py b/faucet/faucet_manager/fund_manager.py index 6e6874ea..dc761336 100644 --- a/faucet/faucet_manager/fund_manager.py +++ b/faucet/faucet_manager/fund_manager.py @@ -39,10 +39,13 @@ def __init__(self, chain: Chain): self.web3_utils.set_account(self.chain.wallet.main_key) self.web3_utils.set_contract(self.get_fund_manager_checksum_address(), abi=manager_abi) + def get_gas_price(self): + return self.web3_utils.get_gas_price() + @property def is_gas_price_too_high(self): try: - gas_price = self.web3_utils.get_gas_price() + gas_price = self.get_gas_price() logging.info(f"Gas price: {gas_price} vs max: {self.chain.max_gas_price}") if gas_price > self.chain.max_gas_price: return True @@ -51,6 +54,9 @@ def is_gas_price_too_high(self): logging.error(e) return True + def get_balance(self, address): + return self.web3_utils.get_balance(address) + def get_fund_manager_checksum_address(self): return self.web3_utils.to_checksum_address(self.chain.fund_manager_address) @@ -63,7 +69,7 @@ def multi_transfer(self, data): def _transfer(self, tx_function_str, *args): tx = self.prepare_tx_for_broadcast(tx_function_str, *args) try: - self.web3_utils.send_raw_tx(tx.rawTransaction) + self.web3_utils.send_raw_tx(tx) return tx["hash"].hex() except Exception as e: raise FundMangerException.RPCError(str(e)) diff --git a/faucet/models.py b/faucet/models.py index 178f15ac..25c8c72e 100644 --- a/faucet/models.py +++ b/faucet/models.py @@ -258,7 +258,7 @@ def get_manager_balance(self): if self.chain_type == NetworkTypes.EVM or int(self.chain_id) == 500: # if self.chain_id == 500: # logging.debug("chain XDC NONEVM is checking its balances") - funds = EVMFundManager(self).w3.eth.get_balance(self.fund_manager_address) + funds = EVMFundManager(self).get_balance(self.fund_manager_address) return funds elif self.chain_type == NetworkTypes.SOLANA: @@ -293,7 +293,7 @@ def get_wallet_balance(self): ) if self.chain_type == NetworkTypes.EVM or int(self.chain_id) == 500: - return EVMFundManager(self).w3.eth.get_balance(self.wallet.address) + return EVMFundManager(self).get_balance(self.wallet.address) elif self.chain_type == NetworkTypes.SOLANA: fund_manager = SolanaFundManager(self) v = fund_manager.w3.get_balance(Pubkey.from_string(self.wallet.address)).value @@ -325,7 +325,7 @@ def gas_price(self): try: from faucet.faucet_manager.fund_manager import EVMFundManager - return EVMFundManager(self).w3.eth.gas_price + return EVMFundManager(self).get_gas_price() except: # noqa: E722 logging.exception(f"Error getting gas price for {self.chain_name}") return self.max_gas_price + 1 From f328ed83d5767130b3928827417598a25fe193e4 Mon Sep 17 00:00:00 2001 From: Shayan Shiravani Date: Tue, 28 Nov 2023 12:07:06 +0330 Subject: [PATCH 2/3] bugfix --- core/utils.py | 6 +++ prizetap/tasks.py | 104 ++++++++++++++++++++++++---------------------- 2 files changed, 60 insertions(+), 50 deletions(-) diff --git a/core/utils.py b/core/utils.py index c28a4db7..1c1b3f2d 100644 --- a/core/utils.py +++ b/core/utils.py @@ -3,6 +3,7 @@ import pytz from web3 import Web3 from web3.contract.contract import Contract, ContractFunction +from web3.logs import DISCARD, IGNORE, STRICT, WARN from web3.middleware import geth_poa_middleware from web3.types import TxParams, Type @@ -58,6 +59,11 @@ def get_first_day_of_last_month(): class Web3Utils: + LOG_STRICT = STRICT + LOG_IGNORE = IGNORE + LOG_DISCARD = DISCARD + LOG_WARN = WARN + def __init__(self, rpc_url, poa=False) -> None: self._rpc_url = rpc_url self._w3 = None diff --git a/prizetap/tasks.py b/prizetap/tasks.py index c7024ca1..f5397b2d 100644 --- a/prizetap/tasks.py +++ b/prizetap/tasks.py @@ -168,56 +168,60 @@ def set_raffle_ids(self): ) if raffles_queryset.count() > 0: for raffle in raffles_queryset: - print(f"Setting the raffle {raffle.name} raffleId") - contract_client = PrizetapContractClient(raffle) - - receipt = contract_client.get_transaction_receipt(raffle.tx_hash) - raffle_created_log = receipt["logs"][1] - log = contract_client.contract.events.RaffleCreated().process_log(raffle_created_log) - - raffle.raffleId = log["args"]["raffleId"] - onchain_raffle = contract_client.get_raffle() - is_valid = True - if onchain_raffle["status"] != 0: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} status") - if onchain_raffle["lastParticipantIndex"] != 0: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} lastParticipantIndex") - if onchain_raffle["lastWinnerIndex"] != 0: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} lastWinnerIndex") - if onchain_raffle["participantsCount"] != 0: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} participantsCount") - if raffle.creator_address != onchain_raffle["initiator"]: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} initiator") - if raffle.max_number_of_entries != onchain_raffle["maxParticipants"]: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} maxParticipants") - if raffle.max_multiplier != onchain_raffle["maxMultiplier"]: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} maxMultiplier") - if int(raffle.start_at.timestamp()) != onchain_raffle["startTime"]: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} startTime") - if int(raffle.deadline.timestamp()) != onchain_raffle["endTime"]: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} endTime") - if raffle.winners_count != onchain_raffle["winnersCount"]: - is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} winnersCount") - if raffle.is_prize_nft: - if raffle.prize_asset != onchain_raffle["collection"]: + try: + print(f"Setting the raffle {raffle.name} raffleId") + contract_client = PrizetapContractClient(raffle) + + receipt = contract_client.get_transaction_receipt(raffle.tx_hash) + log = contract_client.contract.events.RaffleCreated().process_receipt( + receipt, errors=contract_client.LOG_DISCARD + )[0] + + raffle.raffleId = log["args"]["raffleId"] + onchain_raffle = contract_client.get_raffle() + is_valid = True + if onchain_raffle["status"] != 0: is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} collection") - else: - if raffle.prize_amount != onchain_raffle["prizeAmount"]: + logging.error(f"Mismatch raffle {raffle.pk} status") + if onchain_raffle["lastParticipantIndex"] != 0: is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} prizeAmount") - if raffle.prize_asset != onchain_raffle["currency"]: + logging.error(f"Mismatch raffle {raffle.pk} lastParticipantIndex") + if onchain_raffle["lastWinnerIndex"] != 0: is_valid = False - logging.error(f"Mismatch raffle {raffle.pk} currency") - if is_valid: - raffle.save() + logging.error(f"Mismatch raffle {raffle.pk} lastWinnerIndex") + if onchain_raffle["participantsCount"] != 0: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} participantsCount") + if raffle.creator_address != onchain_raffle["initiator"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} initiator") + if raffle.max_number_of_entries != onchain_raffle["maxParticipants"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} maxParticipants") + if raffle.max_multiplier != onchain_raffle["maxMultiplier"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} maxMultiplier") + if int(raffle.start_at.timestamp()) != onchain_raffle["startTime"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} startTime") + if int(raffle.deadline.timestamp()) != onchain_raffle["endTime"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} endTime") + if raffle.winners_count != onchain_raffle["winnersCount"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} winnersCount") + if raffle.is_prize_nft: + if raffle.prize_asset != onchain_raffle["collection"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} collection") + else: + if raffle.prize_amount != onchain_raffle["prizeAmount"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} prizeAmount") + if raffle.prize_asset != onchain_raffle["currency"]: + is_valid = False + logging.error(f"Mismatch raffle {raffle.pk} currency") + if is_valid: + raffle.save() + except Exception as e: + logging.error(e) From 03cf82996aecc2b0d8c9abe0860993d3e17bbe42 Mon Sep 17 00:00:00 2001 From: Shayan Shiravani Date: Wed, 29 Nov 2023 16:46:05 +0330 Subject: [PATCH 3/3] Refactor reversed constraints --- prizetap/serializers.py | 4 ++-- prizetap/tests.py | 13 +++++++++---- prizetap/validators.py | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/prizetap/serializers.py b/prizetap/serializers.py index 1cf26212..f7d502b8 100644 --- a/prizetap/serializers.py +++ b/prizetap/serializers.py @@ -124,11 +124,11 @@ def validate(self, data): constraint_class.is_valid_param_keys(constraint_params[c.name]) except KeyError as e: raise serializers.ValidationError({"constraint_params": [{f"{c.name}": str(e)}]}) - valid_constraints = [c.name for c in constraints] + valid_constraints = [str(c.pk) for c in constraints] if len(reversed_constraints) > 0: for c in reversed_constraints: if c not in valid_constraints: - raise serializers.ValidationError({"reversed_constraints": [{f"{c}": "Invalid constraint name"}]}) + raise serializers.ValidationError({"reversed_constraints": [{f"{c}": "Invalid constraint pk"}]}) if "winners_count" in data and data["winners_count"] > data["max_number_of_entries"]: raise serializers.ValidationError({"winners_count": "Invalid value"}) valid_chains = list(CONTRACT_ADDRESSES.keys()) diff --git a/prizetap/tests.py b/prizetap/tests.py index 291310c5..a410a11e 100644 --- a/prizetap/tests.py +++ b/prizetap/tests.py @@ -243,7 +243,7 @@ def test_create_raffle_with_invalid_constraint_params(self): lambda a, b, c: (True, None), ) def test_reversed_constraints(self): - self.raffle.reversed_constraints = "core.BrightIDMeetVerification" + self.raffle.reversed_constraints = str(self.meet_constraint.pk) self.raffle.save() validator = RaffleEnrollmentValidator(user_profile=self.user_profile, raffle=self.raffle) self.assertRaises(PermissionDenied, validator.check_user_constraints) @@ -251,10 +251,15 @@ def test_reversed_constraints(self): def test_create_raffle_with_invalid_reversed_constraints(self): self.client.force_authenticate(user=self.user_profile.user) self.raffle_data["constraints"] = [self.meet_constraint.pk] - self.raffle_data["reversed_constraints"] = "core.BrightIDAuraVerification" + aura_verified_constraint = Constraint.objects.create( + name="core.BrightIDAuraVerification", + title="BrightID aura", + description="You have to be Aura verified.", + ) + self.raffle_data["reversed_constraints"] = str(aura_verified_constraint.pk) response = self.client.post(reverse("create-raffle"), self.raffle_data) self.assertEqual( - str(response.data["reversed_constraints"][0]["core.BrightIDAuraVerification"]), "Invalid constraint name" + str(response.data["reversed_constraints"][0][str(aura_verified_constraint.pk)]), "Invalid constraint pk" ) self.assertEqual(response.status_code, 400) self.assertEqual(Raffle.objects.count(), 1) @@ -273,7 +278,7 @@ def test_create_raffle_with_invalid_reversed_constraints(self): def test_create_raffle_with_reversed_constraints(self): self.client.force_authenticate(user=self.user_profile.user) self.raffle_data["constraints"] = [self.meet_constraint.pk] - self.raffle_data["reversed_constraints"] = self.meet_constraint.name + self.raffle_data["reversed_constraints"] = str(self.meet_constraint.pk) response = self.client.post(reverse("create-raffle"), self.raffle_data) self.assertEqual(response.status_code, 200) self.assertEqual(Raffle.objects.count(), 2) diff --git a/prizetap/validators.py b/prizetap/validators.py index 7c0c8c5a..2b86ec33 100644 --- a/prizetap/validators.py +++ b/prizetap/validators.py @@ -30,7 +30,7 @@ def check_user_constraints(self): constraint.param_values = param_values[c.name] except KeyError: pass - if c.name in reversed_constraints: + if str(c.pk) in reversed_constraints: if constraint.is_observed(): raise PermissionDenied(constraint.response) else: