1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use crate::*;
use serde::{Deserialize, Serialize};

////////////////////////////////////////////////////////////////////////////
/// EVM
////////////////////////////////////////////////////////////////////////////

/// Represents an Ethereum Virtual Machine (EVM) transaction.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct EvmTransaction {
    /// The expiration time of the transaction in seconds.
    pub expiration_time_seconds: u64,
    /// The maximum amount of gas that can be used for the transaction.
    pub gas_limit: String,
    /// The value of the transaction in wei.
    pub value: String,
    /// The address of the recipient of the transaction.
    pub to: String,
    /// The address of the sender of the transaction.
    pub from: String,
    /// The data payload of the transaction.
    pub data: String,
}

#[derive(Default, Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct EVMFunctionResultV0 {
    // NOTE: tx.len() == signatures.len() must be true
    pub txs: Vec<EvmTransaction>,
    pub signatures: Vec<Vec<u8>>,

    // NOTE: call_ids.len() == checksums.len() must be true - must also be mapped to txs
    // these params should be default if not used (i.e. empty)
    pub call_ids: Vec<Vec<u8>>,
    pub checksums: Vec<Vec<u8>>,
}

#[derive(Default, Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct EVMFunctionResultV1 {
    // id of the executed function
    pub function_id: String,

    // delegated signer address of the executed function
    pub signer: String,

    pub txs: Vec<EvmTransaction>,
    pub signatures: Vec<String>,

    // -- ids resolved by the function output --
    pub resolved_ids: Vec<String>,

    // -- checksums of the params used in the function call --
    pub checksums: Vec<String>,

    // -- error codes assigned to each request id --
    pub error_codes: Vec<u8>,
}

/// Enum representing the result of an EVM function call.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(tag = "version")]
pub enum EVMFunctionResult {
    V0(EVMFunctionResultV0),
    V1(EVMFunctionResultV1),
}
impl Default for EVMFunctionResult {
    fn default() -> Self {
        Self::V1(EVMFunctionResultV1::default())
    }
}

////////////////////////////////////////////////////////////////////////////
/// Solana
////////////////////////////////////////////////////////////////////////////

/// Represents the result of a Solana function call.
#[derive(Default, Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct SOLFunctionResultV0 {
    /// The serialized, partially-signed transaction.
    pub serialized_tx: Vec<u8>,
}

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(tag = "version")]
pub enum SOLFunctionResult {
    V0(SOLFunctionResultV0),
}
impl Default for SOLFunctionResult {
    fn default() -> Self {
        Self::V0(SOLFunctionResultV0::default())
    }
}

////////////////////////////////////////////////////////////////////////////
/// Function result info
////////////////////////////////////////////////////////////////////////////

#[derive(Default, PartialEq, Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "chain")]
pub enum ChainResultInfo {
    #[default]
    None,
    Solana(SOLFunctionResult),
    Evm(EVMFunctionResult),
}

/// The schema of the output data that will be sent to the quote verification sidecar.
#[derive(Clone, PartialEq, Default, Debug, Serialize, Deserialize)]
pub struct FunctionResultV0 {
    /// Buffer containing the quote signing the output
    pub quote: Vec<u8>,
    /// key of the executed function
    pub fn_key: Vec<u8>,
    /// The oracle's signer used to sign off on the execution
    pub signer: Vec<u8>,
    /// If the call was a funciton request, the address of the request account.
    pub fn_request_key: Vec<u8>,
    /// A sha-256 hash of the parameters used in this request call.
    pub fn_request_hash: Vec<u8>,
    /// Chain specific info
    pub chain_result_info: ChainResultInfo,
    /// On function failure, users should emit with error code to avoid
    /// aggressive backoffs
    #[serde(default)]
    pub error_code: u8,
}

/// The schema of the output data that will be sent to the quote verification sidecar.
#[derive(Clone, PartialEq, Default, Debug, Serialize, Deserialize)]
pub struct FunctionResultV1 {
    /// Buffer containing the quote signing the output
    pub quote: Vec<u8>,
    /// Chain specific info
    pub chain_result_info: ChainResultInfo,
    /// Signature of the chain result info (if applicable)
    pub signature: Vec<u8>,
    /// On function failure, users should emit with error code to avoid
    /// aggressive backoffs
    #[serde(default)]
    pub error_code: u8,
}

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(tag = "version")]
pub enum FunctionResult {
    V0(FunctionResultV0),
    V1(FunctionResultV1),
}
impl Default for FunctionResult {
    fn default() -> Self {
        Self::V1(FunctionResultV1::default())
    }
}

pub static FUNCTION_RESULT_PREFIX: &str = "FN_OUT: ";

impl FunctionResult {
    pub fn emit(&self) {
        println!(
            "{}{}",
            FUNCTION_RESULT_PREFIX,
            hex::encode(serde_json::to_string(&self).unwrap())
        );
    }

    pub fn decode(s: &str) -> std::result::Result<Self, SbError> {
        let stripped = s.strip_prefix(FUNCTION_RESULT_PREFIX);
        if stripped.is_none() {
            return Err("String does not start with 'FN_OUT: '".into());
        }
        let stripped = stripped.unwrap();
        let decoded = hex::decode(stripped)?;

        // First try to deserialize into the correct type
        match serde_json::from_slice::<FunctionResult>(&decoded) {
            Ok(deserialized) => return Ok(deserialized),
            Err(e) => log::info!("Failed to decode FunctionResult: {:?}", e),
        };

        // Fallback to using the LegacyFunctionResult if it cant be deserialized
        match serde_json::from_slice::<LegacyFunctionResult>(&decoded) {
            Ok(deserialized) => return Ok(deserialized.into()),
            Err(e) => log::info!("Failed to decode LegacyFunctionResult: {:?}", e),
        };

        Err(SbError::CustomMessage(format!(
            "Failed to decode FunctionResult string {:?}",
            String::from_utf8(decoded).unwrap_or_default()
        )))
    }
}
impl From<LegacyFunctionResult> for FunctionResult {
    fn from(item: LegacyFunctionResult) -> FunctionResult {
        FunctionResult::V0(FunctionResultV0 {
            quote: item.quote,
            fn_key: item.fn_key,
            signer: item.signer,
            fn_request_key: item.fn_request_key,
            fn_request_hash: item.fn_request_hash,
            chain_result_info: item.chain_result_info.into(),
            error_code: item.error_code,
        })
    }
}

/// The schema of the output data that will be sent to the quote verification sidecar.
/// This implementation has been deprecated in favor of `FunctionResult`.
#[derive(Clone, PartialEq, Default, Debug, Serialize, Deserialize)]
pub struct LegacyFunctionResult {
    /// version of the output format
    pub version: u32,
    /// Buffer containing the quote signing the output
    pub quote: Vec<u8>,
    /// key of the executed function
    pub fn_key: Vec<u8>,
    /// The oracle's signer used to sign off on the execution
    pub signer: Vec<u8>,
    /// If the call was a funciton request, the address of the request account.
    pub fn_request_key: Vec<u8>,
    /// A sha-256 hash of the parameters used in this request call.
    pub fn_request_hash: Vec<u8>,
    /// Chain specific info
    pub chain_result_info: LegacyChainResultInfo,
    /// On function failure, users should emit with error code to avoid
    /// aggressive backoffs
    #[serde(default)]
    pub error_code: u8,
}

#[derive(Default, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum LegacyChainResultInfo {
    #[default]
    None,
    Solana(SOLFunctionResult),
    Evm(EVMFunctionResult),
}
impl From<LegacyChainResultInfo> for ChainResultInfo {
    fn from(item: LegacyChainResultInfo) -> ChainResultInfo {
        match item {
            LegacyChainResultInfo::Solana(sol) => ChainResultInfo::Solana(sol),
            LegacyChainResultInfo::Evm(evm) => ChainResultInfo::Evm(evm),
            _ => ChainResultInfo::None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // FunctionResult { version: 0, quote: [], fn_key: [], signer: [], fn_request_key: [], fn_request_hash: [], chain_result_info: None, error_code: 0 }
    pub const EMPTY_ENCODED_FN_RESULT: &str = "7b2276657273696f6e223a302c2271756f7465223a5b5d2c22666e5f6b6579223a5b5d2c227369676e6572223a5b5d2c22666e5f726571756573745f6b6579223a5b5d2c22666e5f726571756573745f68617368223a5b5d2c22636861696e5f726573756c745f696e666f223a224e6f6e65222c226572726f725f636f6465223a307d";

    // FunctionResult { version: 0, quote: [], fn_key: [], signer: [], fn_request_key: [], fn_request_hash: [], chain_result_info: Solana(SOLFunctionResult { serialized_tx: [1, 2, 3] }), error_code: 0 }
    pub const SOL_ENCODED_FN_RESULT: &str = "7b2276657273696f6e223a302c2271756f7465223a5b5d2c22666e5f6b6579223a5b5d2c227369676e6572223a5b5d2c22666e5f726571756573745f6b6579223a5b5d2c22666e5f726571756573745f68617368223a5b5d2c22636861696e5f726573756c745f696e666f223a7b22536f6c616e61223a7b2273657269616c697a65645f7478223a5b312c322c335d7d7d2c226572726f725f636f6465223a307d";

    #[test]
    fn test_legacy_decode() {
        let _ = simple_logger::init_with_level(log::Level::Debug);

        let decoded =
            FunctionResult::decode(&format!("FN_OUT: {}", EMPTY_ENCODED_FN_RESULT)).unwrap();

        assert_eq!(decoded, FunctionResult::default());
    }

    #[test]
    fn test_decode() {
        let _ = simple_logger::init_with_level(log::Level::Debug);

        let fr = FunctionResult::default();

        let encoded = format!(
            "FN_OUT: {}",
            hex::encode(serde_json::to_string(&fr).unwrap())
        );
        println!("Encoded: {:?}", encoded);

        let decoded = FunctionResult::decode(&encoded).unwrap();
        println!("Decoded: {:?}", decoded);

        assert_eq!(decoded, FunctionResult::default());
    }

    #[test]
    fn test_evm_v0_decode() {
        let _ = simple_logger::init_with_level(log::Level::Debug);

        let evm_result = EVMFunctionResultV0::default();
        let fr = FunctionResult::V0(FunctionResultV0 {
            quote: vec![],
            fn_key: vec![],
            signer: vec![],
            fn_request_key: vec![],
            fn_request_hash: vec![],
            chain_result_info: ChainResultInfo::Evm(EVMFunctionResult::V0(evm_result)),
            error_code: 0,
        });

        let encoded = format!(
            "FN_OUT: {}",
            hex::encode(serde_json::to_string(&fr).unwrap())
        );
        println!("Encoded: {:?}", encoded);

        let decoded = FunctionResult::decode(&encoded).unwrap();
        println!("Decoded: {:?}", decoded);

        match decoded {
            FunctionResult::V0(FunctionResultV0 {
                chain_result_info:
                    ChainResultInfo::Evm(EVMFunctionResult::V0(decoded_evm_v0_result)),
                ..
            }) => {
                assert_eq!(decoded_evm_v0_result, EVMFunctionResultV0::default());
            }
            _ => panic!("Expected EVMFunctionResultV0"),
        }

        // assert_eq!(decoded, FunctionResult::default());
    }
}