Ethereum: Converting a JSON containing a SafeOperation into an EthSafeOperation object
==========================================================================================
Since you are already familiar with the Safe SDK, let’s dive into how we can convert a JSON containing a SafeOperation
object into an equivalent EthSafeOperation
object for Ethereum.
Step 1: Parse the JSON
First, we need to parse the JSON containing the SafeOperation
. This will give us a data structure in Python or JavaScript that represents our SafeOperation.
import json
from safe_sdk import SafeOpError

Load the JSON data from the mobile client requestmobile_client_data = json.loads(mobile_client_request)
Parse the JSON into an objectsafe_operation = SafeOp.from_json(mobile_client_data)
Step 2: Check the operation type
Before creating EthSafeOperation
objects, we need to make sure that our operation is valid. We can check the operation type by checking if it is a SafeOperation
.
Check if the operation is a SafeOperationif isinstance(safe_operation, SafeOp):
If it is valid, proceed with the conversionelse:
raise SafeOpError("Invalid operation")
Step 3: Convert the JSON to an EthSafeOperation
Now that we have verified the operation type, we can convert the SafeOperation
object to an equivalent EthSafeOperation
. We use the EthSafeOperation.from_safe_operation()
method provided by the Safe SDK.
Create a new EthSafeOperation from the SafeOperation objecteth_safe_operation = EthSafeOperation.from_safe_operation(safe_operation)
Example code
Let’s put it all together in an example function that can handle multiple JSON inputs:
import json
from safe_sdk import SafeOpError, SafeOp
def convert_safe_operation(json_data):
"""
Convert a JSON containing a SafeOperation object into an equivalent EthSafeOperation object.
Arguments:
json_data (dict): A dictionary representing the JSON data from the mobile client request.
Returns:
EthSafeOperation: An EthSafeOperation object representing the converted operation.
"""
safe_operation = SafeOp.from_json(json_data)
Check if the operation is a SafeOperationif isinstance(safe_operation, SafeOp):
If valid, proceed with the conversioneth_safe_operation = EthSafeOperation.from_safe_operation(safe_operation)
return eth_safe_operation
else:
raise SafeOpError("Invalid operation")
Usage
Here is an example usage of the convert_safe_operation()
function:
mobile_client_data = {
"type": "safeOperation",
"value": {"id": 123, "data": "example data"}
}
eth_safe_operation = convert_safe_operation(mobile_client_data)
print(eth_safe_operation.to_json())
This will output the JSON representation of the converted EthSafeOperation
object.