openzeppelin_relayer/models/transaction/stellar/
conversion.rs1use 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 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 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 log::info!("Applied transaction extension data from simulation");
86 TransactionExt::V1(tx_data)
87 }
88 Err(e) => {
89 log::warn!(
90 "Failed to decode transaction data XDR: {}, using V0",
91 e
92 );
93 TransactionExt::V0
94 }
95 }
96 }
97 None => TransactionExt::V0,
98 };
99
100 Ok(Transaction {
101 source_account,
102 fee,
103 seq_num: SequenceNumber(sequence),
104 cond,
105 memo,
106 operations,
107 ext,
108 })
109 }
110 crate::models::TransactionInput::UnsignedXdr(_)
111 | crate::models::TransactionInput::SignedXdr { .. } => {
112 Err(SignerError::ConversionError(
115 "XDR inputs should not be converted to Transaction - use envelope directly"
116 .into(),
117 ))
118 }
119 }
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::models::transaction::stellar::asset::AssetSpec;
127 use crate::models::transaction::stellar::{MemoSpec, OperationSpec};
128
129 const TEST_PK: &str = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";
130
131 #[test]
132 fn test_basic_transaction() {
133 let data = StellarTransactionData {
134 source_account: TEST_PK.to_string(),
135 fee: Some(100),
136 sequence_number: Some(1),
137 memo: Some(MemoSpec::None),
138 valid_until: None,
139 transaction_input: crate::models::TransactionInput::Operations(vec![
140 OperationSpec::Payment {
141 destination: TEST_PK.to_string(),
142 amount: 1000,
143 asset: AssetSpec::Native,
144 },
145 ]),
146 network_passphrase: "Test SDF Network ; September 2015".to_string(),
147 signatures: Vec::new(),
148 hash: None,
149 simulation_transaction_data: None,
150 signed_envelope_xdr: None,
151 };
152
153 let tx = Transaction::try_from(data).unwrap();
154 assert_eq!(tx.fee, 100);
155 assert_eq!(tx.seq_num.0, 1);
156 assert_eq!(tx.operations.len(), 1);
157 }
158
159 #[test]
160 fn test_transaction_with_time_bounds() {
161 let data = StellarTransactionData {
162 source_account: TEST_PK.to_string(),
163 fee: None,
164 sequence_number: None,
165 memo: None,
166 valid_until: Some("1735689600".to_string()),
167 transaction_input: crate::models::TransactionInput::Operations(vec![
168 OperationSpec::Payment {
169 destination: TEST_PK.to_string(),
170 amount: 1000,
171 asset: AssetSpec::Native,
172 },
173 ]),
174 network_passphrase: "Test SDF Network ; September 2015".to_string(),
175 signatures: Vec::new(),
176 hash: None,
177 simulation_transaction_data: None,
178 signed_envelope_xdr: None,
179 };
180
181 let tx = Transaction::try_from(data).unwrap();
182 if let Preconditions::Time(tb) = tx.cond {
183 assert_eq!(tb.max_time.0, 1735689600);
184 } else {
185 panic!("Expected time bounds");
186 }
187 }
188
189 #[test]
190 fn test_valid_until_numeric_string() {
191 let tb = valid_until_to_time_bounds(Some("12345".to_string())).unwrap();
192 assert_eq!(tb.max_time, 12_345);
193 assert_eq!(tb.min_time, 0);
194 }
195
196 #[test]
197 fn test_valid_until_rfc3339_string() {
198 let tb = valid_until_to_time_bounds(Some("2025-01-01T00:00:00Z".to_string())).unwrap();
199 assert_eq!(tb.max_time, 1_735_689_600);
200 assert_eq!(tb.min_time, 0);
201 }
202
203 #[test]
204 fn test_valid_until_invalid_string() {
205 assert!(valid_until_to_time_bounds(Some("not a date".to_string())).is_none());
206 }
207
208 #[test]
209 fn test_valid_until_none() {
210 assert!(valid_until_to_time_bounds(None).is_none());
211 }
212}