openzeppelin_relayer/domain/relayer/solana/rpc/
handler.rs

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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Handles incoming Solana RPC requests.
//!
//! This module defines the `SolanaRpcHandler` struct that dispatches RPC requests
//! to the appropriate methods. It uses the trait defined in the `methods`
//! module to process specific operations such as fee estimation, transaction
//! preparation, signing, sending, and token retrieval.
//!
//! The handler converts JSON-RPC requests into concrete call parameters and then
//! invokes the respective methods of the underlying implementation.
use super::{SolanaRpcError, SolanaRpcMethods};
use crate::{
    domain::{JsonRpcRequest, JsonRpcResponse},
    models::{NetworkRpcRequest, NetworkRpcResult, SolanaRpcRequest, SolanaRpcResult},
};
use eyre::Result;
use log::info;

pub struct SolanaRpcHandler<T> {
    rpc_methods: T,
}

impl<T: SolanaRpcMethods> SolanaRpcHandler<T> {
    /// Creates a new `SolanaRpcHandler` with the specified RPC methods.
    ///
    /// # Arguments
    ///
    /// * `rpc_methods` - An implementation of the `SolanaRpcMethods` trait that provides the
    ///   necessary methods for handling RPC requests.
    ///
    /// # Returns
    ///
    /// Returns a new instance of `SolanaRpcHandler`
    pub fn new(rpc_methods: T) -> Self {
        Self { rpc_methods }
    }

    /// Handles an incoming JSON-RPC request and dispatches it to the appropriate method.
    ///
    /// This function processes the request by determining the method to call based on
    /// the request's method name, deserializing the parameters, and invoking the corresponding
    /// method on the `rpc_methods` implementation.
    ///
    /// # Arguments
    ///
    /// * `request` - A `JsonRpcRequest` containing the method name and parameters.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing either a `JsonRpcResponse` with the result of the method call
    /// or a `SolanaRpcError` if an error occurred.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The method is unsupported.
    /// * The parameters cannot be deserialized.
    /// * The underlying method call fails.
    pub async fn handle_request(
        &self,
        request: JsonRpcRequest<NetworkRpcRequest>,
    ) -> Result<JsonRpcResponse<NetworkRpcResult>, SolanaRpcError> {
        info!("Received request params: {:?}", request.params);
        // Extract Solana request or return error
        let solana_request = match request.params {
            NetworkRpcRequest::Solana(solana_params) => solana_params,
            _ => {
                return Err(SolanaRpcError::BadRequest(
                    "Expected Solana network request".to_string(),
                ));
            }
        };

        let result = match solana_request {
            SolanaRpcRequest::FeeEstimate(params) => {
                let res = self.rpc_methods.fee_estimate(params).await?;
                SolanaRpcResult::FeeEstimate(res)
            }
            SolanaRpcRequest::TransferTransaction(params) => {
                let res = self.rpc_methods.transfer_transaction(params).await?;
                SolanaRpcResult::TransferTransaction(res)
            }
            SolanaRpcRequest::PrepareTransaction(params) => {
                let res = self.rpc_methods.prepare_transaction(params).await?;
                SolanaRpcResult::PrepareTransaction(res)
            }
            SolanaRpcRequest::SignAndSendTransaction(params) => {
                let res = self.rpc_methods.sign_and_send_transaction(params).await?;
                SolanaRpcResult::SignAndSendTransaction(res)
            }
            SolanaRpcRequest::SignTransaction(params) => {
                let res = self.rpc_methods.sign_transaction(params).await?;
                SolanaRpcResult::SignTransaction(res)
            }
            SolanaRpcRequest::GetSupportedTokens(params) => {
                let res = self.rpc_methods.get_supported_tokens(params).await?;
                SolanaRpcResult::GetSupportedTokens(res)
            }
            SolanaRpcRequest::GetFeaturesEnabled(params) => {
                let res = self.rpc_methods.get_features_enabled(params).await?;
                SolanaRpcResult::GetFeaturesEnabled(res)
            }
        };

        Ok(JsonRpcResponse::result(
            request.id,
            NetworkRpcResult::Solana(result),
        ))
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::{
        domain::MockSolanaRpcMethods,
        models::{
            EncodedSerializedTransaction, FeeEstimateRequestParams, FeeEstimateResult,
            GetFeaturesEnabledRequestParams, GetFeaturesEnabledResult,
            PrepareTransactionRequestParams, PrepareTransactionResult,
            SignAndSendTransactionRequestParams, SignAndSendTransactionResult,
            SignTransactionRequestParams, SignTransactionResult, TransferTransactionRequestParams,
            TransferTransactionResult,
        },
    };

    use super::*;
    use mockall::predicate::{self};

    #[tokio::test]
    async fn test_handle_request_fee_estimate() {
        let mut mock_rpc_methods = MockSolanaRpcMethods::new();
        mock_rpc_methods
            .expect_fee_estimate()
            .with(predicate::eq(FeeEstimateRequestParams {
                transaction: EncodedSerializedTransaction::new("test_transaction".to_string()),
                fee_token: "test_token".to_string(),
            }))
            .returning(|_| {
                Ok(FeeEstimateResult {
                    estimated_fee: "0".to_string(),
                    conversion_rate: "0".to_string(),
                })
            })
            .times(1);
        let mock_handler = Arc::new(SolanaRpcHandler::new(mock_rpc_methods));
        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            params: NetworkRpcRequest::Solana(SolanaRpcRequest::FeeEstimate(
                FeeEstimateRequestParams {
                    transaction: EncodedSerializedTransaction::new("test_transaction".to_string()),
                    fee_token: "test_token".to_string(),
                },
            )),
        };

        let response = mock_handler.handle_request(request).await;

        assert!(response.is_ok(), "Expected Ok response, got {:?}", response);
        let json_response = response.unwrap();
        assert_eq!(
            json_response.result,
            Some(NetworkRpcResult::Solana(SolanaRpcResult::FeeEstimate(
                FeeEstimateResult {
                    estimated_fee: "0".to_string(),
                    conversion_rate: "0".to_string(),
                }
            )))
        );
    }

    #[tokio::test]
    async fn test_handle_request_features_enabled() {
        let mut mock_rpc_methods = MockSolanaRpcMethods::new();
        mock_rpc_methods
            .expect_get_features_enabled()
            .with(predicate::eq(GetFeaturesEnabledRequestParams {}))
            .returning(|_| {
                Ok(GetFeaturesEnabledResult {
                    features: vec!["gasless".to_string()],
                })
            })
            .times(1);
        let mock_handler = Arc::new(SolanaRpcHandler::new(mock_rpc_methods));
        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            params: NetworkRpcRequest::Solana(SolanaRpcRequest::GetFeaturesEnabled(
                GetFeaturesEnabledRequestParams {},
            )),
        };

        let response = mock_handler.handle_request(request).await;

        assert!(response.is_ok(), "Expected Ok response, got {:?}", response);
        let json_response = response.unwrap();
        assert_eq!(
            json_response.result,
            Some(NetworkRpcResult::Solana(
                SolanaRpcResult::GetFeaturesEnabled(GetFeaturesEnabledResult {
                    features: vec!["gasless".to_string()],
                })
            ))
        );
    }

    #[tokio::test]
    async fn test_handle_request_sign_transaction() {
        let mut mock_rpc_methods = MockSolanaRpcMethods::new();

        // Create mock response
        let mock_signature = "5wHu1qwD4kF3wxjejXkgDYNVnEgB1e8uVvrxNwJYRzHPPxWqRA4nxwE1TU4";
        let mock_transaction = "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string();

        mock_rpc_methods
            .expect_sign_transaction()
            .with(predicate::eq(SignTransactionRequestParams {
                transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
            }))
            .returning(move |_| {
                Ok(SignTransactionResult {
                    transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
                    signature: mock_signature.to_string(),
                })
            })
            .times(1);

        let mock_handler = Arc::new(SolanaRpcHandler::new(mock_rpc_methods));

        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            params: NetworkRpcRequest::Solana(SolanaRpcRequest::SignTransaction(
                SignTransactionRequestParams {
                    transaction: EncodedSerializedTransaction::new("AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string()),
                },
            )),
        };

        let response = mock_handler.handle_request(request).await;

        assert!(response.is_ok(), "Expected Ok response, got {:?}", response);
        let json_response = response.unwrap();

        match json_response.result {
            Some(value) => {
                if let NetworkRpcResult::Solana(SolanaRpcResult::SignTransaction(result)) = value {
                    assert_eq!(result.signature, mock_signature);
                } else {
                    panic!("Expected SignTransaction result, got {:?}", value);
                }
            }
            None => panic!("Expected Some result, got None"),
        }
    }

    #[tokio::test]
    async fn test_handle_request_sign_and_send_transaction_success() {
        let mut mock_rpc_methods = MockSolanaRpcMethods::new();

        // Create mock data
        let mock_signature = "5wHu1qwD4kF3wxjejXkgDYNVnEgB1e8uVvrxNwJYRzHPPxWqRA4nxwE1TU4";
        let mock_transaction = "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string();

        mock_rpc_methods
            .expect_sign_and_send_transaction()
            .with(predicate::eq(SignAndSendTransactionRequestParams {
                transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
            }))
            .returning(move |_| {
                Ok(SignAndSendTransactionResult {
                    transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
                    signature: mock_signature.to_string(),
                })
            })
            .times(1);

        let handler = Arc::new(SolanaRpcHandler::new(mock_rpc_methods));

        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            params: NetworkRpcRequest::Solana(SolanaRpcRequest::SignAndSendTransaction(
                SignAndSendTransactionRequestParams {
                    transaction: EncodedSerializedTransaction::new("AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string()),
                },
            )),
        };

        let response = handler.handle_request(request).await;

        assert!(response.is_ok());
        let json_response = response.unwrap();
        match json_response.result {
            Some(value) => {
                if let NetworkRpcResult::Solana(SolanaRpcResult::SignAndSendTransaction(result)) =
                    value
                {
                    assert_eq!(result.signature, mock_signature);
                } else {
                    panic!("Expected SignAndSendTransaction result, got {:?}", value);
                }
            }
            None => panic!("Expected Some result, got None"),
        }
    }

    #[tokio::test]
    async fn test_transfer_transaction_success() {
        let mut mock_rpc_methods = MockSolanaRpcMethods::new();
        let mock_transaction = "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string();

        mock_rpc_methods
            .expect_transfer_transaction()
            .with(predicate::eq(TransferTransactionRequestParams {
                source: "C6VBV1EK2Jx7kFgCkCD5wuDeQtEH8ct2hHGUPzEhUSc8".to_string(),
                destination: "C6VBV1EK2Jx7kFgCkCD5wuDeQtEH8ct2hHGUPzEhUSc8".to_string(),
                amount: 10,
                token: "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr".to_string(), // noboost
            }))
            .returning(move |_| {
                Ok(TransferTransactionResult {
                    fee_in_lamports: "1005000".to_string(),
                    fee_in_spl: "1005000".to_string(),
                    fee_token: "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr".to_string(), // noboost
                    transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
                    valid_until_blockheight: 351207983,
                })
            })
            .times(1);

        let handler = Arc::new(SolanaRpcHandler::new(mock_rpc_methods));

        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            params: NetworkRpcRequest::Solana(SolanaRpcRequest::TransferTransaction(
                TransferTransactionRequestParams {
                    source: "C6VBV1EK2Jx7kFgCkCD5wuDeQtEH8ct2hHGUPzEhUSc8".to_string(),
                    destination: "C6VBV1EK2Jx7kFgCkCD5wuDeQtEH8ct2hHGUPzEhUSc8".to_string(),
                    amount: 10,
                    token: "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr".to_string(), // noboost
                },
            )),
        };

        let response = handler.handle_request(request).await;

        assert!(response.is_ok());
        let json_response = response.unwrap();
        match json_response.result {
            Some(value) => {
                if let NetworkRpcResult::Solana(SolanaRpcResult::TransferTransaction(result)) =
                    value
                {
                    assert!(!result.fee_in_lamports.is_empty());
                    assert!(!result.fee_in_spl.is_empty());
                    assert!(!result.fee_token.is_empty());
                    assert!(!result.transaction.into_inner().is_empty());
                    assert!(result.valid_until_blockheight > 0);
                } else {
                    panic!("Expected TransferTransaction result, got {:?}", value);
                }
            }
            None => panic!("Expected Some result, got None"),
        }
    }

    #[tokio::test]
    async fn test_prepare_transaction_success() {
        let mut mock_rpc_methods = MockSolanaRpcMethods::new();
        let mock_transaction = "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string();

        mock_rpc_methods
            .expect_prepare_transaction()
            .with(predicate::eq(PrepareTransactionRequestParams {
                transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
                fee_token: "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr".to_string(),
            }))
            .returning(move |_| {
                Ok(PrepareTransactionResult {
                    fee_in_lamports: "1005000".to_string(),
                    fee_in_spl: "1005000".to_string(),
                    fee_token: "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr".to_string(),
                    transaction: EncodedSerializedTransaction::new(mock_transaction.clone()),
                    valid_until_blockheight: 351207983,
                })
            })
            .times(1);

        let handler = Arc::new(SolanaRpcHandler::new(mock_rpc_methods));

        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            params: NetworkRpcRequest::Solana(SolanaRpcRequest::PrepareTransaction(
                PrepareTransactionRequestParams {
                    transaction: EncodedSerializedTransaction::new("AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_string()),
                    fee_token: "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr".to_string(),
                },
            )),
        };

        let response = handler.handle_request(request).await;

        assert!(response.is_ok());
        let json_response = response.unwrap();
        match json_response.result {
            Some(value) => {
                if let NetworkRpcResult::Solana(SolanaRpcResult::PrepareTransaction(result)) = value
                {
                    assert!(!result.fee_in_lamports.is_empty());
                    assert!(!result.fee_in_spl.is_empty());
                    assert!(!result.fee_token.is_empty());
                    assert!(!result.transaction.into_inner().is_empty());
                    assert!(result.valid_until_blockheight > 0);
                } else {
                    panic!("Expected PrepareTransaction result, got {:?}", value);
                }
            }
            None => panic!("Expected Some result, got None"),
        }
    }
}