@dvmkit/sdk 0.21.2 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/card-charge-journal-SKMBEPRM.js +44 -0
  2. package/dist/{chunk-MA55LUNR.js → chunk-2WWVI32F.js} +55 -1
  3. package/dist/{chunk-3V6CSTWB.js → chunk-3DGIRHP2.js} +2 -2
  4. package/dist/{chunk-WWKFG6TM.js → chunk-5NMHZIIU.js} +1 -1
  5. package/dist/{chunk-FAT57DAP.js → chunk-5YJWAJ4N.js} +1 -1
  6. package/dist/{chunk-D2MGOQIS.js → chunk-CUWSJQGT.js} +1 -1
  7. package/dist/{chunk-6GZF7VDO.js → chunk-DLRPKEAM.js} +1 -1
  8. package/dist/{chunk-62JG4AF7.js → chunk-DY5QIHJA.js} +1 -1
  9. package/dist/{chunk-LWF4ABYF.js → chunk-EHBUAJ5M.js} +1 -1
  10. package/dist/{chunk-IUFVIIPF.js → chunk-EQIP6TFD.js} +1 -1
  11. package/dist/{chunk-ZBOCNF56.js → chunk-GDZXGB43.js} +3 -3
  12. package/dist/{chunk-2HSWWHXK.js → chunk-HEH7YUGE.js} +1 -1
  13. package/dist/{chunk-B27E7JIR.js → chunk-HVZIITWW.js} +27 -4
  14. package/dist/{chunk-VIAMJ6GS.js → chunk-JINZMDNK.js} +1224 -80
  15. package/dist/{chunk-NRE4NOCY.js → chunk-JMTLK2SZ.js} +1 -1
  16. package/dist/{chunk-LSANCGLP.js → chunk-L35WYOH2.js} +1 -1
  17. package/dist/{chunk-27QB2D3Z.js → chunk-LCNRFKP7.js} +2 -2
  18. package/dist/{chunk-2AGADOX3.js → chunk-QMKGYIBM.js} +1 -1
  19. package/dist/{chunk-JOSNSNS7.js → chunk-SEIMPHIP.js} +225 -11
  20. package/dist/{chunk-Y746QPX7.js → chunk-SQOVLAJ2.js} +1 -1
  21. package/dist/{chunk-XWG54M6T.js → chunk-UVRBD5GR.js} +1 -1
  22. package/dist/{chunk-5RGZN6WQ.js → chunk-XB644VN3.js} +1 -1
  23. package/dist/{chunk-2RZRYMCR.js → chunk-YNHFJE6U.js} +1 -1
  24. package/dist/{chunk-7KNFEDFW.js → chunk-ZH5CLGO6.js} +1 -1
  25. package/dist/{content-retention-efjireLM.d.ts → content-retention-DEvY5vjM.d.ts} +1 -1
  26. package/dist/{credit-ledger-M3EBVMOP.js → credit-ledger-S76KU53A.js} +11 -3
  27. package/dist/{credit-menu-UOOxuxVL.d.ts → credit-menu-BA2my6hE.d.ts} +229 -8
  28. package/dist/{fx-BtxHVj6w.d.ts → fx-J5oXbv9A.d.ts} +1 -1
  29. package/dist/index.d.ts +5 -5
  30. package/dist/index.js +4 -4
  31. package/dist/internal/caller.d.ts +10 -9
  32. package/dist/internal/caller.js +11 -11
  33. package/dist/internal/server.d.ts +7 -7
  34. package/dist/internal/server.js +21 -21
  35. package/dist/{job-store-DWVkleH3.d.ts → job-store-CjPnf0dd.d.ts} +1 -1
  36. package/dist/{lightning-backend-CTijN35u.d.ts → lightning-backend-D9Q2KDS-.d.ts} +1 -1
  37. package/dist/{memory-credit-ledger-WL2VKLE3.js → memory-credit-ledger-5KXHOWB2.js} +4 -4
  38. package/dist/{mpp-setup-DBYDXISN.js → mpp-setup-3YZMURZL.js} +3 -3
  39. package/dist/{payout-reporter-D5TCIBQA.js → payout-reporter-KTLBNJJ7.js} +2 -2
  40. package/dist/{postgres-consumed-credential-store-IPWPJ6V7.js → postgres-consumed-credential-store-Y336KNIB.js} +1 -1
  41. package/dist/{postgres-job-store-POZJNFJU.js → postgres-job-store-ESEAN7JL.js} +2 -2
  42. package/dist/{postgres-replay-store-JQYAKG47.js → postgres-replay-store-6SVCZ475.js} +2 -2
  43. package/dist/{pricing-FGPVRNTL.js → pricing-RP5CGW6I.js} +3 -3
  44. package/dist/{revenue-reporter-QKCBYFWT.js → revenue-reporter-FD3GDQZS.js} +2 -2
  45. package/dist/server/index.d.ts +20 -11
  46. package/dist/server/index.js +292 -28
  47. package/dist/{step-cache-Bx_ZybWF.d.ts → step-cache-DXFftnAc.d.ts} +154 -12
  48. package/dist/{tempo-charge-store-P7ZBR3GG.js → tempo-charge-store-SOIRMEFJ.js} +2 -2
  49. package/dist/{tempo-session-store-ZVRBAMLG.js → tempo-session-store-UBDFFHDG.js} +3 -3
  50. package/dist/testing/index.d.ts +3 -3
  51. package/dist/testing/index.js +6 -6
  52. package/dist/{usd-eOAMEO12.d.ts → usd-Bc_rva_K.d.ts} +1 -1
  53. package/dist/{x402-44JZJQ5F.js → x402-MFBRORHG.js} +5 -5
  54. package/package.json +1 -1
  55. package/dist/{chunk-NUDHO4HV.js → chunk-LABJSMSJ.js} +48 -48
@@ -20,7 +20,7 @@ interface UpfrontPayment {
20
20
  amount_micro?: number;
21
21
  currency?: string;
22
22
  /** Funding rail for a credit hold, or the accepted per-call rail. */
23
- rail?: "cashu" | "x402" | "tempo" | "lightning";
23
+ rail?: "cashu" | "x402" | "tempo" | "lightning" | "stripe";
24
24
  /** Allocated rail-native atomic units, distinct from credit denomination. */
25
25
  native_amount?: number;
26
26
  native_asset?: string;
@@ -1454,9 +1454,10 @@ interface ReceiptPayment {
1454
1454
  /**
1455
1455
  * Rail of the most recent successful credit; `null` when nothing was paid.
1456
1456
  * `lightning` appears on a draw against a credit the caller funded by
1457
- * invoice — it is a funding rail, never an attached-proof one.
1457
+ * invoice — it is a funding rail, never an attached-proof one. `stripe`
1458
+ * likewise appears only on a draw against card-funded credit.
1458
1459
  */
1459
- rail: "cashu" | "x402" | "tempo" | "lightning" | null;
1460
+ rail: "cashu" | "x402" | "tempo" | "lightning" | "stripe" | null;
1460
1461
  /** Rail-native upfront amount (sats / USDC microunits), `null` when absent. */
1461
1462
  native_amount: number | null;
1462
1463
  native_asset: string | null;
@@ -1780,6 +1781,16 @@ declare function verifyDrainReceipt(receipt: DrainReceipt): boolean;
1780
1781
  */
1781
1782
  declare const NON_CHANNEL_BITCOIN_RAILS: readonly ["cashu", "lightning"];
1782
1783
  type NonChannelBitcoinRail = (typeof NON_CHANNEL_BITCOIN_RAILS)[number];
1784
+ /**
1785
+ * Rails whose credit is a card charge the seller refunds through its card
1786
+ * processor rather than in kind. Each funding keeps its own lot so the charge
1787
+ * that bought it (`fundingRef`, the PaymentIntent id) stays addressable for a
1788
+ * partial refund. A card lot carries no sats basis and is never priced in
1789
+ * kind; no Bitcoin path reads it, because every such path is gated on
1790
+ * {@link isNonChannelBitcoinRail} of the credit's own rail.
1791
+ */
1792
+ declare const CARD_FUNDED_RAILS: readonly ["stripe"];
1793
+ type CardFundedRail = (typeof CARD_FUNDED_RAILS)[number];
1783
1794
  declare function isNonChannelBitcoinRail(rail: string | null | undefined): rail is NonChannelBitcoinRail;
1784
1795
  /**
1785
1796
  * One funding event's deposit: the sats that arrived and the credit micro they
@@ -1796,7 +1807,7 @@ declare function isNonChannelBitcoinRail(rail: string | null | undefined): rail
1796
1807
  interface FundingLot {
1797
1808
  lotId: string;
1798
1809
  creditId: string;
1799
- rail: NonChannelBitcoinRail;
1810
+ rail: NonChannelBitcoinRail | CardFundedRail;
1800
1811
  /** Sats this funding delivered. `0` on a credit funded before a rail basis was recorded. */
1801
1812
  satsFunded: number;
1802
1813
  /** Explicit original-asset evidence, including a refund whose integer share is zero sats. */
@@ -3035,7 +3046,9 @@ declare class CreditLedger {
3035
3046
  /**
3036
3047
  * Release expired undrawn balances, retaining readable credit records. Tempo rail or
3037
3048
  * channel-backed credits are excluded because their collateral returns to the caller
3038
- * through the channel lifecycle.
3049
+ * through the channel lifecycle. Card-funded credits are excluded because an expired card
3050
+ * balance is owed back to the card, never released to the builder: it stays on the credit,
3051
+ * where expiry already refuses new draws, until a card refund returns it.
3039
3052
  *
3040
3053
  * Pending holds prevent release: jobs accepted before expiry may still settle or release.
3041
3054
  * Candidates are rechecked under the same parent-credit lock used by draw writes. The
@@ -3061,7 +3074,8 @@ declare class CreditLedger {
3061
3074
  /**
3062
3075
  * Record non-channel Bitcoin funding lots on the funding transaction. An implicit payment
3063
3076
  * also needs a lot: its draw is initially only a hold, and failure releases the whole
3064
- * balance for reclaim. Channel collateral is excluded from Bitcoin lots.
3077
+ * balance for reclaim. Channel collateral is excluded from Bitcoin lots. A card funding
3078
+ * records a lot per charge so a later refund can address the charge that bought it.
3065
3079
  *
3066
3080
  * A zero-sats basis still records a lot, distinguishing covered but basisless credit from a
3067
3081
  * missing-lot coverage gap.
@@ -3450,6 +3464,60 @@ declare class CreditLedger {
3450
3464
  creditId: string;
3451
3465
  drainId: string;
3452
3466
  }): Promise<CreditDrainRecord | undefined>;
3467
+ /**
3468
+ * Store a card refund's plan or progress on its pending `stripe` drain. With `onlyIfUnset`
3469
+ * the first plan wins and every later caller gets that stored plan back, so concurrent
3470
+ * retries send one set of amounts under one set of idempotency keys. Returns what is
3471
+ * stored after the write; null when the drain is not a pending stripe drain with a plan.
3472
+ */
3473
+ saveCardRefund(args: {
3474
+ creditId: string;
3475
+ drainId: string;
3476
+ plan: CardRefundPlan;
3477
+ onlyIfUnset?: boolean;
3478
+ }): Promise<CardRefundPlan | null>;
3479
+ /**
3480
+ * Expired card credits still holding balance, with no pending holds and no card refund in
3481
+ * progress, oldest expiry first. A credit waiting on its refund drops out of the page, so
3482
+ * one that can never finish does not crowd out the rest.
3483
+ */
3484
+ listExpiredCardCredits(args?: {
3485
+ nowMs?: number;
3486
+ limit?: number;
3487
+ }): Promise<string[]>;
3488
+ /**
3489
+ * Turn an expired card credit's whole balance into a pending `stripe` drain owed back to
3490
+ * the card, and close the credit (`refunded`) in the same transaction. Closing is what
3491
+ * makes this terminal: a later top-up cannot revive a balance that went back to the card,
3492
+ * and the builder never receives it. Returns undefined when the credit no longer
3493
+ * qualifies under its lock (not card, not expired, empty, holds pending, or closed).
3494
+ */
3495
+ openCardExpiryRefund(args: {
3496
+ creditId: string;
3497
+ nowMs?: number;
3498
+ }): Promise<CreditDrainRecord | undefined>;
3499
+ /**
3500
+ * Freeze every active credit a disputed card payment funded (`disputed`): no draw, top-up
3501
+ * or drain moves its balance while the card network decides. Returns the credits this
3502
+ * call froze; already-frozen or closed credits are left as they are.
3503
+ */
3504
+ freezeCardCreditsForPaymentIntent(paymentIntentId: string): Promise<string[]>;
3505
+ /**
3506
+ * Frozen credits this PaymentIntent funded, each with every card PaymentIntent that funded
3507
+ * it: the sweep checks all of them with Stripe before lifting a freeze.
3508
+ */
3509
+ disputedCardCreditsFundedBy(paymentIntentId: string): Promise<{
3510
+ creditId: string;
3511
+ paymentIntentIds: string[];
3512
+ }[]>;
3513
+ /**
3514
+ * Lift a dispute freeze: the credit is `active` and refundable again, including at expiry.
3515
+ * The caller decides that no top-up of the credit has an open or lost dispute. Returns
3516
+ * false when the credit was not frozen.
3517
+ */
3518
+ unfreezeCardCredit(creditId: string): Promise<boolean>;
3519
+ /** True when a funding lot books this PaymentIntent: the charge reached a credit. */
3520
+ cardFundingBooked(paymentIntentId: string): Promise<boolean>;
3453
3521
  /**
3454
3522
  * One credit's undepleted funding lots, oldest first — the
3455
3523
  * public read behind the reclaim's own arithmetic, for anything that needs
@@ -3669,6 +3737,7 @@ declare class CreditLedger {
3669
3737
  * a new draw allocates against. One round-trip, since every
3670
3738
  * caller needs the micro sum anyway.
3671
3739
  */
3740
+ private pendingCardRefundDrainId;
3672
3741
  private pendingSums;
3673
3742
  private snapshotFromRow;
3674
3743
  private readTempoCreditLosses;
@@ -3717,6 +3786,32 @@ interface CreditLedgerLike {
3717
3786
  }): Promise<{
3718
3787
  released: CreditExpiryRelease[];
3719
3788
  }>;
3789
+ /** See {@link CreditLedger.saveCardRefund}. */
3790
+ saveCardRefund?(args: {
3791
+ creditId: string;
3792
+ drainId: string;
3793
+ plan: CardRefundPlan;
3794
+ onlyIfUnset?: boolean;
3795
+ }): Promise<CardRefundPlan | null>;
3796
+ /**
3797
+ * Card-refund sweep reads and writes. Optional and Postgres-only, like the expiry sweep:
3798
+ * see {@link CreditLedger.openCardExpiryRefund}.
3799
+ */
3800
+ listExpiredCardCredits?(args?: {
3801
+ nowMs?: number;
3802
+ limit?: number;
3803
+ }): Promise<string[]>;
3804
+ openCardExpiryRefund?(args: {
3805
+ creditId: string;
3806
+ nowMs?: number;
3807
+ }): Promise<CreditDrainRecord | undefined>;
3808
+ freezeCardCreditsForPaymentIntent?(paymentIntentId: string): Promise<string[]>;
3809
+ disputedCardCreditsFundedBy?(paymentIntentId: string): Promise<{
3810
+ creditId: string;
3811
+ paymentIntentIds: string[];
3812
+ }[]>;
3813
+ unfreezeCardCredit?(creditId: string): Promise<boolean>;
3814
+ cardFundingBooked?(paymentIntentId: string): Promise<boolean>;
3720
3815
  /**
3721
3816
  * Ask that gate directly, so a route can refuse a wedged channel **before**
3722
3817
  * the rail moves anything. Optional on the same terms as the
@@ -4061,14 +4156,19 @@ type CreditLedgerPool = Pick<Pool, "query" | "connect">;
4061
4156
  * x402 credit with no remaining liability can be restored to active by channel
4062
4157
  * reconciliation.
4063
4158
  */
4064
- type CreditStatus = "active" | "unbacked";
4159
+ /**
4160
+ * `unbacked`: Tempo backing finalized before the DVM was protected. `refunded`: card credit
4161
+ * whose expired balance went back to the card. `disputed`: a card funding behind it was
4162
+ * disputed, which freezes the remaining balance. None accepts draws, top-ups or drains.
4163
+ */
4164
+ type CreditStatus = "active" | "unbacked" | "refunded" | "disputed";
4065
4165
  /** Draw lifecycle: two-phase hold → terminal settle/release. */
4066
4166
  type DrawStatus = "pending" | "settled" | "released";
4067
4167
  /**
4068
4168
  * Drain payout rails. Direct Lightning send is excluded: deployments reclaiming Bitcoin can
4069
4169
  * use Cashu notes without putting a spending wallet credential in the DVM.
4070
4170
  */
4071
- type DrainMethod = "cashu" | "x402" | "tempo";
4171
+ type DrainMethod = "cashu" | "x402" | "tempo" | "stripe";
4072
4172
  /**
4073
4173
  * Drain lifecycle. `pending` — liability recorded, not yet fulfilled.
4074
4174
  * Cashu: `pending → parked` (token attached by the builder batch job)
@@ -4258,6 +4358,41 @@ interface CreditDrainRecord {
4258
4358
  provenRefundNative?: string | null;
4259
4359
  /** Sticky proof that some refund was paid; false/absent does not prove zero. */
4260
4360
  refundPaymentProven?: boolean;
4361
+ /** A `stripe` drain's refunds to the card: plan and progress. Null until planned. */
4362
+ cardRefund?: CardRefundPlan | null;
4363
+ }
4364
+ /**
4365
+ * One refund of card credit against one funding PaymentIntent. Amounts are US cents.
4366
+ *
4367
+ * `amountCents = grossCents − feeShareCents`: the caller bears the share of Stripe's
4368
+ * processing fee proportional to what goes back, because Stripe keeps its whole fee
4369
+ * on a refund.
4370
+ */
4371
+ interface CardRefundEntry {
4372
+ lotId: string;
4373
+ paymentIntentId: string;
4374
+ /** Credit returned against this charge, before the fee share. */
4375
+ grossCents: number;
4376
+ feeShareCents: number;
4377
+ /** What goes back to the card. Zero when the fee share eats the whole slice. */
4378
+ amountCents: number;
4379
+ /**
4380
+ * Part of the idempotency key. Bumped only after Stripe definitively rejected or failed a
4381
+ * refund, because Stripe replays a key's first answer, errors included.
4382
+ */
4383
+ attempt: number;
4384
+ refundId: string | null;
4385
+ /** Stripe's refund status, `planned` before any refund exists, `rejected` when refused. */
4386
+ status: "planned" | "pending" | "requires_action" | "succeeded" | "failed" | "canceled" | "rejected";
4387
+ /** Stripe's enum code for the last refusal or failure; never Stripe's free text. */
4388
+ lastError: string | null;
4389
+ }
4390
+ interface CardRefundPlan {
4391
+ /** Whole cents of the drained credit: `floor(amountMicro / 10_000)`. */
4392
+ grossCents: number;
4393
+ /** Drained credit below one cent, which no card refund can carry. */
4394
+ subCentMicro: number;
4395
+ entries: CardRefundEntry[];
4261
4396
  }
4262
4397
  /**
4263
4398
  * Keyset cursor for {@link CreditLedger.listChannelDrains} — the last row of
@@ -4643,14 +4778,16 @@ interface BlockedInvoiceCursor {
4643
4778
  creditId: string;
4644
4779
  fundId: string;
4645
4780
  }
4646
- type CreditLedgerErrorCode = "credit_not_found" | "credit_expired" | "credit_unbacked" | "tempo_channel_closing" | "tempo_settlement_pending" | "settlement_pending" | "insufficient_credit" | "draw_conflict" | "invalid_refund" | "draw_not_completed" | "refund_conflict" | "refund_exceeds_draw" | "credit_not_open" | "credit_refund_channel_unsupported" | "credit_refund_basis_unavailable" | "credit_refund_state_unavailable" | "draw_not_found" | "invalid_draw_state" | "funding_replayed" | "currency_mismatch" | "caller_mismatch" | "rail_mismatch" | "invalid_amount" | "invalid_expiry" | "invalid_basis" | "nothing_to_drain" | "drain_below_dust" | "drain_not_found" | "drain_conflict" | "invalid_drain_state" | "tempo_drain_close_pending" | "tempo_drain_refund_paid" | "tempo_drain_refund_unknown" | "invalid_drain_decision" | "drain_not_repairable" | "drain_decision_conflict" | "invoice_not_found" | "invoice_conflict" | "invoice_not_blocked" | "below_rail_minimum";
4781
+ type CreditLedgerErrorCode = "credit_not_found" | "credit_expired" | "credit_unbacked" | "credit_closed" | "tempo_channel_closing" | "tempo_settlement_pending" | "settlement_pending" | "insufficient_credit" | "draw_conflict" | "invalid_refund" | "draw_not_completed" | "refund_conflict" | "refund_exceeds_draw" | "credit_not_open" | "credit_refund_channel_unsupported" | "credit_refund_basis_unavailable" | "credit_refund_state_unavailable" | "draw_not_found" | "invalid_draw_state" | "funding_replayed" | "currency_mismatch" | "caller_mismatch" | "rail_mismatch" | "invalid_amount" | "invalid_expiry" | "invalid_basis" | "nothing_to_drain" | "drain_below_dust" | "drain_not_found" | "drain_conflict" | "invalid_drain_state" | "tempo_drain_close_pending" | "tempo_drain_refund_paid" | "tempo_drain_refund_unknown" | "invalid_drain_decision" | "drain_not_repairable" | "drain_decision_conflict" | "invoice_not_found" | "invoice_conflict" | "invoice_not_blocked" | "below_rail_minimum";
4647
4782
  /**
4648
4783
  * Structured drain_conflict reasons select caller instructions without matching prose. A
4649
4784
  * refund_floor shortfall needs operator resolution, unlike duplicate payout; foreign_credit
4650
4785
  * discloses no liability to the wrong owner; drain_id_retired requires a fresh ID.
4651
4786
  */
4652
- type DrainConflictReason = "pending_draws" | "balance_moved" | "refund_floor";
4787
+ type DrainConflictReason = "pending_draws" | "balance_moved" | "refund_floor" | "card_refund_pending";
4653
4788
  interface CreditLedgerErrorDetails {
4789
+ /** On `credit_closed`: why the card-funded credit no longer moves money. */
4790
+ creditStatus?: "refunded" | "disputed";
4654
4791
  /** On `drain_conflict`: which conflict it is, so a route can answer it without matching on prose. */
4655
4792
  drainConflict?: DrainConflictReason;
4656
4793
  /** On `insufficient_credit`: the spendable balance the draw exceeded. */
@@ -5929,8 +6066,13 @@ interface CapabilityRate {
5929
6066
  * on, nothing to verify inline, and no `lightning` entry in `/v1/info` or
5930
6067
  * `/v1/quote`'s `payment.methods`. Keeping the two types distinct is what
5931
6068
  * stops that dead rail from reappearing every time the funding menu grows.
6069
+ *
6070
+ * `stripe` funds a credit with a Stripe Shared Payment Token over an MPP
6071
+ * `method="stripe"` challenge that only `POST /v1/credit` issues. The card is
6072
+ * charged once, immediately, into the DVM owner's Stripe account; it is never
6073
+ * a per-call job payment method.
5932
6074
  */
5933
- type FundingMethod = PaymentMethod | "lightning";
6075
+ type FundingMethod = PaymentMethod | "lightning" | "stripe";
5934
6076
  /**
5935
6077
  * Whether the payment rail returns value when a job fails. No rail reverses
5936
6078
  * `ctx.fail`: Cashu proofs are committed to the accumulator; Tempo and x402
@@ -6435,4 +6577,4 @@ declare class StepCache {
6435
6577
  static deserialize(records: StepRecord[]): StepCache;
6436
6578
  }
6437
6579
 
6438
- export { type JsonValue as $, type ApprovalContent as A, SIGNED_REQUEST_STATEMENT_VERSION as B, type Currency as C, type DVMConfig as D, type SignedRequestAudience as E, type SignedRequestDomain as F, SignedRequestError as G, type SignedRequestFailure as H, type IncomingMessage as I, type JobCost as J, type KVStore as K, type Logger as L, type SignedRequestReplayStore as M, type SignedRequestSignOpts as N, type SignedRequestStatementHeader as O, type PaymentContent as P, type QuoteConfig as Q, type ResolvedCashuConfig as R, type SDKJobContext as S, type SignedRequestVerifier as T, UnsupportedCurrencyError as U, type UpfrontPayment as V, createSignedRequestVerifier as W, isZodSchema as X, signedRequestStatementHeader as Y, type ZodLike as Z, validateCurrency as _, type DVMDescriptor as a, encodePaymentRequiredHeader as a$, X402_BATCH_SETTLEMENT_SCHEME as a0, X402_EXACT_SCHEME as a1, type DrawFundingReceipt as a2, type FundingReceipt as a3, type JobReceipt as a4, type MessageType as a5, type X402Version as a6, type MppxCredential as a7, type PaymentRequired as a8, type Message as a9, type SettleResponse as aA, StepCache as aB, type StepRecord as aC, type TextContent as aD, type UnsignedDrainReceipt as aE, type UnsignedDrawFundingReceipt as aF, type UnsignedFundingReceipt as aG, type UnsignedJobReceipt as aH, type VerifyResponse as aI, type WorkingContent as aJ, type X402Config$1 as aK, type X402ResponseBody as aL, type X402SelfRelayRpcFailureReason as aM, X402_DEFAULT_NETWORK as aN, X402_V1_VERSION as aO, X402_VERSION as aP, buildPaymentRequiredV2 as aQ, buildPaymentRequirements as aR, caip2ToX402Network as aS, canonicalRequestPath as aT, canonicaliseForSigning as aU, canonicalize as aV, chainIdFromCaip2 as aW, computeResultHash as aX, decodePayment as aY, decodePaymentRequiredHeader as aZ, encodePayment as a_, type MppxChallenge as aa, type ReceiptCredit as ab, type DrainReceipt as ac, type X402Wallet as ad, type PaymentRequirementsV1 as ae, type PaymentRequirementsV2 as af, type BuildPaymentRequirementsOpts as ag, type CapabilityDescriptor as ah, type CashuMode as ai, type CompleteContent as aj, type DrainReceiptEvent as ak, type ExactEvmPayload as al, type ExactEvmPayloadAuthorization as am, type FundingMethod as an, type MessageFrom as ao, type PaymentPayload as ap, type PaymentPayloadV1 as aq, type PaymentPayloadV2 as ar, type PaymentRequestContent as as, type PaymentRequiredV2 as at, type PaymentRequirements as au, type PromptContent as av, RAIL_REFUNDABLE as aw, type ReceiptOutcome as ax, type ReceiptPayment as ay, type ResourceInfo as az, type ArtifactContent as b, type CreditDrawRefundResult as b$, encodeSettleResponseHeader as b0, exactEvmAuthorization as b1, isArtifactMessage as b2, isCancelMessage as b3, isCompleteMessage as b4, isDrainReceipt as b5, isDrawFundingReceipt as b6, isFundingReceipt as b7, isPaymentRequestMessage as b8, isPromptMessage as b9, type MppxServer as bA, NON_CHANNEL_BITCOIN_RAILS as bB, type NonChannelBitcoinRail as bC, PayoutReporter as bD, PostgresTempoSessionStore as bE, RevenueReporter as bF, SIGNED_ENVELOPE_FIELDS as bG, SIGNED_ENVELOPE_TYPES as bH, type X402TrackedChannel as bI, _testing as bJ, createDefaultReplayStore as bK, depleteLots as bL, fifoOrder as bM, inKindDrawMsats as bN, isInKindDepletion as bO, isNonChannelBitcoinRail as bP, lotOwedSats as bQ, netOwedSats as bR, wrapMppx as bS, type CreditLedgerQuerier as bT, type CreditDrainEnqueue as bU, HostedSettlementReportObligations as bV, type DVMAuthScheme as bW, type CreditLedgerLike as bX, type X402RefundSettlementGate as bY, type CreditSnapshot as bZ, type CreditDrawRefundArgs as b_, isSignedJobReceipt as ba, isTextMessage as bb, isWorkingMessage as bc, paymentRequiredV2FromV1 as bd, signDrainReceipt as be, signDrawFundingReceipt as bf, signFundingReceipt as bg, signReceipt as bh, usdcContractByCaip2 as bi, usdcContractFor as bj, usdcDomainNameFor as bk, usdcDomainVersionFor as bl, verifyDrainReceipt as bm, verifyDrawFundingReceipt as bn, verifyFundingReceipt as bo, verifyReceipt as bp, x402NetworkToCaip2 as bq, type X402ExactVersionSupport as br, type X402Receipt as bs, type TransactionalPayoutHook as bt, type CashuMeltCompleted as bu, type CreditDepositPayload as bv, type CreditDrainPayload as bw, type FundingLot as bx, type LotDebit as by, type LotDepletion as bz, type CancelContent as c, allocateDrawValue as c$, type DrawResult as c0, type X402SettlementStatus as c1, type X402UnresolvedRefund as c2, type GrownDrawResult as c3, type DrawResolution as c4, type FundingRecord as c5, type CreditFundingEvidence as c6, type CreditInvoiceRecord as c7, type InvoiceSettlement as c8, type BlockedInvoiceCursor as c9, CreditLedger as cA, CreditLedgerError as cB, type CreditLedgerErrorCode as cC, type CreditLedgerErrorDetails as cD, type CreditLedgerPool as cE, type CreditStatus as cF, DRAIN_DELIVERY_RESERVE_SATS as cG, DVM_PROTOCOL_VERSION as cH, type DrainConflictReason as cI, type DrawRailValue as cJ, type DrawStatus as cK, type HostedTempoCloseReportWriteOff as cL, type JobCostReportPayload as cM, type JobTerminalReportPayload as cN, PostgresX402ChannelStorage as cO, type ReplayStoreBackend as cP, type RevenueSkippedNoRailPayload as cQ, type RevenueSkippedNoRailReason as cR, type Secp256k1AuthOpts as cS, type TempoDrainDecision as cT, type TempoDrainDecisionArgs as cU, type TempoDrainDecisionResult as cV, type TempoDrainHoldReason as cW, type X402ChannelStorageOpts as cX, type X402RelayLockHolder as cY, type X402RelaySubmissionLock as cZ, X402RelaySubmissionLockError as c_, type InvoiceReconciliation as ca, type InvoiceWriteOff as cb, type DrawRecord as cc, type StalePendingDrawCursor as cd, type TempoCreditLossEvidence as ce, type TempoCreditLoss as cf, type X402CreditLossEvidence as cg, type X402CreditLoss as ch, type DrainMethod as ci, type DrainRequestResult as cj, type BitcoinDepositLiability as ck, type CreditDrainRecord as cl, type ChannelDrainCursor as cm, type DrainWriteOff as cn, type DrainTransitionResult as co, type DrainReleaseResult as cp, type DrainFulfilment as cq, HostingCleanupFence as cr, CLIENT_COMPATIBILITY_HEADERS as cs, type ClientCompatibility as ct, type ClientCompatibilityEnv as cu, type ClientCompatibilityGate as cv, type ClientCompatibilityRequirement as cw, type ClientSemVer as cx, type CreditFundingBasis as cy, type CreditInvoiceStatus as cz, type CanonicalEnvelope as d, clientCompatibilityAttributes as d0, clientCompatibilityMiddleware as d1, clientUpgradeRequired as d2, parseClientCapabilities as d3, parseClientCompatibility as d4, parseDvmClient as d5, parseProtocolVersion as d6, requireClientCompatibility as d7, retryHostedTempoCloseReport as d8, secp256k1Auth as d9, signedRequestInput as da, writeOffHostedTempoCloseReport as db, type HostedIntent as dc, type X402SettlementIntent as dd, type HostedFundingReservation as de, type X402SettlementCursor as df, type X402SettlementWriteOff as dg, type X402FacilitatorAuth as dh, type X402BatchSettlementConfig as di, type X402PayoutObserver as dj, type CreditDepositEnqueue as dk, type X402SettlementReconciliationReason as dl, type CreditDrawReleaseEnqueue as dm, type CapabilityRate as e, type CashuConfig as f, type CreateSignedRequestVerifierOpts as g, type CreditConfig as h, type CreditView as i, DEFAULT_CREDIT_MAX as j, DEFAULT_CREDIT_MIN as k, DEFAULT_CREDIT_TTL_SECONDS as l, DEFAULT_JOB_RETENTION_DAYS as m, type DVMRouteContext as n, type InputType as o, InvalidCurrencyError as p, type PaymentMethod as q, type PriceValue as r, type ProgressContent as s, type PromptOpts as t, type QuoteContext as u, type QuoteResult as v, type ResolvedCreditConfig as w, type ResponseContent as x, type SDKPaymentRequestOpts as y, SIGNED_REQUEST_AUTH_ID as z };
6580
+ export { type JsonValue as $, type ApprovalContent as A, SIGNED_REQUEST_STATEMENT_VERSION as B, type Currency as C, type DVMConfig as D, type SignedRequestAudience as E, type SignedRequestDomain as F, SignedRequestError as G, type SignedRequestFailure as H, type IncomingMessage as I, type JobCost as J, type KVStore as K, type Logger as L, type SignedRequestReplayStore as M, type SignedRequestSignOpts as N, type SignedRequestStatementHeader as O, type PaymentContent as P, type QuoteConfig as Q, type ResolvedCashuConfig as R, type SDKJobContext as S, type SignedRequestVerifier as T, UnsupportedCurrencyError as U, type UpfrontPayment as V, createSignedRequestVerifier as W, isZodSchema as X, signedRequestStatementHeader as Y, type ZodLike as Z, validateCurrency as _, type DVMDescriptor as a, encodePaymentRequiredHeader as a$, X402_BATCH_SETTLEMENT_SCHEME as a0, X402_EXACT_SCHEME as a1, type DrawFundingReceipt as a2, type FundingReceipt as a3, type JobReceipt as a4, type MessageType as a5, type X402Version as a6, type MppxCredential as a7, type PaymentRequired as a8, type Message as a9, type SettleResponse as aA, StepCache as aB, type StepRecord as aC, type TextContent as aD, type UnsignedDrainReceipt as aE, type UnsignedDrawFundingReceipt as aF, type UnsignedFundingReceipt as aG, type UnsignedJobReceipt as aH, type VerifyResponse as aI, type WorkingContent as aJ, type X402Config$1 as aK, type X402ResponseBody as aL, type X402SelfRelayRpcFailureReason as aM, X402_DEFAULT_NETWORK as aN, X402_V1_VERSION as aO, X402_VERSION as aP, buildPaymentRequiredV2 as aQ, buildPaymentRequirements as aR, caip2ToX402Network as aS, canonicalRequestPath as aT, canonicaliseForSigning as aU, canonicalize as aV, chainIdFromCaip2 as aW, computeResultHash as aX, decodePayment as aY, decodePaymentRequiredHeader as aZ, encodePayment as a_, type MppxChallenge as aa, type ReceiptCredit as ab, type DrainReceipt as ac, type X402Wallet as ad, type PaymentRequirementsV1 as ae, type PaymentRequirementsV2 as af, type BuildPaymentRequirementsOpts as ag, type CapabilityDescriptor as ah, type CashuMode as ai, type CompleteContent as aj, type DrainReceiptEvent as ak, type ExactEvmPayload as al, type ExactEvmPayloadAuthorization as am, type FundingMethod as an, type MessageFrom as ao, type PaymentPayload as ap, type PaymentPayloadV1 as aq, type PaymentPayloadV2 as ar, type PaymentRequestContent as as, type PaymentRequiredV2 as at, type PaymentRequirements as au, type PromptContent as av, RAIL_REFUNDABLE as aw, type ReceiptOutcome as ax, type ReceiptPayment as ay, type ResourceInfo as az, type ArtifactContent as b, type CreditDrawRefundResult as b$, encodeSettleResponseHeader as b0, exactEvmAuthorization as b1, isArtifactMessage as b2, isCancelMessage as b3, isCompleteMessage as b4, isDrainReceipt as b5, isDrawFundingReceipt as b6, isFundingReceipt as b7, isPaymentRequestMessage as b8, isPromptMessage as b9, type MppxServer as bA, NON_CHANNEL_BITCOIN_RAILS as bB, type NonChannelBitcoinRail as bC, PayoutReporter as bD, PostgresTempoSessionStore as bE, RevenueReporter as bF, SIGNED_ENVELOPE_FIELDS as bG, SIGNED_ENVELOPE_TYPES as bH, type X402TrackedChannel as bI, _testing as bJ, createDefaultReplayStore as bK, depleteLots as bL, fifoOrder as bM, inKindDrawMsats as bN, isInKindDepletion as bO, isNonChannelBitcoinRail as bP, lotOwedSats as bQ, netOwedSats as bR, wrapMppx as bS, type CreditLedgerQuerier as bT, type CreditDrainEnqueue as bU, HostedSettlementReportObligations as bV, type DVMAuthScheme as bW, type CreditLedgerLike as bX, type X402RefundSettlementGate as bY, type CreditSnapshot as bZ, type CreditDrawRefundArgs as b_, isSignedJobReceipt as ba, isTextMessage as bb, isWorkingMessage as bc, paymentRequiredV2FromV1 as bd, signDrainReceipt as be, signDrawFundingReceipt as bf, signFundingReceipt as bg, signReceipt as bh, usdcContractByCaip2 as bi, usdcContractFor as bj, usdcDomainNameFor as bk, usdcDomainVersionFor as bl, verifyDrainReceipt as bm, verifyDrawFundingReceipt as bn, verifyFundingReceipt as bo, verifyReceipt as bp, x402NetworkToCaip2 as bq, type X402ExactVersionSupport as br, type X402Receipt as bs, type TransactionalPayoutHook as bt, type CashuMeltCompleted as bu, type CreditDepositPayload as bv, type CreditDrainPayload as bw, type FundingLot as bx, type LotDebit as by, type LotDepletion as bz, type CancelContent as c, X402RelaySubmissionLockError as c$, type DrawResult as c0, type X402SettlementStatus as c1, type X402UnresolvedRefund as c2, type GrownDrawResult as c3, type DrawResolution as c4, type FundingRecord as c5, type CreditFundingEvidence as c6, type CreditInvoiceRecord as c7, type InvoiceSettlement as c8, type BlockedInvoiceCursor as c9, type CreditInvoiceStatus as cA, CreditLedger as cB, CreditLedgerError as cC, type CreditLedgerErrorCode as cD, type CreditLedgerErrorDetails as cE, type CreditLedgerPool as cF, type CreditStatus as cG, DRAIN_DELIVERY_RESERVE_SATS as cH, DVM_PROTOCOL_VERSION as cI, type DrainConflictReason as cJ, type DrawRailValue as cK, type DrawStatus as cL, type HostedTempoCloseReportWriteOff as cM, type JobCostReportPayload as cN, type JobTerminalReportPayload as cO, PostgresX402ChannelStorage as cP, type ReplayStoreBackend as cQ, type RevenueSkippedNoRailPayload as cR, type RevenueSkippedNoRailReason as cS, type Secp256k1AuthOpts as cT, type TempoDrainDecision as cU, type TempoDrainDecisionArgs as cV, type TempoDrainDecisionResult as cW, type TempoDrainHoldReason as cX, type X402ChannelStorageOpts as cY, type X402RelayLockHolder as cZ, type X402RelaySubmissionLock as c_, type InvoiceReconciliation as ca, type InvoiceWriteOff as cb, type DrawRecord as cc, type StalePendingDrawCursor as cd, type TempoCreditLossEvidence as ce, type TempoCreditLoss as cf, type X402CreditLossEvidence as cg, type X402CreditLoss as ch, type DrainMethod as ci, type DrainRequestResult as cj, type BitcoinDepositLiability as ck, type CreditDrainRecord as cl, type ChannelDrainCursor as cm, type DrainWriteOff as cn, type DrainTransitionResult as co, type DrainReleaseResult as cp, type DrainFulfilment as cq, type CardRefundPlan as cr, HostingCleanupFence as cs, CLIENT_COMPATIBILITY_HEADERS as ct, type ClientCompatibility as cu, type ClientCompatibilityEnv as cv, type ClientCompatibilityGate as cw, type ClientCompatibilityRequirement as cx, type ClientSemVer as cy, type CreditFundingBasis as cz, type CanonicalEnvelope as d, allocateDrawValue as d0, clientCompatibilityAttributes as d1, clientCompatibilityMiddleware as d2, clientUpgradeRequired as d3, parseClientCapabilities as d4, parseClientCompatibility as d5, parseDvmClient as d6, parseProtocolVersion as d7, requireClientCompatibility as d8, retryHostedTempoCloseReport as d9, secp256k1Auth as da, signedRequestInput as db, writeOffHostedTempoCloseReport as dc, type HostedIntent as dd, type X402SettlementIntent as de, type HostedFundingReservation as df, type X402SettlementCursor as dg, type X402SettlementWriteOff as dh, type X402FacilitatorAuth as di, type X402BatchSettlementConfig as dj, type X402PayoutObserver as dk, type CreditDepositEnqueue as dl, type X402SettlementReconciliationReason as dm, type CreditDrawReleaseEnqueue as dn, type CapabilityRate as e, type CashuConfig as f, type CreateSignedRequestVerifierOpts as g, type CreditConfig as h, type CreditView as i, DEFAULT_CREDIT_MAX as j, DEFAULT_CREDIT_MIN as k, DEFAULT_CREDIT_TTL_SECONDS as l, DEFAULT_JOB_RETENTION_DAYS as m, type DVMRouteContext as n, type InputType as o, InvalidCurrencyError as p, type PaymentMethod as q, type PriceValue as r, type ProgressContent as s, type PromptOpts as t, type QuoteContext as u, type QuoteResult as v, type ResolvedCreditConfig as w, type ResponseContent as x, type SDKPaymentRequestOpts as y, SIGNED_REQUEST_AUTH_ID as z };
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  PostgresTempoChargeStore
3
- } from "./chunk-2RZRYMCR.js";
3
+ } from "./chunk-YNHFJE6U.js";
4
4
  import "./chunk-YG7G4DPZ.js";
5
5
  import "./chunk-COYKJRMM.js";
6
- import "./chunk-MA55LUNR.js";
6
+ import "./chunk-2WWVI32F.js";
7
7
  export {
8
8
  PostgresTempoChargeStore
9
9
  };
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  PostgresTempoSessionStore,
3
3
  assertMonotonicTransition
4
- } from "./chunk-FAT57DAP.js";
4
+ } from "./chunk-5YJWAJ4N.js";
5
5
  import "./chunk-YG7G4DPZ.js";
6
6
  import "./chunk-COYKJRMM.js";
7
- import "./chunk-LSANCGLP.js";
8
- import "./chunk-MA55LUNR.js";
7
+ import "./chunk-L35WYOH2.js";
8
+ import "./chunk-2WWVI32F.js";
9
9
  export {
10
10
  PostgresTempoSessionStore,
11
11
  assertMonotonicTransition
@@ -1,6 +1,6 @@
1
- import { C as ContentHoldHistory, a as ContentHoldMutation } from '../content-retention-efjireLM.js';
2
- import { a4 as JobReceipt, a9 as Message, a5 as MessageType, K as KVStore, L as Logger, x as ResponseContent, P as PaymentContent, S as SDKJobContext } from '../step-cache-Bx_ZybWF.js';
3
- import { c as StreamableJobStore, R as ReceiptIssuingStore, J as JobRecord, d as RequestIdClaim, e as RequestIdClaimResult, f as JobRetentionCursor, O as OutgoingMessage, A as AppendOutgoingOptions, P as PaymentCreditDelta, V as VerifyAndCreditResult, g as JobCounters } from '../job-store-DWVkleH3.js';
1
+ import { C as ContentHoldHistory, a as ContentHoldMutation } from '../content-retention-DEvY5vjM.js';
2
+ import { a4 as JobReceipt, a9 as Message, a5 as MessageType, K as KVStore, L as Logger, x as ResponseContent, P as PaymentContent, S as SDKJobContext } from '../step-cache-DXFftnAc.js';
3
+ import { c as StreamableJobStore, R as ReceiptIssuingStore, J as JobRecord, d as RequestIdClaim, e as RequestIdClaimResult, f as JobRetentionCursor, O as OutgoingMessage, A as AppendOutgoingOptions, P as PaymentCreditDelta, V as VerifyAndCreditResult, g as JobCounters } from '../job-store-CjPnf0dd.js';
4
4
  import 'hono';
5
5
  import 'mppx';
6
6
  import '@x402/core/server';
@@ -4,22 +4,22 @@ import {
4
4
  import {
5
5
  MemoryJobStore,
6
6
  createInstrumentedFetch
7
- } from "../chunk-WWKFG6TM.js";
7
+ } from "../chunk-5NMHZIIU.js";
8
8
  import {
9
9
  JobCancelledError
10
10
  } from "../chunk-KVKJ7R5V.js";
11
11
  import {
12
12
  createNoopLogger
13
- } from "../chunk-NRE4NOCY.js";
13
+ } from "../chunk-JMTLK2SZ.js";
14
14
  import "../chunk-FUJ36YDV.js";
15
15
  import "../chunk-BQJIFRAZ.js";
16
- import "../chunk-LWF4ABYF.js";
16
+ import "../chunk-EHBUAJ5M.js";
17
17
  import {
18
18
  validateCurrency
19
- } from "../chunk-XWG54M6T.js";
20
- import "../chunk-7KNFEDFW.js";
19
+ } from "../chunk-UVRBD5GR.js";
20
+ import "../chunk-ZH5CLGO6.js";
21
21
  import "../chunk-66HGCPBU.js";
22
- import "../chunk-MA55LUNR.js";
22
+ import "../chunk-2WWVI32F.js";
23
23
 
24
24
  // src/sdk/testing/test-context.ts
25
25
  function createTestContext(opts) {
@@ -1,4 +1,4 @@
1
- import { C as Currency } from './step-cache-Bx_ZybWF.js';
1
+ import { C as Currency } from './step-cache-DXFftnAc.js';
2
2
 
3
3
  /**
4
4
  * Thrown by `fiatToSatsCeil` / `satsToFiat` when the supplied `ratePerBtc` is
@@ -3,11 +3,11 @@ import {
3
3
  generateX402PrivateKey,
4
4
  getX402Balance,
5
5
  resolveX402Asset
6
- } from "./chunk-5RGZN6WQ.js";
6
+ } from "./chunk-XB644VN3.js";
7
7
  import {
8
8
  verifyX402Payment
9
- } from "./chunk-ZBOCNF56.js";
10
- import "./chunk-3V6CSTWB.js";
9
+ } from "./chunk-GDZXGB43.js";
10
+ import "./chunk-3DGIRHP2.js";
11
11
  import {
12
12
  X402_DEFAULT_FACILITATOR,
13
13
  X402_DEFAULT_NETWORK,
@@ -26,7 +26,7 @@ import {
26
26
  paymentRequiredV2FromV1,
27
27
  usdcContractByCaip2,
28
28
  x402NetworkToCaip2
29
- } from "./chunk-NUDHO4HV.js";
29
+ } from "./chunk-LABJSMSJ.js";
30
30
  import "./chunk-FUJ36YDV.js";
31
31
  import {
32
32
  X402_NETWORKS,
@@ -37,7 +37,7 @@ import {
37
37
  x402SupportedNetworksHint
38
38
  } from "./chunk-BPYMEMQX.js";
39
39
  import "./chunk-66HGCPBU.js";
40
- import "./chunk-MA55LUNR.js";
40
+ import "./chunk-2WWVI32F.js";
41
41
  export {
42
42
  X402_DEFAULT_FACILITATOR,
43
43
  X402_DEFAULT_NETWORK,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dvmkit/sdk",
3
- "version": "0.21.2",
3
+ "version": "0.22.0",
4
4
  "description": "SDK for building Digital Vending Machines: pay-per-use HTTPS services AI agents can find, pay, and call with no account or API key",
5
5
  "author": "DVM Technologies Ltd",
6
6
  "keywords": [
@@ -3,6 +3,47 @@ import {
3
3
  x402NetworkBySlug
4
4
  } from "./chunk-BPYMEMQX.js";
5
5
 
6
+ // src/lib/payment-amounts.ts
7
+ function msatsToUsd(msats, rate) {
8
+ return msats / 1e11 * rate;
9
+ }
10
+ function usdToMsats(usd, rate) {
11
+ return Math.round(usd / rate * 1e11);
12
+ }
13
+ function msatsToUsdCents(msats, btcPriceUsd) {
14
+ const usd = msatsToUsd(msats, btcPriceUsd);
15
+ return Math.round(usd * 100);
16
+ }
17
+ function msatsToUsdc(msats, btcUsdRate) {
18
+ if (!Number.isSafeInteger(msats) || msats < 0) {
19
+ throw new RangeError("msats must be a non-negative safe integer");
20
+ }
21
+ if (!Number.isFinite(btcUsdRate) || btcUsdRate <= 0) {
22
+ throw new RangeError("BTC/USD rate must be finite and positive");
23
+ }
24
+ const [mantissa, exponent = "0"] = btcUsdRate.toString().split("e");
25
+ const decimalPlaces = mantissa.split(".")[1]?.length ?? 0;
26
+ const shift = Number(exponent) - decimalPlaces;
27
+ let numerator = BigInt(msats) * BigInt(mantissa.replace(".", ""));
28
+ let denominator = 100000n;
29
+ if (shift > 0) numerator *= 10n ** BigInt(shift);
30
+ else if (shift < 0) denominator *= 10n ** BigInt(-shift);
31
+ const micro = (numerator + denominator - 1n) / denominator;
32
+ if (micro > BigInt(Number.MAX_SAFE_INTEGER)) {
33
+ throw new RangeError("USDC micro-unit amount exceeds the safe integer range");
34
+ }
35
+ return Number(micro);
36
+ }
37
+ function usdcToMsats(usdc, btcUsdRate) {
38
+ return usdToMsats(usdc, btcUsdRate);
39
+ }
40
+ function msatsToMicro(msats, btcRate) {
41
+ return Math.round(msatsToUsd(msats, btcRate) * 1e6);
42
+ }
43
+ function microToSats(micro, btcRate) {
44
+ return Math.ceil(usdToMsats(micro / 1e6, btcRate) / 1e3);
45
+ }
46
+
6
47
  // src/lib/x402/constants.ts
7
48
  var X402_DEFAULT_FACILITATOR = "https://x402.org/facilitator";
8
49
 
@@ -206,47 +247,6 @@ function isOptionalRecord(value) {
206
247
  return value === void 0 || value === null || isRecord(value);
207
248
  }
208
249
 
209
- // src/lib/payment-amounts.ts
210
- function msatsToUsd(msats, rate) {
211
- return msats / 1e11 * rate;
212
- }
213
- function usdToMsats(usd, rate) {
214
- return Math.round(usd / rate * 1e11);
215
- }
216
- function msatsToUsdCents(msats, btcPriceUsd) {
217
- const usd = msatsToUsd(msats, btcPriceUsd);
218
- return Math.round(usd * 100);
219
- }
220
- function msatsToUsdc(msats, btcUsdRate) {
221
- if (!Number.isSafeInteger(msats) || msats < 0) {
222
- throw new RangeError("msats must be a non-negative safe integer");
223
- }
224
- if (!Number.isFinite(btcUsdRate) || btcUsdRate <= 0) {
225
- throw new RangeError("BTC/USD rate must be finite and positive");
226
- }
227
- const [mantissa, exponent = "0"] = btcUsdRate.toString().split("e");
228
- const decimalPlaces = mantissa.split(".")[1]?.length ?? 0;
229
- const shift = Number(exponent) - decimalPlaces;
230
- let numerator = BigInt(msats) * BigInt(mantissa.replace(".", ""));
231
- let denominator = 100000n;
232
- if (shift > 0) numerator *= 10n ** BigInt(shift);
233
- else if (shift < 0) denominator *= 10n ** BigInt(-shift);
234
- const micro = (numerator + denominator - 1n) / denominator;
235
- if (micro > BigInt(Number.MAX_SAFE_INTEGER)) {
236
- throw new RangeError("USDC micro-unit amount exceeds the safe integer range");
237
- }
238
- return Number(micro);
239
- }
240
- function usdcToMsats(usdc, btcUsdRate) {
241
- return usdToMsats(usdc, btcUsdRate);
242
- }
243
- function msatsToMicro(msats, btcRate) {
244
- return Math.round(msatsToUsd(msats, btcRate) * 1e6);
245
- }
246
- function microToSats(micro, btcRate) {
247
- return Math.ceil(usdToMsats(micro / 1e6, btcRate) / 1e3);
248
- }
249
-
250
250
  // src/lib/payment-rails/rpc.ts
251
251
  function resolveRpcOverride(envValue, bundled) {
252
252
  const override = envValue?.trim() ?? "";
@@ -274,6 +274,13 @@ function resolveRpcHttpTransportOptions(source, envValue) {
274
274
  }
275
275
 
276
276
  export {
277
+ msatsToUsd,
278
+ usdToMsats,
279
+ msatsToUsdCents,
280
+ msatsToUsdc,
281
+ usdcToMsats,
282
+ msatsToMicro,
283
+ microToSats,
277
284
  X402_DEFAULT_FACILITATOR,
278
285
  X402_VERSION,
279
286
  X402_V1_VERSION,
@@ -296,13 +303,6 @@ export {
296
303
  decodePaymentRequiredHeader,
297
304
  exactEvmAuthorization,
298
305
  encodeSettleResponseHeader,
299
- msatsToUsd,
300
- usdToMsats,
301
- msatsToUsdCents,
302
- msatsToUsdc,
303
- usdcToMsats,
304
- msatsToMicro,
305
- microToSats,
306
306
  resolveRpcOverride,
307
307
  resolveRpcHttpTransportOptions
308
308
  };