From 322e05565d70e37e1936a930d63b5827badf2f1c Mon Sep 17 00:00:00 2001 From: Pooya Fekri Date: Sun, 10 Dec 2023 08:55:30 +0330 Subject: [PATCH] mv web3 usage tokentap to core --- core/utils.py | 23 +++++++++++++++++++++++ tokenTap/helpers.py | 22 +++------------------- 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/core/utils.py b/core/utils.py index 544cfb07..3be210b6 100644 --- a/core/utils.py +++ b/core/utils.py @@ -3,6 +3,8 @@ from contextlib import contextmanager import pytz +from eth_account.messages import encode_defunct +from web3 import Account, Web3 from django.core.cache import cache from web3 import Web3 from web3.contract.contract import Contract, ContractFunction @@ -175,6 +177,27 @@ def from_wei(self, value: int, unit: str = "ether"): def to_checksum_address(address: str): return Web3.to_checksum_address(address.lower()) + @staticmethod + def hash_message(user, token, amount, nonce): + message_hash = Web3().solidity_keccak( + ["address", "address", "uint256", "uint32"], + [ + Web3.to_checksum_address(user), + Web3.to_checksum_address(token), + amount, + nonce, + ], + ) + hashed_message = encode_defunct(hexstr=message_hash.hex()) + + return hashed_message + + @staticmethod + def sign_hashed_message(private_key, hashed_message): + account = Account.from_key(private_key) + signed_message = account.sign_message(hashed_message) + return signed_message.signature.hex() + def get_transaction_receipt(self, tx_hash): return self.w3.eth.get_transaction_receipt(tx_hash) diff --git a/tokenTap/helpers.py b/tokenTap/helpers.py index 5736268c..581cd186 100644 --- a/tokenTap/helpers.py +++ b/tokenTap/helpers.py @@ -1,9 +1,7 @@ import random -from eth_account.messages import encode_defunct -from web3 import Account, Web3 - from core.models import NetworkTypes, WalletAccount +from core.utils import Web3Utils from faucet.faucet_manager.credit_strategy import RoundCreditStrategy from faucet.models import GlobalSettings @@ -21,27 +19,13 @@ def create_uint32_random_nonce(): def hash_message(user, token, amount, nonce): - message_hash = Web3().solidity_keccak( - ["address", "address", "uint256", "uint32"], - [ - Web3.to_checksum_address(user), - Web3.to_checksum_address(token), - amount, - nonce, - ], - ) - hashed_message = encode_defunct(hexstr=message_hash.hex()) - + hashed_message = Web3Utils.hash_message(user, token, amount, nonce) return hashed_message def sign_hashed_message(hashed_message): private_key = WalletAccount.objects.get(network_type=NetworkTypes.EVM).private_key - account = Account.from_key(private_key) - - signed_message = account.sign_message(hashed_message) - - return signed_message.signature.hex() + return Web3Utils.sign_hashed_message(private_key, hashed_message) def has_weekly_credit_left(user_profile):