This module provides a standardized response structure for smart contract query operations, making it easier for off-chain integrations to handle responses consistently.
pub struct Response<T> {
pub success: bool,
pub data: Option<T>,
pub error: Option<u32>,
}{
"success": true,
"data": { /* actual data */ },
"error": null
}{
"success": false,
"data": null,
"error": 7 // ContractError code
}use crate::response::Response;
pub fn query_remittance(env: Env, remittance_id: u64) -> Response<Remittance> {
match get_remittance(&env, remittance_id) {
Ok(data) => Response::ok(data),
Err(e) => Response::err(e as u32),
}
}// Success response
let response = Response::ok(remittance_data);
// Error response
let response = Response::err(ContractError::RemittanceNotFound as u32);- Consistency: All query functions return the same structure
- Type Safety: Generic type parameter ensures correct data types
- Error Handling: Standardized error codes from ContractError enum
- Off-Chain Integration: Easy to parse and handle in client applications
The response wrapper can be used alongside existing functions:
- Existing:
get_remittance()returnsResult<Remittance, ContractError> - New:
query_remittance()returnsResponse<Remittance>
This maintains backward compatibility while providing a new standardized interface.
Error codes correspond to the ContractError enum:
| Code | Error | Description |
|---|---|---|
| 1 | AlreadyInitialized | Contract already initialized |
| 2 | NotInitialized | Contract not initialized |
| 3 | InvalidAmount | Amount must be greater than 0 |
| 4 | InvalidFeeBps | Fee must be between 0-10000 bps |
| 5 | AgentNotRegistered | Agent not in approved list |
| 6 | RemittanceNotFound | Remittance ID does not exist |
| 7 | InvalidStatus | Operation not allowed in current status |
| 8 | Overflow | Arithmetic overflow detected |
| 9 | NoFeesToWithdraw | No accumulated fees available |
// JavaScript/TypeScript client example
const response = await contract.query_remittance({ remittance_id: 42 });
if (response.success) {
console.log("Remittance data:", response.data);
} else {
console.error("Error code:", response.error);
handleError(response.error);
}Potential additions:
- Add error message strings
- Include timestamp in responses
- Add pagination metadata for list queries
- Support for batch queries
This module provides the response wrapper type. To use it in contract functions, you'll need to:
- Import the module in
lib.rs - Create wrapper functions that use
Response<T> - Export the wrapper functions in the contract interface
The module is designed to be minimal and focused, following the principle of doing one thing well.