openzeppelin_relayer/models/transaction/stellar/
conversion.rs

1//! Transaction conversion logic for Stellar
2
3use crate::constants::STELLAR_DEFAULT_TRANSACTION_FEE;
4use crate::domain::string_to_muxed_account;
5use crate::models::transaction::repository::StellarTransactionData;
6use crate::models::SignerError;
7use chrono::DateTime;
8use soroban_rs::xdr::{
9    Limits, Memo, Operation, Preconditions, ReadXdr, SequenceNumber, TimeBounds, TimePoint,
10    Transaction, TransactionExt, VecM,
11};
12use std::convert::TryFrom;
13
14pub type DecoratedSignature = soroban_rs::xdr::DecoratedSignature;
15
16#[derive(Debug, Clone)]
17pub struct TimeBoundsSpec {
18    pub min_time: u64,
19    pub max_time: u64,
20}
21
22fn valid_until_to_time_bounds(valid_until: Option<String>) -> Option<TimeBoundsSpec> {
23    valid_until.and_then(|expiry| {
24        if let Ok(expiry_time) = expiry.parse::<u64>() {
25            Some(TimeBoundsSpec {
26                min_time: 0,
27                max_time: expiry_time,
28            })
29        } else if let Ok(dt) = DateTime::parse_from_rfc3339(&expiry) {
30            Some(TimeBoundsSpec {
31                min_time: 0,
32                max_time: dt.timestamp() as u64,
33            })
34        } else {
35            None
36        }
37    })
38}
39
40impl TryFrom<StellarTransactionData> for Transaction {
41    type Error = SignerError;
42
43    fn try_from(data: StellarTransactionData) -> Result<Self, Self::Error> {
44        match &data.transaction_input {
45            crate::models::TransactionInput::Operations(ops) => {
46                // Build transaction from operations
47                let converted_ops: Result<Vec<Operation>, SignerError> = ops
48                    .iter()
49                    .map(|op| Operation::try_from(op.clone()))
50                    .collect();
51                let operations = converted_ops?;
52
53                let operations: VecM<Operation, 100> = operations
54                    .try_into()
55                    .map_err(|_| SignerError::ConversionError("op count > 100".into()))?;
56
57                let time_bounds = valid_until_to_time_bounds(data.valid_until);
58                let cond = match time_bounds {
59                    None => Preconditions::None,
60                    Some(tb) => Preconditions::Time(TimeBounds {
61                        min_time: TimePoint(tb.min_time),
62                        max_time: TimePoint(tb.max_time),
63                    }),
64                };
65
66                let memo = match &data.memo {
67                    Some(memo_spec) => Memo::try_from(memo_spec.clone())?,
68                    None => Memo::None,
69                };
70
71                let fee = data.fee.unwrap_or(STELLAR_DEFAULT_TRANSACTION_FEE);
72                let sequence = data.sequence_number.unwrap_or(0);
73
74                let source_account =
75                    string_to_muxed_account(&data.source_account).map_err(|e| {
76                        SignerError::ConversionError(format!("Invalid source account: {e}"))
77                    })?;
78
79                // Apply transaction extension data from simulation if available
80                let ext = match &data.simulation_transaction_data {
81                    Some(xdr_data) => {
82                        use soroban_rs::xdr::SorobanTransactionData;
83                        match SorobanTransactionData::from_xdr_base64(xdr_data, Limits::none()) {
84                            Ok(tx_data) => {
85                                tracing::info!(
86                                    "Applied transaction extension data from simulation"
87                                );
88                                TransactionExt::V1(tx_data)
89                            }
90                            Err(e) => {
91                                tracing::warn!(
92                                    "Failed to decode transaction data XDR: {}, using V0",
93                                    e
94                                );
95                                TransactionExt::V0
96                            }
97                        }
98                    }
99                    None => TransactionExt::V0,
100                };
101
102                Ok(Transaction {
103                    source_account,
104                    fee,
105                    seq_num: SequenceNumber(sequence),
106                    cond,
107                    memo,
108                    operations,
109                    ext,
110                })
111            }
112            crate::models::TransactionInput::UnsignedXdr(_)
113            | crate::models::TransactionInput::SignedXdr { .. } => {
114                // XDR inputs should not be converted to Transaction
115                // The signer handles TransactionEnvelope XDR directly
116                Err(SignerError::ConversionError(
117                    "XDR inputs should not be converted to Transaction - use envelope directly"
118                        .into(),
119                ))
120            }
121        }
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::models::transaction::stellar::asset::AssetSpec;
129    use crate::models::transaction::stellar::{MemoSpec, OperationSpec};
130
131    const TEST_PK: &str = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";
132
133    #[test]
134    fn test_basic_transaction() {
135        let data = StellarTransactionData {
136            source_account: TEST_PK.to_string(),
137            fee: Some(100),
138            sequence_number: Some(1),
139            memo: Some(MemoSpec::None),
140            valid_until: None,
141            transaction_input: crate::models::TransactionInput::Operations(vec![
142                OperationSpec::Payment {
143                    destination: TEST_PK.to_string(),
144                    amount: 1000,
145                    asset: AssetSpec::Native,
146                },
147            ]),
148            network_passphrase: "Test SDF Network ; September 2015".to_string(),
149            signatures: Vec::new(),
150            hash: None,
151            simulation_transaction_data: None,
152            signed_envelope_xdr: None,
153        };
154
155        let tx = Transaction::try_from(data).unwrap();
156        assert_eq!(tx.fee, 100);
157        assert_eq!(tx.seq_num.0, 1);
158        assert_eq!(tx.operations.len(), 1);
159    }
160
161    #[test]
162    fn test_transaction_with_time_bounds() {
163        let data = StellarTransactionData {
164            source_account: TEST_PK.to_string(),
165            fee: None,
166            sequence_number: None,
167            memo: None,
168            valid_until: Some("1735689600".to_string()),
169            transaction_input: crate::models::TransactionInput::Operations(vec![
170                OperationSpec::Payment {
171                    destination: TEST_PK.to_string(),
172                    amount: 1000,
173                    asset: AssetSpec::Native,
174                },
175            ]),
176            network_passphrase: "Test SDF Network ; September 2015".to_string(),
177            signatures: Vec::new(),
178            hash: None,
179            simulation_transaction_data: None,
180            signed_envelope_xdr: None,
181        };
182
183        let tx = Transaction::try_from(data).unwrap();
184        if let Preconditions::Time(tb) = tx.cond {
185            assert_eq!(tb.max_time.0, 1735689600);
186        } else {
187            panic!("Expected time bounds");
188        }
189    }
190
191    #[test]
192    fn test_valid_until_numeric_string() {
193        let tb = valid_until_to_time_bounds(Some("12345".to_string())).unwrap();
194        assert_eq!(tb.max_time, 12_345);
195        assert_eq!(tb.min_time, 0);
196    }
197
198    #[test]
199    fn test_valid_until_rfc3339_string() {
200        let tb = valid_until_to_time_bounds(Some("2025-01-01T00:00:00Z".to_string())).unwrap();
201        assert_eq!(tb.max_time, 1_735_689_600);
202        assert_eq!(tb.min_time, 0);
203    }
204
205    #[test]
206    fn test_valid_until_invalid_string() {
207        assert!(valid_until_to_time_bounds(Some("not a date".to_string())).is_none());
208    }
209
210    #[test]
211    fn test_valid_until_none() {
212        assert!(valid_until_to_time_bounds(None).is_none());
213    }
214}