• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

safe-global / safe-eth-py / 10793540350

10 Sep 2024 01:31PM UTC coverage: 93.551% (-0.3%) from 93.892%
10793540350

push

github

falvaradorodriguez
Fix cowswap test

8777 of 9382 relevant lines covered (93.55%)

3.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.61
/safe_eth/safe/safe_tx.py
1
from functools import cached_property
4✔
2
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Type
4✔
3

4
from eth_account import Account
4✔
5
from eth_typing import ChecksumAddress
4✔
6
from hexbytes import HexBytes
4✔
7
from packaging.version import Version
4✔
8
from web3.contract.contract import ContractFunction
4✔
9
from web3.exceptions import Web3Exception
4✔
10
from web3.types import BlockIdentifier, Nonce, TxParams, Wei
4✔
11

12
from safe_eth.eth import EthereumClient
4✔
13
from safe_eth.eth.constants import NULL_ADDRESS
4✔
14
from safe_eth.eth.contracts import get_safe_contract
4✔
15
from safe_eth.eth.eip712 import eip712_encode
4✔
16
from safe_eth.eth.ethereum_client import TxSpeed
4✔
17

18
from ..eth.utils import fast_keccak
4✔
19
from .exceptions import (
4✔
20
    CouldNotFinishInitialization,
21
    CouldNotPayGasWithEther,
22
    CouldNotPayGasWithToken,
23
    HashHasNotBeenApproved,
24
    InvalidContractSignatureLocation,
25
    InvalidInternalTx,
26
    InvalidMultisigTx,
27
    InvalidOwnerProvided,
28
    InvalidSignaturesProvided,
29
    MethodCanOnlyBeCalledFromThisContract,
30
    ModuleManagerException,
31
    NotEnoughSafeTransactionGas,
32
    OnlyOwnersCanApproveAHash,
33
    OwnerManagerException,
34
    SafeTransactionFailedWhenGasPriceAndSafeTxGasEmpty,
35
    SignatureNotProvidedByOwner,
36
    SignaturesDataTooShort,
37
    ThresholdNeedsToBeDefined,
38
)
39
from .safe_signature import SafeSignature
4✔
40
from .signatures import signature_to_bytes
4✔
41

42

43
class SafeTx:
4✔
44
    def __init__(
4✔
45
        self,
46
        ethereum_client: EthereumClient,
47
        safe_address: ChecksumAddress,
48
        to: Optional[ChecksumAddress],
49
        value: int,
50
        data: bytes,
51
        operation: int,
52
        safe_tx_gas: int,
53
        base_gas: int,
54
        gas_price: int,
55
        gas_token: Optional[ChecksumAddress],
56
        refund_receiver: Optional[ChecksumAddress],
57
        signatures: Optional[bytes] = None,
58
        safe_nonce: Optional[int] = None,
59
        safe_version: Optional[str] = None,
60
        chain_id: Optional[int] = None,
61
    ):
62
        """
63
        :param ethereum_client:
64
        :param safe_address:
65
        :param to:
66
        :param value:
67
        :param data:
68
        :param operation:
69
        :param safe_tx_gas:
70
        :param base_gas:
71
        :param gas_price:
72
        :param gas_token:
73
        :param refund_receiver:
74
        :param signatures:
75
        :param safe_nonce: Current nonce of the Safe. If not provided, it will be retrieved from network
76
        :param safe_version: Safe version 1.0.0 renamed `baseGas` to `dataGas`. Safe version 1.3.0 added `chainId` to
77
        the `domainSeparator`. If not provided, it will be retrieved from network
78
        :param chain_id: Ethereum network chain_id is used in hash calculation for Safes >= 1.3.0. If not provided,
79
        it will be retrieved from the provided ethereum_client
80
        """
81

82
        self.ethereum_client = ethereum_client
4✔
83
        self.safe_address = safe_address
4✔
84
        self.to = to or NULL_ADDRESS
4✔
85
        self.value = int(value)
4✔
86
        self.data = HexBytes(data) if data else b""
4✔
87
        self.operation = int(operation)
4✔
88
        self.safe_tx_gas = int(safe_tx_gas)
4✔
89
        self.base_gas = int(base_gas)
4✔
90
        self.gas_price = int(gas_price)
4✔
91
        self.gas_token = gas_token or NULL_ADDRESS
4✔
92
        self.refund_receiver = refund_receiver or NULL_ADDRESS
4✔
93
        self.signatures = signatures or b""
4✔
94
        self._safe_nonce = safe_nonce and int(safe_nonce)
4✔
95
        self._safe_version = safe_version
4✔
96
        self._chain_id = chain_id and int(chain_id)
4✔
97

98
        self.tx: Optional[TxParams] = None  # If executed, `tx` is set
4✔
99
        self.tx_hash: Optional[bytes] = None  # If executed, `tx_hash` is set
4✔
100

101
    def __str__(self):
4✔
102
        return (
×
103
            f"SafeTx - safe={self.safe_address} - to={self.to} - value={self.value} - data={self.data.hex()} - "
104
            f"operation={self.operation} - safe-tx-gas={self.safe_tx_gas} - base-gas={self.base_gas} - "
105
            f"gas-price={self.gas_price} - gas-token={self.gas_token} - refund-receiver={self.refund_receiver} - "
106
            f"signers = {self.signers}"
107
        )
108

109
    @property
4✔
110
    def w3(self):
4✔
111
        return self.ethereum_client.w3
4✔
112

113
    @cached_property
4✔
114
    def contract(self):
4✔
115
        return get_safe_contract(self.w3, address=self.safe_address)
4✔
116

117
    @cached_property
4✔
118
    def chain_id(self) -> int:
4✔
119
        if self._chain_id is not None:
4✔
120
            return self._chain_id
4✔
121
        else:
122
            return self.ethereum_client.get_chain_id()
4✔
123

124
    @cached_property
4✔
125
    def safe_nonce(self) -> int:
4✔
126
        if self._safe_nonce is not None:
4✔
127
            return self._safe_nonce
4✔
128
        else:
129
            return self.contract.functions.nonce().call()
×
130

131
    @cached_property
4✔
132
    def safe_version(self) -> str:
4✔
133
        if self._safe_version is not None:
4✔
134
            return self._safe_version
4✔
135
        else:
136
            return self.contract.functions.VERSION().call()
4✔
137

138
    @property
4✔
139
    def eip712_structured_data(self) -> Dict[str, Any]:
4✔
140
        safe_version = Version(self.safe_version)
4✔
141

142
        # Safes >= 1.0.0 Renamed `baseGas` to `dataGas`
143
        base_gas_key = "baseGas" if safe_version >= Version("1.0.0") else "dataGas"
4✔
144

145
        types = {
4✔
146
            "EIP712Domain": [{"name": "verifyingContract", "type": "address"}],
147
            "SafeTx": [
148
                {"name": "to", "type": "address"},
149
                {"name": "value", "type": "uint256"},
150
                {"name": "data", "type": "bytes"},
151
                {"name": "operation", "type": "uint8"},
152
                {"name": "safeTxGas", "type": "uint256"},
153
                {"name": base_gas_key, "type": "uint256"},
154
                {"name": "gasPrice", "type": "uint256"},
155
                {"name": "gasToken", "type": "address"},
156
                {"name": "refundReceiver", "type": "address"},
157
                {"name": "nonce", "type": "uint256"},
158
            ],
159
        }
160
        message = {
4✔
161
            "to": self.to,
162
            "value": self.value,
163
            "data": self.data,
164
            "operation": self.operation,
165
            "safeTxGas": self.safe_tx_gas,
166
            base_gas_key: self.base_gas,
167
            "dataGas": self.base_gas,
168
            "gasPrice": self.gas_price,
169
            "gasToken": self.gas_token,
170
            "refundReceiver": self.refund_receiver,
171
            "nonce": self.safe_nonce,
172
        }
173

174
        payload: Dict[str, Any] = {
4✔
175
            "types": types,
176
            "primaryType": "SafeTx",
177
            "domain": {"verifyingContract": self.safe_address},
178
            "message": message,
179
        }
180

181
        # Enable chainId from v1.3.0 onwards
182
        if safe_version >= Version("1.3.0"):
4✔
183
            payload["domain"]["chainId"] = self.chain_id
4✔
184
            types["EIP712Domain"].insert(0, {"name": "chainId", "type": "uint256"})
4✔
185

186
        return payload
4✔
187

188
    @property
4✔
189
    def safe_tx_hash_preimage(self) -> HexBytes:
4✔
190
        return HexBytes(b"".join(eip712_encode(self.eip712_structured_data)))
4✔
191

192
    @property
4✔
193
    def safe_tx_hash(self) -> HexBytes:
4✔
194
        return HexBytes(fast_keccak(self.safe_tx_hash_preimage))
4✔
195

196
    @property
4✔
197
    def signers(self) -> List[str]:
4✔
198
        if not self.signatures:
4✔
199
            return []
4✔
200
        else:
201
            return [
4✔
202
                safe_signature.owner
203
                for safe_signature in SafeSignature.parse_signature(
204
                    self.signatures, self.safe_tx_hash
205
                )
206
            ]
207

208
    @property
4✔
209
    def sorted_signers(self):
4✔
210
        return sorted(self.signers, key=lambda x: int(x, 16))
4✔
211

212
    @property
4✔
213
    def w3_tx(self) -> ContractFunction:
4✔
214
        """
215
        :return: Web3 contract tx prepared for `call`, `transact` or `build_transaction`
216
        """
217
        return self.contract.functions.execTransaction(
4✔
218
            self.to,
219
            self.value,
220
            self.data,
221
            self.operation,
222
            self.safe_tx_gas,
223
            self.base_gas,
224
            self.gas_price,
225
            self.gas_token,
226
            self.refund_receiver,
227
            self.signatures,
228
        )
229

230
    def _raise_safe_vm_exception(self, message: str) -> NoReturn:
4✔
231
        error_with_exception: Dict[str, Type[InvalidMultisigTx]] = {
4✔
232
            # https://github.com/safe-global/safe-contracts/blob/v1.3.0/docs/error_codes.md
233
            "GS000": CouldNotFinishInitialization,
234
            "GS001": ThresholdNeedsToBeDefined,
235
            "Could not pay gas costs with ether": CouldNotPayGasWithEther,
236
            "GS011": CouldNotPayGasWithEther,
237
            "Could not pay gas costs with token": CouldNotPayGasWithToken,
238
            "GS012": CouldNotPayGasWithToken,
239
            "GS013": SafeTransactionFailedWhenGasPriceAndSafeTxGasEmpty,
240
            "Hash has not been approved": HashHasNotBeenApproved,
241
            "Hash not approved": HashHasNotBeenApproved,
242
            "GS025": HashHasNotBeenApproved,
243
            "Invalid contract signature location: data not complete": InvalidContractSignatureLocation,
244
            "GS023": InvalidContractSignatureLocation,
245
            "Invalid contract signature location: inside static part": InvalidContractSignatureLocation,
246
            "GS021": InvalidContractSignatureLocation,
247
            "Invalid contract signature location: length not present": InvalidContractSignatureLocation,
248
            "GS022": InvalidContractSignatureLocation,
249
            "Invalid contract signature provided": InvalidContractSignatureLocation,
250
            "GS024": InvalidContractSignatureLocation,
251
            "Invalid owner provided": InvalidOwnerProvided,
252
            "Invalid owner address provided": InvalidOwnerProvided,
253
            "GS026": InvalidOwnerProvided,
254
            "Invalid signatures provided": InvalidSignaturesProvided,
255
            "Not enough gas to execute safe transaction": NotEnoughSafeTransactionGas,
256
            "GS010": NotEnoughSafeTransactionGas,
257
            "Only owners can approve a hash": OnlyOwnersCanApproveAHash,
258
            "GS030": OnlyOwnersCanApproveAHash,
259
            "GS031": MethodCanOnlyBeCalledFromThisContract,
260
            "Signature not provided by owner": SignatureNotProvidedByOwner,
261
            "Signatures data too short": SignaturesDataTooShort,
262
            "GS020": SignaturesDataTooShort,
263
            # ModuleManager
264
            "GS100": ModuleManagerException,
265
            "Invalid module address provided": ModuleManagerException,
266
            "GS101": ModuleManagerException,
267
            "GS102": ModuleManagerException,
268
            "Invalid prevModule, module pair provided": ModuleManagerException,
269
            "GS103": ModuleManagerException,
270
            "Method can only be called from an enabled module": ModuleManagerException,
271
            "GS104": ModuleManagerException,
272
            "Module has already been added": ModuleManagerException,
273
            # OwnerManager
274
            "Address is already an owner": OwnerManagerException,
275
            "GS200": OwnerManagerException,  # Owners have already been setup
276
            "GS201": OwnerManagerException,  # Threshold cannot exceed owner count
277
            "GS202": OwnerManagerException,  # Invalid owner address provided
278
            "GS203": OwnerManagerException,  # Invalid ower address provided
279
            "GS204": OwnerManagerException,  # Address is already an owner
280
            "GS205": OwnerManagerException,  # Invalid prevOwner, owner pair provided
281
            "Invalid prevOwner, owner pair provided": OwnerManagerException,
282
            "New owner count needs to be larger than new threshold": OwnerManagerException,
283
            "Threshold cannot exceed owner count": OwnerManagerException,
284
            "Threshold needs to be greater than 0": OwnerManagerException,
285
        }
286

287
        for reason, custom_exception in error_with_exception.items():
4✔
288
            if reason in message:
4✔
289
                raise custom_exception(message)
4✔
290
        raise InvalidMultisigTx(message)
×
291

292
    def call(
4✔
293
        self,
294
        tx_sender_address: Optional[str] = None,
295
        tx_gas: Optional[int] = None,
296
        block_identifier: Optional[BlockIdentifier] = "latest",
297
    ) -> int:
298
        """
299
        :param tx_sender_address:
300
        :param tx_gas: Force a gas limit
301
        :param block_identifier:
302
        :return: `1` if everything ok
303
        """
304
        parameters: TxParams = {
4✔
305
            "from": tx_sender_address if tx_sender_address else self.safe_address
306
        }
307

308
        if tx_gas:
4✔
309
            parameters["gas"] = tx_gas
4✔
310
        try:
4✔
311
            success = self.w3_tx.call(
4✔
312
                parameters,
313
                block_identifier=block_identifier
314
                if block_identifier is not None
315
                else "latest",
316
            )
317

318
            if not success:
4✔
319
                raise InvalidInternalTx(
4✔
320
                    "Success bit is %d, should be equal to 1" % success
321
                )
322
            return success
4✔
323
        except (Web3Exception, ValueError) as exc:
4✔
324
            # e.g. web3.exceptions.ContractLogicError: execution reverted: Invalid owner provided
325
            return self._raise_safe_vm_exception(str(exc))
4✔
326
        except ValueError as exc:  # Parity
4✔
327
            """
328
            Parity throws a ValueError, e.g.
329
            {'code': -32015,
330
             'message': 'VM execution error.',
331
             'data': 'Reverted 0x08c379a0000000000000000000000000000000000000000000000000000000000000020000000000000000
332
                      000000000000000000000000000000000000000000000001b496e76616c6964207369676e6174757265732070726f7669
333
                      6465640000000000'
334
            }
335
            """
336
            error_dict = exc.args[0]
×
337
            data = error_dict.get("data")
×
338
            if data and isinstance(data, str) and "Reverted " in data:
×
339
                # Parity
340
                result = HexBytes(data.replace("Reverted ", ""))
×
341
                return self._raise_safe_vm_exception(str(result))
×
342
            else:
343
                raise exc
×
344

345
    def recommended_gas(self) -> Wei:
4✔
346
        """
347
        :return: Recommended gas to use on the ethereum_tx
348
        """
349
        return Wei(self.base_gas + self.safe_tx_gas + 75000)
4✔
350

351
    def execute(
4✔
352
        self,
353
        tx_sender_private_key: str,
354
        tx_gas: Optional[int] = None,
355
        tx_gas_price: Optional[int] = None,
356
        tx_nonce: Optional[int] = None,
357
        block_identifier: Optional[BlockIdentifier] = "latest",
358
        eip1559_speed: Optional[TxSpeed] = None,
359
    ) -> Tuple[HexBytes, TxParams]:
360
        """
361
        Send multisig tx to the Safe
362

363
        :param tx_sender_private_key: Sender private key
364
        :param tx_gas: Gas for the external tx. If not, `(safe_tx_gas + base_gas) * 2` will be used
365
        :param tx_gas_price: Gas price of the external tx. If not, `gas_price` will be used
366
        :param tx_nonce: Force nonce for `tx_sender`
367
        :param block_identifier: `latest` or `pending`
368
        :param eip1559_speed: If provided, use EIP1559 transaction
369
        :return: Tuple(tx_hash, tx)
370
        :raises: InvalidMultisigTx: If user tx cannot go through the Safe
371
        """
372

373
        sender_account = Account.from_key(tx_sender_private_key)
4✔
374
        if eip1559_speed and self.ethereum_client.is_eip1559_supported():
4✔
375
            tx_parameters = self.ethereum_client.set_eip1559_fees(
×
376
                {
377
                    "from": sender_account.address,
378
                },
379
                tx_speed=eip1559_speed,
380
            )
381
        else:
382
            tx_parameters = {
4✔
383
                "from": sender_account.address,
384
                "gasPrice": Wei(tx_gas_price)
385
                if tx_gas_price
386
                else self.w3.eth.gas_price,
387
            }
388

389
        if tx_gas:
4✔
390
            tx_parameters["gas"] = tx_gas
×
391
        if tx_nonce is not None:
4✔
392
            tx_parameters["nonce"] = Nonce(tx_nonce)
×
393

394
        self.tx = self.w3_tx.build_transaction(tx_parameters)
4✔
395
        self.tx["gas"] = Wei(
4✔
396
            tx_gas or (max(self.tx["gas"] + 75000, self.recommended_gas()))
397
        )
398

399
        self.tx_hash = self.ethereum_client.send_unsigned_transaction(
4✔
400
            self.tx,
401
            private_key=sender_account.key,
402
            retry=False if tx_nonce is not None else True,
403
            block_identifier=block_identifier,
404
        )
405

406
        # Set signatures empty after executing the tx. `Nonce` is increased even if it fails,
407
        # so signatures are not valid anymore
408
        self.signatures = b""
4✔
409
        return self.tx_hash, self.tx
4✔
410

411
    def sign(self, private_key: str) -> bytes:
4✔
412
        """
413
        {bytes32 r}{bytes32 s}{uint8 v}
414
        :param private_key:
415
        :return: Signature
416
        """
417
        account = Account.from_key(private_key)
4✔
418
        signature_dict = account.signHash(self.safe_tx_hash)
4✔
419
        signature = signature_to_bytes(
4✔
420
            signature_dict["v"], signature_dict["r"], signature_dict["s"]
421
        )
422

423
        # Insert signature sorted
424
        if account.address not in self.signers:
4✔
425
            unsorted_signatures = SafeSignature.parse_signature(
4✔
426
                self.signatures + signature, self.safe_tx_hash
427
            )
428
            self.signatures = SafeSignature.export_signatures(unsorted_signatures)
4✔
429

430
        return signature
4✔
431

432
    def unsign(self, address: str) -> bool:
4✔
433
        current_tx_signatures = SafeSignature.parse_signature(
4✔
434
            self.signatures, self.safe_tx_hash
435
        )
436
        filtered_tx_signatures = list(
4✔
437
            filter(lambda x: x.owner != address, current_tx_signatures)
438
        )
439
        if current_tx_signatures != filtered_tx_signatures:
4✔
440
            self.signatures = SafeSignature.export_signatures(filtered_tx_signatures)
4✔
441
            return True
4✔
442
        return False
4✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc