Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add receipt / txn_hash to ContractInstance #955

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/userguides/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def main():
or

```python
from ape import project, chain, accounts
from ape import project, accounts

def main():
account = accounts.test_accounts[0]
Expand Down
14 changes: 14 additions & 0 deletions docs/userguides/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,23 @@ from ape import accounts, project

def deploy():
account = accounts.load("MyAccount")
# Assume you have a contract named `MyContract` in your project's contracts folder.
return account.deploy(project.MyContract)
antazoey marked this conversation as resolved.
Show resolved Hide resolved
```

To get the receipt of a `deploy` transaction, use the [ContractInstance.receipt](../methoddocs/contracts.html#ape.contracts.base.ContractInstance.receipt) property:

```python
from ape import accounts, project

dev = accounts.load("dev")
contract = project.MyContract.deploy(sender=dev)

# The receipt is available on the contract instance and has the expected sender.
receipt = contract.receipt
assert receipt.sender == dev
```

### Deployment from Ape Console

Deploying from [ape console](./console.html) allows you to interact with a contract in real time. You can also use the `--network` flag to connect a live network.
Expand Down
14 changes: 7 additions & 7 deletions src/ape/api/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,22 +165,22 @@ def deploy(self, contract: "ContractContainer", *args, **kwargs) -> "ContractIns
:class:`~ape.contracts.ContractInstance`: An instance of the deployed contract.
"""

from ape.contracts import ContractInstance

txn = contract(*args, **kwargs)
txn.sender = self.address
receipt = self.call(txn)

if not receipt.contract_address:
raise AccountsError(f"'{receipt.txn_hash}' did not create a contract.")

address = self.provider.network.ecosystem.decode_address(receipt.contract_address)
contract_type = contract.contract_type
styled_address = click.style(receipt.contract_address, bold=True)
contract_name = contract.contract_type.name or "<Unnamed Contract>"
contract_name = contract_type.name or "<Unnamed Contract>"
logger.success(f"Contract '{contract_name}' deployed to: {styled_address}")
contract_instance = self.chain_manager.contracts.instance_at(
address, contract.contract_type
)
self.chain_manager.contracts[address] = contract_instance.contract_type
return contract_instance
instance = ContractInstance.from_receipt(receipt, contract_type)
self.chain_manager.contracts.cache_deployment(instance)
return instance

def check_signature(
self,
Expand Down
68 changes: 55 additions & 13 deletions src/ape/contracts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,10 +572,51 @@ class ContractInstance(BaseAddress):
contract = a.deploy(project.MyContract) # The result of 'deploy()' is a ContractInstance
"""

def __init__(self, address: AddressType, contract_type: ContractType) -> None:
def __init__(
self,
address: Union[AddressType, str],
contract_type: ContractType,
txn_hash: Optional[str] = None,
) -> None:
super().__init__()
self._address = address
self.contract_type = contract_type
self.txn_hash = txn_hash
self._cached_receipt: Optional[ReceiptAPI] = None

@classmethod
def from_receipt(cls, receipt: ReceiptAPI, contract_type: ContractType) -> "ContractInstance":
address = receipt.contract_address
if not address:
raise ContractError(
"Receipt missing 'contract_address' field. "
"Was this from a deploy transaction (e.g. `project.MyContract.deploy()`)?"
)

instance = cls(
address=address,
contract_type=contract_type,
txn_hash=receipt.txn_hash,
)
instance._cached_receipt = receipt
return instance

@property
def receipt(self) -> Optional[ReceiptAPI]:
"""
The receipt associated with deploying the contract instance,
if it is known and exists.
"""

if not self._cached_receipt and self.txn_hash:
receipt = self.provider.get_transaction(self.txn_hash)
self._cached_receipt = receipt
return receipt

elif self._cached_receipt:
return self._cached_receipt

return None

def __repr__(self) -> str:
contract_name = self.contract_type.name or "Unnamed contract"
Expand All @@ -589,7 +630,8 @@ def address(self) -> AddressType:
Returns:
``AddressType``
"""
return self._address

return self.provider.network.ecosystem.decode_address(self._address)

@cached_property
def _view_methods_(self) -> Dict[str, ContractCallHandler]:
Expand Down Expand Up @@ -774,7 +816,7 @@ def deployments(self):

return self.chain_manager.contracts.get_deployments(self)

def at(self, address: AddressType) -> ContractInstance:
def at(self, address: AddressType, txn_hash: Optional[str] = None) -> ContractInstance:
"""
Get a contract at the given address.

Expand All @@ -789,12 +831,16 @@ def at(self, address: AddressType) -> ContractInstance:
**NOTE**: Things will not work as expected if the contract is not actually
deployed to this address or if the contract at the given address has
a different ABI than :attr:`~ape.contracts.ContractContainer.contract_type`.
txn_hash (str): The hash of the transaction that deployed the contract, if
available. Defaults to ``None``.

Returns:
:class:`~ape.contracts.ContractInstance`
"""

return self.chain_manager.contracts.instance_at(address, self.contract_type)
return self.chain_manager.contracts.instance_at(
address, self.contract_type, txn_hash=txn_hash
)

def __call__(self, *args, **kwargs) -> TransactionAPI:
args = self.conversion_manager.convert(args, tuple)
Expand Down Expand Up @@ -826,16 +872,12 @@ def deploy(self, *args, **kwargs) -> ContractInstance:
if not receipt.contract_address:
raise ContractError(f"'{receipt.txn_hash}' did not create a contract.")

address = click.style(receipt.contract_address, bold=True)
styled_address = click.style(receipt.contract_address, bold=True)
contract_name = self.contract_type.name or "<Unnamed Contract>"
logger.success(f"Contract '{contract_name}' deployed to: {address}")

contract_instance = ContractInstance(
address=receipt.contract_address, # type: ignore
contract_type=self.contract_type,
)
self.chain_manager.contracts[contract_instance.address] = contract_instance.contract_type
return contract_instance
logger.success(f"Contract '{contract_name}' deployed to: {styled_address}")
instance = ContractInstance.from_receipt(receipt, self.contract_type)
self.chain_manager.contracts.cache_deployment(instance)
return instance


def _get_non_contract_error(address: str, network_name: str) -> ContractError:
Expand Down
3 changes: 1 addition & 2 deletions src/ape/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ class SignatureError(AccountsError):

class ContractError(ApeException):
"""
Raised when issues occur when interacting with a contract
(calls or transactions).
Raised when issues occur with contracts.
"""


Expand Down