bitmomo 0.1.0

BitMomo merchant SDK: accept crypto payments and verify webhooks in Rust
Documentation
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! Request parameters and response models. Field names match the API.

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Value};

use crate::Decimal;
#[cfg(feature = "client")]
use crate::{decimal::is_plain_decimal, Error};

/// A payment's lifecycle state. Unknown values from a newer API are kept in
/// [`PaymentStatus::Other`] instead of failing.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PaymentStatus {
    Created,
    Locked,
    Pending,
    Detected,
    Confirming,
    Confirmed,
    Settling,
    Completed,
    Expired,
    Failed,
    Flagged,
    NeedsReview,
    Orphaned,
    Cancelled,
    Other(String),
}

impl PaymentStatus {
    /// Every known status, in lifecycle order.
    pub const ALL: [PaymentStatus; 14] = [
        PaymentStatus::Created,
        PaymentStatus::Locked,
        PaymentStatus::Pending,
        PaymentStatus::Detected,
        PaymentStatus::Confirming,
        PaymentStatus::Confirmed,
        PaymentStatus::Settling,
        PaymentStatus::Completed,
        PaymentStatus::Expired,
        PaymentStatus::Failed,
        PaymentStatus::Flagged,
        PaymentStatus::NeedsReview,
        PaymentStatus::Orphaned,
        PaymentStatus::Cancelled,
    ];

    /// The wire form, such as `"needs_review"`.
    pub fn as_str(&self) -> &str {
        match self {
            PaymentStatus::Created => "created",
            PaymentStatus::Locked => "locked",
            PaymentStatus::Pending => "pending",
            PaymentStatus::Detected => "detected",
            PaymentStatus::Confirming => "confirming",
            PaymentStatus::Confirmed => "confirmed",
            PaymentStatus::Settling => "settling",
            PaymentStatus::Completed => "completed",
            PaymentStatus::Expired => "expired",
            PaymentStatus::Failed => "failed",
            PaymentStatus::Flagged => "flagged",
            PaymentStatus::NeedsReview => "needs_review",
            PaymentStatus::Orphaned => "orphaned",
            PaymentStatus::Cancelled => "cancelled",
            PaymentStatus::Other(s) => s,
        }
    }

    /// Map a wire value to a status; unknown values become [`PaymentStatus::Other`].
    pub fn parse(value: &str) -> Self {
        PaymentStatus::ALL
            .iter()
            .find(|s| s.as_str() == value)
            .cloned()
            .unwrap_or_else(|| PaymentStatus::Other(value.to_string()))
    }

    /// True for the 14 statuses this SDK version knows.
    pub fn is_known(&self) -> bool {
        !matches!(self, PaymentStatus::Other(_))
    }
}

impl fmt::Display for PaymentStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for PaymentStatus {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for PaymentStatus {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(PaymentStatus::parse(&String::deserialize(deserializer)?))
    }
}

fn digits<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
    let value = String::deserialize(deserializer)?;
    if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) {
        Ok(value)
    } else {
        Err(serde::de::Error::custom(format!(
            "expected a string of digits, got {value:?}"
        )))
    }
}

// ---------------------------------------------------------------------------
// Requests
// ---------------------------------------------------------------------------

/// Inputs to [`Client::create_payment`](crate::Client::create_payment). The amount is in GHS.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreatePaymentParams {
    pub amount: Decimal,
    pub crypto_type: String,
    /// Reuse the same key when you retry, so a retry cannot create a second payment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guest_session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub callback_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redirect_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fiat_currency: Option<String>,
}

impl CreatePaymentParams {
    /// A payment of `amount` GHS paid in `crypto_type` (for example `"USDT_TRC20"`).
    pub fn new(amount: Decimal, crypto_type: impl Into<String>) -> Self {
        CreatePaymentParams {
            amount,
            crypto_type: crypto_type.into(),
            idempotency_key: None,
            description: None,
            order_id: None,
            customer_id: None,
            guest_session_id: None,
            metadata: None,
            callback_url: None,
            redirect_url: None,
            fiat_currency: None,
        }
    }

    /// Set the idempotency key.
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }

    /// Set your order reference.
    pub fn order_id(mut self, order_id: impl Into<String>) -> Self {
        self.order_id = Some(order_id.into());
        self
    }

    /// Set a description shown to the customer.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Filters for [`Client::list_payments`](crate::Client::list_payments).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ListPaymentsParams {
    #[serde(default)]
    pub page: Option<u32>,
    /// 1 to 100.
    #[serde(default)]
    pub limit: Option<u32>,
    #[serde(default)]
    pub status: Option<PaymentStatus>,
}

/// Inputs to [`Client::request_payout`](crate::Client::request_payout).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PayoutParams {
    pub amount: Decimal,
    /// Required. Mint once per payout with [`new_idempotency_key`](crate::new_idempotency_key)
    /// and reuse it on retry; the server then returns the original payout.
    pub idempotency_key: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub settlement_method: Option<String>,
}

impl PayoutParams {
    pub fn new(amount: Decimal, idempotency_key: impl Into<String>) -> Self {
        PayoutParams {
            amount,
            idempotency_key: idempotency_key.into(),
            settlement_method: None,
        }
    }
}

/// Replaces the webhook settings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpdateWebhookConfigParams {
    pub url: String,
    pub events: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
}

/// Inputs to [`Client::create_payment_link`](crate::Client::create_payment_link).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct CreatePaymentLinkParams {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slug: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset_amount_ghs: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset_crypto_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowed_cryptos: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note_for_customer: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
}

// ---------------------------------------------------------------------------
// Responses
// ---------------------------------------------------------------------------

/// Returned by `create_payment`. Show `qr_code_data` (or `deposit_address` and
/// `crypto_amount`) to the customer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreatedPayment {
    pub id: String,
    pub environment: String,
    pub session_code: String,
    pub status: PaymentStatus,
    pub amount_ghs: Decimal,
    pub crypto_type: String,
    pub crypto_amount: Decimal,
    pub locked_rate: Decimal,
    pub deposit_address: String,
    pub chain_type: String,
    pub network: String,
    pub qr_code_data: String,
    pub expires_at: String,
    pub expires_in_seconds: i64,
    pub merchant_id: String,
    pub created_at: String,
    pub quote_id: String,
    pub rate_locked_at: String,
    pub rate_expires_at: String,
    pub token_decimals: i64,
    #[serde(default)]
    pub token_contract: Option<String>,
}

/// What the payment was worth once received, and what the merchant keeps.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaymentEconomics {
    pub policy_version: String,
    pub invoice_ghs: Decimal,
    pub received_value_ghs: Decimal,
    pub recognized_gross_ghs: Decimal,
    pub merchant_discount_ghs: Decimal,
    pub surplus_ghs: Decimal,
    pub fee_ghs: Decimal,
    pub merchant_net_ghs: Decimal,
    #[serde(default)]
    pub discount_authority: Option<String>,
    #[serde(default)]
    pub approved_by: Option<String>,
    #[serde(default)]
    pub approval_reason: Option<String>,
}

/// The quote terms locked when the payment was created.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaymentPricingTerms {
    pub policy_version: String,
    pub invoice_ghs: Decimal,
    pub locked_rate: Decimal,
    pub fee_percent: Decimal,
    pub spread_bps: i64,
}

/// The merchant's order details.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaymentOrderTerms {
    #[serde(default)]
    pub order_id: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub redirect_url: Option<String>,
}

/// The plain-language payout state for a payment.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PayoutView {
    pub tone: String,
    pub headline: String,
    pub detail: String,
    #[serde(default)]
    pub settlement_id: Option<String>,
    #[serde(default)]
    pub settlement_status: Option<String>,
    #[serde(default)]
    pub settlement_method: Option<String>,
    #[serde(default)]
    pub support_contact: Option<String>,
}

/// The full payment returned by `get_payment`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Payment {
    pub id: String,
    pub environment: String,
    pub merchant_id: String,
    pub session_code: String,
    pub status: PaymentStatus,
    pub amount_ghs: Decimal,
    pub crypto_amount: Decimal,
    pub locked_rate: Decimal,
    #[serde(default)]
    pub fiat_currency: Option<String>,
    #[serde(default)]
    pub crypto_type: Option<String>,
    #[serde(default)]
    pub chain_type: Option<String>,
    #[serde(default)]
    pub network: Option<String>,
    #[serde(default)]
    pub deposit_address: Option<String>,
    #[serde(default)]
    pub qr_code_data: Option<String>,
    #[serde(default)]
    pub token_contract: Option<String>,
    #[serde(default)]
    pub token_decimals: Option<i64>,
    #[serde(default)]
    pub quote_id: Option<String>,
    #[serde(default)]
    pub rate_locked_at: Option<String>,
    #[serde(default)]
    pub rate_expires_at: Option<String>,
    #[serde(default)]
    pub risk_status: Option<String>,
    #[serde(default)]
    pub tx_hash: Option<String>,
    #[serde(default)]
    pub confirmations_required: Option<i64>,
    #[serde(default)]
    pub confirmations_received: Option<i64>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub metadata: Option<Map<String, Value>>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub updated_at: Option<String>,
    #[serde(default)]
    pub completed_at: Option<String>,
    #[serde(default)]
    pub expires_at: Option<String>,
    #[serde(default)]
    pub economics: Option<PaymentEconomics>,
    #[serde(default)]
    pub pricing_terms: Option<PaymentPricingTerms>,
    #[serde(default)]
    pub order_terms: Option<PaymentOrderTerms>,
    #[serde(default)]
    pub payout: Option<PayoutView>,
}

/// One row of `list_payments`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaymentSummary {
    pub id: String,
    pub environment: String,
    pub merchant_id: String,
    pub status: PaymentStatus,
    pub amount_fiat: Decimal,
    pub currency: String,
    pub crypto_amount: Decimal,
    pub crypto_type: String,
    pub deposit_address: String,
    pub rate_locked: Decimal,
    pub created_at: String,
    /// The sale credited before fees; `None` until the payment has an outcome.
    #[serde(default)]
    pub recognized_amount_fiat: Option<Decimal>,
}

/// A page of payments, newest first.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaymentList {
    pub payments: Vec<PaymentSummary>,
    pub total: i64,
    pub page: i64,
    pub limit: i64,
    pub total_pages: i64,
}

/// Returned by `request_payout`. `replayed` is true when the idempotency key
/// was used before and the original payout was returned.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PayoutResponse {
    pub status: String,
    pub settlement_method: String,
    pub message: String,
    #[serde(default)]
    pub replayed: Option<bool>,
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub amount: Option<Decimal>,
    #[serde(default)]
    pub currency: Option<String>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub settlements: Option<Vec<Map<String, Value>>>,
    #[serde(default)]
    pub fill_id: Option<String>,
}

/// One crypto-to-fiat rate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExchangeRate {
    pub crypto_type: String,
    pub fiat_currency: String,
    pub rate: Decimal,
}

/// The balance of one asset.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssetBalance {
    pub currency: String,
    pub cleared: Decimal,
    pub reserved: Decimal,
    pub available: Decimal,
}

/// Deposits that could not be matched to a payment, in the asset's smallest unit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnallocatedBucket {
    pub asset: String,
    pub count: i64,
    #[serde(deserialize_with = "digits")]
    pub total_amount_smallest: String,
}

/// Unmatched deposits, grouped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnallocatedBuckets {
    pub dust: Vec<UnallocatedBucket>,
    pub excess: Vec<UnallocatedBucket>,
}

/// Returned by `get_balances`. Use the `*_exact` decimals; the `f64` fields
/// are for display only.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Balances {
    pub merchant_id: String,
    pub environment: String,
    pub settlement_preference: String,
    pub ghs_available_exact: Decimal,
    pub ghs_cleared_exact: Decimal,
    pub ghs_reserved_exact: Decimal,
    pub usdt_treasury_exact: Decimal,
    pub usdt_available_exact: Decimal,
    pub usdt_cleared_exact: Decimal,
    pub usdt_reserved_exact: Decimal,
    #[serde(default)]
    pub ghs_available: Option<f64>,
    #[serde(default)]
    pub ghs_cleared: Option<f64>,
    #[serde(default)]
    pub ghs_reserved: Option<f64>,
    #[serde(default)]
    pub usdt_treasury: Option<f64>,
    #[serde(default)]
    pub usdt_available: Option<f64>,
    #[serde(default)]
    pub usdt_cleared: Option<f64>,
    #[serde(default)]
    pub usdt_reserved: Option<f64>,
    #[serde(default)]
    pub currencies: Option<std::collections::BTreeMap<String, Decimal>>,
    #[serde(default)]
    pub asset_balances: Option<Vec<AssetBalance>>,
    #[serde(default)]
    pub unallocated_buckets: Option<UnallocatedBuckets>,
}

/// One configured webhook.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebhookEndpoint {
    pub id: String,
    pub url: String,
    pub events: Vec<String>,
    pub enabled: bool,
    pub secret_version: i64,
    pub sequence: i64,
}

/// The webhook settings. `secret` is only set right after the secret was
/// created; store it then.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebhookConfig {
    pub url: String,
    pub events: Vec<String>,
    pub enabled: bool,
    #[serde(default)]
    pub secret: Option<String>,
    #[serde(default)]
    pub secret_version: Option<i64>,
    #[serde(default)]
    pub webhooks: Option<Vec<WebhookEndpoint>>,
    #[serde(default)]
    pub message: Option<String>,
}

/// Returned by `rotate_webhook_secret`. The new secret is shown once; the
/// previous one keeps working for `previous_secret_grace_hours`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RotatedWebhookSecret {
    pub message: String,
    pub webhook_id: String,
    pub secret: String,
    pub secret_version: i64,
    pub previous_secret_grace_hours: i64,
}

/// A reusable link customers can pay through.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaymentLink {
    pub id: String,
    pub merchant_id: String,
    pub name: String,
    pub is_active: bool,
    pub created_at: String,
    #[serde(default)]
    pub slug: Option<String>,
    #[serde(default)]
    pub preset_amount_ghs: Option<f64>,
    #[serde(default)]
    pub preset_crypto_type: Option<String>,
    #[serde(default)]
    pub allowed_cryptos: Option<Vec<String>>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub note_for_customer: Option<String>,
    #[serde(default)]
    pub link_views: Option<i64>,
    #[serde(default)]
    pub link_payments: Option<i64>,
    #[serde(default)]
    pub total_amount_received: Option<f64>,
    #[serde(default)]
    pub statistics_scope: Option<String>,
    #[serde(default)]
    pub last_payment_at: Option<String>,
    #[serde(default)]
    pub updated_at: Option<String>,
}

#[cfg(feature = "client")]
#[derive(Deserialize)]
pub(crate) struct PaymentLinks {
    pub payment_links: Vec<PaymentLink>,
}

/// Parse a `GET /rates` body into rates sorted by crypto type, then fiat.
#[cfg(feature = "client")]
pub(crate) fn parse_rates(raw: &Value) -> Result<Vec<ExchangeRate>, Error> {
    let doc = raw
        .as_object()
        .ok_or_else(|| Error::schema("expected an object for the rates response"))?;
    let assets = match doc.get("ASSETS").or_else(|| doc.get("assets")) {
        None => return Ok(Vec::new()),
        Some(v) => v
            .as_object()
            .ok_or_else(|| Error::schema("rates.assets must be an object"))?,
    };
    let mut out = Vec::new();
    for (symbol, legs) in assets {
        let Some(legs) = legs.as_object() else {
            continue;
        };
        for (fiat, rate) in legs {
            let text = match rate {
                Value::String(s) if is_plain_decimal(s) => s.clone(),
                Value::Number(n) => number_text(n).ok_or_else(|| {
                    Error::schema(format!("rates.{symbol}.{fiat} must be a decimal"))
                })?,
                _ => {
                    return Err(Error::schema(format!(
                        "rates.{symbol}.{fiat} must be a decimal"
                    )))
                }
            };
            out.push(ExchangeRate {
                crypto_type: symbol.clone(),
                fiat_currency: fiat.clone(),
                rate: Decimal::from_trusted(text),
            });
        }
    }
    out.sort_by(|a, b| {
        a.crypto_type
            .cmp(&b.crypto_type)
            .then_with(|| a.fiat_currency.cmp(&b.fiat_currency))
    });
    Ok(out)
}

#[cfg(feature = "client")]
fn number_text(n: &serde_json::Number) -> Option<String> {
    if let Some(i) = n.as_i64() {
        return Some(i.to_string());
    }
    if let Some(u) = n.as_u64() {
        return Some(u.to_string());
    }
    let f = n.as_f64()?;
    if !f.is_finite() {
        return None;
    }
    let text = format!("{f}");
    if is_plain_decimal(&text) {
        Some(text)
    } else {
        None
    }
}