Skip to content

Commit

Permalink
:Merge branch 'develop' of https://github.com/UnitapApp/unitap-backend
Browse files Browse the repository at this point in the history
…into fix/change-api/v1-to-api/gastap
  • Loading branch information
Mohamad Bastin committed Nov 29, 2023
2 parents 7ad6ce4 + dc89de5 commit 5741af9
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 62 deletions.
9 changes: 9 additions & 0 deletions core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -146,3 +152,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)
10 changes: 8 additions & 2 deletions faucet/faucet_manager/fund_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand All @@ -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))
Expand Down
6 changes: 3 additions & 3 deletions faucet/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions prizetap/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
104 changes: 54 additions & 50 deletions prizetap/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
13 changes: 9 additions & 4 deletions prizetap/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,18 +243,23 @@ 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)

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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion prizetap/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 5741af9

Please sign in to comment.