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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: estimate gas #37

Merged
merged 9 commits into from
Feb 27, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions ape_safe/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,21 @@ def load_submitter(

def prepare_transaction(self, txn: TransactionAPI) -> TransactionAPI:
# NOTE: Need to override `AccountAPI` behavior for balance checks
if txn.gas_limit is None:
txn.gas_limit = self.estimate_gas_cost(txn=txn)

return self.provider.prepare_transaction(txn)

def estimate_gas_cost(self, **kwargs) -> int:
operation = kwargs.pop("operation", 0)
txn = kwargs.pop("txn", self.as_transaction(**kwargs))
return (
self.client.estimate_gas_cost(
txn.receiver or ZERO_ADDRESS, txn.value, txn.data, operation=operation
)
or 0
)

def _preapproved_signature(
self, signer: Union[AddressType, BaseAddress, str]
) -> MessageSignature:
Expand Down
14 changes: 14 additions & 0 deletions ape_safe/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,20 @@ def post_signatures(

raise # The error from BaseClient we are already raising (no changes)

def estimate_gas_cost(
self, receiver: AddressType, value: int, data: bytes, operation: int = 0
) -> Optional[int]:
url = f"safes/{self.address}/multisig-transactions/estimations"
request: Dict = {
"to": receiver,
"value": value,
"data": HexBytes(data).hex(),
"operation": operation,
}
result = self._post(url, json=request).json()
gas = result.get("safeTxGas")
return int(HexBytes(gas).hex(), 16)


__all__ = [
"ExecutedTxData",
Expand Down
5 changes: 5 additions & 0 deletions ape_safe/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ def post_signatures(
signatures: Dict[AddressType, MessageSignature],
): ...

@abstractmethod
def estimate_gas_cost(
self, receiver: AddressType, value: int, data: bytes, operation: int = 0
) -> Optional[int]: ...

"""Shared methods"""

def get_transactions(
Expand Down
7 changes: 6 additions & 1 deletion ape_safe/client/mock.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime, timezone
from typing import Dict, Iterator, List, Union, cast
from typing import Dict, Iterator, List, Optional, Union, cast

from ape.contracts import ContractInstance
from ape.types import AddressType, MessageSignature
Expand Down Expand Up @@ -109,3 +109,8 @@ def post_signatures(
signatureType=SignatureType.EOA,
)
)

def estimate_gas_cost(
self, receiver: AddressType, value: int, data: bytes, operation: int = 0
) -> Optional[int]:
return None # Estimate gas normally
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming this works in the tests, but if not I think the issue is likely that the gas prices are nonzero

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What issue?

40 changes: 22 additions & 18 deletions tests/functional/test_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_init(safe, OWNERS, THRESHOLD, safe_contract):
assert safe.next_nonce == 0


@pytest.mark.parametrize("mode", ["impersonate", "api", "sign"])
@pytest.mark.parametrize("mode", ("impersonate", "api", "sign"))
def test_swap_owner(safe, accounts, OWNERS, mode):
impersonate = mode == "impersonate"
submit = mode != "api"
Expand All @@ -30,21 +30,24 @@ def test_swap_owner(safe, accounts, OWNERS, mode):
# NOTE: Since the signers are processed in order, we replace the last account

prev_owner = safe.compute_prev_signer(old_owner)
exec_transaction = lambda: safe.contract.swapOwner( # noqa: E731
prev_owner,
old_owner,
new_owner,
sender=safe,
impersonate=impersonate,
submit=submit,
)

def exec_transaction():
return safe.contract.swapOwner(
prev_owner,
old_owner,
new_owner,
sender=safe,
impersonate=impersonate,
submit=submit,
)

if submit:
receipt = exec_transaction()

else:
# Attempting to execute should raise `SignatureError` and push `safe_tx` to mock client
assert len(list(safe.client.get_transactions(confirmed=False))) == 0
size = len(list(safe.client.get_transactions(confirmed=False)))
assert size == 0

with pytest.raises(SignatureError):
exec_transaction()
Expand Down Expand Up @@ -78,21 +81,22 @@ def test_swap_owner(safe, accounts, OWNERS, mode):
assert new_owner.address in safe.signers


@pytest.mark.parametrize("mode", ["impersonate", "api", "sign"])
@pytest.mark.parametrize("mode", ("impersonate", "api", "sign"))
def test_add_owner(safe, accounts, OWNERS, mode):
impersonate = mode == "impersonate"
submit = mode != "api"

new_owner = accounts[len(OWNERS)] # replace owner 1 with account N + 1
assert new_owner.address not in safe.signers

exec_transaction = lambda: safe.contract.addOwnerWithThreshold( # noqa: E731
new_owner,
safe.confirmations_required,
sender=safe,
impersonate=impersonate,
submit=submit,
)
def exec_transaction():
return safe.contract.addOwnerWithThreshold(
new_owner,
safe.confirmations_required,
sender=safe,
impersonate=impersonate,
submit=submit,
)

if submit:
receipt = exec_transaction()
Expand Down
Loading