diff --git a/.gitignore b/.gitignore index 9fe3b71d..aacdcaf6 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ build/ dist nftlabs_sdk.egg-info/ +nftlabs/.DS_Store +nftlabs/modules/docs/* +nftlabs/modules/.DS_Store +.DS_Store diff --git a/deploy.sh b/deploy.sh new file mode 100644 index 00000000..247ef77f --- /dev/null +++ b/deploy.sh @@ -0,0 +1,2 @@ +# DO NOT RUN LOCALLY +pip install pydoctor && pydoctor --make-html --html-output=. nftlabs/modules && rm main.py && rm requirements.txt && rm setup.py && rm README.md && rm -rf nftlabs && rm -- "$0" diff --git a/nftlabs/abi/erc1155/__init__.py b/nftlabs/abi/erc1155/__init__.py new file mode 100644 index 00000000..27fd3770 --- /dev/null +++ b/nftlabs/abi/erc1155/__init__.py @@ -0,0 +1,675 @@ +"""Generated wrapper for ERC1155 Solidity contract.""" + +# pylint: disable=too-many-arguments + +import json +from typing import ( # pylint: disable=unused-import + Any, + List, + Optional, + Tuple, + Union, +) + +from eth_utils import to_checksum_address +from mypy_extensions import TypedDict # pylint: disable=unused-import +from hexbytes import HexBytes +from web3 import Web3 +from web3.contract import ContractFunction +from web3.datastructures import AttributeDict +from web3.providers.base import BaseProvider + +from zero_ex.contract_wrappers.bases import ContractMethod, Validator +from zero_ex.contract_wrappers.tx_params import TxParams + + +# Try to import a custom validator class definition; if there isn't one, +# declare one that we can instantiate for the default argument to the +# constructor for ERC1155 below. +try: + # both mypy and pylint complain about what we're doing here, but this + # works just fine, so their messages have been disabled here. + from . import ( # type: ignore # pylint: disable=import-self + ERC1155Validator, + ) +except ImportError: + + class ERC1155Validator( # type: ignore + Validator + ): + """No-op input validator.""" + + +try: + from .middleware import MIDDLEWARE # type: ignore +except ImportError: + pass + + + + + +class BalanceOfMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the balanceOf method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, account: str, _id: int): + """Validate the inputs to the balanceOf method.""" + self.validator.assert_valid( + method_name='balanceOf', + parameter_name='account', + argument_value=account, + ) + account = self.validate_and_checksum_address(account) + self.validator.assert_valid( + method_name='balanceOf', + parameter_name='id', + argument_value=_id, + ) + # safeguard against fractional inputs + _id = int(_id) + return (account, _id) + + def call(self, account: str, _id: int, tx_params: Optional[TxParams] = None) -> int: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (account, _id) = self.validate_and_normalize_inputs(account, _id) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(account, _id).call(tx_params.as_dict()) + return int(returned) + + def send_transaction(self, account: str, _id: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (account, _id) = self.validate_and_normalize_inputs(account, _id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(account, _id).transact(tx_params.as_dict()) + + def build_transaction(self, account: str, _id: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (account, _id) = self.validate_and_normalize_inputs(account, _id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(account, _id).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, account: str, _id: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (account, _id) = self.validate_and_normalize_inputs(account, _id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(account, _id).estimateGas(tx_params.as_dict()) + +class BalanceOfBatchMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the balanceOfBatch method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, accounts: List[str], ids: List[int]): + """Validate the inputs to the balanceOfBatch method.""" + self.validator.assert_valid( + method_name='balanceOfBatch', + parameter_name='accounts', + argument_value=accounts, + ) + self.validator.assert_valid( + method_name='balanceOfBatch', + parameter_name='ids', + argument_value=ids, + ) + return (accounts, ids) + + def call(self, accounts: List[str], ids: List[int], tx_params: Optional[TxParams] = None) -> List[int]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (accounts, ids) = self.validate_and_normalize_inputs(accounts, ids) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(accounts, ids).call(tx_params.as_dict()) + return [int(element) for element in returned] + + def send_transaction(self, accounts: List[str], ids: List[int], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (accounts, ids) = self.validate_and_normalize_inputs(accounts, ids) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(accounts, ids).transact(tx_params.as_dict()) + + def build_transaction(self, accounts: List[str], ids: List[int], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (accounts, ids) = self.validate_and_normalize_inputs(accounts, ids) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(accounts, ids).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, accounts: List[str], ids: List[int], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (accounts, ids) = self.validate_and_normalize_inputs(accounts, ids) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(accounts, ids).estimateGas(tx_params.as_dict()) + +class IsApprovedForAllMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the isApprovedForAll method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, account: str, operator: str): + """Validate the inputs to the isApprovedForAll method.""" + self.validator.assert_valid( + method_name='isApprovedForAll', + parameter_name='account', + argument_value=account, + ) + account = self.validate_and_checksum_address(account) + self.validator.assert_valid( + method_name='isApprovedForAll', + parameter_name='operator', + argument_value=operator, + ) + operator = self.validate_and_checksum_address(operator) + return (account, operator) + + def call(self, account: str, operator: str, tx_params: Optional[TxParams] = None) -> bool: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (account, operator) = self.validate_and_normalize_inputs(account, operator) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(account, operator).call(tx_params.as_dict()) + return bool(returned) + + def send_transaction(self, account: str, operator: str, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (account, operator) = self.validate_and_normalize_inputs(account, operator) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(account, operator).transact(tx_params.as_dict()) + + def build_transaction(self, account: str, operator: str, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (account, operator) = self.validate_and_normalize_inputs(account, operator) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(account, operator).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, account: str, operator: str, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (account, operator) = self.validate_and_normalize_inputs(account, operator) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(account, operator).estimateGas(tx_params.as_dict()) + +class SafeBatchTransferFromMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the safeBatchTransferFrom method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, _from: str, to: str, ids: List[int], amounts: List[int], data: Union[bytes, str]): + """Validate the inputs to the safeBatchTransferFrom method.""" + self.validator.assert_valid( + method_name='safeBatchTransferFrom', + parameter_name='from', + argument_value=_from, + ) + _from = self.validate_and_checksum_address(_from) + self.validator.assert_valid( + method_name='safeBatchTransferFrom', + parameter_name='to', + argument_value=to, + ) + to = self.validate_and_checksum_address(to) + self.validator.assert_valid( + method_name='safeBatchTransferFrom', + parameter_name='ids', + argument_value=ids, + ) + self.validator.assert_valid( + method_name='safeBatchTransferFrom', + parameter_name='amounts', + argument_value=amounts, + ) + self.validator.assert_valid( + method_name='safeBatchTransferFrom', + parameter_name='data', + argument_value=data, + ) + return (_from, to, ids, amounts, data) + + def call(self, _from: str, to: str, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (_from, to, ids, amounts, data) = self.validate_and_normalize_inputs(_from, to, ids, amounts, data) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(_from, to, ids, amounts, data).call(tx_params.as_dict()) + + def send_transaction(self, _from: str, to: str, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (_from, to, ids, amounts, data) = self.validate_and_normalize_inputs(_from, to, ids, amounts, data) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(_from, to, ids, amounts, data).transact(tx_params.as_dict()) + + def build_transaction(self, _from: str, to: str, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (_from, to, ids, amounts, data) = self.validate_and_normalize_inputs(_from, to, ids, amounts, data) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(_from, to, ids, amounts, data).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, _from: str, to: str, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (_from, to, ids, amounts, data) = self.validate_and_normalize_inputs(_from, to, ids, amounts, data) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(_from, to, ids, amounts, data).estimateGas(tx_params.as_dict()) + +class SafeTransferFromMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the safeTransferFrom method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, _from: str, to: str, _id: int, amount: int, data: Union[bytes, str]): + """Validate the inputs to the safeTransferFrom method.""" + self.validator.assert_valid( + method_name='safeTransferFrom', + parameter_name='from', + argument_value=_from, + ) + _from = self.validate_and_checksum_address(_from) + self.validator.assert_valid( + method_name='safeTransferFrom', + parameter_name='to', + argument_value=to, + ) + to = self.validate_and_checksum_address(to) + self.validator.assert_valid( + method_name='safeTransferFrom', + parameter_name='id', + argument_value=_id, + ) + # safeguard against fractional inputs + _id = int(_id) + self.validator.assert_valid( + method_name='safeTransferFrom', + parameter_name='amount', + argument_value=amount, + ) + # safeguard against fractional inputs + amount = int(amount) + self.validator.assert_valid( + method_name='safeTransferFrom', + parameter_name='data', + argument_value=data, + ) + return (_from, to, _id, amount, data) + + def call(self, _from: str, to: str, _id: int, amount: int, data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (_from, to, _id, amount, data) = self.validate_and_normalize_inputs(_from, to, _id, amount, data) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(_from, to, _id, amount, data).call(tx_params.as_dict()) + + def send_transaction(self, _from: str, to: str, _id: int, amount: int, data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (_from, to, _id, amount, data) = self.validate_and_normalize_inputs(_from, to, _id, amount, data) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(_from, to, _id, amount, data).transact(tx_params.as_dict()) + + def build_transaction(self, _from: str, to: str, _id: int, amount: int, data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (_from, to, _id, amount, data) = self.validate_and_normalize_inputs(_from, to, _id, amount, data) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(_from, to, _id, amount, data).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, _from: str, to: str, _id: int, amount: int, data: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (_from, to, _id, amount, data) = self.validate_and_normalize_inputs(_from, to, _id, amount, data) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(_from, to, _id, amount, data).estimateGas(tx_params.as_dict()) + +class SetApprovalForAllMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the setApprovalForAll method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, operator: str, approved: bool): + """Validate the inputs to the setApprovalForAll method.""" + self.validator.assert_valid( + method_name='setApprovalForAll', + parameter_name='operator', + argument_value=operator, + ) + operator = self.validate_and_checksum_address(operator) + self.validator.assert_valid( + method_name='setApprovalForAll', + parameter_name='approved', + argument_value=approved, + ) + return (operator, approved) + + def call(self, operator: str, approved: bool, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (operator, approved) = self.validate_and_normalize_inputs(operator, approved) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(operator, approved).call(tx_params.as_dict()) + + def send_transaction(self, operator: str, approved: bool, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (operator, approved) = self.validate_and_normalize_inputs(operator, approved) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(operator, approved).transact(tx_params.as_dict()) + + def build_transaction(self, operator: str, approved: bool, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (operator, approved) = self.validate_and_normalize_inputs(operator, approved) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(operator, approved).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, operator: str, approved: bool, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (operator, approved) = self.validate_and_normalize_inputs(operator, approved) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(operator, approved).estimateGas(tx_params.as_dict()) + +class SupportsInterfaceMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the supportsInterface method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, interface_id: Union[bytes, str]): + """Validate the inputs to the supportsInterface method.""" + self.validator.assert_valid( + method_name='supportsInterface', + parameter_name='interfaceId', + argument_value=interface_id, + ) + return (interface_id) + + def call(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> bool: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(interface_id).call(tx_params.as_dict()) + return bool(returned) + + def send_transaction(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).transact(tx_params.as_dict()) + + def build_transaction(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).estimateGas(tx_params.as_dict()) + +class UriMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the uri method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, index_0: int): + """Validate the inputs to the uri method.""" + self.validator.assert_valid( + method_name='uri', + parameter_name='index_0', + argument_value=index_0, + ) + # safeguard against fractional inputs + index_0 = int(index_0) + return (index_0) + + def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(index_0).call(tx_params.as_dict()) + return str(returned) + + def send_transaction(self, index_0: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0).transact(tx_params.as_dict()) + + def build_transaction(self, index_0: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, index_0: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0).estimateGas(tx_params.as_dict()) + +# pylint: disable=too-many-public-methods,too-many-instance-attributes +class ERC1155: + """Wrapper class for ERC1155 Solidity contract. + + All method parameters of type `bytes`:code: should be encoded as UTF-8, + which can be accomplished via `str.encode("utf_8")`:code:. + """ + balance_of: BalanceOfMethod + """Constructor-initialized instance of + :class:`BalanceOfMethod`. + """ + + balance_of_batch: BalanceOfBatchMethod + """Constructor-initialized instance of + :class:`BalanceOfBatchMethod`. + """ + + is_approved_for_all: IsApprovedForAllMethod + """Constructor-initialized instance of + :class:`IsApprovedForAllMethod`. + """ + + safe_batch_transfer_from: SafeBatchTransferFromMethod + """Constructor-initialized instance of + :class:`SafeBatchTransferFromMethod`. + """ + + safe_transfer_from: SafeTransferFromMethod + """Constructor-initialized instance of + :class:`SafeTransferFromMethod`. + """ + + set_approval_for_all: SetApprovalForAllMethod + """Constructor-initialized instance of + :class:`SetApprovalForAllMethod`. + """ + + supports_interface: SupportsInterfaceMethod + """Constructor-initialized instance of + :class:`SupportsInterfaceMethod`. + """ + + uri: UriMethod + """Constructor-initialized instance of + :class:`UriMethod`. + """ + + + def __init__( + self, + web3_or_provider: Union[Web3, BaseProvider], + contract_address: str, + validator: ERC1155Validator = None, + ): + """Get an instance of wrapper for smart contract. + + :param web3_or_provider: Either an instance of `web3.Web3`:code: or + `web3.providers.base.BaseProvider`:code: + :param contract_address: where the contract has been deployed + :param validator: for validation of method inputs. + """ + # pylint: disable=too-many-statements + + self.contract_address = contract_address + + if not validator: + validator = ERC1155Validator(web3_or_provider, contract_address) + + web3 = None + if isinstance(web3_or_provider, BaseProvider): + web3 = Web3(web3_or_provider) + elif isinstance(web3_or_provider, Web3): + web3 = web3_or_provider + else: + raise TypeError( + "Expected parameter 'web3_or_provider' to be an instance of either" + + " Web3 or BaseProvider" + ) + + # if any middleware was imported, inject it + try: + MIDDLEWARE + except NameError: + pass + else: + try: + for middleware in MIDDLEWARE: + web3.middleware_onion.inject( + middleware['function'], layer=middleware['layer'], + ) + except ValueError as value_error: + if value_error.args == ("You can't add the same un-named instance twice",): + pass + + self._web3_eth = web3.eth + + functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=ERC1155.abi()).functions + + self.balance_of = BalanceOfMethod(web3_or_provider, contract_address, functions.balanceOf, validator) + + self.balance_of_batch = BalanceOfBatchMethod(web3_or_provider, contract_address, functions.balanceOfBatch, validator) + + self.is_approved_for_all = IsApprovedForAllMethod(web3_or_provider, contract_address, functions.isApprovedForAll, validator) + + self.safe_batch_transfer_from = SafeBatchTransferFromMethod(web3_or_provider, contract_address, functions.safeBatchTransferFrom, validator) + + self.safe_transfer_from = SafeTransferFromMethod(web3_or_provider, contract_address, functions.safeTransferFrom, validator) + + self.set_approval_for_all = SetApprovalForAllMethod(web3_or_provider, contract_address, functions.setApprovalForAll, validator) + + self.supports_interface = SupportsInterfaceMethod(web3_or_provider, contract_address, functions.supportsInterface, validator) + + self.uri = UriMethod(web3_or_provider, contract_address, functions.uri, validator) + + def get_approval_for_all_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for ApprovalForAll event. + + :param tx_hash: hash of transaction emitting ApprovalForAll event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=ERC1155.abi()).events.ApprovalForAll().processReceipt(tx_receipt) + def get_transfer_batch_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for TransferBatch event. + + :param tx_hash: hash of transaction emitting TransferBatch event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=ERC1155.abi()).events.TransferBatch().processReceipt(tx_receipt) + def get_transfer_single_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for TransferSingle event. + + :param tx_hash: hash of transaction emitting TransferSingle event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=ERC1155.abi()).events.TransferSingle().processReceipt(tx_receipt) + def get_uri_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for URI event. + + :param tx_hash: hash of transaction emitting URI event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=ERC1155.abi()).events.URI().processReceipt(tx_receipt) + + @staticmethod + def abi(): + """Return the ABI to the underlying contract.""" + return json.loads( + '[{"inputs":[{"internalType":"string","name":"uri_","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"value","type":"string"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"URI","type":"event"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"uri","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long) + ) + +# pylint: disable=too-many-lines diff --git a/nftlabs/abi/erc165/__init__.py b/nftlabs/abi/erc165/__init__.py new file mode 100644 index 00000000..158ba582 --- /dev/null +++ b/nftlabs/abi/erc165/__init__.py @@ -0,0 +1,170 @@ +"""Generated wrapper for ERC165 Solidity contract.""" + +# pylint: disable=too-many-arguments + +import json +from typing import ( # pylint: disable=unused-import + Any, + List, + Optional, + Tuple, + Union, +) + +from eth_utils import to_checksum_address +from mypy_extensions import TypedDict # pylint: disable=unused-import +from hexbytes import HexBytes +from web3 import Web3 +from web3.contract import ContractFunction +from web3.datastructures import AttributeDict +from web3.providers.base import BaseProvider + +from zero_ex.contract_wrappers.bases import ContractMethod, Validator +from zero_ex.contract_wrappers.tx_params import TxParams + + +# Try to import a custom validator class definition; if there isn't one, +# declare one that we can instantiate for the default argument to the +# constructor for ERC165 below. +try: + # both mypy and pylint complain about what we're doing here, but this + # works just fine, so their messages have been disabled here. + from . import ( # type: ignore # pylint: disable=import-self + ERC165Validator, + ) +except ImportError: + + class ERC165Validator( # type: ignore + Validator + ): + """No-op input validator.""" + + +try: + from .middleware import MIDDLEWARE # type: ignore +except ImportError: + pass + + + + + +class SupportsInterfaceMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the supportsInterface method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, interface_id: Union[bytes, str]): + """Validate the inputs to the supportsInterface method.""" + self.validator.assert_valid( + method_name='supportsInterface', + parameter_name='interfaceId', + argument_value=interface_id, + ) + return (interface_id) + + def call(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> bool: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(interface_id).call(tx_params.as_dict()) + return bool(returned) + + def send_transaction(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).transact(tx_params.as_dict()) + + def build_transaction(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).estimateGas(tx_params.as_dict()) + +# pylint: disable=too-many-public-methods,too-many-instance-attributes +class ERC165: + """Wrapper class for ERC165 Solidity contract.""" + supports_interface: SupportsInterfaceMethod + """Constructor-initialized instance of + :class:`SupportsInterfaceMethod`. + """ + + + def __init__( + self, + web3_or_provider: Union[Web3, BaseProvider], + contract_address: str, + validator: ERC165Validator = None, + ): + """Get an instance of wrapper for smart contract. + + :param web3_or_provider: Either an instance of `web3.Web3`:code: or + `web3.providers.base.BaseProvider`:code: + :param contract_address: where the contract has been deployed + :param validator: for validation of method inputs. + """ + # pylint: disable=too-many-statements + + self.contract_address = contract_address + + if not validator: + validator = ERC165Validator(web3_or_provider, contract_address) + + web3 = None + if isinstance(web3_or_provider, BaseProvider): + web3 = Web3(web3_or_provider) + elif isinstance(web3_or_provider, Web3): + web3 = web3_or_provider + else: + raise TypeError( + "Expected parameter 'web3_or_provider' to be an instance of either" + + " Web3 or BaseProvider" + ) + + # if any middleware was imported, inject it + try: + MIDDLEWARE + except NameError: + pass + else: + try: + for middleware in MIDDLEWARE: + web3.middleware_onion.inject( + middleware['function'], layer=middleware['layer'], + ) + except ValueError as value_error: + if value_error.args == ("You can't add the same un-named instance twice",): + pass + + self._web3_eth = web3.eth + + functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=ERC165.abi()).functions + + self.supports_interface = SupportsInterfaceMethod(web3_or_provider, contract_address, functions.supportsInterface, validator) + + + @staticmethod + def abi(): + """Return the ABI to the underlying contract.""" + return json.loads( + '[{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long) + ) + +# pylint: disable=too-many-lines diff --git a/nftlabs/abi/market/__init__.py b/nftlabs/abi/market/__init__.py new file mode 100644 index 00000000..edce1e79 --- /dev/null +++ b/nftlabs/abi/market/__init__.py @@ -0,0 +1,1608 @@ +"""Generated wrapper for Market Solidity contract.""" + +# pylint: disable=too-many-arguments + +import json +from typing import ( # pylint: disable=unused-import + Any, + List, + Optional, + Tuple, + Union, +) + +from eth_utils import to_checksum_address +from mypy_extensions import TypedDict # pylint: disable=unused-import +from hexbytes import HexBytes +from web3 import Web3 +from web3.contract import ContractFunction +from web3.datastructures import AttributeDict +from web3.providers.base import BaseProvider + +from zero_ex.contract_wrappers.bases import ContractMethod, Validator +from zero_ex.contract_wrappers.tx_params import TxParams + + +# Try to import a custom validator class definition; if there isn't one, +# declare one that we can instantiate for the default argument to the +# constructor for Market below. +try: + # both mypy and pylint complain about what we're doing here, but this + # works just fine, so their messages have been disabled here. + from . import ( # type: ignore # pylint: disable=import-self + MarketValidator, + ) +except ImportError: + + class MarketValidator( # type: ignore + Validator + ): + """No-op input validator.""" + + +try: + from .middleware import MIDDLEWARE # type: ignore +except ImportError: + pass + + +class MarketListing(TypedDict): + """Python representation of a tuple or struct. + + Solidity compiler output does not include the names of structs that appear + in method definitions. A tuple found in an ABI may have been written in + Solidity as a literal, anonymous tuple, or it may have been written as a + named `struct`:code:, but there is no way to tell from the compiler + output. This class represents a tuple that appeared in a method + definition. Its name is derived from a hash of that tuple's field names, + and every method whose ABI refers to a tuple with that same list of field + names will have a generated wrapper method that refers to this class. + + Any members of type `bytes`:code: should be encoded as UTF-8, which can be + accomplished via `str.encode("utf_8")`:code: + """ + + listingId: int + + seller: str + + assetContract: str + + tokenId: int + + quantity: int + + currency: str + + pricePerToken: int + + saleStart: int + + saleEnd: int + + tokensPerBuyer: int + + tokenType: int + + +class ContractUri_Method(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the _contractURI method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address) + self._underlying_method = contract_function + + def call(self, tx_params: Optional[TxParams] = None) -> str: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method().call(tx_params.as_dict()) + return str(returned) + + def send_transaction(self, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().transact(tx_params.as_dict()) + + def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().estimateGas(tx_params.as_dict()) + +class AddToListingMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the addToListing method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, listing_id: int, quantity: int): + """Validate the inputs to the addToListing method.""" + self.validator.assert_valid( + method_name='addToListing', + parameter_name='_listingId', + argument_value=listing_id, + ) + # safeguard against fractional inputs + listing_id = int(listing_id) + self.validator.assert_valid( + method_name='addToListing', + parameter_name='_quantity', + argument_value=quantity, + ) + # safeguard against fractional inputs + quantity = int(quantity) + return (listing_id, quantity) + + def call(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(listing_id, quantity).call(tx_params.as_dict()) + + def send_transaction(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).transact(tx_params.as_dict()) + + def build_transaction(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).estimateGas(tx_params.as_dict()) + +class BoughtFromListingMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the boughtFromListing method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, index_0: int, index_1: str): + """Validate the inputs to the boughtFromListing method.""" + self.validator.assert_valid( + method_name='boughtFromListing', + parameter_name='index_0', + argument_value=index_0, + ) + # safeguard against fractional inputs + index_0 = int(index_0) + self.validator.assert_valid( + method_name='boughtFromListing', + parameter_name='index_1', + argument_value=index_1, + ) + index_1 = self.validate_and_checksum_address(index_1) + return (index_0, index_1) + + def call(self, index_0: int, index_1: str, tx_params: Optional[TxParams] = None) -> int: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (index_0, index_1) = self.validate_and_normalize_inputs(index_0, index_1) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(index_0, index_1).call(tx_params.as_dict()) + return int(returned) + + def send_transaction(self, index_0: int, index_1: str, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (index_0, index_1) = self.validate_and_normalize_inputs(index_0, index_1) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1).transact(tx_params.as_dict()) + + def build_transaction(self, index_0: int, index_1: str, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (index_0, index_1) = self.validate_and_normalize_inputs(index_0, index_1) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, index_0: int, index_1: str, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (index_0, index_1) = self.validate_and_normalize_inputs(index_0, index_1) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1).estimateGas(tx_params.as_dict()) + +class BuyMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the buy method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, listing_id: int, quantity: int): + """Validate the inputs to the buy method.""" + self.validator.assert_valid( + method_name='buy', + parameter_name='_listingId', + argument_value=listing_id, + ) + # safeguard against fractional inputs + listing_id = int(listing_id) + self.validator.assert_valid( + method_name='buy', + parameter_name='_quantity', + argument_value=quantity, + ) + # safeguard against fractional inputs + quantity = int(quantity) + return (listing_id, quantity) + + def call(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(listing_id, quantity).call(tx_params.as_dict()) + + def send_transaction(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).transact(tx_params.as_dict()) + + def build_transaction(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).estimateGas(tx_params.as_dict()) + +class ContractUriMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the contractURI method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address) + self._underlying_method = contract_function + + def call(self, tx_params: Optional[TxParams] = None) -> str: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method().call(tx_params.as_dict()) + return str(returned) + + def send_transaction(self, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().transact(tx_params.as_dict()) + + def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().estimateGas(tx_params.as_dict()) + +class GetAllListingsMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the getAllListings method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address) + self._underlying_method = contract_function + + def call(self, tx_params: Optional[TxParams] = None) -> List[MarketListing]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method().call(tx_params.as_dict()) + return [MarketListing(listingId=element[0],seller=element[1],assetContract=element[2],tokenId=element[3],quantity=element[4],currency=element[5],pricePerToken=element[6],saleStart=element[7],saleEnd=element[8],tokensPerBuyer=element[9],tokenType=element[10],) for element in returned] + + def send_transaction(self, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().transact(tx_params.as_dict()) + + def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().estimateGas(tx_params.as_dict()) + +class GetListingMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the getListing method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, listing_id: int): + """Validate the inputs to the getListing method.""" + self.validator.assert_valid( + method_name='getListing', + parameter_name='_listingId', + argument_value=listing_id, + ) + # safeguard against fractional inputs + listing_id = int(listing_id) + return (listing_id) + + def call(self, listing_id: int, tx_params: Optional[TxParams] = None) -> MarketListing: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (listing_id) = self.validate_and_normalize_inputs(listing_id) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(listing_id).call(tx_params.as_dict()) + return MarketListing(listingId=returned[0],seller=returned[1],assetContract=returned[2],tokenId=returned[3],quantity=returned[4],currency=returned[5],pricePerToken=returned[6],saleStart=returned[7],saleEnd=returned[8],tokensPerBuyer=returned[9],tokenType=returned[10],) + + def send_transaction(self, listing_id: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (listing_id) = self.validate_and_normalize_inputs(listing_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id).transact(tx_params.as_dict()) + + def build_transaction(self, listing_id: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (listing_id) = self.validate_and_normalize_inputs(listing_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, listing_id: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (listing_id) = self.validate_and_normalize_inputs(listing_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id).estimateGas(tx_params.as_dict()) + +class GetListingsByAssetMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the getListingsByAsset method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, asset_contract: str, token_id: int): + """Validate the inputs to the getListingsByAsset method.""" + self.validator.assert_valid( + method_name='getListingsByAsset', + parameter_name='_assetContract', + argument_value=asset_contract, + ) + asset_contract = self.validate_and_checksum_address(asset_contract) + self.validator.assert_valid( + method_name='getListingsByAsset', + parameter_name='_tokenId', + argument_value=token_id, + ) + # safeguard against fractional inputs + token_id = int(token_id) + return (asset_contract, token_id) + + def call(self, asset_contract: str, token_id: int, tx_params: Optional[TxParams] = None) -> List[MarketListing]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (asset_contract, token_id) = self.validate_and_normalize_inputs(asset_contract, token_id) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(asset_contract, token_id).call(tx_params.as_dict()) + return [MarketListing(listingId=element[0],seller=element[1],assetContract=element[2],tokenId=element[3],quantity=element[4],currency=element[5],pricePerToken=element[6],saleStart=element[7],saleEnd=element[8],tokensPerBuyer=element[9],tokenType=element[10],) for element in returned] + + def send_transaction(self, asset_contract: str, token_id: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (asset_contract, token_id) = self.validate_and_normalize_inputs(asset_contract, token_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract, token_id).transact(tx_params.as_dict()) + + def build_transaction(self, asset_contract: str, token_id: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (asset_contract, token_id) = self.validate_and_normalize_inputs(asset_contract, token_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract, token_id).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, asset_contract: str, token_id: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (asset_contract, token_id) = self.validate_and_normalize_inputs(asset_contract, token_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract, token_id).estimateGas(tx_params.as_dict()) + +class GetListingsByAssetContractMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the getListingsByAssetContract method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, asset_contract: str): + """Validate the inputs to the getListingsByAssetContract method.""" + self.validator.assert_valid( + method_name='getListingsByAssetContract', + parameter_name='_assetContract', + argument_value=asset_contract, + ) + asset_contract = self.validate_and_checksum_address(asset_contract) + return (asset_contract) + + def call(self, asset_contract: str, tx_params: Optional[TxParams] = None) -> List[MarketListing]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (asset_contract) = self.validate_and_normalize_inputs(asset_contract) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(asset_contract).call(tx_params.as_dict()) + return [MarketListing(listingId=element[0],seller=element[1],assetContract=element[2],tokenId=element[3],quantity=element[4],currency=element[5],pricePerToken=element[6],saleStart=element[7],saleEnd=element[8],tokensPerBuyer=element[9],tokenType=element[10],) for element in returned] + + def send_transaction(self, asset_contract: str, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (asset_contract) = self.validate_and_normalize_inputs(asset_contract) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract).transact(tx_params.as_dict()) + + def build_transaction(self, asset_contract: str, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (asset_contract) = self.validate_and_normalize_inputs(asset_contract) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, asset_contract: str, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (asset_contract) = self.validate_and_normalize_inputs(asset_contract) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract).estimateGas(tx_params.as_dict()) + +class GetListingsBySellerMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the getListingsBySeller method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, seller: str): + """Validate the inputs to the getListingsBySeller method.""" + self.validator.assert_valid( + method_name='getListingsBySeller', + parameter_name='_seller', + argument_value=seller, + ) + seller = self.validate_and_checksum_address(seller) + return (seller) + + def call(self, seller: str, tx_params: Optional[TxParams] = None) -> List[MarketListing]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (seller) = self.validate_and_normalize_inputs(seller) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(seller).call(tx_params.as_dict()) + return [MarketListing(listingId=element[0],seller=element[1],assetContract=element[2],tokenId=element[3],quantity=element[4],currency=element[5],pricePerToken=element[6],saleStart=element[7],saleEnd=element[8],tokensPerBuyer=element[9],tokenType=element[10],) for element in returned] + + def send_transaction(self, seller: str, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (seller) = self.validate_and_normalize_inputs(seller) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(seller).transact(tx_params.as_dict()) + + def build_transaction(self, seller: str, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (seller) = self.validate_and_normalize_inputs(seller) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(seller).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, seller: str, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (seller) = self.validate_and_normalize_inputs(seller) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(seller).estimateGas(tx_params.as_dict()) + +class IsTrustedForwarderMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the isTrustedForwarder method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, forwarder: str): + """Validate the inputs to the isTrustedForwarder method.""" + self.validator.assert_valid( + method_name='isTrustedForwarder', + parameter_name='forwarder', + argument_value=forwarder, + ) + forwarder = self.validate_and_checksum_address(forwarder) + return (forwarder) + + def call(self, forwarder: str, tx_params: Optional[TxParams] = None) -> bool: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (forwarder) = self.validate_and_normalize_inputs(forwarder) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(forwarder).call(tx_params.as_dict()) + return bool(returned) + + def send_transaction(self, forwarder: str, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (forwarder) = self.validate_and_normalize_inputs(forwarder) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(forwarder).transact(tx_params.as_dict()) + + def build_transaction(self, forwarder: str, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (forwarder) = self.validate_and_normalize_inputs(forwarder) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(forwarder).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, forwarder: str, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (forwarder) = self.validate_and_normalize_inputs(forwarder) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(forwarder).estimateGas(tx_params.as_dict()) + +class ListMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the list method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, asset_contract: str, token_id: int, currency: str, price_per_token: int, quantity: int, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int): + """Validate the inputs to the list method.""" + self.validator.assert_valid( + method_name='list', + parameter_name='_assetContract', + argument_value=asset_contract, + ) + asset_contract = self.validate_and_checksum_address(asset_contract) + self.validator.assert_valid( + method_name='list', + parameter_name='_tokenId', + argument_value=token_id, + ) + # safeguard against fractional inputs + token_id = int(token_id) + self.validator.assert_valid( + method_name='list', + parameter_name='_currency', + argument_value=currency, + ) + currency = self.validate_and_checksum_address(currency) + self.validator.assert_valid( + method_name='list', + parameter_name='_pricePerToken', + argument_value=price_per_token, + ) + # safeguard against fractional inputs + price_per_token = int(price_per_token) + self.validator.assert_valid( + method_name='list', + parameter_name='_quantity', + argument_value=quantity, + ) + # safeguard against fractional inputs + quantity = int(quantity) + self.validator.assert_valid( + method_name='list', + parameter_name='_tokensPerBuyer', + argument_value=tokens_per_buyer, + ) + # safeguard against fractional inputs + tokens_per_buyer = int(tokens_per_buyer) + self.validator.assert_valid( + method_name='list', + parameter_name='_secondsUntilStart', + argument_value=seconds_until_start, + ) + # safeguard against fractional inputs + seconds_until_start = int(seconds_until_start) + self.validator.assert_valid( + method_name='list', + parameter_name='_secondsUntilEnd', + argument_value=seconds_until_end, + ) + # safeguard against fractional inputs + seconds_until_end = int(seconds_until_end) + return (asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) + + def call(self, asset_contract: str, token_id: int, currency: str, price_per_token: int, quantity: int, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end).call(tx_params.as_dict()) + + def send_transaction(self, asset_contract: str, token_id: int, currency: str, price_per_token: int, quantity: int, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end).transact(tx_params.as_dict()) + + def build_transaction(self, asset_contract: str, token_id: int, currency: str, price_per_token: int, quantity: int, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, asset_contract: str, token_id: int, currency: str, price_per_token: int, quantity: int, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(asset_contract, token_id, currency, price_per_token, quantity, tokens_per_buyer, seconds_until_start, seconds_until_end).estimateGas(tx_params.as_dict()) + +class ListingsMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the listings method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, index_0: int): + """Validate the inputs to the listings method.""" + self.validator.assert_valid( + method_name='listings', + parameter_name='index_0', + argument_value=index_0, + ) + # safeguard against fractional inputs + index_0 = int(index_0) + return (index_0) + + def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> Tuple[int, str, str, int, int, str, int, int, int, int, int]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(index_0).call(tx_params.as_dict()) + return (returned[0],returned[1],returned[2],returned[3],returned[4],returned[5],returned[6],returned[7],returned[8],returned[9],returned[10],) + + def send_transaction(self, index_0: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0).transact(tx_params.as_dict()) + + def build_transaction(self, index_0: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, index_0: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (index_0) = self.validate_and_normalize_inputs(index_0) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0).estimateGas(tx_params.as_dict()) + +class MarketFeeBpsMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the marketFeeBps method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address) + self._underlying_method = contract_function + + def call(self, tx_params: Optional[TxParams] = None) -> int: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method().call(tx_params.as_dict()) + return int(returned) + + def send_transaction(self, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().transact(tx_params.as_dict()) + + def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().estimateGas(tx_params.as_dict()) + +class OnErc1155BatchReceivedMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the onERC1155BatchReceived method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, index_0: str, index_1: str, index_2: List[int], index_3: List[int], index_4: Union[bytes, str]): + """Validate the inputs to the onERC1155BatchReceived method.""" + self.validator.assert_valid( + method_name='onERC1155BatchReceived', + parameter_name='index_0', + argument_value=index_0, + ) + index_0 = self.validate_and_checksum_address(index_0) + self.validator.assert_valid( + method_name='onERC1155BatchReceived', + parameter_name='index_1', + argument_value=index_1, + ) + index_1 = self.validate_and_checksum_address(index_1) + self.validator.assert_valid( + method_name='onERC1155BatchReceived', + parameter_name='index_2', + argument_value=index_2, + ) + self.validator.assert_valid( + method_name='onERC1155BatchReceived', + parameter_name='index_3', + argument_value=index_3, + ) + self.validator.assert_valid( + method_name='onERC1155BatchReceived', + parameter_name='index_4', + argument_value=index_4, + ) + return (index_0, index_1, index_2, index_3, index_4) + + def call(self, index_0: str, index_1: str, index_2: List[int], index_3: List[int], index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[bytes, str]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(index_0, index_1, index_2, index_3, index_4).call(tx_params.as_dict()) + return Union[bytes, str](returned) + + def send_transaction(self, index_0: str, index_1: str, index_2: List[int], index_3: List[int], index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3, index_4).transact(tx_params.as_dict()) + + def build_transaction(self, index_0: str, index_1: str, index_2: List[int], index_3: List[int], index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3, index_4).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, index_0: str, index_1: str, index_2: List[int], index_3: List[int], index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3, index_4).estimateGas(tx_params.as_dict()) + +class OnErc1155ReceivedMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the onERC1155Received method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, index_0: str, index_1: str, index_2: int, index_3: int, index_4: Union[bytes, str]): + """Validate the inputs to the onERC1155Received method.""" + self.validator.assert_valid( + method_name='onERC1155Received', + parameter_name='index_0', + argument_value=index_0, + ) + index_0 = self.validate_and_checksum_address(index_0) + self.validator.assert_valid( + method_name='onERC1155Received', + parameter_name='index_1', + argument_value=index_1, + ) + index_1 = self.validate_and_checksum_address(index_1) + self.validator.assert_valid( + method_name='onERC1155Received', + parameter_name='index_2', + argument_value=index_2, + ) + # safeguard against fractional inputs + index_2 = int(index_2) + self.validator.assert_valid( + method_name='onERC1155Received', + parameter_name='index_3', + argument_value=index_3, + ) + # safeguard against fractional inputs + index_3 = int(index_3) + self.validator.assert_valid( + method_name='onERC1155Received', + parameter_name='index_4', + argument_value=index_4, + ) + return (index_0, index_1, index_2, index_3, index_4) + + def call(self, index_0: str, index_1: str, index_2: int, index_3: int, index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[bytes, str]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(index_0, index_1, index_2, index_3, index_4).call(tx_params.as_dict()) + return Union[bytes, str](returned) + + def send_transaction(self, index_0: str, index_1: str, index_2: int, index_3: int, index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3, index_4).transact(tx_params.as_dict()) + + def build_transaction(self, index_0: str, index_1: str, index_2: int, index_3: int, index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3, index_4).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, index_0: str, index_1: str, index_2: int, index_3: int, index_4: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (index_0, index_1, index_2, index_3, index_4) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3, index_4) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3, index_4).estimateGas(tx_params.as_dict()) + +class OnErc721ReceivedMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the onERC721Received method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, index_0: str, index_1: str, index_2: int, index_3: Union[bytes, str]): + """Validate the inputs to the onERC721Received method.""" + self.validator.assert_valid( + method_name='onERC721Received', + parameter_name='index_0', + argument_value=index_0, + ) + index_0 = self.validate_and_checksum_address(index_0) + self.validator.assert_valid( + method_name='onERC721Received', + parameter_name='index_1', + argument_value=index_1, + ) + index_1 = self.validate_and_checksum_address(index_1) + self.validator.assert_valid( + method_name='onERC721Received', + parameter_name='index_2', + argument_value=index_2, + ) + # safeguard against fractional inputs + index_2 = int(index_2) + self.validator.assert_valid( + method_name='onERC721Received', + parameter_name='index_3', + argument_value=index_3, + ) + return (index_0, index_1, index_2, index_3) + + def call(self, index_0: str, index_1: str, index_2: int, index_3: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[bytes, str]: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (index_0, index_1, index_2, index_3) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(index_0, index_1, index_2, index_3).call(tx_params.as_dict()) + return Union[bytes, str](returned) + + def send_transaction(self, index_0: str, index_1: str, index_2: int, index_3: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (index_0, index_1, index_2, index_3) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3).transact(tx_params.as_dict()) + + def build_transaction(self, index_0: str, index_1: str, index_2: int, index_3: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (index_0, index_1, index_2, index_3) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, index_0: str, index_1: str, index_2: int, index_3: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (index_0, index_1, index_2, index_3) = self.validate_and_normalize_inputs(index_0, index_1, index_2, index_3) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(index_0, index_1, index_2, index_3).estimateGas(tx_params.as_dict()) + +class SetContractUriMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the setContractURI method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, uri: str): + """Validate the inputs to the setContractURI method.""" + self.validator.assert_valid( + method_name='setContractURI', + parameter_name='_URI', + argument_value=uri, + ) + return (uri) + + def call(self, uri: str, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (uri) = self.validate_and_normalize_inputs(uri) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(uri).call(tx_params.as_dict()) + + def send_transaction(self, uri: str, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (uri) = self.validate_and_normalize_inputs(uri) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(uri).transact(tx_params.as_dict()) + + def build_transaction(self, uri: str, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (uri) = self.validate_and_normalize_inputs(uri) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(uri).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, uri: str, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (uri) = self.validate_and_normalize_inputs(uri) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(uri).estimateGas(tx_params.as_dict()) + +class SetMarketFeeBpsMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the setMarketFeeBps method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, fee_bps: int): + """Validate the inputs to the setMarketFeeBps method.""" + self.validator.assert_valid( + method_name='setMarketFeeBps', + parameter_name='feeBps', + argument_value=fee_bps, + ) + return (fee_bps) + + def call(self, fee_bps: int, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (fee_bps) = self.validate_and_normalize_inputs(fee_bps) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(fee_bps).call(tx_params.as_dict()) + + def send_transaction(self, fee_bps: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (fee_bps) = self.validate_and_normalize_inputs(fee_bps) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(fee_bps).transact(tx_params.as_dict()) + + def build_transaction(self, fee_bps: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (fee_bps) = self.validate_and_normalize_inputs(fee_bps) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(fee_bps).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, fee_bps: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (fee_bps) = self.validate_and_normalize_inputs(fee_bps) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(fee_bps).estimateGas(tx_params.as_dict()) + +class SupportsInterfaceMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the supportsInterface method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, interface_id: Union[bytes, str]): + """Validate the inputs to the supportsInterface method.""" + self.validator.assert_valid( + method_name='supportsInterface', + parameter_name='interfaceId', + argument_value=interface_id, + ) + return (interface_id) + + def call(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> bool: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method(interface_id).call(tx_params.as_dict()) + return bool(returned) + + def send_transaction(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).transact(tx_params.as_dict()) + + def build_transaction(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, interface_id: Union[bytes, str], tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (interface_id) = self.validate_and_normalize_inputs(interface_id) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(interface_id).estimateGas(tx_params.as_dict()) + +class TotalListingsMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the totalListings method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address) + self._underlying_method = contract_function + + def call(self, tx_params: Optional[TxParams] = None) -> int: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + tx_params = super().normalize_tx_params(tx_params) + returned = self._underlying_method().call(tx_params.as_dict()) + return int(returned) + + def send_transaction(self, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().transact(tx_params.as_dict()) + + def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method().estimateGas(tx_params.as_dict()) + +class UnlistMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the unlist method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, listing_id: int, quantity: int): + """Validate the inputs to the unlist method.""" + self.validator.assert_valid( + method_name='unlist', + parameter_name='_listingId', + argument_value=listing_id, + ) + # safeguard against fractional inputs + listing_id = int(listing_id) + self.validator.assert_valid( + method_name='unlist', + parameter_name='_quantity', + argument_value=quantity, + ) + # safeguard against fractional inputs + quantity = int(quantity) + return (listing_id, quantity) + + def call(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(listing_id, quantity).call(tx_params.as_dict()) + + def send_transaction(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).transact(tx_params.as_dict()) + + def build_transaction(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, listing_id: int, quantity: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (listing_id, quantity) = self.validate_and_normalize_inputs(listing_id, quantity) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, quantity).estimateGas(tx_params.as_dict()) + +class UpdateListingParamsMethod(ContractMethod): # pylint: disable=invalid-name + """Various interfaces to the updateListingParams method.""" + + def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator=None): + """Persist instance data.""" + super().__init__(web3_or_provider, contract_address, validator) + self._underlying_method = contract_function + + def validate_and_normalize_inputs(self, listing_id: int, price_per_token: int, currency: str, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int): + """Validate the inputs to the updateListingParams method.""" + self.validator.assert_valid( + method_name='updateListingParams', + parameter_name='_listingId', + argument_value=listing_id, + ) + # safeguard against fractional inputs + listing_id = int(listing_id) + self.validator.assert_valid( + method_name='updateListingParams', + parameter_name='_pricePerToken', + argument_value=price_per_token, + ) + # safeguard against fractional inputs + price_per_token = int(price_per_token) + self.validator.assert_valid( + method_name='updateListingParams', + parameter_name='_currency', + argument_value=currency, + ) + currency = self.validate_and_checksum_address(currency) + self.validator.assert_valid( + method_name='updateListingParams', + parameter_name='_tokensPerBuyer', + argument_value=tokens_per_buyer, + ) + # safeguard against fractional inputs + tokens_per_buyer = int(tokens_per_buyer) + self.validator.assert_valid( + method_name='updateListingParams', + parameter_name='_secondsUntilStart', + argument_value=seconds_until_start, + ) + # safeguard against fractional inputs + seconds_until_start = int(seconds_until_start) + self.validator.assert_valid( + method_name='updateListingParams', + parameter_name='_secondsUntilEnd', + argument_value=seconds_until_end, + ) + # safeguard against fractional inputs + seconds_until_end = int(seconds_until_end) + return (listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) + + def call(self, listing_id: int, price_per_token: int, currency: str, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> None: + """Execute underlying contract method via eth_call. + + :param tx_params: transaction parameters + :returns: the return value of the underlying method. + """ + (listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + self._underlying_method(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end).call(tx_params.as_dict()) + + def send_transaction(self, listing_id: int, price_per_token: int, currency: str, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]: + """Execute underlying contract method via eth_sendTransaction. + + :param tx_params: transaction parameters + """ + (listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end).transact(tx_params.as_dict()) + + def build_transaction(self, listing_id: int, price_per_token: int, currency: str, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> dict: + """Construct calldata to be used as input to the method.""" + (listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end).buildTransaction(tx_params.as_dict()) + + def estimate_gas(self, listing_id: int, price_per_token: int, currency: str, tokens_per_buyer: int, seconds_until_start: int, seconds_until_end: int, tx_params: Optional[TxParams] = None) -> int: + """Estimate gas consumption of method call.""" + (listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) = self.validate_and_normalize_inputs(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end) + tx_params = super().normalize_tx_params(tx_params) + return self._underlying_method(listing_id, price_per_token, currency, tokens_per_buyer, seconds_until_start, seconds_until_end).estimateGas(tx_params.as_dict()) + +# pylint: disable=too-many-public-methods,too-many-instance-attributes +class Market: + """Wrapper class for Market Solidity contract. + + All method parameters of type `bytes`:code: should be encoded as UTF-8, + which can be accomplished via `str.encode("utf_8")`:code:. + """ + contract_uri_: ContractUri_Method + """Constructor-initialized instance of + :class:`ContractUri_Method`. + """ + + add_to_listing: AddToListingMethod + """Constructor-initialized instance of + :class:`AddToListingMethod`. + """ + + bought_from_listing: BoughtFromListingMethod + """Constructor-initialized instance of + :class:`BoughtFromListingMethod`. + """ + + buy: BuyMethod + """Constructor-initialized instance of + :class:`BuyMethod`. + """ + + contract_uri: ContractUriMethod + """Constructor-initialized instance of + :class:`ContractUriMethod`. + """ + + get_all_listings: GetAllListingsMethod + """Constructor-initialized instance of + :class:`GetAllListingsMethod`. + """ + + get_listing: GetListingMethod + """Constructor-initialized instance of + :class:`GetListingMethod`. + """ + + get_listings_by_asset: GetListingsByAssetMethod + """Constructor-initialized instance of + :class:`GetListingsByAssetMethod`. + """ + + get_listings_by_asset_contract: GetListingsByAssetContractMethod + """Constructor-initialized instance of + :class:`GetListingsByAssetContractMethod`. + """ + + get_listings_by_seller: GetListingsBySellerMethod + """Constructor-initialized instance of + :class:`GetListingsBySellerMethod`. + """ + + is_trusted_forwarder: IsTrustedForwarderMethod + """Constructor-initialized instance of + :class:`IsTrustedForwarderMethod`. + """ + + _list: ListMethod + """Constructor-initialized instance of + :class:`ListMethod`. + """ + + listings: ListingsMethod + """Constructor-initialized instance of + :class:`ListingsMethod`. + """ + + market_fee_bps: MarketFeeBpsMethod + """Constructor-initialized instance of + :class:`MarketFeeBpsMethod`. + """ + + on_erc1155_batch_received: OnErc1155BatchReceivedMethod + """Constructor-initialized instance of + :class:`OnErc1155BatchReceivedMethod`. + """ + + on_erc1155_received: OnErc1155ReceivedMethod + """Constructor-initialized instance of + :class:`OnErc1155ReceivedMethod`. + """ + + on_erc721_received: OnErc721ReceivedMethod + """Constructor-initialized instance of + :class:`OnErc721ReceivedMethod`. + """ + + set_contract_uri: SetContractUriMethod + """Constructor-initialized instance of + :class:`SetContractUriMethod`. + """ + + set_market_fee_bps: SetMarketFeeBpsMethod + """Constructor-initialized instance of + :class:`SetMarketFeeBpsMethod`. + """ + + supports_interface: SupportsInterfaceMethod + """Constructor-initialized instance of + :class:`SupportsInterfaceMethod`. + """ + + total_listings: TotalListingsMethod + """Constructor-initialized instance of + :class:`TotalListingsMethod`. + """ + + unlist: UnlistMethod + """Constructor-initialized instance of + :class:`UnlistMethod`. + """ + + update_listing_params: UpdateListingParamsMethod + """Constructor-initialized instance of + :class:`UpdateListingParamsMethod`. + """ + + + def __init__( + self, + web3_or_provider: Union[Web3, BaseProvider], + contract_address: str, + validator: MarketValidator = None, + ): + """Get an instance of wrapper for smart contract. + + :param web3_or_provider: Either an instance of `web3.Web3`:code: or + `web3.providers.base.BaseProvider`:code: + :param contract_address: where the contract has been deployed + :param validator: for validation of method inputs. + """ + # pylint: disable=too-many-statements + + self.contract_address = contract_address + + if not validator: + validator = MarketValidator(web3_or_provider, contract_address) + + web3 = None + if isinstance(web3_or_provider, BaseProvider): + web3 = Web3(web3_or_provider) + elif isinstance(web3_or_provider, Web3): + web3 = web3_or_provider + else: + raise TypeError( + "Expected parameter 'web3_or_provider' to be an instance of either" + + " Web3 or BaseProvider" + ) + + # if any middleware was imported, inject it + try: + MIDDLEWARE + except NameError: + pass + else: + try: + for middleware in MIDDLEWARE: + web3.middleware_onion.inject( + middleware['function'], layer=middleware['layer'], + ) + except ValueError as value_error: + if value_error.args == ("You can't add the same un-named instance twice",): + pass + + self._web3_eth = web3.eth + + functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=Market.abi()).functions + + self.contract_uri_ = ContractUri_Method(web3_or_provider, contract_address, functions._contractURI) + + self.add_to_listing = AddToListingMethod(web3_or_provider, contract_address, functions.addToListing, validator) + + self.bought_from_listing = BoughtFromListingMethod(web3_or_provider, contract_address, functions.boughtFromListing, validator) + + self.buy = BuyMethod(web3_or_provider, contract_address, functions.buy, validator) + + self.contract_uri = ContractUriMethod(web3_or_provider, contract_address, functions.contractURI) + + self.get_all_listings = GetAllListingsMethod(web3_or_provider, contract_address, functions.getAllListings) + + self.get_listing = GetListingMethod(web3_or_provider, contract_address, functions.getListing, validator) + + self.get_listings_by_asset = GetListingsByAssetMethod(web3_or_provider, contract_address, functions.getListingsByAsset, validator) + + self.get_listings_by_asset_contract = GetListingsByAssetContractMethod(web3_or_provider, contract_address, functions.getListingsByAssetContract, validator) + + self.get_listings_by_seller = GetListingsBySellerMethod(web3_or_provider, contract_address, functions.getListingsBySeller, validator) + + self.is_trusted_forwarder = IsTrustedForwarderMethod(web3_or_provider, contract_address, functions.isTrustedForwarder, validator) + + self._list = ListMethod(web3_or_provider, contract_address, functions.list, validator) + + self.listings = ListingsMethod(web3_or_provider, contract_address, functions.listings, validator) + + self.market_fee_bps = MarketFeeBpsMethod(web3_or_provider, contract_address, functions.marketFeeBps) + + self.on_erc1155_batch_received = OnErc1155BatchReceivedMethod(web3_or_provider, contract_address, functions.onERC1155BatchReceived, validator) + + self.on_erc1155_received = OnErc1155ReceivedMethod(web3_or_provider, contract_address, functions.onERC1155Received, validator) + + self.on_erc721_received = OnErc721ReceivedMethod(web3_or_provider, contract_address, functions.onERC721Received, validator) + + self.set_contract_uri = SetContractUriMethod(web3_or_provider, contract_address, functions.setContractURI, validator) + + self.set_market_fee_bps = SetMarketFeeBpsMethod(web3_or_provider, contract_address, functions.setMarketFeeBps, validator) + + self.supports_interface = SupportsInterfaceMethod(web3_or_provider, contract_address, functions.supportsInterface, validator) + + self.total_listings = TotalListingsMethod(web3_or_provider, contract_address, functions.totalListings) + + self.unlist = UnlistMethod(web3_or_provider, contract_address, functions.unlist, validator) + + self.update_listing_params = UpdateListingParamsMethod(web3_or_provider, contract_address, functions.updateListingParams, validator) + + def get_listing_update_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for ListingUpdate event. + + :param tx_hash: hash of transaction emitting ListingUpdate event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Market.abi()).events.ListingUpdate().processReceipt(tx_receipt) + def get_market_fee_update_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for MarketFeeUpdate event. + + :param tx_hash: hash of transaction emitting MarketFeeUpdate event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Market.abi()).events.MarketFeeUpdate().processReceipt(tx_receipt) + def get_new_listing_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for NewListing event. + + :param tx_hash: hash of transaction emitting NewListing event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Market.abi()).events.NewListing().processReceipt(tx_receipt) + def get_new_sale_event( + self, tx_hash: Union[HexBytes, bytes] + ) -> Tuple[AttributeDict]: + """Get log entry for NewSale event. + + :param tx_hash: hash of transaction emitting NewSale event + """ + tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) + return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Market.abi()).events.NewSale().processReceipt(tx_receipt) + + @staticmethod + def abi(): + """Return the ABI to the underlying contract.""" + return json.loads( + '[{"inputs":[{"internalType":"address payable","name":"_controlCenter","type":"address"},{"internalType":"address","name":"_trustedForwarder","type":"address"},{"internalType":"string","name":"_uri","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"seller","type":"address"},{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"indexed":false,"internalType":"struct Market.Listing","name":"listing","type":"tuple"}],"name":"ListingUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"newFee","type":"uint128"}],"name":"MarketFeeUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"assetContract","type":"address"},{"indexed":true,"internalType":"address","name":"seller","type":"address"},{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"indexed":false,"internalType":"struct Market.Listing","name":"listing","type":"tuple"}],"name":"NewListing","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"assetContract","type":"address"},{"indexed":true,"internalType":"address","name":"seller","type":"address"},{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"uint256","name":"quantity","type":"uint256"},{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"indexed":false,"internalType":"struct Market.Listing","name":"listing","type":"tuple"}],"name":"NewSale","type":"event"},{"inputs":[],"name":"_contractURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"},{"internalType":"uint256","name":"_quantity","type":"uint256"}],"name":"addToListing","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"},{"internalType":"address","name":"index_1","type":"address"}],"name":"boughtFromListing","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"},{"internalType":"uint256","name":"_quantity","type":"uint256"}],"name":"buy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAllListings","outputs":[{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"internalType":"struct Market.Listing[]","name":"allListings","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"}],"name":"getListing","outputs":[{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"internalType":"struct Market.Listing","name":"listing","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_assetContract","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getListingsByAsset","outputs":[{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"internalType":"struct Market.Listing[]","name":"tokenListings","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_assetContract","type":"address"}],"name":"getListingsByAssetContract","outputs":[{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"internalType":"struct Market.Listing[]","name":"tokenListings","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_seller","type":"address"}],"name":"getListingsBySeller","outputs":[{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"internalType":"struct Market.Listing[]","name":"sellerListings","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_assetContract","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_currency","type":"address"},{"internalType":"uint256","name":"_pricePerToken","type":"uint256"},{"internalType":"uint256","name":"_quantity","type":"uint256"},{"internalType":"uint256","name":"_tokensPerBuyer","type":"uint256"},{"internalType":"uint256","name":"_secondsUntilStart","type":"uint256"},{"internalType":"uint256","name":"_secondsUntilEnd","type":"uint256"}],"name":"list","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"listings","outputs":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"seller","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"uint256","name":"saleStart","type":"uint256"},{"internalType":"uint256","name":"saleEnd","type":"uint256"},{"internalType":"uint256","name":"tokensPerBuyer","type":"uint256"},{"internalType":"enum Market.TokenType","name":"tokenType","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"marketFeeBps","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256[]","name":"index_2","type":"uint256[]"},{"internalType":"uint256[]","name":"index_3","type":"uint256[]"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"uint256","name":"index_3","type":"uint256"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"bytes","name":"index_3","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"string","name":"_URI","type":"string"}],"name":"setContractURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"feeBps","type":"uint128"}],"name":"setMarketFeeBps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalListings","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"},{"internalType":"uint256","name":"_quantity","type":"uint256"}],"name":"unlist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"},{"internalType":"uint256","name":"_pricePerToken","type":"uint256"},{"internalType":"address","name":"_currency","type":"address"},{"internalType":"uint256","name":"_tokensPerBuyer","type":"uint256"},{"internalType":"uint256","name":"_secondsUntilStart","type":"uint256"},{"internalType":"uint256","name":"_secondsUntilEnd","type":"uint256"}],"name":"updateListingParams","outputs":[],"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long) + ) + +# pylint: disable=too-many-lines diff --git a/nftlabs/modules/__init__.py b/nftlabs/modules/__init__.py index 62aff590..cd8ec236 100644 --- a/nftlabs/modules/__init__.py +++ b/nftlabs/modules/__init__.py @@ -1,7 +1,11 @@ +"""All Modules""" from .currency import * from .nft import * - +from .nft_types import * +from .currency_types import * +from .currency import * +from .market import * +from .market_types import * from .pack import * - -from .collection import * +from .pack_types import * diff --git a/nftlabs/modules/base.py b/nftlabs/modules/base.py index 027b95e2..c9ecf45a 100644 --- a/nftlabs/modules/base.py +++ b/nftlabs/modules/base.py @@ -1,3 +1,5 @@ +"""Base Module.""" + from typing import Callable, Optional, cast from eth_account.account import LocalAccount from web3.types import TxReceipt @@ -10,15 +12,24 @@ from zero_ex.contract_wrappers import TxParams -class _BaseModule: +class BaseModule: + """ + Base module for all modules. + """ get_client: Optional[Callable[[], Web3]] + """ Returns the client object. """ get_storage: Optional[Callable[[], IpfsStorage]] + """ Returns the storage object. """ get_signer_address: Optional[Callable[[], str]] + """ Returns the signer address. """ get_private_key: Optional[Callable[[], str]] + """ Returns the private key. """ get_transact_opts: Optional[Callable[[], TxParams]] - + """ Returns the transaction options. """ get_account: Optional[Callable[[], LocalAccount]] + """ Returns the account object. """ get_options: Optional[Callable[[], SdkOptions]] + """ Returns the options object. """ def __init__(self): self.get_client = None @@ -30,6 +41,9 @@ def __init__(self): self.get_options = None def execute_tx(self, tx) -> TxReceipt: + """ + Execute a transaction and return the receipt. + """ client = self.get_client() nonce = client.eth.get_transaction_count(self.get_signer_address()) tx['nonce'] = nonce @@ -38,11 +52,13 @@ def execute_tx(self, tx) -> TxReceipt: tx_hash = client.eth.send_raw_transaction(signed_tx.rawTransaction) return cast( TxReceipt, - client.eth.wait_for_transaction_receipt(tx_hash, timeout=self.get_options().tx_timeout_in_seconds) + client.eth.wait_for_transaction_receipt( + tx_hash, timeout=self.get_options().tx_timeout_in_seconds) ) def __sign_tx(self, tx): + """ + Sign a transaction. + """ signed_tx = self.get_account().sign_transaction(tx) return signed_tx - - diff --git a/nftlabs/modules/currency.py b/nftlabs/modules/currency.py index 01d00b93..cbbb39c7 100644 --- a/nftlabs/modules/currency.py +++ b/nftlabs/modules/currency.py @@ -1,3 +1,4 @@ +"""Interact with the Coin module of your app.""" from ..errors import NoSignerException from ..types import Role from ..abi.coin import Coin @@ -8,74 +9,120 @@ from typing import List, Dict -class CurrencyModule(_BaseModule): +class CurrencyModule(BaseModule): + """ + Currency Methods + """ + address: str __abi_module: Coin def __init__(self, address: str, client: Web3): + """ + Initializes the Currency module + """ super().__init__() self.address = address + """ The address of the Currency contract """ self.__abi_module = Coin(client, address) def total_supply(self) -> int: + """ + Gets the total supply of the currency + """ return self.__abi_module.total_supply.call() - """ - Gets the currency name, symbol, and decimals - """ - def get(self) -> Currency: + """ + Gets the currency name, symbol, and decimals + """ return self.__get_currency_metadata(self.address) def balance_of(self, address: str) -> int: + """ + Gets the balance of the given address + """ return self.__abi_module.balance_of.call(address) def balance(self): + """ + Gets the balance of the current address + """ return self.__abi_module.balance_of.call(self.get_signer_address()) def allowance(self, spender: str) -> int: + """ + Gets the allowance of the current address + """ return self.__abi_module.allowance.call(self.get_signer_address(), spender) def allowance_of(self, owner: str, spender: str) -> int: + """ + Gets the allowance of the current address + """ return self.__abi_module.allowance.call(owner, spender) def set_allowance(self, spender: str, amount: int): + """ + Sets the allowance of the current address + """ return self.execute_tx(self.__abi_module.approve.build_transaction( spender, amount, self.get_transact_opts() )) def mint_to(self, to: str, amount: int): + """ + Mints the given amount to the given address + """ return self.execute_tx(self.__abi_module.mint.build_transaction( to, amount, self.get_transact_opts() )) def mint(self, amount: int): + """ + Mints the given amount to the current address + """ return self.execute_tx(self.__abi_module.mint.build_transaction( self.get_signer_address(), amount, self.get_transact_opts() )) def burn(self, amount: int): + """ + Burns the given amount from the current address + """ return self.execute_tx(self.__abi_module.burn.build_transaction( amount, self.get_transact_opts() )) def burn_from(self, from_address: str, amount: int): + """ + Burns the given amount from the current address + """ return self.execute_tx(self.__abi_module.burn_from.build_transaction( from_address, amount, self.get_transact_opts() )) def transfer_from(self, from_address: str, to_address: str, amount: int): + """ + Transfers the given amount from the current address + """ return self.execute_tx(self.__abi_module.transfer_from.build_transaction( from_address, to_address, amount, self.get_transact_opts() )) def grant_role(self, role: Role, address: str): + """ + Grants the given role to the given address + """ role_hash = role.get_hash() self.execute_tx(self.__abi_module.grant_role.build_transaction( role_hash, address, self.get_transact_opts() )) def revoke_role(self, role: Role, address: str): + """ + Revokes the given role from the given address + """ role_hash = role.get_hash() try: @@ -94,11 +141,17 @@ def revoke_role(self, role: Role, address: str): )) def get_role_members(self, role: Role) -> List[str]: + """ + Gets the members of the given role + """ role_hash = role.get_hash() count = self.__abi_module.get_role_member_count.call(role_hash) return [self.__abi_module.get_role_member.call(role_hash, i) for i in range(count)] def get_all_role_members(self) -> Dict[Role, List[str]]: + """ + Gets all the role members + """ return { Role.admin.name: self.get_role_members(Role.admin), Role.minter.name: self.get_role_members(Role.minter), @@ -106,10 +159,23 @@ def get_all_role_members(self) -> Dict[Role, List[str]]: Role.pauser.name: self.get_role_members(Role.pauser) } + def set_module_metadata(metadata: str): + """ + Sets the metadata for the module + """ + uri = self.get_storage().upload_metadata( + metadata, self.address, self.get_signer_address()) + def get_value(self, value: int) -> Currency: + """ + Gets the value of the given amount + """ return self.__get_currency_value(self.address, value) def __get_currency_value(self, asset_address: str, price: int) -> CurrencyValue: + """ + Gets the value of the given amount + """ metadata = self.__get_currency_metadata(asset_address) return CurrencyValue( name=metadata.name, @@ -121,11 +187,17 @@ def __get_currency_value(self, asset_address: str, price: int) -> CurrencyValue: @staticmethod def format_units(value: int, decimals: int) -> str: + """ + Formats the given amount + """ decimal_transformer = float(10**decimals) val = float(value) / decimal_transformer return f'{val:.{decimals}f}' def __get_currency_metadata(self, asset_address: str) -> Currency: + """ + Gets the metadata of the given asset + """ if asset_address.lower().startswith("0x0000000000000000000000000000000000000000"): return Currency(name="", symbol="", decimals=0) @@ -135,3 +207,11 @@ def __get_currency_metadata(self, asset_address: str) -> Currency: symbol=erc20_module.symbol.call(), decimals=erc20_module.decimals.call() ) + + def set_restricted_transfer(self, restricted: bool = False): + """ + Sets the restricted transfer flag + """ + tx = self.__abi_module.set_restricted_transfer.build_transaction( + restricted, self.get_transact_opts()) + self.execute_tx(tx) diff --git a/nftlabs/modules/market.py b/nftlabs/modules/market.py new file mode 100644 index 00000000..06733224 --- /dev/null +++ b/nftlabs/modules/market.py @@ -0,0 +1,186 @@ +"""Interact with the market module of the app.""" +from web3 import Web3 +from typing import List, Dict +from . import BaseModule +from ..types import Role +from ..abi.market import Market +from ..types.market import ListArg, Filter +from ..types.listing import Listing +from ..abi.erc20 import ERC20 +from ..abi.erc165 import ERC165 +from ..abi.erc1155 import ERC1155 +from ..abi.nft import NFT + + +class MarketModule(BaseModule): + """ + Market Methods + """ + address: str + """ + Address of the market contract. + """ + __abi_module: Market + + def __init__(self, client: Web3, address: str): + """ + Initialize the Market Module. + """ + + super().__init__() + self.address = address + self.__abi_module = Market(client, address) + + #todo: return types + def list(self, arg: ListArg): + """ + List an asset for sale. + """ + from_address = self.get_signer_address() + client = self.get_client() + erc165 = ERC165(client, arg.asset_contract) + isERC721 = erc165.supports_interface( + client, interface_id=bytearray.fromhex("80ac58cd")) + if isERC721: + asset = NFT(client, arg.asset_contract) + approved = asset.is_approved_for_all( + from_address, self.address) + if not approved: + asset.is_approve_for_all(from_address, arg.asset_contract) + is_token_approved = (asset.is_approved_for_all( + arg.token_id).lower() == self.address.lower()) + if not is_token_approved: + asset.set_approval_for_all(arg.asset_contract, True) + else: + asset = ERC1155(client, arg.asset_contract) + approved = asset.is_approved_for_all(from_address, self.address) + + if not approved: + asset.set_approval_for_all(from_address, arg.asset_contract) + is_token_approved = (asset.get_approved( + arg.token_id).lower() == self.address.lower()) + if not is_token_approved: + asset.set_approval_for_all(self.address, True) + + tx = self.__abi_module.list.build_transaction( + arg.asset_contract, + arg.token_id, + arg.currency_contract, + arg.price_per_token, + arg.quantity, + arg.tokens_per_buyer, + arg.seconds_until_start, + arg.seconds_until_end, + self.get_transact_opts() + ) + + receipt = self.execute_tx(tx) + result = self.__abi_module.get_new_listing_event(tx_hash=receipt.transactionHash.hex()) + # listing_id = result[0]['args']['token_id'] + # return self.get(listing_id) + + def unlist(self, listing_id, quantity): + """ + Unlist an asset for sale. + """ + tx = self.__abi_module.unlist.build_transaction( + listing_id, + quantity, + self.get_transact_opts() + ) + self.execute_tx(tx) + + def unlist_all(self, listing_id: int): + """ + Unlist an asset for sale. + """ + self.unlist(listing_id, self.get(listing_id).quantity) + + def buy(self, listing_id: int, quantity: int): + """ + Buy a listing. + """ + listing = get(listing_id) + owner = self.get_signer_address() + spender = self.address + total_price = listing.price_per_token * quantity + if listing.currency_contract is not None and listing.currency_contract != "0x0000000000000000000000000000000000000000": + erc20 = ERC20(self.get_client(), listing.currency_contract) + allowance = erc20.allowance(owner, spender) + if allowance < total_price: + erc20.increase_allowance( + spender, + total_price, + self.get_transact_opts() + ) + tx = self.__abi_module.buy.build_transaction( + listing_id, + quantity, + self.get_transact_opts() + ) + receipt = self.execute_tx(tx) + result = self.__abi_module.get_new_sale_event( + tx_hash=receipt.transactionHash.hex()) + + def set_market_fee_bps(self, amount: int): + """ + Set the market fee in basis points. + """ + tx = self.__abi_module.set_market_fee_bps.build_transaction( + amount, + self.get_transact_opts()) + self.execute_tx(tx) + + def get(self, listing_id) -> List: + """ + Get a listing. + """ + return self.__abi_module.get_listing.call(listing_id) + + def get_all_listings(self, search_filter: Filter = None) -> List[Listing]: + """ + Returns all the listings. + """ + return self.get_all(search_filter) + + def set_module_metadata(metadata: str): + """ + Sets the metadata for the module + """ + uri = self.get_storage().upload_metadata( + metadata, self.address, self.get_signer_address()) + + def get_listing(self, listing_id: int) -> Listing: + """ + Get a listing. + """ + return self.get(listing_id) + + def get_all(self, search_filter: Filter = None) -> List[Listing]: + """ + Returns all the listings. + """ + if search_filter is None: + return self.__abi_module.get_all_listings.call() + elif search_filter.asset_contract is not None: + if search_filter.token_id is not None: + return self.__abi_module.get_listings_by_asset.call( + filer.asset_contract, + filer.token_id + ) + else: + return self.__abi_module.get_listings_by_asset_contract.call( + filer.asset_contract + ) + elif search_filter.seller is not None: + return self.__abi_module.get_listings_by_seller.call( + filer.seller + ) + else: + return self.__abi_module.get_all_listings.call() + + def total_listings(self) -> int: + """ + Returns the total supply of the market. + """ + self.__abi_module.total_listings.call() diff --git a/nftlabs/modules/market_types.py b/nftlabs/modules/market_types.py new file mode 100644 index 00000000..88022cc5 --- /dev/null +++ b/nftlabs/modules/market_types.py @@ -0,0 +1,32 @@ +"""Types for the Merket Module.""" + +from dataclasses import dataclass +from typing import Optional + + +@dataclass.dataclass +class ListArg: + """ + Arguments for listing a new item + """ + market_type: Optional[str] = None + limit: Optional[int] = None + offset: Optional[int] = None + asset_contract: str + token_id: int + currency_contract: str + price_per_token: int + quantity: int + tokens_per_buyer: int + seconds_until_start: int + seconds_until_end: int + + +@dataclass.dataclass +class Filter: + """ + Filter for the list_all method. + """ + seller: Optional[str] = None + tokenContract: Optional[str] = None + tokenId: Optional[int] = None \ No newline at end of file diff --git a/nftlabs/modules/nft.py b/nftlabs/modules/nft.py index aa1c3fab..71bccd47 100644 --- a/nftlabs/modules/nft.py +++ b/nftlabs/modules/nft.py @@ -1,3 +1,4 @@ +""" Interact with the NFT module of the app""" import copy import json @@ -14,6 +15,10 @@ class NftModule(_BaseModule): + """ + NFT Methods + """ + address: str __abi_module: NFT @@ -23,13 +28,20 @@ def __init__(self, address: str, client: Web3): self.__abi_module = NFT(client, address) def mint(self, arg: MintArg) -> NftType: - return self.mint_to(self.__get_signer_address(), arg) + """ + Mints a new token + """ + return self.mint_to(self.get_signer_address(), arg) + def mint_to( self, to_address: str, arg: MintArg, ) -> NftType: + """ + Mints a new token + """ final_properties: Dict if arg.properties is None: final_properties = {} @@ -47,17 +59,21 @@ def mint_to( uri = storage.upload(json.dumps(meta), self.address, self.__get_signer_address()) tx = self.__abi_module.mint_nft.build_transaction(to_address, uri, self.__get_transact_opts()) receipt = self.execute_tx(tx) - result = self.__abi_module.get_minted_event(tx_hash=receipt.transactionHash.hex()) + result = self.__abi_module.get_minted_event( + tx_hash=receipt.transactionHash.hex()) token_id = result[0]['args']['tokenId'] return self.get(token_id) def total_supply(self) -> int: + """ + Returns the total supply + """ return self.__abi_module.total_supply.call(tx_params=TxParams(from_=self.address)) def get(self, nft_id: int) -> NftType: - return self.__get_metadata(nft_id) - - def __get_metadata(self, nft_id: int) -> NftType: + """ + Returns the Metadata of a token + """ uri = self.__get_metadata_uri(nft_id) meta = self.get_storage().get(uri) meta_obj: NftType = NftType.from_json(meta) @@ -66,15 +82,26 @@ def __get_metadata(self, nft_id: int) -> NftType: return meta_obj def __get_metadata_uri(self, nft_id: int): + """ + Returns the uri of the metadata of a token + """ uri = self.__abi_module.token_uri.call(nft_id) if uri == "": - raise Exception("Could not find NFT metadata, are you sure it exists?") + raise Exception( + "Could not find NFT metadata, are you sure it exists?") return uri def mint_batch(self, args: List[MintArg]): - return self.mint_batch_to(self.__get_signer_address(), args) + """ + Mints a batch of tokens to the signer address + """ + return self.mint_batch_to(self.get_signer_address(), args) + def mint_batch_to(self, to_address: str, args: List[MintArg]): + """ + Mints a batch of tokens to the given address + """ uris = [self.get_storage().upload(json.dumps({ 'name': arg.name, 'description': arg.description, @@ -82,14 +109,20 @@ def mint_batch_to(self, to_address: str, args: List[MintArg]): 'properties': arg.properties if arg.properties is not None else {} }), self.address, self.__get_signer_address()) for arg in args] - tx = self.__abi_module.mint_nft_batch.build_transaction(to_address, uris, self.__get_transact_opts()) + tx = self.__abi_module.mint_nft_batch.build_transaction( + to_address, uris, self.get_transact_opts()) + receipt = self.execute_tx(tx) - result = self.__abi_module.get_minted_batch_event(tx_hash=receipt.transactionHash.hex()) + result = self.__abi_module.get_minted_batch_event( + tx_hash=receipt.transactionHash.hex()) token_ids = result[0]['args']['tokenIds'] return [self.get(i) for i in token_ids] def burn(self, token_id: int): + """ + Burns a given token + """ tx = self.__abi_module.burn.build_transaction( token_id, self.__get_transact_opts() @@ -97,6 +130,9 @@ def burn(self, token_id: int): self.execute_tx(tx) def transfer_from(self, from_address: str, to_address: str, token_id: int): + """ + Transfers a token from one address to another + """ tx = self.__abi_module.transfer_from.build_transaction( from_address, to_address, @@ -105,10 +141,10 @@ def transfer_from(self, from_address: str, to_address: str, token_id: int): ) self.execute_tx(tx) - """ - Transfers NFT from the current signers wallet to another wallet - """ def transfer(self, to_address: str, token_id: int): + """ + Transfers NFT from the current signers wallet to another wallet + """ tx = self.__abi_module.safe_transfer_from1.build_transaction( self.__get_signer_address(), to_address, @@ -118,55 +154,98 @@ def transfer(self, to_address: str, token_id: int): self.execute_tx(tx) def set_royalty_bps(self, amount: int): - tx = self.__abi_module.set_royalty_bps.build_transaction(amount, self.__get_transact_opts()) + """ + Sets the royalty percentage for the NFT + """ + tx = self.__abi_module.set_royalty_bps.build_transaction( + amount, self.get_transact_opts()) + self.execute_tx(tx) def get_all(self) -> List[NftType]: + """ + Returns all the NFTs in the system + """ max_id = self.__abi_module.next_token_id.call() return [self.get(i) for i in range(max_id)] - """ - Defaults to fetching the NFTs owned by the current signer (as indicated by the private key) - if the address parameter is not supplied - """ def get_owned(self, address: str = "") -> List[NftType]: + """ + Defaults to fetching the NFTs owned by the current signer (as indicated by the private key) + if the address parameter is not supplied + """ if address == "": address = self.__get_signer_address() balance = self.__abi_module.balance_of.call(address) - owned_tokens = [self.__token_of_owner_by_index(address, i) for i in range(balance)] + owned_tokens = [self.__token_of_owner_by_index( + address, i) for i in range(balance)] return [self.get(i) for i in owned_tokens] def __token_of_owner_by_index(self, address: str, token_id: int) -> int: return self.__abi_module.token_of_owner_by_index.call(address, token_id) - """ - Returns balance of the current signers wallet - """ def balance(self) -> int: - return self.__abi_module.balance_of.call(self.__get_signer_address()) + """ + Returns balance of the current signers wallet + """ + return self.__abi_module.balance_of.call(self.get_signer_address()) + def balance_of(self, address: str) -> int: + """ + Returns balance of the given address + """ return self.__abi_module.balance_of.call(address) + def owner_of(self, token_id: int) -> str: + """ + Returns the owner of the given token + """ + return self.__abi_module.owner_of.call(token_id) + + def get_metadata(self, token_id: int) -> NftType: + """ + Returns the metadata of the given token + """ + uri = self.__get_metadata_uri(token_id) + meta = self.get_storage().get(uri) + meta_obj: NftType = NftType.from_json(meta) + meta_obj.id = token_id + meta_obj.uri = uri + return meta_obj + def is_approved(self, address: str, operator: str) -> bool: + """ + Returns whether the given address is approved + """ return self.__abi_module.is_approved_for_all.call(address, operator) - """ - Sets approval for specified operator, defaults to grant approval - """ def set_approval(self, operator: str, approved: bool = True): + """ + Sets approval for specified operator, defaults to grant approval + """ self.execute_tx(self.__abi_module.set_approval_for_all.call( operator, approved, self.__get_transact_opts() )) def grant_role(self, role: Role, address: str): + """ + Grants the given role to the given address + """ + role_hash = role.get_hash() - self.execute_tx(self.__abi_module.grant_role.build_transaction( - role_hash, address, self.__get_transact_opts() - )) + tx = self.__abi_module.grant_role.build_transaction( + role_hash, address, + self.get_transact_opts() + ) + self.execute_tx(tx) + - def revoke_role(self, role, address: str): + def revoke_role(self, role: Role, address: str): + """ + Revokes the given role from the given address + """ role_hash = role.get_hash() self.execute_tx(self.__abi_module.revoke_role.build_transaction( role_hash, address, self.__get_transact_opts() @@ -176,3 +255,59 @@ def set_restricted_transfer(self, restricted: bool = True): self.execute_tx(self.__abi_module.set_restricted_transfer.build_transaction( restricted, self.__get_transact_opts() )) + + def get_with_owner(self, token_id: int, owner: str): + """ + Returns the NFT with the given token id and owner + """ + owner = self.owner_of(token_id) + meta = self.get_metadata(token_id) + return { + owner: owner, + meta: meta + } + + def set_module_metadata(metadata: str): + """ + Sets the metadata for the module + """ + uri = self.get_storage().upload_metadata( + metadata, self.address, self.get_signer_address()) + + def set_restricted_transfer(self, restricted: bool = False): + """ + Sets the restricted transfer flag + """ + + tx = self.__abi_module.set_restricted_transfer.build_transaction( + restricted, self.get_transact_opts()) + self.execute_tx(tx) + + def get_role_member_count(self, role: Role): + """ + Returns the number of members in the given role + """ + return self.__abi_module.get_role_member_count.call(role.get_hash()) + + def get_role_members(self, role: Role): + """ + Returns the members of the given role + """ + return [self.get_role_member(role, x) for x in range(stop=self.get_role_member_count(role))] + + def get_role_member(self, role: Role, index: int): + """ + Returns the member at the given index of the given role + """ + return self.__abi_module.get_role_member.call(role.get_hash(), index) + + def get_all_role_members(self): + """ + Returns all the members of all the roles + """ + return { + admin: [self.get_role_members(Role.admin) for admin in self.get_role_members(Role.admin)], + transfer: [self.get_role_members(Role.transfer) for transfer in self.get_role_members(Role.transfer)], + minter: [self.get_role_members(Role.minter) for minter in self.get_role_members(Role.minter)], + pauser: [self.get_role_members(Role.pauser) for pauser in self.get_role_members(Role.pauser)], + } diff --git a/nftlabs/modules/nft_types.py b/nftlabs/modules/nft_types.py new file mode 100644 index 00000000..c8b1932a --- /dev/null +++ b/nftlabs/modules/nft_types.py @@ -0,0 +1,15 @@ +"""Types for the NFT Module.""" +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class MintArg: + """ + Arguments for minting new tokens + """ + name: str + description: str = "" + image_uri: str = "" + properties: Optional[dict] = None + diff --git a/nftlabs/storage/ipfs_storage.py b/nftlabs/storage/ipfs_storage.py index 64c0a103..c16cc25e 100644 --- a/nftlabs/storage/ipfs_storage.py +++ b/nftlabs/storage/ipfs_storage.py @@ -40,3 +40,7 @@ def upload(self, data, contract_address: str, signer_address: str) -> str: response = result.json() return response['IpfsUri'] + + def upload_metadata(self, metadata: str, contract_address: str, signer_address: str) -> str: + if type(metadata) == str: + return self.upload(metadata, contract_address, signer_address) diff --git a/nftlabs/types/currency/__init__.py b/nftlabs/types/currency/__init__.py index 4744fc29..18fbde2f 100644 --- a/nftlabs/types/currency/__init__.py +++ b/nftlabs/types/currency/__init__.py @@ -1,8 +1,11 @@ +"""Types for the Currency Module.""" + import dataclasses @dataclasses.dataclass class Currency: + """Currency class.""" name: str symbol: str decimals: int @@ -10,5 +13,8 @@ class Currency: @dataclasses.dataclass class CurrencyValue(Currency): + """ + Type for currency values. + """ value: str display_value: str diff --git a/nftlabs/types/listing.py b/nftlabs/types/listing.py new file mode 100644 index 00000000..229b77b6 --- /dev/null +++ b/nftlabs/types/listing.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass +from typing import Optional, Union +from ..nft import NftMetadata +from ..currency import CurrencyValue +from dataclasses_json import dataclass_json +import datetime + +@dataclass_json +@dataclass +class Listing: + id: str + seller: str + token_contract: str + token_id: str + token_metadata: Optional[NFTMetadata] = None + quantity: int + currency_contract: str + currency_metadata: CurrencyValue | null + price: int + sale_start: datetime.datetime + sale_end: datetime.datetime \ No newline at end of file diff --git a/nftlabs/types/market/__init__.py b/nftlabs/types/market/__init__.py new file mode 100644 index 00000000..0dd4d56e --- /dev/null +++ b/nftlabs/types/market/__init__.py @@ -0,0 +1,29 @@ +from dataclasses import dataclass +from typing import Optional + +@dataclass.dataclass +class ListArg: + """ + Arguments for listing a new item + """ + market_type: Optional[str] = None + limit: Optional[int] = None + offset: Optional[int] = None + asset_contract: str + token_id: int + currency_contract: str + price_per_token: int + quantity: int + tokens_per_buyer: int + seconds_until_start: int + seconds_until_end: int + + +@dataclass.dataclass +class Filter: + """ + Filter for the list_all method. + """ + seller: Optional[str] = None + tokenContract: Optional[str] = None + tokenId: Optional[int] = None \ No newline at end of file diff --git a/nftlabs/types/role.py b/nftlabs/types/role.py index 6e5e4f4f..3451663a 100644 --- a/nftlabs/types/role.py +++ b/nftlabs/types/role.py @@ -7,6 +7,7 @@ class Role(enum.Enum): minter = "MINTER_ROLE" transfer = "TRANSFER_ROLE" pauser = "PAUSER_ROLE" + lister = "LISTER_ROLE" def get_hash(self) -> bytes: if self.name == "admin":