Skip to content

Commit

Permalink
fix: estimate gas (#37)
Browse files Browse the repository at this point in the history
Co-authored-by: fubuloubu <[email protected]>
  • Loading branch information
antazoey and fubuloubu authored Feb 27, 2024
1 parent ea9f9aa commit 55c8853
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 19 deletions.
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
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

0 comments on commit 55c8853

Please sign in to comment.