thunder-bridge 0.8.0 → 0.8.1

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.
package/dist/index.d.cts CHANGED
@@ -152,6 +152,12 @@ declare class ThunderBridge {
152
152
  private readonly verify;
153
153
  private readonly token;
154
154
  constructor(baseUrl: string, options?: ThunderBridgeOptions);
155
+ /**
156
+ * Whether a token was given, which is what makes an instance yours: a gateway
157
+ * started with `GATEWAY_TOKEN` answers nobody else, so anything you hand it
158
+ * stays between you and it
159
+ */
160
+ get isPrivate(): boolean;
155
161
  /**
156
162
  * Ask the gateway for an invoice payable to the first address on your list
157
163
  * that can issue a provable one, throws `NoWalletAvailableError` when none can
@@ -168,6 +174,12 @@ declare class ThunderBridge {
168
174
  createQuote(params: CreateQuoteParams): Promise<Quote>;
169
175
  /** Read a payment back, null when the gateway has never heard of it */
170
176
  getPayment(id: string): Promise<Payment | null>;
177
+ /**
178
+ * Read back a payment the gateway is only watching, null when it has never
179
+ * heard of it. A watched payment carries no address, amount or invoice, so
180
+ * `getPayment` refuses it and this reads the shape both rails share
181
+ */
182
+ getWatched(id: string): Promise<TriggerEvent | null>;
171
183
  /**
172
184
  * List what this gateway is watching, newest first. Only a gateway started
173
185
  * with `GATEWAY_TOKEN` serves this, because on a shared one it would hand
@@ -188,6 +200,36 @@ declare class ThunderBridge {
188
200
  * ends by itself
189
201
  */
190
202
  waitForPayment(id: string, options?: WaitOptions): Promise<Payment>;
203
+ /**
204
+ * Follow a payment the gateway is only watching, one it did not mint, until it
205
+ * is paid or expired.
206
+ *
207
+ * A watched payment carries no address, no amount and no invoice, because the
208
+ * gateway was told none of them, so it reads back as the shape a trigger
209
+ * streams rather than as a `Payment`. That is every bank transfer, and every
210
+ * Lightning invoice registered with `watchPayment` instead of `createPayment`.
211
+ */
212
+ waitForWatched(id: string, options?: WaitOptions): Promise<TriggerEvent>;
213
+ private followed;
214
+ /**
215
+ * Wait on several payments and keep the first one that is really paid, then stop
216
+ * waiting on the losers, which closes their sockets.
217
+ *
218
+ * This is how one order offers two rails. A Lightning invoice and a bank
219
+ * transfer for the same thing are two payments here, and the payer picks one, so
220
+ * what you want is the one that arrives and nothing further from the other.
221
+ *
222
+ * A leg that expires is a loser, not a winner, which is the whole reason this is
223
+ * not a race: `waitForPayment` ends on `paid` and on `expired` alike, and a
224
+ * Lightning invoice expires in an hour while a bank transfer takes days. `null`
225
+ * means every leg ended without being paid.
226
+ *
227
+ * Stopping the wait is not revoking the invoice. Nobody can revoke one, because
228
+ * the recipient's own wallet minted it, so a payer who pays the loser afterwards
229
+ * really does pay twice and that shows up on `followTrigger` as a second
230
+ * settlement to refund.
231
+ */
232
+ firstToSettle(ids: string[], options?: WaitOptions): Promise<TriggerEvent | null>;
191
233
  /**
192
234
  * Hand over an invoice you obtained yourself so the gateway watches it without
193
235
  * being told the address or the amount. It can then only refuse everyone
@@ -282,6 +324,233 @@ interface Minted {
282
324
  */
283
325
  declare function lnurlPayEndpoint(config: TriggerConfig): (request: Request) => Promise<Response>;
284
326
 
327
+ /** One incoming payment as the bank booked it, in the smallest unit of its currency */
328
+ interface Credit {
329
+ amountMinor: number;
330
+ currency: string;
331
+ /** Whatever the payer wrote, wherever this bank puts it. Matching is a substring, so noise around it is fine */
332
+ reference: string;
333
+ bookedAt: number;
334
+ }
335
+ /**
336
+ * Recent credits on one account, oldest or newest first, it makes no difference.
337
+ * This is the whole plugin seam: a bank is a function of this shape, and
338
+ * `fioStatement` is one implementation of it
339
+ */
340
+ type Statement = (sinceUnix: number) => Promise<Credit[]>;
341
+ interface BankTransferParams {
342
+ /**
343
+ * The gateway that will watch this transfer. It has to be one of your own,
344
+ * meaning one you gave a token, unless `allowPublicGateway` says otherwise
345
+ */
346
+ gateway: ThunderBridge;
347
+ /** Long lived and server side. The preimage is derived from it, so losing it loses every proof */
348
+ secret: string;
349
+ /** What the payer must leave on the transfer, an order id or a nonce. It is matched, not stored */
350
+ reference: string;
351
+ /** The price in the smallest unit, so 48055 is 480.55 CZK */
352
+ amountMinor: number;
353
+ /** The account the money goes to, as an IBAN */
354
+ iban: string;
355
+ /** Where `bankVerifyEndpoint` is mounted, a public https URL with no query of its own */
356
+ verifyUrl: string;
357
+ /** When the offer dies, in unix seconds. Money in a bank moves on banking days, so give it days */
358
+ expiresAt: number;
359
+ /** Defaults to CZK */
360
+ currency?: string;
361
+ /** Up to ten digits, for accounting systems that still want one */
362
+ variableSymbol?: string;
363
+ /**
364
+ * Groups this transfer with everything else paid to the same secret, so one
365
+ * `followTrigger` socket hears about it. Give the Lightning leg of the same
366
+ * order the same secret and both rails arrive on one stream
367
+ */
368
+ trigger?: string;
369
+ /**
370
+ * Handed back untouched on that stream, so a watcher learns which order settled
371
+ * without asking anyone. `seal` it and the gateway cannot read it either
372
+ */
373
+ sealed?: string;
374
+ /**
375
+ * Register on a gateway you do not own anyway. The verify URL names the amount
376
+ * and the reference, so its operator ends up reading your order book, and the
377
+ * URL itself answers whether that order was paid. Say true only when the order
378
+ * book is not worth hiding
379
+ */
380
+ allowPublicGateway?: boolean;
381
+ }
382
+ interface BankTransfer {
383
+ /** The watched payment's id at the gateway, which is how you read this order back */
384
+ id: string;
385
+ /** What the gateway was given, and what the preimage has to hash to */
386
+ paymentHash: string;
387
+ /** The same URL you mounted, carrying what to look for and a signature over it */
388
+ verifyUrl: string;
389
+ /** The payer scans this, it is a Short Payment Descriptor, the Czech QR platba format */
390
+ spd: string;
391
+ }
392
+ interface BankVerifyConfig {
393
+ /** The same secret `bankTransfer` was given */
394
+ secret: string;
395
+ /** The account to read */
396
+ statement: Statement;
397
+ /** How far back a credit still counts, seven days by default */
398
+ lookBackSecs?: number;
399
+ }
400
+ /**
401
+ * Ask for a bank transfer and put it under the gateway's watch, so it settles
402
+ * the way a Lightning payment does.
403
+ *
404
+ * A BOLT11 payment proves settlement with a preimage whose sha256 the payer's
405
+ * invoice pins. A bank transfer has no such thing, so this mints one: the
406
+ * preimage is an HMAC of what is being asked for, and its hash is what the
407
+ * gateway is given. The money still moves straight to your account, and the
408
+ * gateway still learns only a hash and a URL to poll.
409
+ *
410
+ * What the preimage proves is therefore what LUD-21 proves and no more: that
411
+ * the server holding the secret saw the money arrive. It is the recipient's
412
+ * own word, made unforgeable by anyone else.
413
+ *
414
+ * The gateway has to be one of your own. Unlike a blind Lightning watch, which
415
+ * hands over a hash and an opaque wallet URL, this hands over a URL naming the
416
+ * amount and the reference, so whoever runs the gateway can read your order book
417
+ * from the watches alone.
418
+ */
419
+ declare function bankTransfer(params: BankTransferParams): Promise<BankTransfer>;
420
+ /**
421
+ * The verify endpoint the gateway polls, as a Fetch handler, so it runs wherever
422
+ * `lnurlPayEndpoint` does.
423
+ *
424
+ * It answers the LUD-21 shape: `settled` false until a matching credit is on the
425
+ * statement, then `settled` true with the preimage. Nothing is stored, because
426
+ * the preimage is derived again from the secret every time it is asked for.
427
+ *
428
+ * The query has to carry the signature `bankTransfer` put there. Without that
429
+ * check this would answer "did anyone send you 480.55 with this note" to whoever
430
+ * asked, which is your bank statement handed out one question at a time.
431
+ */
432
+ declare function bankVerifyEndpoint(config: BankVerifyConfig): (request: Request) => Promise<Response>;
433
+
434
+ interface FioConfig {
435
+ /**
436
+ * A token with "Sledování účtu" rights, which is read only and cannot move
437
+ * money. One token is one account, which is why this takes no account number.
438
+ *
439
+ * Give it several and they are used in turn. Fio's window is per token rather
440
+ * than per account, so five tokens on one account is a read every six seconds,
441
+ * and generating another token for the same account is what Fio's own
442
+ * documentation suggests when one is not enough
443
+ */
444
+ token: string | string[];
445
+ /**
446
+ * Fio's window for one token, 30 seconds. No token is ever asked twice inside
447
+ * it, and the gap between reads is this divided by however many tokens were
448
+ * given, so the answers stay evenly spaced rather than arriving in bursts.
449
+ * Inside that gap the last answer is handed back. Only helps a process that
450
+ * stays up
451
+ */
452
+ minIntervalSecs?: number;
453
+ /** Override to point at a mock */
454
+ baseUrl?: string;
455
+ }
456
+ /**
457
+ * Read one Fio account as a `Statement`, so a bank transfer proves itself the
458
+ * way a Lightning payment does.
459
+ *
460
+ * The token is the read only kind, generated in internetbanking under Nastavení
461
+ * and API, and it is the whole configuration: a token belongs to one account, so
462
+ * there is no account number to get wrong. It cannot pay anyone, and the worst a
463
+ * leaked one costs you is that someone else can read the statement.
464
+ *
465
+ * Every field on a Fio transaction is optional and arrives as `null` when it is
466
+ * absent, the amount carries its direction in its sign rather than in a flag,
467
+ * and the date is unix milliseconds. This reads all three the way the bank
468
+ * documents them and treats a missing field as absent rather than guessing.
469
+ */
470
+ declare function fioStatement(config: FioConfig): Statement;
471
+
472
+ /**
473
+ * How many minor units of `currency` one bitcoin costs at one venue, so 134883815
474
+ * is 1,348,838.15 CZK. Throws when that venue does not quote that currency, which
475
+ * is a normal answer rather than a fault: Kraken and Bitstamp have no CZK pair
476
+ *
477
+ * This is the plugin seam for prices. Another venue is another function of this
478
+ * shape
479
+ */
480
+ type Ticker = (currency: string) => Promise<number>;
481
+ interface MedianOptions {
482
+ /**
483
+ * How many venues have to answer before a price is usable. Two is the floor
484
+ * worth having, because one venue is a number nobody checked
485
+ */
486
+ minVenues?: number;
487
+ /**
488
+ * Refuse the lot when the cheapest and dearest answers are further apart than
489
+ * this many basis points. Venues normally sit inside 50, so a wider spread means
490
+ * one of them is broken or stale rather than that the market moved
491
+ */
492
+ maxSpreadBps?: number;
493
+ /** Hold the last answer this long per currency, so an order page is not four requests */
494
+ holdForSecs?: number;
495
+ }
496
+ /** Coinbase, CASP authorised in Luxembourg. Quotes CZK, EUR and most fiat */
497
+ declare function coinbase(baseUrl?: string): Ticker;
498
+ /** Kraken, CASP authorised by the Central Bank of Ireland. Quotes EUR and USD, no CZK */
499
+ declare function kraken(baseUrl?: string): Ticker;
500
+ /**
501
+ * Bitstamp, CASP authorised by the CSSF in Luxembourg. Quotes EUR and USD, no CZK.
502
+ *
503
+ * An unknown pair is answered with a `200` and the whole ticker list, whose first
504
+ * entry is BTC/USD, so asking it for CZK and reading the number would quote a
505
+ * bitcoin at 64,000 crowns. Anything but a single object is therefore refused
506
+ */
507
+ declare function bitstamp(baseUrl?: string): Ticker;
508
+ /** Coinmate, on the ESMA CASP register, Czech and the one with a real BTC/CZK book */
509
+ declare function coinmate(baseUrl?: string): Ticker;
510
+ /**
511
+ * Ask several venues and take the middle answer, refusing the lot when they
512
+ * disagree too much.
513
+ *
514
+ * The default is the four MiCA authorised venues below, and every one of them is
515
+ * replaceable: pass your own list, or one venue, or a function that reads a price
516
+ * you already have. A venue that does not quote the currency is skipped rather
517
+ * than fatal, which for CZK leaves Coinbase and Coinmate.
518
+ *
519
+ * The middle is taken rather than the mean so one stuck venue moves the answer by
520
+ * nothing instead of by half its error, and the spread check is what catches the
521
+ * stuck venue that stays inside the pack.
522
+ */
523
+ declare function medianOf(tickers?: Ticker[], options?: MedianOptions): Ticker;
524
+ /**
525
+ * What to ask for over Lightning for a price named in fiat, in millisatoshi.
526
+ *
527
+ * `priceMinorPerBtc` is what a `Ticker` returns. The arithmetic is exact, in
528
+ * BigInt, because a million crown order times a hundred billion millisatoshi
529
+ * leaves what a double can count, and it rounds up, because the extra
530
+ * millisatoshi is worth nothing and belongs to the recipient rather than to a
531
+ * rounding rule.
532
+ *
533
+ * `spreadBps` is yours to set, in basis points, and defaults to none. A Lightning
534
+ * invoice lives an hour and a bank transfer takes days, so a shop pricing in fiat is
535
+ * carrying that volatility whether or not it charges for it
536
+ */
537
+ declare function msatFor(amountMinor: number, priceMinorPerBtc: number, options?: {
538
+ spreadBps?: number;
539
+ }): number;
540
+
541
+ /**
542
+ * How many digits ISO 4217 gives the currency's minor unit, so 2 for a crown and a
543
+ * euro, 0 for a yen and 3 for a dinar.
544
+ *
545
+ * There is no sane default here, which is why an unlisted code throws rather than
546
+ * being treated as two. Assuming two turns 1000 yen into 10 and a dinar into a
547
+ * tenth of itself, and a payment library that guesses at this is a payment library
548
+ * that moves the wrong amount.
549
+ */
550
+ declare function minorUnitsOf(currency: string): number;
551
+ /** The scale that minor unit implies, so 100 for a crown, 1 for a yen, 1000 for a dinar */
552
+ declare function minorScaleOf(currency: string): number;
553
+
285
554
  /**
286
555
  * Prove the invoice really is the one the recipient issued for what you asked,
287
556
  * before the payer ever sees it, both fetches go straight to the recipient's own
@@ -338,6 +607,14 @@ declare function invoiceToDataUrl(destination: string, options?: QrOptions): str
338
607
  declare function lnurlToSvg(endpoint: string, options?: QrOptions): string;
339
608
  /** SVG data URL of the endpoint's QR, for an `<img>` `src` */
340
609
  declare function lnurlToDataUrl(endpoint: string, options?: QrOptions): string;
610
+ /**
611
+ * Render the `spd` from `bankTransfer` as the QR a Czech banking app scans. The
612
+ * payload is a Short Payment Descriptor, so it carries the account, the amount
613
+ * and the reference the payer must leave on the transfer
614
+ */
615
+ declare function spdToSvg(spd: string, options?: QrOptions): string;
616
+ /** SVG data URL of the bank transfer's QR, for an `<img>` `src` */
617
+ declare function spdToDataUrl(spd: string, options?: QrOptions): string;
341
618
 
342
619
  /**
343
620
  * Bech32-encode a pay endpoint as the `LNURL1` string LUD-01 defines, uppercase
@@ -398,10 +675,21 @@ declare class ProblemError extends Error {
398
675
  detail?: string;
399
676
  });
400
677
  }
401
- declare const NO_WALLET_AVAILABLE = "urn:problem-type:thunder-bridge-direct:no-wallet-available";
402
- declare const REQUEST_IN_FLIGHT = "urn:problem-type:thunder-bridge-direct:request-in-flight";
403
- declare const IDEMPOTENCY_KEY_REUSED = "urn:problem-type:thunder-bridge-direct:idempotency-key-reused";
404
- declare const PAYMENT_ALREADY_WATCHED = "urn:problem-type:thunder-bridge-direct:payment-already-watched";
678
+ /**
679
+ * Whether a problem document carries this type, accepting the namespace this
680
+ * project used before `direct` left its name.
681
+ *
682
+ * A problem type is an identifier clients branch on, so renaming one is a breaking
683
+ * change. The gateway emits only the new spelling, and this reads both, so a client
684
+ * that has been updated still types the errors of an instance that has not
685
+ */
686
+ declare function isProblemType(problem: {
687
+ type?: string;
688
+ }, type: string): boolean;
689
+ declare const NO_WALLET_AVAILABLE = "urn:problem-type:thunder-bridge:no-wallet-available";
690
+ declare const REQUEST_IN_FLIGHT = "urn:problem-type:thunder-bridge:request-in-flight";
691
+ declare const IDEMPOTENCY_KEY_REUSED = "urn:problem-type:thunder-bridge:idempotency-key-reused";
692
+ declare const PAYMENT_ALREADY_WATCHED = "urn:problem-type:thunder-bridge:payment-already-watched";
405
693
  /**
406
694
  * Why an `Idempotency-Key` was refused, `request-in-flight` is the benign one and
407
695
  * `key-reused` means the same key was sent for a different request
@@ -432,4 +720,4 @@ declare class NoWalletAvailableError extends ProblemError {
432
720
  }, wallets: WalletFailure[]);
433
721
  }
434
722
 
435
- export { type CreateOptions, type CreatePaymentParams, type CreateQuoteParams, type FollowOptions, type GatewayCheatCode, GatewayCheatError, IDEMPOTENCY_KEY_REUSED, type IdempotencyConflict, IdempotencyConflictError, type Invoice, type Minted, NO_WALLET_AVAILABLE, NoWalletAvailableError, PAYMENT_ALREADY_WATCHED, type Payment, type PaymentStatus, ProblemError, type QrOptions, type Quote, REQUEST_IN_FLIGHT, ThunderBridge, type ThunderBridgeOptions, type TriggerConfig, type TriggerEvent, UnverifiedRecipientError, type WaitOptions, type WalletFailure, type WalletReason, type WatchPaymentParams, type WebhookOptions, decodeInvoice, invoiceToDataUrl, invoiceToSvg, isProvablyPaid, lnurlPayEndpoint, lnurlToDataUrl, lnurlToSvg, parseWebhook, parseWebhookRequest, preimageMatchesHash, proveOrigin, proveSettlement, seal, toLnurl, unseal, verifyWebhookSignature };
723
+ export { type BankTransfer, type BankTransferParams, type BankVerifyConfig, type CreateOptions, type CreatePaymentParams, type CreateQuoteParams, type Credit, type FioConfig, type FollowOptions, type GatewayCheatCode, GatewayCheatError, IDEMPOTENCY_KEY_REUSED, type IdempotencyConflict, IdempotencyConflictError, type Invoice, type MedianOptions, type Minted, NO_WALLET_AVAILABLE, NoWalletAvailableError, PAYMENT_ALREADY_WATCHED, type Payment, type PaymentStatus, ProblemError, type QrOptions, type Quote, REQUEST_IN_FLIGHT, type Statement, ThunderBridge, type ThunderBridgeOptions, type Ticker, type TriggerConfig, type TriggerEvent, UnverifiedRecipientError, type WaitOptions, type WalletFailure, type WalletReason, type WatchPaymentParams, type WebhookOptions, bankTransfer, bankVerifyEndpoint, bitstamp, coinbase, coinmate, decodeInvoice, fioStatement, invoiceToDataUrl, invoiceToSvg, isProblemType, isProvablyPaid, kraken, lnurlPayEndpoint, lnurlToDataUrl, lnurlToSvg, medianOf, minorScaleOf, minorUnitsOf, msatFor, parseWebhook, parseWebhookRequest, preimageMatchesHash, proveOrigin, proveSettlement, seal, spdToDataUrl, spdToSvg, toLnurl, unseal, verifyWebhookSignature };