Files
sc-templates/python/process.py

141 lines
3.9 KiB
Python
Executable File

"""
Smart Contract Processing Logic
This file contains the transaction processing logic for your smart contract.
Modify the `process` function to implement your business logic.
"""
import json
from dataclasses import dataclass
from typing import Any, Optional
# =============================================================================
# SMART CONTRACT IMPLEMENTATION - MODIFY THIS FILE
# =============================================================================
@dataclass
class TransactionHeader:
"""Transaction metadata from Dragonchain."""
tag: str
dc_id: str
txn_id: str
block_id: str
txn_type: str
timestamp: str
invoker: str
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "TransactionHeader":
"""Parse header from dictionary."""
return cls(
tag=data.get("tag", ""),
dc_id=data.get("dc_id", ""),
txn_id=data.get("txn_id", ""),
block_id=data.get("block_id", ""),
txn_type=data.get("txn_type", ""),
timestamp=data.get("timestamp", ""),
invoker=data.get("invoker", ""),
)
@dataclass
class Transaction:
"""
Parsed transaction from the server.
Customize this class to match your transaction payload structure.
"""
version: str
header: TransactionHeader
payload: dict[str, Any]
@classmethod
def from_json(cls, json_str: str) -> "Transaction":
"""Parse a transaction from JSON string."""
data = json.loads(json_str)
return cls(
version=data.get("version", ""),
header=TransactionHeader.from_dict(data.get("header", {})),
payload=data.get("payload", {}),
)
@dataclass
class ProcessResult:
"""Result from the process function."""
data: Optional[dict[str, Any]] = None
output_to_chain: bool = True
error: Optional[str] = None
def process(
tx_json: str,
env_vars: dict[str, str],
secrets: dict[str, str],
) -> ProcessResult:
"""
Process an incoming transaction.
Implement your smart contract logic here.
Args:
tx_json: Raw transaction JSON string
env_vars: Environment variables passed from the server
secrets: Secrets passed from the server (e.g., API keys, credentials)
Returns:
ProcessResult containing the result data, whether to output to chain, and any error
"""
try:
# Parse the transaction JSON
tx = Transaction.from_json(tx_json)
except json.JSONDecodeError as e:
return ProcessResult(error=f"Failed to parse transaction: {e}")
# ==========================================================================
# TODO: Implement your smart contract logic here
# ==========================================================================
#
# Example: Access transaction data
# txn_id = tx.header.txn_id
# txn_type = tx.header.txn_type
# payload = tx.payload
#
# Example: Access environment variables
# sc_name = env_vars.get("SMART_CONTRACT_NAME")
# dc_id = env_vars.get("DRAGONCHAIN_ID")
#
# Example: Access secrets
# api_key = secrets.get("SC_SECRET_MY_API_KEY")
#
# Example: Process based on payload action
# action = tx.payload.get("action")
# if action == "create":
# # Handle create operation
# pass
# elif action == "update":
# # Handle update operation
# pass
# else:
# return ProcessResult(error=f"Unknown action: {action}")
# Default implementation: echo back the transaction
result = {
"status": "processed",
"transaction_id": tx.header.txn_id,
"txn_type": tx.header.txn_type,
"payload": tx.payload,
"message": "Transaction processed successfully",
}
return ProcessResult(
data=result,
output_to_chain=True,
error=None,
)