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
mod query_parameters;

use solana_program::pubkey::{ParsePubkeyError, Pubkey};
use std::collections::HashSet;
use std::str::FromStr;
use std::{convert::TryFrom, num::ParseFloatError};
use thiserror::Error;
use query_parameters::QueryParameter;
use url::{ParseError, Url};

const SOLANA_PAY_SCHEME: &str = "solana";

#[derive(Error, Debug)]
pub enum SolanaPayError {
    #[error("Could not parse number {0}")]
    ParseFloatError(#[from] ParseFloatError),
    #[error("Could not parse Pubkey {0}")]
    ParsePubkeyError(#[from] ParsePubkeyError),
    #[error("Must define a postive number for `amount`")]
    NegativeAmount,
    #[error("Must define a postive number for `amount` not {0}")]
    UnknownAmountType(String),
    #[error("Url length is invalid: `{0}`")]
    UrlInvalidLength(usize),
    #[error("{0} cannot be defined twice in the URL")]
    DefinedTwice(String),
    #[error("Cannot parse URL: Err({0})")]
    InvalidUrl(#[from] ParseError),
    #[error("Invalid URL key: {0} with value: {1}")]
    InvalidUrlKey(String, String),
    #[error("Invalid URL key: {0}")]
    InvalidKey(String),
    #[error("Invalid scheme {0}")]
    IncorrectScheme(String),
}

/// Represents a request payload that can be a user and send or receive.
/// # Examples
///
/// ## Encoding a `SolanaPayRequest` as a url
/// ```rust
/// use solana_pay::SolanaPayRequest;
/// use url::Url;
/// use solana_program::pubkey::Pubkey;
///
/// let recipient = Pubkey::new_unique();
/// let param_struct = SolanaPayRequest {
///     recipient: recipient.clone(),
///     amount: Some(100.0),
///     spl_token: None,
///     references: vec![],
///     label: Some("label with spaces".to_string()),
///     message: Some("message with spaces".to_string()),
///     memo: Some("memo with spaces".to_string()),
///     extensions: vec![],
/// };
/// assert_eq!(
///     Url::from(param_struct).to_string(),
///     format!(
///         "solana:{}?amount=100&label=label+with+spaces&message=message+with+spaces&memo=memo+with+spaces",
///         recipient.to_string()
///     )
/// );
///```
///
/// ## Decoding a url as a string
/// ```rust
/// use solana_pay::SolanaPayRequest;
/// use url::Url;
/// use solana_program::pubkey::Pubkey;
///
/// let param_struct = SolanaPayRequest::try_from(&format!(
///     "solana:{}?amount=100&label=label+with+spaces&message=message+with+spaces",
///     Pubkey::new_unique().to_string()
///  )).unwrap();
/// assert_eq!(param_struct.amount, Some(100 as f64));
/// assert_eq!(param_struct.label.unwrap(), "label with spaces".to_string());
/// assert_eq!(param_struct.references, vec![]);
/// assert_eq!(param_struct.memo, None);
/// assert_eq!(
///     param_struct.message.unwrap(),
///     "message with spaces".to_string()
/// );
/// ```
#[derive(Default, PartialEq, Debug, Clone)]
pub struct SolanaPayRequest {
    /// `recipient` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#recipient)
    pub recipient: Pubkey,
    /// `amount` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#amount)
    pub amount: Option<f64>,
    /// `spl-token` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#spl-token)
    pub spl_token: Option<Pubkey>,
    /// `reference` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#reference)
    pub references: Vec<Pubkey>,
    /// `label` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#label)
    pub label: Option<String>,
    /// `message` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#message)
    pub message: Option<String>,
    /// `memo` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#memo)
    pub memo: Option<String>,
    /// `extensions` in the [Solana Pay spec](https://github.com/solana-labs/solana-pay/blob/master/SPEC.md#extensions)
    pub extensions: Vec<(String, String)>,
}

fn tokenize_params(url: Url) -> Result<Vec<(QueryParameter, String)>, SolanaPayError> {
    let mut params: Vec<(QueryParameter, String)> = vec![];
    let mut seen_set: HashSet<QueryParameter> = HashSet::new();

    for (key, value) in url.query_pairs() {
        let param = QueryParameter::from(key.as_ref());
        if !param.allows_multiple() && seen_set.contains(&param) {
            return Err(SolanaPayError::DefinedTwice(key.to_string()));
        } else {
            seen_set.insert(param.clone());
            params.push((param, value.to_string()));
        }
    }
    Ok(params)
}

impl IntoIterator for SolanaPayRequest {
    type Item = (String, String);
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        use query_parameters::QueryParameter as QP;

        std::iter::empty()
            .chain(
                self.amount
                    .map(|field| (QP::Amount.to_string(), field.to_string())),
            )
            .chain(
                self.spl_token
                    .map(|field| (QP::SplToken.to_string(), field.to_string())),
            )
            .chain(
                self.references
                    .into_iter()
                    .map(|v| (QP::Amount.to_string(), v.to_string())),
            )
            .chain(self.label.map(|field| (QP::Label.to_string(), field)))
            .chain(self.message.map(|field| (QP::Message.to_string(), field)))
            .chain(self.memo.map(|field| (QP::Memo.to_string(), field)))
            .chain(self.extensions)
            .collect::<Vec<_>>()
            .into_iter()
    }
}

impl SolanaPayRequest {
    fn append_value(&mut self, key: &QueryParameter, value: &str) -> Result<(), SolanaPayError> {
        match key {
            QueryParameter::Amount => {
                let amount = value.parse::<f64>()?;
                if amount < 0.0 {
                    return Err(SolanaPayError::NegativeAmount);
                }
                self.amount = Some(amount);
            }
            QueryParameter::SplToken => self.spl_token = Some(Pubkey::from_str(value)?),
            QueryParameter::Reference => self.references.push(Pubkey::from_str(value)?),
            QueryParameter::Label => self.label = Some(value.to_string()),
            QueryParameter::Message => self.message = Some(value.to_string()),
            QueryParameter::Memo => self.memo = Some(value.to_string()),
            QueryParameter::Extension(extension) => self
                .extensions
                .push((extension.to_owned(), value.to_string())),
        };
        Ok(())
    }
}
impl From<SolanaPayRequest> for Url {
    fn from(url_params: SolanaPayRequest) -> Url {
        let mut url = Url::parse(&format!("{}:{}", SOLANA_PAY_SCHEME, url_params.recipient))
            .expect("pubkey contained invalid URL characters");
        url_params.into_iter().for_each(|(name, value)| {
            url.query_pairs_mut().append_pair(&name, &value);
        });
        url
    }
}
impl TryFrom<&String> for SolanaPayRequest {
    type Error = SolanaPayError;

    fn try_from(url: &String) -> Result<SolanaPayRequest, SolanaPayError> {
        if url.len() > 2048 {
            return Err(SolanaPayError::UrlInvalidLength(url.len()));
        }

        let url = Url::parse(url)?;
        if url.scheme() != SOLANA_PAY_SCHEME {
            return Err(SolanaPayError::IncorrectScheme(url.scheme().to_string()));
        }

        let mut params = SolanaPayRequest {
            recipient: Pubkey::from_str(url.path())?,
            ..Default::default()
        };

        for (token, value) in tokenize_params(url)? {
            params.append_value(&token, value.as_ref())?;
        }
        Ok(params)
    }
}
#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_decoding_url() {
        let param_struct = SolanaPayRequest::try_from(&format!(
            "solana:{}?amount=100&label=label+with+spaces&message=message+with+spaces",
            Pubkey::new_unique().to_string()
        ))
        .unwrap();
        assert_eq!(param_struct.amount, Some(100 as f64));
        assert_eq!(param_struct.label.unwrap(), "label with spaces".to_string());
        assert_eq!(param_struct.references, vec![]);
        assert_eq!(param_struct.memo, None);
        assert_eq!(
            param_struct.message.unwrap(),
            "message with spaces".to_string()
        );
    }
    #[test]
    fn test_encoding_url() {
        let recipient = Pubkey::new_unique();
        let param_struct = SolanaPayRequest {
            recipient: recipient.clone(),
            amount: Some(100.0),
            spl_token: None,
            references: vec![],
            label: Some("label with spaces".to_string()),
            message: Some("message with spaces".to_string()),
            memo: Some("memo with spaces".to_string()),
            extensions: vec![],
        };
        assert_eq!(
            Url::from(param_struct).to_string(),
            format!(
                "solana:{}?amount=100&label=label+with+spaces&message=message+with+spaces&memo=memo+with+spaces",
                recipient.to_string()
            )
        );
    }

    #[test]
    fn test_encoding_url_with_extensions() {
        let recipient = Pubkey::new_unique();
        let param_struct = SolanaPayRequest {
            recipient: recipient.clone(),
            amount: Some(100.0),
            spl_token: None,
            references: vec![],
            label: Some("label with spaces".to_string()),
            message: Some("message with spaces".to_string()),
            memo: Some("memo with spaces".to_string()),
            extensions: vec![("a", "1"), ("b", "2")]
                .into_iter()
                .map(|(x, y)| (x.to_string(), y.to_string()))
                .collect(),
        };
        assert_eq!(
            Url::from(param_struct).to_string(),
            format!(
                "solana:{}?amount=100&label=label+with+spaces&message=message+with+spaces&memo=memo+with+spaces&a=1&b=2",
                recipient.to_string()
            )
        );
    }

    #[test]
    fn test_assert_amount_is_0_padded() {
        let recipient = Pubkey::new_unique();
        let param_struct = SolanaPayRequest {
            recipient: recipient.clone(),
            amount: Some(0.123),
            spl_token: None,
            references: vec![],
            label: None,
            message: None,
            memo: None,
            extensions: vec![],
        };
        assert_eq!(
            Url::from(param_struct).to_string(),
            format!("solana:{}?amount=0.123", recipient.to_string())
        );
    }

    #[test]
    fn test_multiple_query_params_decode_reference() {
        let r1 = Pubkey::new_unique();
        let r2 = Pubkey::new_unique();
        let param_struct = SolanaPayRequest::try_from(&format!(
            "solana:{}?reference={}&reference={}",
            Pubkey::new_unique().to_string(),
            r1,
            r2
        ))
        .unwrap();
        assert_eq!(param_struct.references, vec![r1, r2]);
    }

    #[test]
    fn test_multiple_query_params_extensions() {
        let param_struct = SolanaPayRequest::try_from(&format!(
            "solana:{}?extension_1=a&extension_2=b",
            Pubkey::new_unique().to_string(),
        ))
        .unwrap();
        assert_eq!(
            param_struct.extensions,
            vec![
                ("extension_1".to_string(), "a".to_string()),
                ("extension_2".to_string(), "b".to_string())
            ]
        );
    }

    #[test]
    fn test_dont_allow_multiple_query_params() {
        let param_struct = SolanaPayRequest::try_from(&format!(
            "solana:{}?amount=0&amount=0",
            Pubkey::new_unique().to_string(),
        ));
        assert!(param_struct.is_err());
    }
}