subscription.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //! Subscription types and traits
  2. #[cfg(feature = "mint")]
  3. use std::str::FromStr;
  4. use cashu::nut17::{self};
  5. #[cfg(feature = "mint")]
  6. use cashu::nut17::{Error, Kind, Notification};
  7. #[cfg(feature = "mint")]
  8. use cashu::{NotificationPayload, PublicKey};
  9. #[cfg(feature = "mint")]
  10. use serde::{Deserialize, Serialize};
  11. #[cfg(feature = "mint")]
  12. use uuid::Uuid;
  13. #[cfg(feature = "mint")]
  14. use crate::pub_sub::index::{Index, Indexable, SubscriptionGlobalId};
  15. use crate::pub_sub::SubId;
  16. /// Subscription parameters.
  17. ///
  18. /// This is a concrete type alias for `nut17::Params<SubId>`.
  19. pub type Params = nut17::Params<SubId>;
  20. /// Wrapper around `nut17::Params` to implement `Indexable` for `Notification`.
  21. #[cfg(feature = "mint")]
  22. #[derive(Debug, Clone, Serialize, Deserialize)]
  23. pub struct IndexableParams(Params);
  24. #[cfg(feature = "mint")]
  25. impl From<Params> for IndexableParams {
  26. fn from(params: Params) -> Self {
  27. Self(params)
  28. }
  29. }
  30. #[cfg(feature = "mint")]
  31. impl TryFrom<IndexableParams> for Vec<Index<Notification>> {
  32. type Error = Error;
  33. fn try_from(params: IndexableParams) -> Result<Self, Self::Error> {
  34. let sub_id: SubscriptionGlobalId = Default::default();
  35. let params = params.0;
  36. params
  37. .filters
  38. .into_iter()
  39. .map(|filter| {
  40. let idx = match params.kind {
  41. Kind::Bolt11MeltQuote => {
  42. Notification::MeltQuoteBolt11(Uuid::from_str(&filter)?)
  43. }
  44. Kind::Bolt11MintQuote => {
  45. Notification::MintQuoteBolt11(Uuid::from_str(&filter)?)
  46. }
  47. Kind::ProofState => Notification::ProofState(PublicKey::from_str(&filter)?),
  48. };
  49. Ok(Index::from((idx, params.id.clone(), sub_id)))
  50. })
  51. .collect::<Result<_, _>>()
  52. }
  53. }
  54. #[cfg(feature = "mint")]
  55. impl AsRef<SubId> for IndexableParams {
  56. fn as_ref(&self) -> &SubId {
  57. &self.0.id
  58. }
  59. }
  60. #[cfg(feature = "mint")]
  61. impl Indexable for NotificationPayload<Uuid> {
  62. type Type = Notification;
  63. fn to_indexes(&self) -> Vec<Index<Self::Type>> {
  64. match self {
  65. NotificationPayload::ProofState(proof_state) => {
  66. vec![Index::from(Notification::ProofState(proof_state.y))]
  67. }
  68. NotificationPayload::MeltQuoteBolt11Response(melt_quote) => {
  69. vec![Index::from(Notification::MeltQuoteBolt11(melt_quote.quote))]
  70. }
  71. NotificationPayload::MintQuoteBolt11Response(mint_quote) => {
  72. vec![Index::from(Notification::MintQuoteBolt11(mint_quote.quote))]
  73. }
  74. }
  75. }
  76. }