Skip to content

Commit

Permalink
chore: lint the source code
Browse files Browse the repository at this point in the history
  • Loading branch information
danijelTxFusion committed Jan 10, 2024
1 parent d028e3d commit fda3670
Show file tree
Hide file tree
Showing 21 changed files with 1,058 additions and 875 deletions.
14 changes: 8 additions & 6 deletions zksync2/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
from enum import Enum

ADDRESS_DEFAULT = HexStr("0x" + "0" * 40)
L2_ETH_TOKEN_ADDRESS = HexStr('0x000000000000000000000000000000000000800a')
L2_ETH_TOKEN_ADDRESS = HexStr("0x000000000000000000000000000000000000800a")

TokenAddress = NewType('token_address', HexStr)
TokenAddress = NewType("token_address", HexStr)
TransactionHash = Union[Hash32, HexBytes, HexStr]
L2WithdrawTxHash = Union[Hash32, HexBytes, HexStr]
From = NewType("from", int)
Limit = NewType('limit', int)
Limit = NewType("limit", int)


class ZkBlockParams(Enum):
Expand All @@ -36,8 +36,10 @@ def format_token(self, amount) -> str:
return str(Decimal(amount) / Decimal(10) ** self.decimals)

def is_eth(self) -> bool:
return self.l1_address.lower() == ADDRESS_DEFAULT or \
self.l2_address.lower() == L2_ETH_TOKEN_ADDRESS
return (
self.l1_address.lower() == ADDRESS_DEFAULT
or self.l2_address.lower() == L2_ETH_TOKEN_ADDRESS
)

def into_decimal(self, amount: int) -> Decimal:
return Decimal(amount).scaleb(self.decimals) // Decimal(10) ** self.decimals
Expand All @@ -48,7 +50,7 @@ def to_int(self, amount: Union[Decimal, int, float]) -> int:
return int(amount * (Decimal(10) ** self.decimals))

@classmethod
def create_eth(cls) -> 'Token':
def create_eth(cls) -> "Token":
return Token(ADDRESS_DEFAULT, L2_ETH_TOKEN_ADDRESS, "ETH", 18)


Expand Down
10 changes: 5 additions & 5 deletions zksync2/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ def hash_byte_code(bytecode: bytes) -> bytes:
bytecode_len = len(bytecode)
bytecode_size = int(bytecode_len / 32)
if bytecode_len % 32 != 0:
raise RuntimeError('Bytecode length in 32-byte words must be odd')
if bytecode_size > 2 ** 16:
raise RuntimeError("Bytecode length in 32-byte words must be odd")
if bytecode_size > 2**16:
raise OverflowError("hash_byte_code, bytecode length must be less than 2^16")
bytecode_hash = sha256(bytecode).digest()
encoded_len = bytecode_size.to_bytes(2, byteorder='big')
ret = b'\x01\00' + encoded_len + bytecode_hash[4:]
encoded_len = bytecode_size.to_bytes(2, byteorder="big")
ret = b"\x01\00" + encoded_len + bytecode_hash[4:]
return ret


def pad_front_bytes(bs: bytes, needed_length: int):
padded = b'\0' * (needed_length - len(bs)) + bs
padded = b"\0" * (needed_length - len(bs)) + bs
return padded


Expand Down
20 changes: 14 additions & 6 deletions zksync2/manage_contracts/contract_encoder_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,20 @@ class JsonConfiguration(Enum):


class BaseContractEncoder:

@classmethod
def from_json(cls, web3: Web3, compiled_contract: Path, conf_type: JsonConfiguration = JsonConfiguration.COMBINED):
with compiled_contract.open(mode='r') as json_f:
def from_json(
cls,
web3: Web3,
compiled_contract: Path,
conf_type: JsonConfiguration = JsonConfiguration.COMBINED,
):
with compiled_contract.open(mode="r") as json_f:
data = json.load(json_f)
if conf_type == JsonConfiguration.COMBINED:
return [cls(web3, abi=v["abi"], bytecode=v["bin"]) for k, v in data["contracts"].items()]
return [
cls(web3, abi=v["abi"], bytecode=v["bin"])
for k, v in data["contracts"].items()
]
else:
return cls(web3, abi=data["abi"], bytecode=data["bytecode"])

Expand All @@ -31,7 +38,9 @@ def __init__(self, web3: Web3, abi, bytecode: Optional[bytes] = None):
if bytecode is None:
self.instance_contract = self.web3.eth.contract(abi=self.abi)
else:
self.instance_contract = self.web3.eth.contract(abi=self.abi, bytecode=bytecode)
self.instance_contract = self.web3.eth.contract(
abi=self.abi, bytecode=bytecode
)

def encode_method(self, fn_name, args: tuple) -> HexStr:
return self.instance_contract.encodeABI(fn_name, args)
Expand All @@ -42,7 +51,6 @@ def contract(self):


class ContractEncoder(BaseContractEncoder):

def __init__(self, web3: Web3, abi, bytecode):
super(ContractEncoder, self).__init__(web3, abi, bytecode)

Expand Down
143 changes: 78 additions & 65 deletions zksync2/manage_contracts/contract_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
from web3 import Web3
from web3.contract import Contract
from zksync2.core.types import EthBlockParams
from zksync2.manage_contracts.precompute_contract_deployer import PrecomputeContractDeployer
from zksync2.manage_contracts.precompute_contract_deployer import (
PrecomputeContractDeployer,
)
from zksync2.manage_contracts.contract_encoder_base import ContractEncoder
from zksync2.signer.eth_signer import EthSignerBase
from zksync2.transaction.transaction_builders import TxCreateContract, TxCreate2Contract
Expand All @@ -19,43 +21,49 @@ class DeploymentType(Enum):


class LegacyContractFactory:

@classmethod
def from_json(cls,
zksync: Web3,
compiled_contract: Path,
account: BaseAccount,
signer: EthSignerBase,
deployment_type: DeploymentType = DeploymentType.CREATE):
with compiled_contract.open(mode='r') as json_f:
def from_json(
cls,
zksync: Web3,
compiled_contract: Path,
account: BaseAccount,
signer: EthSignerBase,
deployment_type: DeploymentType = DeploymentType.CREATE,
):
with compiled_contract.open(mode="r") as json_f:
data = json.load(json_f)
bytecode = bytes.fromhex(remove_0x_prefix(data["bytecode"]))
return cls(zksync=zksync,
abi=data["abi"],
bytecode=bytecode,
account=account,
signer=signer,
deployment_type=deployment_type)

def __init__(self,
zksync: Web3,
abi,
bytecode,
account: BaseAccount,
signer: EthSignerBase,
deployment_type: DeploymentType = DeploymentType.CREATE):
return cls(
zksync=zksync,
abi=data["abi"],
bytecode=bytecode,
account=account,
signer=signer,
deployment_type=deployment_type,
)

def __init__(
self,
zksync: Web3,
abi,
bytecode,
account: BaseAccount,
signer: EthSignerBase,
deployment_type: DeploymentType = DeploymentType.CREATE,
):
self.web3 = zksync
self.abi = abi
self.byte_code = bytecode
self.account = account
self.type = deployment_type
self.signer = signer

def _deploy_create(self,
salt: bytes = None,
args: Optional[Any] = None,
deps: List[bytes] = None) -> Contract:
nonce = self.web3.zksync.get_transaction_count(self.account.address, EthBlockParams.PENDING.value)
def _deploy_create(
self, salt: bytes = None, args: Optional[Any] = None, deps: List[bytes] = None
) -> Contract:
nonce = self.web3.zksync.get_transaction_count(
self.account.address, EthBlockParams.PENDING.value
)
call_data = None
if args is not None:
encoder = ContractEncoder(self.web3, abi=self.abi, bytecode=self.byte_code)
Expand All @@ -65,38 +73,41 @@ def _deploy_create(self,
if deps is not None:
factory_deps = deps

create_contract = TxCreateContract(web3=self.web3,
chain_id=self.web3.zksync.chain_id,
nonce=nonce,
from_=self.account.address,
gas_limit=0,
gas_price=self.web3.zksync.gas_price,
bytecode=self.byte_code,
call_data=call_data,
deps=factory_deps,
salt=salt)
create_contract = TxCreateContract(
web3=self.web3,
chain_id=self.web3.zksync.chain_id,
nonce=nonce,
from_=self.account.address,
gas_limit=0,
gas_price=self.web3.zksync.gas_price,
bytecode=self.byte_code,
call_data=call_data,
deps=factory_deps,
salt=salt,
)

estimate_gas = self.web3.zksync.eth_estimate_gas(create_contract.tx)

tx_712 = create_contract.tx712(estimate_gas)
singed_message = self.signer.sign_typed_data(tx_712.to_eip712_struct())
msg = tx_712.encode(singed_message)
tx_hash = self.web3.zksync.send_raw_transaction(msg)
tx_receipt = self.web3.zksync.wait_for_transaction_receipt(tx_hash, timeout=240, poll_latency=0.5)
tx_receipt = self.web3.zksync.wait_for_transaction_receipt(
tx_hash, timeout=240, poll_latency=0.5
)
if factory_deps is not None:
contract_deployer = PrecomputeContractDeployer(self.web3)
contract_address = contract_deployer.extract_contract_address(tx_receipt)
else:
contract_address = tx_receipt["contractAddress"]
return self.web3.zksync.contract(address=contract_address,
abi=self.abi)

def _deploy_create2(self,
salt: bytes = None,
args: Optional[Any] = None,
deps: List[bytes] = None) -> Contract:

nonce = self.web3.zksync.get_transaction_count(self.account.address, EthBlockParams.PENDING.value)
return self.web3.zksync.contract(address=contract_address, abi=self.abi)

def _deploy_create2(
self, salt: bytes = None, args: Optional[Any] = None, deps: List[bytes] = None
) -> Contract:
nonce = self.web3.zksync.get_transaction_count(
self.account.address, EthBlockParams.PENDING.value
)
gas_price = self.web3.zksync.gas_price
call_data = None
if args is not None:
Expand All @@ -107,35 +118,37 @@ def _deploy_create2(self,
if deps is not None:
factory_deps = deps

create2_contract = TxCreate2Contract(web3=self.web3,
chain_id=self.web3.zksync.chain_id,
nonce=nonce,
from_=self.account.address,
gas_limit=0,
gas_price=gas_price,
bytecode=self.byte_code,
call_data=call_data,
deps=factory_deps,
salt=salt)
create2_contract = TxCreate2Contract(
web3=self.web3,
chain_id=self.web3.zksync.chain_id,
nonce=nonce,
from_=self.account.address,
gas_limit=0,
gas_price=gas_price,
bytecode=self.byte_code,
call_data=call_data,
deps=factory_deps,
salt=salt,
)
estimate_gas = self.web3.zksync.eth_estimate_gas(create2_contract.tx)
tx_712 = create2_contract.tx712(estimate_gas)
singed_message = self.signer.sign_typed_data(tx_712.to_eip712_struct())
msg = tx_712.encode(singed_message)
tx_hash = self.web3.zksync.send_raw_transaction(msg)
tx_receipt = self.web3.zksync.wait_for_transaction_receipt(tx_hash, timeout=240, poll_latency=0.5)
tx_receipt = self.web3.zksync.wait_for_transaction_receipt(
tx_hash, timeout=240, poll_latency=0.5
)

if factory_deps is not None:
contract_deployer = PrecomputeContractDeployer(self.web3)
contract_address = contract_deployer.extract_contract_address(tx_receipt)
else:
contract_address = tx_receipt["contractAddress"]
return self.web3.zksync.contract(address=contract_address,
abi=self.abi)
return self.web3.zksync.contract(address=contract_address, abi=self.abi)

def deploy(self,
salt: bytes = None,
args: Optional[Any] = None,
deps: List[bytes] = None) -> Contract:
def deploy(
self, salt: bytes = None, args: Optional[Any] = None, deps: List[bytes] = None
) -> Contract:
if self.type == DeploymentType.CREATE2:
return self._deploy_create2(salt, args, deps)
return self._deploy_create(salt, args, deps)
34 changes: 14 additions & 20 deletions zksync2/manage_contracts/erc20_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,17 @@ def get_erc20_abi():

if erc_20_abi_cache is None:
with pkg_resources.path(contract_abi, "IERC20.json") as p:
with p.open(mode='r') as json_file:
with p.open(mode="r") as json_file:
data = json.load(json_file)
erc_20_abi_cache = data['abi']
erc_20_abi_cache = data["abi"]
return erc_20_abi_cache


class ERC20Contract:
MAX_ERC20_APPROVE_AMOUNT = 2 ^ 256 - 1
ERC20_APPROVE_THRESHOLD = 2 ^ 255

def __init__(self, web3: Module,
contract_address: HexStr,
account: BaseAccount):
def __init__(self, web3: Module, contract_address: HexStr, account: BaseAccount):
check_sum_address = Web3.to_checksum_address(contract_address)
self.contract_address = check_sum_address
self.module = web3
Expand All @@ -39,21 +37,18 @@ def __init__(self, web3: Module,
def _nonce(self) -> int:
return self.module.get_transaction_count(self.account.address)

def approve(self,
zksync_address: HexStr,
amount,
gas_limit: int) -> TxReceipt:
def approve(self, zksync_address: HexStr, amount, gas_limit: int) -> TxReceipt:
nonce = self._nonce()
gas_price = self.module.gas_price
tx = self.contract.functions.approve(zksync_address,
amount).build_transaction(
tx = self.contract.functions.approve(zksync_address, amount).build_transaction(
{
"chainId": self.module.chain_id,
"from": self.account.address,
"gasPrice": gas_price,
"gas": gas_limit,
"nonce": nonce
})
"nonce": nonce,
}
)
signed_tx = self.account.sign_transaction(tx)
tx_hash = self.module.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = self.module.wait_for_transaction_receipt(tx_hash)
Expand All @@ -64,25 +59,24 @@ def allowance(self, owner: HexStr, sender: HexStr) -> int:
{
"chainId": self.module.chain_id,
"from": self.account.address,
})
}
)

def transfer(self, _to: str, _value: int):
return self.contract.functions.transfer(_to, _value).call(
{
"chainId": self.module.chain_id,
"from": self.account.address,
})
}
)

def balance_of(self, addr: HexStr):
return self.contract.functions.balanceOf(addr).call(
{
"chainId": self.module.chain_id,
"from": self.account.address
})
{"chainId": self.module.chain_id, "from": self.account.address}
)


class ERC20Encoder(BaseContractEncoder):

def __init__(self, web3: Web3, abi: Optional[dict] = None):
if abi is None:
abi = get_erc20_abi()
Expand Down
Loading

0 comments on commit fda3670

Please sign in to comment.