In my previous post we looked at what Safe is and how the contracts are structured. This time we get our hands dirty and talk to the contracts directly from Python.

I deliberately don’t use the Safe SDK (safe-eth-py) here. It’s great, but it hides exactly the parts I want to see: what gets signed, how the signatures are packed, and what each parameter of execTransaction actually does. So we’ll do everything with plain web3.py.

We’ll go through:

  • Creating a Safe and predicting its address
  • Building, signing, and executing a Safe transaction
  • All signature types (ECDSA, eth_sign, approved hash, contract signatures)
  • Adding, removing, and swapping owners
  • Enabling, using, and disabling modules
  • Batching transactions with MultiSendCallOnly
  • Enabling a module during setup
  • Failing transactions, safeTxGas, and gas refunds
  • EIP-1271 signatures through the fallback handler
  • A Safe owned by another Safe

All snippets below build on each other. If you paste them into one file in order, you get a script that runs from top to bottom. I tested it with web3.py 8.0.0 and eth-account 0.14.0 against the Safe v1.4.1 contracts.

Table of contents

  1. Setup
  2. Creating a Safe
  3. Building and Signing a Safe Transaction
  4. Other Signature Types
  5. Managing Owners
  6. Modules
  7. Batching with MultiSendCallOnly
  8. Enabling a Module During Setup
  9. Failing Transactions, safeTxGas and Gas Refunds
  10. EIP-1271 Signatures
  11. A Safe Owned by Another Safe
  12. Conclusion

0. Setup

We don’t need to deploy any Safe contracts ourselves. They are already deployed on Sepolia (and most other EVM chains) at the same addresses. To avoid needing Sepolia ETH, we run Anvil as a local fork of Sepolia:

anvil --fork-url https://ethereum-sepolia-rpc.publicnode.com

And install web3.py:

pip install web3

Now the imports, the contract addresses, and some accounts:

from eth_abi import encode
from eth_account import Account
from eth_account.messages import encode_defunct, encode_typed_data
from web3 import Web3
from web3.logs import DISCARD

w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
assert w3.is_connected()

# Safe v1.4.1 deployments (same address on most EVM chains)
SAFE_SINGLETON = "0x41675C099F32341bf84BFc5382aF534df5C7461a"
SAFE_PROXY_FACTORY = "0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67"
FALLBACK_HANDLER = "0xfd0732Dc9E303f09fCEf3a7388Ad10A83459Ec99"  # CompatibilityFallbackHandler
MULTI_SEND_CALL_ONLY = "0x9641d764fc13c8B624c04430C7356C1C7C8102e2"
SIGN_MESSAGE_LIB = "0xd53cd0aB83D845Ac265BE939c57F53AD838012c9"

ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
SENTINEL = "0x0000000000000000000000000000000000000001"
CALL, DELEGATE_CALL = 0, 1

# Fresh random accounts, funded through Anvil. (Anvil's well-known default
# accounts are EIP-7702 delegated on Sepolia, which breaks the gas refund example.)
owner1, owner2, owner3, owner4, module, relayer = (Account.create() for _ in range(6))
for account in (owner1, owner2, owner3, owner4, module, relayer):
    w3.provider.make_request("anvil_setBalance", [account.address, hex(Web3.to_wei(10, "ether"))])
receiver = "0x000000000000000000000000000000000000dEaD"

A quick note on the accounts. My first version used Anvil’s well-known default accounts (0xf39F...2266 and friends). On a Sepolia fork that’s a bad idea: many of them have EIP-7702 code (0xef0100...), because people have delegated them to sweeper contracts. If you read my EIP-7702 post, you know that this means the address now behaves like a contract. Paying such an address with Solidity’s send() and its 2300 gas stipend fails, and that broke the gas refund example further down. Fresh random accounts avoid that.

Next, the ABIs. Instead of pasting huge JSON files, I use two small helpers and only add the functions we actually need:

def fn(name, inputs, outputs=(), state="nonpayable"):
    """Small helper to write ABI entries as (type, name) tuples."""
    return {
        "type": "function",
        "name": name,
        "stateMutability": state,
        "inputs": [{"type": t, "name": n} for t, n in inputs],
        "outputs": [{"type": t, "name": n} for t, n in outputs],
    }


def event(name, inputs):
    return {
        "type": "event",
        "name": name,
        "anonymous": False,
        "inputs": [{"type": t, "name": n, "indexed": i} for t, n, i in inputs],
    }


SAFE_TX_PARAMS = [
    ("address", "to"), ("uint256", "value"), ("bytes", "data"), ("uint8", "operation"),
    ("uint256", "safeTxGas"), ("uint256", "baseGas"), ("uint256", "gasPrice"),
    ("address", "gasToken"), ("address", "refundReceiver"),
]

SAFE_ABI = [
    fn("setup", [("address[]", "_owners"), ("uint256", "_threshold"), ("address", "to"),
                 ("bytes", "data"), ("address", "fallbackHandler"), ("address", "paymentToken"),
                 ("uint256", "payment"), ("address", "paymentReceiver")]),
    fn("execTransaction", SAFE_TX_PARAMS + [("bytes", "signatures")], [("bool", "success")], "payable"),
    fn("getTransactionHash", SAFE_TX_PARAMS + [("uint256", "_nonce")], [("bytes32", "")], "view"),
    fn("encodeTransactionData", SAFE_TX_PARAMS + [("uint256", "_nonce")], [("bytes", "")], "view"),
    fn("nonce", [], [("uint256", "")], "view"),
    fn("VERSION", [], [("string", "")], "view"),
    fn("domainSeparator", [], [("bytes32", "")], "view"),
    fn("getOwners", [], [("address[]", "")], "view"),
    fn("getThreshold", [], [("uint256", "")], "view"),
    fn("isOwner", [("address", "owner")], [("bool", "")], "view"),
    fn("addOwnerWithThreshold", [("address", "owner"), ("uint256", "_threshold")]),
    fn("removeOwner", [("address", "prevOwner"), ("address", "owner"), ("uint256", "_threshold")]),
    fn("swapOwner", [("address", "prevOwner"), ("address", "oldOwner"), ("address", "newOwner")]),
    fn("changeThreshold", [("uint256", "_threshold")]),
    fn("approveHash", [("bytes32", "hashToApprove")]),
    fn("approvedHashes", [("address", ""), ("bytes32", "")], [("uint256", "")], "view"),
    fn("enableModule", [("address", "module")]),
    fn("disableModule", [("address", "prevModule"), ("address", "module")]),
    fn("isModuleEnabled", [("address", "module")], [("bool", "")], "view"),
    fn("getModulesPaginated", [("address", "start"), ("uint256", "pageSize")],
       [("address[]", "array"), ("address", "next")], "view"),
    fn("execTransactionFromModule", [("address", "to"), ("uint256", "value"), ("bytes", "data"),
                                     ("uint8", "operation")], [("bool", "success")]),
    fn("signedMessages", [("bytes32", "")], [("uint256", "")], "view"),
    # Not part of Safe.sol: these are answered by the CompatibilityFallbackHandler
    fn("isValidSignature", [("bytes32", "_dataHash"), ("bytes", "_signature")], [("bytes4", "")], "view"),
    fn("getMessageHash", [("bytes", "message")], [("bytes32", "")], "view"),
    event("ExecutionSuccess", [("bytes32", "txHash", True), ("uint256", "payment", False)]),
    event("ExecutionFailure", [("bytes32", "txHash", True), ("uint256", "payment", False)]),
    event("ExecutionFromModuleSuccess", [("address", "module", True)]),
]

FACTORY_ABI = [
    fn("createProxyWithNonce", [("address", "_singleton"), ("bytes", "initializer"),
                                ("uint256", "saltNonce")], [("address", "proxy")]),
    fn("proxyCreationCode", [], [("bytes", "")], "pure"),
    event("ProxyCreation", [("address", "proxy", True), ("address", "singleton", False)]),
]

MULTI_SEND_ABI = [fn("multiSend", [("bytes", "transactions")], [], "payable")]
SIGN_MESSAGE_LIB_ABI = [fn("signMessage", [("bytes", "_data")])]

singleton = w3.eth.contract(address=SAFE_SINGLETON, abi=SAFE_ABI)
factory = w3.eth.contract(address=SAFE_PROXY_FACTORY, abi=FACTORY_ABI)
multi_send = w3.eth.contract(address=MULTI_SEND_CALL_ONLY, abi=MULTI_SEND_ABI)
sign_message_lib = w3.eth.contract(address=SIGN_MESSAGE_LIB, abi=SIGN_MESSAGE_LIB_ABI)

Two things worth pointing out:

  • isValidSignature and getMessageHash are not part of Safe.sol. When we call them on a Safe, the Safe doesn’t find them, and its fallback forwards the call to the CompatibilityFallbackHandler. For web3.py that’s invisible, so we can just add them to the Safe ABI.
  • In v1.4.1, txHash in ExecutionSuccess and ExecutionFailure is indexed. I first had it as non-indexed, and web3.py silently didn’t find any events. The ABI has to match exactly.

Finally, a helper that builds, signs, and sends a normal Ethereum transaction:

def send(contract_fn, sender, value=0, gas=None):
    """Build, sign and send a transaction. Returns the receipt."""
    params = {
        "from": sender.address,
        "nonce": w3.eth.get_transaction_count(sender.address),
        "value": value,
    }
    if gas:
        params["gas"] = gas  # skip estimation
    tx = contract_fn.build_transaction(params)
    signed = sender.sign_transaction(tx)
    tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    assert receipt.status == 1, "transaction reverted"
    return receipt

1. Creating a Safe

A Safe is created by calling createProxyWithNonce on the SafeProxyFactory. The factory deploys a SafeProxy and calls it with the initializer, which is an encoded call to setup. Here are all setup parameters:

def setup_data(owners, threshold, to=ZERO_ADDRESS, data=b"",
               payment_token=ZERO_ADDRESS, payment=0, payment_receiver=ZERO_ADDRESS):
    return singleton.encode_abi("setup", args=[
        owners,             # _owners
        threshold,          # _threshold
        to,                 # to: optional delegatecall during setup
        data,               # data: payload for that delegatecall
        FALLBACK_HANDLER,   # fallbackHandler
        payment_token,      # paymentToken (0x0 = ETH)
        payment,            # payment
        payment_receiver,   # paymentReceiver (0x0 = tx.origin)
    ])
  • owners and threshold: the multisig configuration.
  • to and data: an optional delegatecall that runs during setup. We use it in section 7 to enable a module.
  • fallbackHandler: the contract that answers calls the Safe doesn’t know. Without it the Safe can’t validate EIP-1271 signatures, and it can’t receive NFTs via safeTransferFrom.
  • paymentToken, payment, paymentReceiver: lets the Safe pay back whoever deployed it. For now we pay for the deployment ourselves, so payment is 0. We’ll see a paid deployment below.

Since the factory uses CREATE2, we can calculate the address of the Safe before deploying it. The salt is the hash of the initializer combined with a nonce of our choice:

def predict_safe_address(initializer, salt_nonce):
    initializer = bytes.fromhex(initializer[2:]) if isinstance(initializer, str) else initializer
    salt = Web3.keccak(Web3.keccak(initializer) + encode(["uint256"], [salt_nonce]))
    deployment_data = factory.functions.proxyCreationCode().call() + encode(["address"], [SAFE_SINGLETON])
    address = Web3.keccak(
        b"\xff" + bytes.fromhex(SAFE_PROXY_FACTORY[2:]) + salt + Web3.keccak(deployment_data)
    )[12:]
    return Web3.to_checksum_address(address)

This is the standard CREATE2 formula: keccak256(0xff ++ factory ++ salt ++ keccak256(init_code))[12:]. The init code is the proxy’s creation code followed by the singleton address as its constructor argument.

Now we create the Safe and check that the prediction was right:

def create_safe(owners, threshold, salt_nonce, to=ZERO_ADDRESS, data=b""):
    initializer = setup_data(owners, threshold, to, data)
    predicted = predict_safe_address(initializer, salt_nonce)
    receipt = send(factory.functions.createProxyWithNonce(SAFE_SINGLETON, initializer, salt_nonce), owner1)
    created = factory.events.ProxyCreation().process_receipt(receipt, errors=DISCARD)[0].args.proxy
    assert created == predicted
    return w3.eth.contract(address=created, abi=SAFE_ABI)


salt_nonce = w3.eth.block_number  # any number; a new one gives a new address
safe = create_safe([owner1.address, owner2.address, owner3.address], 2, salt_nonce)
print("Safe:", safe.address)
print("  version:  ", safe.functions.VERSION().call())
print("  owners:   ", safe.functions.getOwners().call())
print("  threshold:", safe.functions.getThreshold().call())
print("  nonce:    ", safe.functions.nonce().call())

def send_eth(sender, to, amount):
    """A plain ETH transfer, e.g. to fund a Safe."""
    tx = sender.sign_transaction({
        "to": to, "value": amount, "gas": 50_000,
        "maxFeePerGas": w3.eth.gas_price * 2, "maxPriorityFeePerGas": 0,
        "nonce": w3.eth.get_transaction_count(sender.address), "chainId": w3.eth.chain_id,
    })
    w3.eth.wait_for_transaction_receipt(w3.eth.send_raw_transaction(tx.raw_transaction))


send_eth(owner1, safe.address, Web3.to_wei(1, "ether"))
print("  balance:  ", Web3.from_wei(w3.eth.get_balance(safe.address), "ether"), "ETH")

Notice that we use the singleton’s ABI for the Safe. The proxy has no functions of its own, it forwards everything to the singleton via delegatecall.

Safe: 0x6744f0cB1f2Ba9ECbf32f75d6cf5f5be67f785E2
  version:   1.4.1
  owners:    ['0xf103...e102', '0xeFbe...BE7e', '0xF7a6...1Be7']
  threshold: 2
  nonce:     0
  balance:   1 ETH

Your addresses will be different, since the accounts are random.

Letting someone else deploy the Safe

Above, owner1 deployed the Safe and paid the gas. But what if the owners don’t have any ETH yet, or a wallet app wants to deploy Safes for its users? Then someone else (a relayer) can deploy the Safe, and the new Safe pays them back during setup.

This works because of the address prediction from above. The flow is:

  1. Pick the configuration, including the payment for the deployer.
  2. Calculate the Safe’s address and send funds to it. There is no contract at that address yet, but it can already receive ETH.
  3. The relayer calls createProxyWithNonce with the same initializer and salt. During setup, the Safe pays payment to the relayer from the funds that are already there.
# 1. The configuration, including the payment for whoever deploys the Safe
payment = Web3.to_wei(0.01, "ether")
initializer = setup_data(
    [owner1.address, owner2.address], 2,
    payment_token=ZERO_ADDRESS,      # pay in ETH
    payment=payment,                 # how much the deployer gets
    payment_receiver=ZERO_ADDRESS,   # 0x0 = tx.origin, i.e. whoever deploys it
)
sponsored_salt = salt_nonce + 100
sponsored_address = predict_safe_address(initializer, sponsored_salt)

# 2. Fund the address before the Safe exists
send_eth(owner1, sponsored_address, Web3.to_wei(0.1, "ether"))
print("\n1b. address:", sponsored_address,
      "| code:", len(w3.eth.get_code(sponsored_address)), "bytes",
      "| balance:", Web3.from_wei(w3.eth.get_balance(sponsored_address), "ether"), "ETH")

# 3. The relayer deploys it and is paid during setup.
#    Gas estimation leaves out the payment (see below), so we set the gas limit ourselves.
relayer_before = w3.eth.get_balance(relayer.address)
receipt = send(factory.functions.createProxyWithNonce(SAFE_SINGLETON, initializer, sponsored_salt),
               relayer, gas=400_000)
gas_cost = receipt.gasUsed * receipt.effectiveGasPrice
relayer_after = w3.eth.get_balance(relayer.address)

sponsored_safe = w3.eth.contract(address=sponsored_address, abi=SAFE_ABI)
print("    deployed:", len(w3.eth.get_code(sponsored_address)) > 0,
      "| owners:", sponsored_safe.functions.getOwners().call() == [owner1.address, owner2.address],
      "| Safe balance:", Web3.from_wei(w3.eth.get_balance(sponsored_address), "ether"), "ETH")
print("    relayer: paid", gas_cost, "wei for gas, received", payment, "wei, net",
      relayer_after - relayer_before, "wei")
1b. address: 0xf1Bd...26Dd | code: 0 bytes | balance: 0.1 ETH
    deployed: True | owners: True | Safe balance: 0.09 ETH
    relayer: paid 289803003477636 wei for gas, received 10000000000000000 wei, net 9710196996522364 wei

Before the deployment there is no code at the address, but it already holds 0.1 ETH. After the deployment the Safe exists, and 0.01 ETH went to the relayer.

A few things worth knowing:

  • The relayer can’t change anything. The payment is part of the initializer, and the initializer is part of the CREATE2 salt. If the relayer changes the owners or the payment, they get a Safe at a different address, one without our funds.
  • paymentReceiver = 0x0 means “pay whoever deploys it” (tx.origin). That’s handy for open relayer networks: anyone can deploy the Safe and earn the fee. If you want only one specific relayer to get paid, put their address in paymentReceiver.
  • payment is a fixed amount, not a gas refund like the one in section 8. The relayer has to estimate the deployment cost themselves and set a fee that covers it.
  • Gas estimation is too low again. Internally, setup pays the deployer through the same function as the gas refund in section 8, with a “gas price” of 1. So the payment is really payment × min(1, tx.gasprice). During gas estimation the gas price seems to be 0, so the payment is skipped and its ~9,000 gas aren’t counted. My first run ran out of gas exactly there, which is why we pass gas=400_000.
  • paymentToken can also be an ERC-20 token. Then the Safe pays the relayer in that token instead of ETH, e.g. in USDC, if the owners don’t have any ETH at all.

2. Building and Signing a Safe Transaction

The term “Safe transaction” can be confusing at first, because it is not an Ethereum transaction. It’s a description of a call that we want the Safe to make. Think of it as a normal contract call (to, value, data), plus a few extra fields the Safe needs.

So there are two layers:

  1. The Safe transaction: the call the Safe should make. The owners sign it off-chain. Nothing is sent to the chain yet, and nobody pays gas.
  2. The Ethereum transaction: once there are enough signatures, someone sends a normal Ethereum transaction to the Safe that calls execTransaction(...) with the Safe transaction and the signatures. The Safe checks the signatures and then makes the call.
 Layer 1: Safe transaction (off-chain)            Layer 2: Ethereum transaction (on-chain)
┌──────────────────────────────────────┐        ┌──────────────────────────────────────────┐
│ to, value, data      <- the call     │        │ from: anyone (owner, relayer, ...)       │
│ operation            <- call/delegate│ signed │ to:   the Safe                           │
│ safeTxGas, baseGas,  <- gas/refund   │ ─────► │ data: execTransaction(                   │
│ gasPrice, gasToken,                  │ by the │         to, value, data, operation,      │
│ refundReceiver                       │ owners │         safeTxGas, ..., refundReceiver,  │
│ nonce                <- Safe's nonce │        │         signatures)                      │
└──────────────────────────────────────┘        └──────────────────────────────────────────┘
                                                                      │
                                                                      ▼
                                                  Safe checks signatures, then calls `to`

That’s also why the Ethereum transaction can come from anyone. The signatures authorize the call, not msg.sender.

Let’s start with layer 1. A Safe transaction has these fields:

def build_safe_tx(safe, to, value=0, data=b"", operation=CALL, safe_tx_gas=0,
                  base_gas=0, gas_price=0, gas_token=ZERO_ADDRESS, refund_receiver=ZERO_ADDRESS):
    return {
        "to": to,
        "value": value,
        "data": data if isinstance(data, bytes) else bytes.fromhex(data[2:]),
        "operation": operation,
        "safeTxGas": safe_tx_gas,
        "baseGas": base_gas,
        "gasPrice": gas_price,
        "gasToken": gas_token,
        "refundReceiver": refund_receiver,
        "nonce": safe.functions.nonce().call(),
    }
  • to, value, data: what to call, like a normal transaction.
  • operation: CALL (0) or DELEGATE_CALL (1).
  • safeTxGas, baseGas, gasPrice, gasToken, refundReceiver: only relevant for gas refunds and failing transactions. We’ll look at them in section 8. For now they’re all 0.
  • nonce: the Safe’s current nonce. Every transaction must use the current nonce, so they are executed in order.

The owners sign this Safe transaction as EIP-712 typed data. SafeTx is just the fields from above, and the domain only contains the chain ID and the Safe’s address. Because of that, a signature is only valid for this one Safe on this one chain:

def safe_tx_typed_data(safe, safe_tx):
    return {
        "types": {
            "EIP712Domain": [
                {"name": "chainId", "type": "uint256"},
                {"name": "verifyingContract", "type": "address"},
            ],
            "SafeTx": [
                {"name": "to", "type": "address"},
                {"name": "value", "type": "uint256"},
                {"name": "data", "type": "bytes"},
                {"name": "operation", "type": "uint8"},
                {"name": "safeTxGas", "type": "uint256"},
                {"name": "baseGas", "type": "uint256"},
                {"name": "gasPrice", "type": "uint256"},
                {"name": "gasToken", "type": "address"},
                {"name": "refundReceiver", "type": "address"},
                {"name": "nonce", "type": "uint256"},
            ],
        },
        "primaryType": "SafeTx",
        "domain": {"chainId": w3.eth.chain_id, "verifyingContract": safe.address},
        "message": safe_tx,
    }


def safe_tx_hash(safe, safe_tx):
    signable = encode_typed_data(full_message=safe_tx_typed_data(safe, safe_tx))
    local = Web3.keccak(b"\x19" + signable.version + signable.header + signable.body)
    on_chain = safe.functions.getTransactionHash(*safe_tx.values()).call()
    assert local == on_chain
    return local

safe_tx_hash calculates the hash locally and compares it with getTransactionHash on the Safe. If they ever differ, something in our typed data is wrong. That’s a cheap sanity check worth having.

Signing is a normal EIP-712 signature:

def sign_safe_tx(safe, safe_tx, owner):
    """Signature type 1: plain EIP-712 ECDSA signature (v = 27 / 28)."""
    signable = encode_typed_data(full_message=safe_tx_typed_data(safe, safe_tx))
    return owner.sign_message(signable).signature

That’s layer 1 done. For layer 2, we put the Safe transaction and the signatures into a normal Ethereum transaction that calls execTransaction. The signatures are concatenated, sorted by owner address. The Safe requires this order so it can cheaply make sure that nobody signs twice:

def address_as_number(address):
    """Compare addresses by their numeric value. Sorting the strings would not work,
    because checksummed addresses mix upper and lower case."""
    return int(address, 16)


def join_signatures(signatures):
    """signatures: {owner_address: signature_bytes}.
    Returns all signatures as one bytes value, sorted by owner address."""
    joined = b""
    for owner in sorted(signatures, key=address_as_number):
        joined += signatures[owner]
    return joined


def exec_safe_tx(safe, safe_tx, signatures, executor, gas=None):
    """signatures: {owner_address: signature_bytes}"""
    packed = join_signatures(signatures)
    params = list(safe_tx.values())[:-1]  # everything except the nonce
    receipt = send(safe.functions.execTransaction(*params, packed), executor, gas=gas)
    ok = safe.events.ExecutionSuccess().process_receipt(receipt, errors=DISCARD)
    failed = safe.events.ExecutionFailure().process_receipt(receipt, errors=DISCARD)
    return receipt, ok, failed

Note that execTransaction doesn’t take the nonce as a parameter. The Safe always uses its current nonce. If you sign with a different nonce, the hash doesn’t match and the signatures are invalid.

Let’s send 0.1 ETH from the Safe:

# Send 0.1 ETH from the Safe, signed by owner1 and owner2
tx = build_safe_tx(safe, receiver, value=Web3.to_wei(0.1, "ether"))
tx_hash = safe_tx_hash(safe, tx)
signatures = {
    owner1.address: sign_safe_tx(safe, tx, owner1),
    owner2.address: sign_safe_tx(safe, tx, owner2),
}
_, ok, _ = exec_safe_tx(safe, tx, signatures, executor=relayer)  # anyone can submit it
print("\n2. ETH transfer:", ok[0].args.txHash.hex() == tx_hash.hex(), "| nonce now", safe.functions.nonce().call())
2. ETH transfer: True | nonce now 1

The transaction is submitted by relayer, who is not an owner. That’s fine: the signatures are what authorize the transaction, not msg.sender. Anyone can submit a Safe transaction once it has enough signatures.

Calling a contract

Sending ETH only uses to and value. Calling a contract is the same, except that we also fill data. To try it, we need a contract. Here is a small Counter that also remembers who called it last:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract Counter {
    uint256 public number;
    address public lastCaller;

    function increment() external {
        number += 1;
        lastCaller = msg.sender;
    }

    function setNumber(uint256 newNumber) external {
        number = newNumber;
        lastCaller = msg.sender;
    }
}

So you don’t need Foundry or solc, I compiled it (Solidity 0.8.28, optimizer with 200 runs), and we deploy the bytecode directly from Python:

# Counter.sol compiled with solc 0.8.28, optimizer enabled (200 runs)
COUNTER_BYTECODE = "0x6080604052348015600e575f5ffd5b506101598061001c5f395ff3fe608060405234801561000f575f5ffd5b506004361061004a575f3560e01c80632113522a1461004e5780633fb5c1cb1461007e5780638381f58a146100a4578063d09de08a146100ba575b5f5ffd5b600154610061906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6100a261008c3660046100e7565b5f55600180546001600160a01b03191633179055565b005b6100ac5f5481565b604051908152602001610075565b6100a260015f5f8282546100ce91906100fe565b9091555050600180546001600160a01b03191633179055565b5f602082840312156100f7575f5ffd5b5035919050565b8082018082111561011d57634e487b7160e01b5f52601160045260245ffd5b9291505056fea264697066735822122053cd1b94745dc6a358937395931ccbc5cc1c244621213b429dfbba94485b67cb64736f6c634300081c0033"
COUNTER_ABI = [
    fn("number", [], [("uint256", "")], "view"),
    fn("lastCaller", [], [("address", "")], "view"),
    fn("increment", []),
    fn("setNumber", [("uint256", "newNumber")]),
]

receipt = send(w3.eth.contract(abi=COUNTER_ABI, bytecode=COUNTER_BYTECODE).constructor(), owner1)
counter = w3.eth.contract(address=receipt.contractAddress, abi=COUNTER_ABI)

Now the Safe calls setNumber(42). The calldata is encoded exactly like for any other contract call. The only difference is that it goes into the data field of the Safe transaction instead of being sent directly:

# The call we want the Safe to make, encoded like any other contract call
data = counter.encode_abi("setNumber", args=[42])
tx = build_safe_tx(safe, counter.address, data=data)
signatures = {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]}
exec_safe_tx(safe, tx, signatures, executor=relayer)
print("\n2b. number:", counter.functions.number().call(),
      "| lastCaller is the Safe:", counter.functions.lastCaller().call() == safe.address)

# Functions without arguments work the same way
tx = build_safe_tx(safe, counter.address, data=counter.encode_abi("increment"))
signatures = {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]}
exec_safe_tx(safe, tx, signatures, executor=relayer)
print("    after increment:", counter.functions.number().call())
2b. number: 42 | lastCaller is the Safe: True
    after increment: 43

Note lastCaller. The Ethereum transaction was sent by the relayer, but from the Counter’s point of view the caller is the Safe. That’s the whole point: for every contract the Safe interacts with, the Safe is msg.sender, no matter who submitted the transaction or who signed it.

3. Other Signature Types

ECDSA over the EIP-712 hash is the most common signature type, but not the only one. The Safe looks at the v byte of each signature to know how to verify it:

v Type
27 / 28 ECDSA over the EIP-712 hash (what we did above)
> 30 eth_sign over the hash, with v + 4
1 Approved hash: on-chain approval, or the owner is msg.sender
0 Contract signature (EIP-1271), see section 10
def sign_eth_sign(safe_tx_hash, owner):
    """Signature type 2: eth_sign / personal_sign over the hash. v is increased by 4."""
    sig = owner.sign_message(encode_defunct(primitive=safe_tx_hash)).signature
    return sig[:64] + bytes([sig[64] + 4])


def approved_hash_signature(owner_address):
    """Signature type 3: v = 1, r = owner address, s unused.
    Valid if the owner called approveHash(hash) or is the one submitting the transaction."""
    return encode(["address", "uint256"], [owner_address, 0]) + b"\x01"

eth_sign signatures are for wallets that can’t sign EIP-712 typed data (e.g. some hardware wallets). They sign the hash with the \x19Ethereum Signed Message:\n32 prefix. The + 4 on v tells the Safe to add this prefix back when it recovers the signer.

The approved hash type doesn’t contain a real signature at all. r is the owner’s address, and the Safe checks on-chain whether that owner approved the hash. This is useful for owners that are contracts without EIP-1271 support, or if you just want to sign through a normal transaction.

Let’s combine an eth_sign signature with an on-chain approval:

tx = build_safe_tx(safe, receiver, value=Web3.to_wei(0.1, "ether"))
tx_hash = safe_tx_hash(safe, tx)

# owner3 approves the hash on-chain
send(safe.functions.approveHash(tx_hash), owner3)
print("\n3. owner3 approved:", safe.functions.approvedHashes(owner3.address, tx_hash).call())

signatures = {
    owner2.address: sign_eth_sign(tx_hash, owner2),     # eth_sign
    owner3.address: approved_hash_signature(owner3.address),  # on-chain approval
}
_, ok, _ = exec_safe_tx(safe, tx, signatures, executor=relayer)
print("   eth_sign + approved hash:", bool(ok))

There is one more trick with v = 1. If the owner is the one submitting the transaction (msg.sender), they don’t need to approve anything. Sending the transaction is the approval:

# The submitter's own approval: owner1 executes and signs implicitly
tx = build_safe_tx(safe, receiver, value=Web3.to_wei(0.1, "ether"))
signatures = {
    owner1.address: approved_hash_signature(owner1.address),  # msg.sender == owner1
    owner3.address: sign_safe_tx(safe, tx, owner3),
}
_, ok, _ = exec_safe_tx(safe, tx, signatures, executor=owner1)
print("   msg.sender approval + ECDSA:", bool(ok))
3. owner3 approved: 1
   eth_sign + approved hash: True
   msg.sender approval + ECDSA: True

This is what the Safe Wallet UI does when the last owner clicks “Execute”: they don’t sign a separate message, their transaction counts as their signature.

4. Managing Owners

All owner functions are authorized, which means only the Safe itself can call them. So to change owners, we create a Safe transaction where to is the Safe’s own address:

def prev_owner(safe, owner):
    owners = safe.functions.getOwners().call()
    i = owners.index(owner)
    return SENTINEL if i == 0 else owners[i - 1]


def self_call(safe, data, signers, executor=relayer):
    """Execute a Safe transaction that calls the Safe itself."""
    tx = build_safe_tx(safe, safe.address, data=data)
    sigs = {o.address: sign_safe_tx(safe, tx, o) for o in signers}
    return exec_safe_tx(safe, tx, sigs, executor)

prev_owner is needed because owners are stored as a linked list (see the previous post). To remove an owner, the Safe needs to know who points to it. The first owner is pointed to by the sentinel 0x1.

Now let’s add an owner, change the threshold, remove an owner, and swap one:

print("\n4. owners before:", safe.functions.getOwners().call())

self_call(safe, safe.encode_abi("addOwnerWithThreshold", args=[owner4.address, 3]), [owner1, owner2])
print("   add owner4 (threshold 3):", safe.functions.getOwners().call(), safe.functions.getThreshold().call())

self_call(safe, safe.encode_abi("changeThreshold", args=[2]), [owner1, owner2, owner3])
print("   threshold back to:", safe.functions.getThreshold().call())

data = safe.encode_abi("removeOwner", args=[prev_owner(safe, owner2.address), owner2.address, 2])
self_call(safe, data, [owner1, owner3])
print("   remove owner2:", safe.functions.getOwners().call())

data = safe.encode_abi("swapOwner", args=[prev_owner(safe, owner3.address), owner3.address, owner2.address])
self_call(safe, data, [owner1, owner4])
print("   swap owner3 -> owner2:", safe.functions.getOwners().call())
4. owners before: [owner1, owner2, owner3]
   add owner4 (threshold 3): [owner4, owner1, owner2, owner3] 3
   threshold back to: 2
   remove owner2: [owner4, owner1, owner3]
   swap owner3 -> owner2: [owner4, owner1, owner2]

A few things to notice:

  • The new owner is added at the front of the list. That’s the cheapest place to insert into a linked list: right after the sentinel.
  • After adding owner4 the threshold is 3, so changing it back needs three signatures.
  • removeOwner takes the new threshold as a parameter. That way you can’t end up with a threshold higher than the number of owners.
  • swapOwner replaces an owner in place, without changing the threshold.

5. Modules

A module is any address that can execute transactions on behalf of the Safe, without signatures. Usually it’s a contract with its own rules. To keep things simple we enable a plain EOA as a module, which shows nicely how much power a module has:

self_call(safe, safe.encode_abi("enableModule", args=[module.address]), [owner1, owner2])
print("\n5. module enabled:", safe.functions.isModuleEnabled(module.address).call())
print("   modules:", safe.functions.getModulesPaginated(SENTINEL, 10).call())

# The module moves funds without any owner signature
before = w3.eth.get_balance(receiver)
receipt = send(safe.functions.execTransactionFromModule(receiver, Web3.to_wei(0.1, "ether"), b"", CALL), module)
print("   module tx:", bool(safe.events.ExecutionFromModuleSuccess().process_receipt(receipt, errors=DISCARD)),
      "| receiver +", Web3.from_wei(w3.eth.get_balance(receiver) - before, "ether"), "ETH",
      "| nonce unchanged:", safe.functions.nonce().call())

modules, _ = safe.functions.getModulesPaginated(SENTINEL, 10).call()
i = modules.index(module.address)
prev_module = SENTINEL if i == 0 else modules[i - 1]
self_call(safe, safe.encode_abi("disableModule", args=[prev_module, module.address]), [owner1, owner2])
print("   module disabled:", not safe.functions.isModuleEnabled(module.address).call())
5. module enabled: True
   modules: [['0xC2da...b9c5'], '0x0000000000000000000000000000000000000001']
   module tx: True | receiver + 0.1 ETH | nonce unchanged: 10
   module disabled: True

The module moved 0.1 ETH out of the Safe with a single call. No signatures, no threshold, and the nonce didn’t change either. That’s why you should only enable modules you trust as much as the owners.

Modules are stored in a linked list as well, so disableModule also needs the previous module. getModulesPaginated returns the modules plus a next pointer for the next page. When next is the sentinel, there are no more pages.

6. Batching with MultiSendCallOnly

A Safe transaction has a single to. To do several things at once, the Safe delegatecalls the MultiSendCallOnly contract, which then executes a list of calls in the context of the Safe.

The transactions are packed, not ABI-encoded. Each one is:

operation (1 byte) | to (20 bytes) | value (32 bytes) | data length (32 bytes) | data
def encode_multisend(txs):
    """txs: list of (operation, to, value, data). Packed encoding, NOT abi.encode."""
    packed = b""
    for operation, to, value, data in txs:
        packed += (
            operation.to_bytes(1, "big")
            + bytes.fromhex(to[2:])
            + value.to_bytes(32, "big")
            + len(data).to_bytes(32, "big")
            + data
        )
    return multi_send.encode_abi("multiSend", args=[packed])

Let’s send ETH to two addresses and lower the threshold, all in one Safe transaction:

one_eth_tenth = Web3.to_wei(0.1, "ether")
batch = encode_multisend([
    (CALL, receiver, one_eth_tenth, b""),
    (CALL, owner4.address, one_eth_tenth, b""),
    (CALL, safe.address, 0, bytes.fromhex(safe.encode_abi("changeThreshold", args=[1])[2:])),
])
before = w3.eth.get_balance(receiver), w3.eth.get_balance(owner4.address)
tx = build_safe_tx(safe, MULTI_SEND_CALL_ONLY, data=batch, operation=DELEGATE_CALL)
_, ok, _ = exec_safe_tx(safe, tx, {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]}, relayer)
print("\n6. batch ok:", bool(ok),
      "| receiver +", Web3.from_wei(w3.eth.get_balance(receiver) - before[0], "ether"),
      "| owner4 +", Web3.from_wei(w3.eth.get_balance(owner4.address) - before[1], "ether"),
      "| threshold:", safe.functions.getThreshold().call())
6. batch ok: True | receiver + 0.1 | owner4 + 0.1 | threshold: 1

Two things to note:

  • The outer Safe transaction uses DELEGATE_CALL, while each inner transaction uses CALL. MultiSendCallOnly only allows CALL for the inner transactions. The plain MultiSend also allows DELEGATE_CALL there, but that’s rarely needed and more dangerous.
  • The changeThreshold call works because it comes from the Safe. The MultiSendCallOnly code runs inside the Safe (thanks to the delegatecall), so the calls it makes have the Safe as msg.sender.

7. Enabling a Module During Setup

Remember the to and data parameters of setup? They let us run a delegatecall while the Safe is being created. A common use case is enabling modules right away, e.g. the Safe 4337 module.

My first idea was to use MultiSendCallOnly again, with a call to enableModule on the new Safe. But that doesn’t work: the address of the Safe depends on the initializer, so we can’t put the Safe’s own address into the initializer. I also tried passing to = 0x0, hoping MultiSend would replace it with the Safe’s address. In v1.4.1 it doesn’t. The call just went to 0x0, “succeeded”, and no module was enabled.

What works is a small contract that calls enableModule on address(this). When it’s delegatecalled by the Safe, address(this) is the Safe. Safe ships such a contract with its 4337 module, called SafeModuleSetup:

# SafeModuleSetup (from the Safe 4337 module v0.3.0 deployments) is delegatecalled
# during setup and calls enableModule on the Safe itself.
SAFE_MODULE_SETUP = "0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47"
module_setup = w3.eth.contract(address=SAFE_MODULE_SETUP,
                               abi=[fn("enableModules", [("address[]", "modules")])])
setup_call = module_setup.encode_abi("enableModules", args=[[module.address]])
safe2 = create_safe([owner1.address, owner2.address], 2, salt_nonce + 1,
                    to=SAFE_MODULE_SETUP, data=setup_call)
print("\n7. new Safe:", safe2.address, "| module enabled at setup:",
      safe2.functions.isModuleEnabled(module.address).call())
7. new Safe: 0x8116...4F5b | module enabled at setup: True

This only works because setup runs the delegatecall after the owners and module list are initialized, and because enableModule is called by the Safe itself, so authorized passes.

8. Failing Transactions, safeTxGas and Gas Refunds

Now for the gas-related parameters. First, what happens if the inner call of a Safe transaction fails? That depends on safeTxGas and gasPrice:

  • If both are 0, the whole transaction reverts (GS013). Nothing happens, and the nonce isn’t used.
  • If either is set, the Safe catches the failure. The outer transaction succeeds, the Safe emits ExecutionFailure, and the nonce is used up.

Why the difference? If a relayer is paid to submit the transaction (gasPrice > 0) or a gas limit was agreed on (safeTxGas > 0), the relayer should get paid even if the call itself fails. Otherwise someone could make relayers waste gas for free.

Let’s try both with a call that always fails: changeThreshold(10) on a Safe with three owners (GS201):

self_call(safe, safe.encode_abi("changeThreshold", args=[2]), [owner1])  # threshold is 1 right now

# changeThreshold(10) reverts inside the Safe (GS201: threshold > owner count)
bad_data = safe.encode_abi("changeThreshold", args=[10])
tx = build_safe_tx(safe, safe.address, data=bad_data, safe_tx_gas=100_000)
nonce_before = tx["nonce"]
_, ok, failed = exec_safe_tx(safe, tx, {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]}, relayer)
print("\n8. inner call failed:", bool(failed), "| outer tx succeeded, nonce",
      nonce_before, "->", safe.functions.nonce().call())

# Same call with safeTxGas = 0 and gasPrice = 0: the whole transaction reverts (GS013)
tx = build_safe_tx(safe, safe.address, data=bad_data)
try:
    exec_safe_tx(safe, tx, {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]}, relayer)
except Exception as e:
    print("   with safeTxGas = gasPrice = 0 it reverts:", type(e).__name__, str(e)[:60])
8. inner call failed: True | outer tx succeeded, nonce 13 -> 14
   with safeTxGas = gasPrice = 0 it reverts: ContractLogicError ('execution reverted: GS013', ...

Now the refund. The relayer pays the gas, and the Safe pays it back. The refund is calculated like this (for ETH):

\[\text{payment} = (\text{gasUsed} + \text{baseGas}) \times \min(\text{gasPrice}, \text{tx.gasprice})\]
  • gasUsed is measured by the Safe itself.
  • baseGas covers everything the Safe can’t measure.
  • gasPrice is the highest price the owners are willing to refund. The Safe never pays more than the actual gas price of the transaction.
  • gasToken is the token to pay in (0x0 means ETH).
  • refundReceiver is who gets paid (0x0 means tx.origin).
# Gas refund in ETH: the relayer pays the gas, the Safe pays the relayer back
tx = build_safe_tx(
    safe, receiver, value=one_eth_tenth,
    base_gas=80_000,                       # gas the Safe doesn't measure: 21k base, calldata, signature checks, refund
    gas_price=Web3.to_wei(100, "gwei"),    # max price the Safe is willing to refund
    gas_token=ZERO_ADDRESS,                # refund in ETH
    refund_receiver=ZERO_ADDRESS,          # 0x0 = tx.origin, i.e. the relayer
)
relayer_before = w3.eth.get_balance(relayer.address)
# Gas estimation doesn't account for the refund payment, so set the gas limit ourselves
receipt, ok, _ = exec_safe_tx(safe, tx, {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]},
                              relayer, gas=150_000)
gas_cost = receipt.gasUsed * receipt.effectiveGasPrice
refund = ok[0].args.payment
print("   refund covers", refund // receipt.effectiveGasPrice, "gas | relayer used", receipt.gasUsed,
      "gas | relayer net:", w3.eth.get_balance(relayer.address) - relayer_before, "wei")
   refund covers 89694 gas | relayer used 73051 gas | relayer net: 16643000133144 wei

I ran into two things here that are worth knowing:

  1. Gas estimation is too low. My first run reverted with out of gas, right at the refund payment. As far as I can tell, eth_estimateGas ran with a gas price of 0, so the Safe calculated a payment of 0 and skipped the transfer. The real transaction then needed ~9,000 more gas for it. That’s why we set gas=150_000 ourselves.
  2. baseGas has to cover more than you’d think. The Safe only starts measuring gasUsed after it has checked the signatures. The 21,000 base transaction cost, the calldata, and the signature checks all have to be covered by baseGas. With baseGas = 50_000 the relayer was refunded for ~60k gas but paid for ~73k, so they lost money. With 80_000 they come out slightly ahead.

9. EIP-1271 Signatures

So far the owners signed transactions. But a Safe can also “sign” messages, for example to log into a dApp. Other contracts check such signatures with EIP-1271: they call isValidSignature(hash, signature) on the Safe and expect the magic value 0x1626ba7e back.

Safe.sol doesn’t implement isValidSignature itself. The call ends up in the CompatibilityFallbackHandler we set during setup. There are two ways to make the Safe sign a message.

a) Off-chain: The owners sign a SafeMessage (EIP-712, with the Safe as the domain), and the signatures are passed to isValidSignature:

message = "Hello from my Safe"
message_hash = Web3.keccak(text=message)  # what a dApp would ask the Safe to sign (simplified)

# a) Off-chain: owners sign the SafeMessage, the Safe checks it like a transaction
safe_message_typed_data = {
    "types": {
        "EIP712Domain": [
            {"name": "chainId", "type": "uint256"},
            {"name": "verifyingContract", "type": "address"},
        ],
        "SafeMessage": [{"name": "message", "type": "bytes"}],
    },
    "primaryType": "SafeMessage",
    "domain": {"chainId": w3.eth.chain_id, "verifyingContract": safe.address},
    "message": {"message": message_hash},
}
signable = encode_typed_data(full_message=safe_message_typed_data)
safe_message_hash = Web3.keccak(b"\x19" + signable.version + signable.header + signable.body)
assert safe_message_hash == safe.functions.getMessageHash(message_hash).call()

sigs = {o.address: o.sign_message(signable).signature for o in [owner1, owner2]}
packed = join_signatures(sigs)
result = safe.functions.isValidSignature(message_hash, packed).call()
print("\n9a. off-chain signature valid:", result.hex() == "1626ba7e")

Note that the message field contains the 32-byte hash as bytes, because in v1.4.1 the handler wraps the bytes32 hash into bytes before checking it.

b) On-chain: The Safe executes a transaction that delegatecalls SignMessageLib.signMessage. This marks the message as signed in the Safe’s storage (signedMessages). After that, anyone can verify it with an empty signature:

# b) On-chain: delegatecall SignMessageLib, then anyone can check with an empty signature
data = sign_message_lib.encode_abi("signMessage", args=[message_hash])
tx = build_safe_tx(safe, SIGN_MESSAGE_LIB, data=data, operation=DELEGATE_CALL)
exec_safe_tx(safe, tx, {o.address: sign_safe_tx(safe, tx, o) for o in [owner1, owner2]}, relayer)
print("9b. signedMessages set:", safe.functions.signedMessages(safe_message_hash).call() == 1,
      "| isValidSignature(hash, ''):", safe.functions.isValidSignature(message_hash, b"").call().hex() == "1626ba7e")
9a. off-chain signature valid: True
9b. signedMessages set: True | isValidSignature(hash, ''): True

The off-chain way is free but needs the signatures to be passed around. The on-chain way costs a transaction, but afterwards the signature is just “there”.

10. A Safe Owned by Another Safe

The last signature type is v = 0: a contract signature. It’s used when an owner is a contract, for example another Safe. Let’s build that: an inner Safe (owned by owner3 and owner4) is one of the two owners of an outer Safe.

inner = create_safe([owner3.address, owner4.address], 2, salt_nonce + 2)
outer = create_safe([owner1.address, inner.address], 2, salt_nonce + 3)
send_eth(owner1, outer.address, Web3.to_wei(1, "ether"))

When the outer Safe checks a contract signature, it calls isValidSignature on the inner Safe. In v1.4.1 it uses the legacy variant isValidSignature(bytes data, bytes signature), where data is the full EIP-712 preimage of the outer transaction (not its hash). The inner Safe’s owners therefore sign a SafeMessage containing that preimage:

tx = build_safe_tx(outer, receiver, value=one_eth_tenth)
# In v1.4.1 the outer Safe asks the inner Safe isValidSignature(bytes data, bytes signature),
# where data is the full EIP-712 preimage of the outer transaction.
tx_preimage = outer.functions.encodeTransactionData(*tx.values()).call()

inner_message = {
    "types": safe_message_typed_data["types"],
    "primaryType": "SafeMessage",
    "domain": {"chainId": w3.eth.chain_id, "verifyingContract": inner.address},
    "message": {"message": tx_preimage},
}
inner_signable = encode_typed_data(full_message=inner_message)
inner_sigs = {o.address: o.sign_message(inner_signable).signature for o in [owner3, owner4]}
inner_signature = join_signatures(inner_sigs)

The tricky part is packing it. Every signature still has a 65-byte slot, but for a contract signature that slot only contains a pointer:

  • r: the contract owner’s address (the inner Safe)
  • s: the offset where the actual signature data starts
  • v: 0

The actual signature data (length + bytes) is appended after all 65-byte slots:

| owner1: r s v (65 bytes) | inner: address, offset, 0 (65 bytes) | length | inner signatures ... |
                                         └──────── points to ────────┘
def pack_signatures(static, dynamic):
    """static: {owner: 65 bytes}, dynamic: {contract_owner: signature bytes}.
    Contract signatures: r = owner address, s = offset of the data, v = 0.
    The data (length + bytes) is appended after all 65-byte parts."""
    owners = sorted(list(static) + list(dynamic), key=address_as_number)
    head, tail = b"", b""
    offset = 65 * len(owners)
    for owner in owners:
        if owner in static:
            head += static[owner]
        else:
            data = dynamic[owner]
            head += encode(["address", "uint256"], [owner, offset + len(tail)]) + b"\x00"
            tail += len(data).to_bytes(32, "big") + data
    return head + tail


packed = pack_signatures(
    static={owner1.address: sign_safe_tx(outer, tx, owner1)},
    dynamic={inner.address: inner_signature},
)
params = list(tx.values())[:-1]
receipt = send(outer.functions.execTransaction(*params, packed), relayer)
print("\n10. nested Safe tx ok:", bool(outer.events.ExecutionSuccess().process_receipt(receipt, errors=DISCARD)))
10. nested Safe tx ok: True

So the outer Safe executed a transaction signed by owner1 and by the inner Safe, and the inner Safe’s “signature” was itself two signatures from its own owners.

This part changed in v1.5.0: the legacy isValidSignature(bytes, bytes) was removed, and contract signatures are checked against the bytes32 hash instead. If you use v1.5.0 Safes, the inner owners sign a SafeMessage over the outer safeTxHash instead of the full preimage.

Conclusion

That was a lot of code, but I think it’s worth going through it once without an SDK. A few things I took away from it:

  • Everything is a Safe transaction. Changing owners, enabling modules, signing messages: it’s all execTransaction with the Safe calling itself or delegatecalling a helper contract.
  • The signature format is flexible. ECDSA, eth_sign, on-chain approvals, msg.sender, and contract signatures can all be mixed in one transaction, as long as they’re sorted by owner address.
  • Modules are powerful. One enabled module can move funds with a single call, without signatures and without using the nonce.
  • Gas refunds need care. baseGas must cover everything the Safe doesn’t measure, and gas estimation won’t include the refund payment.
  • Test on a fork. Two of my assumptions (MultiSend replacing 0x0, and the Anvil default accounts being plain EOAs) were wrong, and I only found out by running the code.

What’s missing are guards. They need a contract that implements checkTransaction and checkAfterExecution, so I’ll leave them for a future post, where we’ll write our own guard and module in Solidity.