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
//! A client that exposes methods for interacting with the XRP Ledger.
//!
//! # Example Usage
//! ```
//! use std::convert::TryInto;
//! use xrpl_rs::{XRPL, transports::HTTP, types::account::AccountInfoRequest, types::CurrencyAmount};
//! use tokio_test::block_on;
//!
//! // Create a new XRPL client with the HTTP transport.
//! let xrpl = XRPL::new(
//!     HTTP::builder()
//!         .with_endpoint("http://s1.ripple.com:51234/")
//!         .unwrap()
//!         .build()
//!         .unwrap());
//!
//! // Create a request
//! let mut req = AccountInfoRequest::default();
//! req.account = "rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn".to_owned();
//!
//! // Fetch the account info for an address.
//! let account_info = block_on(async {
//!     xrpl
//!         .account_info(req)
//!         .await
//!         .unwrap()
//! });
//!
//! assert_eq!(account_info.account_data.balance, CurrencyAmount::xrp(9977));
//! ```

use std::pin::Pin;

use futures::stream::Stream;
use serde::de::DeserializeOwned;
use transports::{DuplexTransport, Transport, TransportError};
use types::{
    account::{
        AccountChannelsRequest, AccountChannelsResponse, AccountCurrenciesRequest,
        AccountCurrenciesResponse, AccountInfoRequest, AccountInfoResponse, AccountLinesRequest,
        AccountLinesResponse, AccountOfferRequest, AccountOfferResponse,
    },
    channels::{ChannelVerifyRequest, ChannelVerifyResponse},
    fee::{FeeRequest, FeeResponse},
    ledger::{LedgerRequest, LedgerResponse},
    submit::{SignAndSubmitRequest, SubmitRequest, SubmitResponse},
    subscribe::{SubscribeRequest, SubscriptionEvent},
    tx::{TxRequest, TxResponse},
    TransactionEntryRequest, TransactionEntryResponse,
};

pub mod transaction;
pub mod transports;
pub mod types;
pub mod utils;
pub mod wallet;

/// An enum providing error types that can be returned when calling XRPL methods.
#[derive(Debug)]
pub enum Error {
    TransportError(TransportError),
}

impl From<TransportError> for Error {
    fn from(e: TransportError) -> Self {
        Self::TransportError(e)
    }
}

/// A client that exposes methods for interacting with the XRP Ledger.
///
/// # Examples
/// ```
/// use std::convert::TryInto;
/// use xrpl_rs::{XRPL, transports::HTTP, types::account::AccountInfoRequest, types::CurrencyAmount};
/// use tokio_test::block_on;
///
/// // Create a new XRPL client with the HTTP transport.
/// let xrpl = XRPL::new(
///     HTTP::builder()
///         .with_endpoint("http://s1.ripple.com:51234/")
///         .unwrap()
///         .build()
///         .unwrap());
///
/// // Create a request
/// let mut req = AccountInfoRequest::default();
/// req.account = "rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn".to_owned();
///
/// // Fetch the account info for an address.
/// let account_info = block_on(async {
///     xrpl
///         .account_info(req)
///         .await
///         .unwrap()
/// });
///
/// assert_eq!(account_info.account_data.balance, CurrencyAmount::xrp(9977));
/// ```
pub struct XRPL<T: Transport> {
    transport: T,
}

macro_rules! impl_rpc_method {
    ($(#[$attr:meta])* $name: ident, $method: expr, $request: ident, $response: ident) => {
        $(#[$attr])*
        pub async fn $name(&self, params: $request) -> Result<$response, Error> {
            Ok(self
                .transport
                .send_request::<$request, $response>($method, params)
                .await?)
        }
    };
}

impl<T: Transport> XRPL<T> {
    pub fn new(transport: T) -> Self {
        Self { transport }
    }
    impl_rpc_method!(
        /// The account_channels method returns information about an account's Payment Channels. This includes only channels where the specified account is the channel's source, not the destination. (A channel's "source" and "owner" are the same.) All information retrieved is relative to a particular version of the ledger.
        account_channels,
        "account_channels",
        AccountChannelsRequest,
        AccountChannelsResponse
    );
    impl_rpc_method!(
        /// The account_currencies command retrieves a list of currencies that an account can send or receive, based on its trust lines. (This is not a thoroughly confirmed list, but it can be used to populate user interfaces.)
        account_currencies,
        "account_currencies",
        AccountCurrenciesRequest,
        AccountCurrenciesResponse
    );
    impl_rpc_method!(
        /// The account_info command retrieves information about an account, its activity, and its XRP balance. All information retrieved is relative to a particular version of the ledger.
        account_info,
        "account_info",
        AccountInfoRequest,
        AccountInfoResponse
    );
    impl_rpc_method!(
        /// The account_lines method returns information about an account's trust lines, including balances in all non-XRP currencies and assets. All information retrieved is relative to a particular version of the ledger.
        account_lines,
        "account_lines",
        AccountLinesRequest,
        AccountLinesResponse
    );
    impl_rpc_method!(
        /// The account_offers method retrieves a list of offers made by a given account that are outstanding as of a particular ledger version.
        account_offers,
        "account_offers",
        AccountOfferRequest,
        AccountOfferResponse
    );
    impl_rpc_method!(
        /// The transaction_entry method retrieves information on a single transaction from a specific ledger version. (The tx method, by contrast, searches all ledgers for the specified transaction. We recommend using that method instead.)
        transaction_entry,
        "transaction_entry",
        TransactionEntryRequest,
        TransactionEntryResponse
    );
    impl_rpc_method!(
        /// The submit method applies a transaction and sends it to the network to be confirmed and included in future ledgers.
        submit,
        "submit",
        SubmitRequest,
        SubmitResponse
    );
    impl_rpc_method!(
        /// The sign_and_submit method applies a transaction and sends it to the network to be confirmed and included in future ledgers.
        sign_and_submit,
        "submit",
        SignAndSubmitRequest,
        SubmitResponse
    );
    impl_rpc_method!(
        /// The fee command reports the current state of the open-ledger requirements for the transaction cost. This requires the FeeEscalation amendment to be enabled. New in: rippled 0.31.0.
        fee,
        "fee",
        FeeRequest,
        FeeResponse
    );
    impl_rpc_method!(
        /// Retrieve information about the public ledger.
        ledger,
        "ledger",
        LedgerRequest,
        LedgerResponse
    );
    impl_rpc_method!(
        /// The channel_verify method checks the validity of a signature that can be used to redeem a specific amount of XRP from a payment channel.
        channel_verify,
        "channel_verify",
        ChannelVerifyRequest,
        ChannelVerifyResponse
    );
    impl_rpc_method!(
        /// The tx method retrieves information on a single transaction, by its identifying hash.
        tx,
        "tx",
        TxRequest,
        TxResponse
    );
}

impl<T: DuplexTransport> XRPL<T> {
    pub async fn subscribe(
        &self,
        request: SubscribeRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<SubscriptionEvent, TransportError>>>>, TransportError> {
        self.transport.subscribe(request).await
    }
}

#[cfg(test)]
mod tests {
    use crate::types::{BigInt, CurrencyAmount};

    use super::{transports::HTTPBuilder, types, XRPL};
    #[test]
    fn create_client() {
        let _ = XRPL::new(
            HTTPBuilder::default()
                .with_endpoint("http://s1.ripple.com:51234/")
                .unwrap()
                .build()
                .unwrap(),
        );
    }
    #[tokio::test]
    async fn account_info() {
        let c = XRPL::new(
            HTTPBuilder::default()
                .with_endpoint("http://s1.ripple.com:51234/")
                .unwrap()
                .build()
                .unwrap(),
        );
        let res = c
            .account_info(types::account::AccountInfoRequest {
                account: "rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn".to_owned(),
                strict: None,
                queue: None,
                ledger_info: types::LedgerInfo::default(),
                signer_lists: None,
            })
            .await;
        match res {
            Err(e) => {
                eprintln!("test failed: {:?}", e);
            }
            Ok(res) => {
                assert_eq!(res.account_data.balance, CurrencyAmount::XRP(BigInt(9977)),);
            }
        }
    }
}