commit bf2e571a281b1cec26f5921077b0d7fa79703539
parent a60f1c6c9e834c9ca87a4a70e6d25a508619bab4
Author: Florian Dold <dold@taler.net>
Date: Tue, 10 Nov 2026 22:09:00 +0100
wallet-core: observe snapshots for all transaction types
Replace observePeerPushCredit with observeTransaction and explicit types.
Diffstat:
13 files changed, 2840 insertions(+), 1323 deletions(-)
diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md
@@ -1,9 +1,9 @@
-# Wallet snapshot observations
+# Wallet transaction snapshot observations
-Wallet observations provide complete, consistent snapshots for a UI view.
-They implement the approach in https://bugs.gnunet.org/view?id=11794, starting
-with incoming peer push payments. Preparing a payment remains a separate
-operation: `observePeerPushCredit` requires an existing transaction ID.
+Wallet observations provide complete, consistent snapshots for a UI view,
+implementing https://bugs.gnunet.org/view?id=11794. `observeTransaction` supports
+all transaction types. Preparation remains a separate operation and supplies the
+transaction ID to observe.
## Register and receive
@@ -12,180 +12,150 @@ Install the notification listener before making this request:
```json
{
"id": "101",
- "operation": "observePeerPushCredit",
+ "operation": "observeTransaction",
"args": {
- "transactionId": "txn:peer-push-credit:example",
- "observationId": "receive-screen-17"
+ "transactionId": "txn:payment:example",
+ "observationId": "payment-screen-17"
}
}
```
The response is `{}`. The initial snapshot arrives through the notification
-channel, just like every subsequent snapshot, and may precede the response.
-Registration validates the transaction ID, its type, and its existence. A
-failed registration leaves no observation behind.
-
-All snapshot observations use `type: "observation-snapshot"`.
-`observationType` discriminates the domain-specific payload; adding another
-domain does not require another outer notification type. The first variant is:
+channel and may precede the response. Registration validates the ID and record's
+existence. Failed registration leaves no observation behind.
```typescript
-interface PeerPushCreditSnapshotNotification {
+interface TransactionSnapshotNotification {
type: "observation-snapshot";
- observationType: "peer-push-credit";
+ observationType: "transaction";
observationId: string;
revision: number;
transactionId: string;
- snapshot: PeerPushCreditSnapshot | null;
+ snapshot: TransactionSnapshot | null;
}
```
-Revision 1 is the initial snapshot. Revisions increase only when the snapshot
-changes. The UI replaces its previous snapshot in full, including clearing
-optional fields that disappeared. It can discard revisions no newer than the
-one it has applied. Revisions belong to one observation, not to the database
-or transaction. Updates can be coalesced; this is a current-state view, not an
-event log or a promise to report every intermediate state.
-
-## Peer push credit snapshot
-
-`transaction` contains the public transaction view, including IDs, timestamps,
-scopes, state, actions, amounts, summary, expiration, icon ID and KYC link.
-Amounts have the same meaning as in `getTransactionById`: `amountEffective`
-preserves the initial estimate and `amountEffectiveFinal`, when available,
-describes the settled balance effect.
-
-Transaction errors and failure/abort reasons contain only `code`, `hint`, and
-`message` (each text field limited to 1024 characters). Fetch
-`getTransactionById` for full diagnostic details. Internal state IDs and KYC
-access tokens/payto hashes are omitted.
-
-`exchange` contains the relevant exchange presentation and prerequisite data:
-terms status and ETag, key-change information, update status, currency display
-specification, the wallet KYC requested threshold, known soft/hard
-limits and a summary of the last update error. It is `null` if the exchange
-entry is absent. Limits are the wallet's current cached knowledge and do not
-predict whether a subsequent exchange request will require KYC.
-
-`confirmation.unavailableReasons` is empty when confirmation is available
-based on local knowledge. Its possible entries are:
-`not-proposed`, `expired`, `exchange-not-ready`, `exchange-keys-not-accepted`,
-`exchange-tos-not-accepted`, and `kyc-hard-limit`. The UI can render its Receive
-button without making an exchange query or duplicating those checks.
-`confirmPeerPushCredit` remains authoritative and rechecks prerequisites.
-Expiration can update confirmation availability without changing persisted
-transaction state. Generic transaction actions continue to use `txActions`.
-
-Snapshots exclude full contract terms, images and terms-of-service documents.
-Preparation already supplies peer contract terms; `getExchangeTos` supplies
-the terms document when the user opens it.
-
-## Active KYC and errors
-
-`transaction.txState` is the authoritative status, including KYC in the associated
-withdrawal. There is no separate KYC state or phase. `kyc-init`, `kyc`, and
-`balance-kyc` retain their existing meanings; the major state distinguishes
-pending and suspended processing.
-
-`transaction.kycUrl` belongs to the active requirement. A link left over from
-merge KYC is not exposed during ordinary withdrawal or after completion.
-`transaction.kycAmlReview` carries the exchange's `aml_review` hint for that
-requirement. When true, show “Waiting for review”; a portal link can offer details
-without asserting that the user must submit information. False means the exchange
-is not reporting this condition, not that no review exists. An absent field means
-no applicable reported value. Neither the URL nor this flag establishes KYC
-clearance for future operations.
-
-`transaction.error` comes from the active operation: peer merge, wallet-balance
-KYC, or withdrawal. When an error is present, `retryInfo` contains that same
-task's stored `retryCounter` and `nextRetry` timestamp. It describes automatic
-retry scheduling; supported user actions still come from `txActions`. Errors
-and retry information disappear together when that task recovers.
-
-The exchange's `walletKycRequestedThreshold` is account-level metadata and must
-not independently trigger a transaction KYC prompt. There is no balance preview
-or additional KYC prediction in this API.
-
-## Lifetime and failure
-
-Observation IDs are caller-generated, nonempty strings (at most 256 characters),
-unique across the wallet instance. Use a fresh ID for each registration.
-Registering an already active ID fails with `WALLET_CORE_API_BAD_REQUEST`.
-Multiple observations of the same transaction are independent.
-
-Call `stopObservation` with `{ "observationId": "receive-screen-17" }` when
-closing the view. It returns `{}` and is idempotent. It cancels observation,
-not transaction processing. Remove the UI's routing entry before stopping:
-notifications already queued on the transport can still arrive. In-flight
-snapshot reads cannot publish new snapshots after stopping.
-
-Completed, failed and aborted transactions remain observable. Deletion emits
-one final notification with `snapshot: null` and ends the observation. Importing
-or clearing the database refreshes active observations against the committed
-replacement. Wallet shutdown discards observations; reconnecting clients must
-register again.
-
-If a later snapshot cannot be built, core sends `observation-error` with the
-observation ID, observation type, and a compact error summary, then ends the
-observation. This is an observation failure, not a failed payment; the UI may
-register again with a fresh ID. Initial read failures are request errors.
-
-## Implementation and consistency
-
-Register before reading the initial snapshot. Read transaction, exchange,
-amount and prerequisite data within one database transaction, without network
-requests or changing the observed operation. Committed writes to snapshot
-inputs mark observations dirty; rolled-back writes do not. Reads are serialized
-per observation and a change during a read schedules another read. Unchanged
-snapshots are suppressed. A timer refreshes a proposed payment's confirmation
-availability when its purse expires.
-
-Invalidation covers peer credits, their withdrawal groups, retries, reserves,
-exchange details, contract summaries, currency/scope information and settled
-amount inputs. This does not depend on public state-transition notifications.
-
-## Web UI consumer
-
-The receive route owns preparation and its progress/errors. Once push preparation
-returns a transaction ID, it mounts an observed review keyed by that ID. Full
-contract terms stay with preparation for document use. The review waits for its
-first snapshot and never falls back to preparation amounts, summary, expiration,
-or exchange data. Peer-pull review continues using its preparation response.
-Both reviews share confirmation state, error handling, the storage durability
-check, and successful navigation/inbox completion through
-`usePeerPaymentConfirmation`. Each review supplies its own typed API call;
-push confirmation retains progress and cancellation support.
-
-Peer-credit transaction details have a dedicated observation-based route. Other
-transaction types retain their query-based route; both share presentation and
-transaction-action handling. No observation is adapted into a query result.
-
-`usePeerCreditObservation(connection, transactionId)` requires an ID and returns
-`{ state, retry }`. Its explicit subscription states are `loading`, `ready`,
-`disconnected`, `failed`, and `deleted`. A ready state contains a snapshot;
-loading, disconnected, and failed states may retain the last snapshot. Failed
-states also carry an error. Deleted is terminal and contains no snapshot.
-
-```typescript
-const { state, retry } = usePeerCreditObservation(connection, transactionId);
-const canConfirm =
- state.status === "ready" &&
- state.snapshot.confirmation.unavailableReasons.length === 0;
-```
+`TransactionSnapshot` is a discriminated union: narrow `snapshot.type` to access
+its typed `transaction` and domain fields. `transaction.type` matches the outer
+discriminator. Every variant contains an `exchanges` array of relevant cached
+exchange summaries; missing exchange records do not prevent viewing a transaction.
-These are subscription states; payment state remains `transaction.txState`.
-The receive presentation translates core's blockers in their supplied order,
-with key/terms recovery links and authoritative confirmation-request errors.
-It does not reconstruct eligibility from raw exchange fields. Loading, connection
-loss, failure, and deletion are visible even when no amount is available.
-
-The helper installs the listener before registration and stops on unmount,
-including registration races. Reconnection registers a fresh ID and retains
-any previous snapshot while waiting for a new one; confirmation stays disabled
-until ready. Observation failures offer explicit retry. Changing connection or
-transaction ID discards the previous target's value and rejects late deliveries.
-Extension ports clean up their registrations on disconnect; the PWA uses a
-dedicated worker.
-
-No transaction or exchange query is needed to reconstruct ordinary updates.
-Full documents and diagnostic payloads remain on-demand data.
+Revision 1 is the initial snapshot. Revisions increase only when the snapshot
+changes. Replace the previous snapshot in full, including clearing optional
+fields that disappeared. Ignore revisions no newer than the last applied one.
+Revisions belong to one observation, not the database. Updates can be coalesced:
+this is a current-state view, not an event log.
+
+## Snapshot contents
+
+Every transaction includes public identifiers, timestamps, scopes, state, actions,
+amounts, and its type-specific presentation. `amountEffective` preserves the
+initial estimate; `amountEffectiveFinal`, when available, describes the settled
+balance effect. Full diagnostics and contract documents remain separate reads.
+Explicit observation interfaces list the public fields, and the projection
+copies them individually. New diagnostic fields do not automatically enter
+snapshots.
+
+| Type | Additional presentation |
+| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `payment` | `payment` holds choices, affordability, costs, token availability and automatic/default selection, without full contract terms. It is null outside the review or before contract download. `confirmation` reports local review blockers. `currentDonauInfo` supplies the configured donation service URL, without the taxpayer identifier. The transaction retains refund totals/references, fulfillment and PoS information. |
+| `withdrawal` | Transfer instructions, reserve readiness, bank confirmation link, KYC and errors. `bank`, when available, carries cached bank presentation, including configurable amounts and bank status. Exchange candidates for an editable setup form remain a separate setup query. |
+| `deposit` | Submission status, wire-transfer progress and tracking, KYC authentication instructions, and recovery amounts. |
+| `peer-push-credit` | Confirmation blockers; the relevant exchange summary is in `exchanges`. |
+| `peer-pull-credit` | Invoice link, expiration, active peer/withdrawal/balance-KYC state and errors. |
+| `peer-pull-debit` | Confirmation blockers for transaction state, expiration and exchange prerequisites. Amounts retain the estimate recorded during preparation. |
+| `peer-push-debit` | Share link, collection/cancellation state, expiration and recovery amounts. |
+| `refund`, `refresh`, `recoup`, `denom-loss` | Public transaction details, amounts, supported actions and compact errors. |
+| `internal-withdrawal` | Explicit lookup of the underlying withdrawal. It stays hidden from ordinary history, has no independent UI actions, and must not be added to the parent transaction's balance effect. |
+
+Confirmation availability is based on local knowledge. Merchant choices retain
+individual affordability results. Confirmation requests remain authoritative and
+recheck prerequisites and remote state. Observation does not reserve coins or
+predict future KYC decisions. Peer-invoice observations preserve the preparation
+estimate; confirmation checks the current purse balance and selects available
+coins. An expired peer link is omitted even if persisted transaction processing
+has not yet caught up.
+
+Exchange summaries contain terms status/ETag, key-change information, update
+status, currency display specification, and compact update errors. Peer credits
+also expose known soft/hard limits. These are cached limits; the account-level
+`walletKycRequestedThreshold` must not independently trigger a transaction KYC
+prompt.
+
+Errors and failure/abort reasons contain `code`, `hint`, and `message`, with
+text limited to 1024 characters. Transaction key-change and terms errors also
+retain `exchangeBaseUrl` so the UI can offer the relevant recovery action. Internal state IDs, standalone KYC access tokens
+and payto hashes are omitted. Actionable KYC URLs and transfer instructions remain
+available. Fetch `getTransactionById` for full diagnostics.
+
+`txState` is authoritative for active KYC, including an associated withdrawal.
+`kycUrl` and `kycAmlReview` describe the active requirement only. True means the
+exchange reports waiting for review; false does not rule out an undisclosed
+review. An absent field means unknown or inapplicable. `retryInfo`, when present,
+belongs to the operation supplying the error, and disappears with that error.
+
+## Lifetime and failures
+
+Observation IDs are caller-generated, nonempty strings of at most 256 characters,
+unique across the wallet instance. Reusing an active ID is an API error. Multiple
+observations of the same transaction are independent.
+
+Call `stopObservation({ observationId })` when closing a view. It is idempotent
+and cancels observation, not transaction processing. Remove the UI routing entry
+before stopping because notifications already queued on the transport can still
+arrive. Stopped observations cannot publish new in-flight reads.
+
+Completed, failed and aborted transactions remain observable. Deletion emits one
+final notification with `snapshot: null` and ends the observation. Database import
+or clear refreshes observations against the committed replacement. Shutdown
+forgets observations; reconnecting clients register with fresh IDs.
+
+A later snapshot-read failure emits `observation-error` with the observation ID,
+`observationType: "transaction"`, and a compact error, then ends the observation.
+This is a subscription failure, not a transaction failure. Initial read failures
+are request errors. Retry uses a fresh observation ID.
+
+## Consistency and time
+
+Register before reading the initial snapshot. Assemble transaction, choices,
+exchange and prerequisite data in one database transaction, without network
+requests or persistent writes. Committed writes to all snapshot inputs invalidate
+observations; rolled-back writes do not. Reads are serialized per observation;
+a change during a read schedules another read. Unchanged snapshots are suppressed.
+
+Invalidation includes all transaction records and their withdrawal/refresh/recovery
+dependencies, coin availability/history, tokens/slates, retries, reserves, exchange
+and currency data, contract terms, configuration, and settled amount inputs.
+It does not rely on public state-transition notifications. Snapshot readers
+register purse and payment expiry explicitly. Payment choice reads additionally
+track typed denomination, token and exchange-fee records for validity boundaries.
+`ObservationDeadlines` selects the next future boundary; there is no recursive
+field-name scan, and these deadlines do not enter the wire payload.
+
+Bank preparation initializes cached bank presentation. Existing withdrawal tasks
+update it from both status reads and reserve-registration responses; observations
+never perform bank requests. The transaction state takes precedence over cached
+bank presentation, including when the exchange finds the reserve already funded.
+Older records acquire this optional presentation when prepared again.
+
+## Web UI and migration
+
+The generic controller and `useTransactionObservation` retain explicit `loading`,
+`ready`, `disconnected`, `failed`, and `deleted` states. Loading, disconnect and
+failure may retain the last snapshot, but confirmation requires a fresh ready
+snapshot. Failure offers retry; deletion is terminal. Changing connection or
+transaction rejects late deliveries and discards the previous target's value.
+
+Transaction details, merchant review/results, peer receive/pay/share, and withdrawal
+tracking consume observations. Full merchant documents are loaded separately when
+the contract hash becomes available or changes. Failed document reads can be retried
+and are retried after reconnecting. Preparation owns peer documents;
+its amounts/status do not substitute for an observed review. Request progress,
+durability checks, action errors and fulfillment navigation remain separate from
+subscription state. The extension cleans up subscriptions on port disconnect.
+
+`observePeerPushCredit` and its `observationType: "peer-push-credit"` notification
+have been removed. Consumers must call `observeTransaction`, accept
+`observationType: "transaction"`, and narrow `snapshot.type`. `stopObservation`
+and lifecycle rules are unchanged. Transaction lists and balances retain their
+existing query/notification behavior.
diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts
@@ -36,7 +36,7 @@ import {
import { AmountString } from "./types-taler-common.js";
import type {
ObservationType,
- PeerPushCreditSnapshot,
+ TransactionSnapshot,
} from "./types-taler-wallet-observations.js";
export enum NotificationType {
@@ -66,20 +66,19 @@ export interface ErrorInfoSummary {
message?: string;
}
-export interface PeerPushCreditSnapshotNotification {
+export interface TransactionSnapshotNotification {
type: NotificationType.ObservationSnapshot;
- observationType: ObservationType.PeerPushCredit;
+ observationType: ObservationType.Transaction;
observationId: string;
/** Starts at 1; increases within this observation when its value changes. */
revision: number;
transactionId: TransactionIdStr;
/** Null is the final snapshot after deletion. */
- snapshot: PeerPushCreditSnapshot | null;
+ snapshot: TransactionSnapshot | null;
}
/** Extend this union with a discriminated variant for each observed domain. */
-export type ObservationSnapshotNotification =
- PeerPushCreditSnapshotNotification;
+export type ObservationSnapshotNotification = TransactionSnapshotNotification;
/** Ends the observation; does not describe the outcome of the transaction. */
export interface ObservationErrorNotification {
diff --git a/packages/taler-util/src/types-taler-wallet-observations.ts b/packages/taler-util/src/types-taler-wallet-observations.ts
@@ -5,34 +5,48 @@
*/
import { buildCodecForObject, codecForString } from "./codec.js";
+import { assertUnreachable } from "./errors.js";
import type { ErrorInfoSummary } from "./notifications.js";
+import { TalerErrorCode } from "./taler-error-codes.js";
+import type { TalerUriString } from "./taleruri.js";
+import type { TalerPreciseTimestamp, TalerProtocolTimestamp } from "./time.js";
+import type { WithdrawalOperationStatusFlag } from "./types-taler-bank-integration.js";
import type {
AmountString,
CurrencySpecification,
} from "./types-taler-common.js";
-import type { TalerPreciseTimestamp } from "./time.js";
import { codecForTransactionIdStr } from "./types-taler-wallet.js";
import type {
+ ChoiceSelectionDetail,
ExchangeKeyChangeInfo,
ExchangeTosStatus,
ExchangeUpdateStatus,
+ RefreshReason,
ScopeInfo,
+ TalerErrorDetail,
TransactionIdStr,
- WithdrawUriInfoResponse,
} from "./types-taler-wallet.js";
+import { TransactionType } from "./types-taler-wallet-transactions.js";
import type {
+ DenomLossEventType,
+ DepositTransactionTrackingState,
+ KycAuthTransferInfo,
+ OrderShortInfo,
PeerInfoShort,
+ RefundInfoShort,
+ RefundPaymentInfo,
+ Transaction,
TransactionAction,
- TransactionState,
- TransactionType,
TransactionRetryInfo,
+ TransactionState,
+ WithdrawalDetails,
} from "./types-taler-wallet-transactions.js";
export enum ObservationType {
- PeerPushCredit = "peer-push-credit",
+ Transaction = "transaction",
}
-export interface ObservePeerPushCreditRequest {
+export interface ObserveTransactionRequest {
transactionId: TransactionIdStr;
/** Fresh caller-generated ID, unique within this wallet instance. */
observationId: string;
@@ -42,11 +56,11 @@ export interface StopObservationRequest {
observationId: string;
}
-export const codecForObservePeerPushCreditRequest = () =>
- buildCodecForObject<ObservePeerPushCreditRequest>()
+export const codecForObserveTransactionRequest = () =>
+ buildCodecForObject<ObserveTransactionRequest>()
.property("transactionId", codecForTransactionIdStr())
.property("observationId", codecForString())
- .build("ObservePeerPushCreditRequest");
+ .build("ObserveTransactionRequest");
export const codecForStopObservationRequest = () =>
buildCodecForObject<StopObservationRequest>()
@@ -61,9 +75,27 @@ export type PeerPushCreditConfirmationUnavailableReason =
| "exchange-tos-not-accepted"
| "kyc-hard-limit";
-/** The transaction view with diagnostic payloads and internal fields omitted. */
-export interface ObservedPeerPushCreditTransaction {
- type: TransactionType.PeerPushCredit;
+export interface ObservedExchange {
+ exchangeBaseUrl: string;
+ tosStatus: ExchangeTosStatus;
+ unconfirmedKeyChange?: ExchangeKeyChangeInfo;
+ exchangeUpdateStatus: ExchangeUpdateStatus;
+ currencySpec: CurrencySpecification;
+ /** Exchange-account request, not an independent transaction KYC status. */
+ walletKycRequestedThreshold?: string;
+ tosCurrentEtag?: string;
+ kycHardLimit?: AmountString;
+ kycSoftLimit?: AmountString;
+ lastUpdateError?: ErrorInfoSummary;
+}
+
+/** Compact diagnostics plus a public target for actionable exchange errors. */
+export interface ObservedTransactionError extends ErrorInfoSummary {
+ exchangeBaseUrl?: string;
+}
+
+/** Public transaction fields shared by every observation variant. */
+export interface ObservedTransactionCommon {
transactionId: TransactionIdStr;
localTransactionId?: string;
legacy?: boolean;
@@ -72,60 +104,393 @@ export interface ObservedPeerPushCreditTransaction {
txState: TransactionState;
txActions: TransactionAction[];
amountRaw: AmountString;
- /** Initial estimate, including fees; preserved even after failure. */
+ /** Initial estimate including fees, retained after failure. */
amountEffective: AmountString;
- /** Settled balance effect; absent until it can be established. */
+ /** Settled balance effect, when it can be established. */
amountEffectiveFinal?: AmountString;
- info: PeerInfoShort;
- exchangeBaseUrl: string;
kycUrl?: string;
- /** Exchange-reported waiting-for-review hint for active KYC only.
- * Absence means unknown/not applicable; false does not exclude undisclosed review.
- */
+ /** Exchange-reported review hint for the active KYC requirement. */
kycAmlReview?: boolean;
+ kycAuthTransferInfo?: KycAuthTransferInfo;
+ /** Retry information for the operation supplying error. */
retryInfo?: TransactionRetryInfo;
- error?: ErrorInfoSummary;
- abortReason?: ErrorInfoSummary;
- failReason?: ErrorInfoSummary;
+ error?: ObservedTransactionError;
+ abortReason?: ObservedTransactionError;
+ failReason?: ObservedTransactionError;
}
-export interface PeerPushCreditExchangeSnapshot {
+export interface ObservedPaymentTransaction extends ObservedTransactionCommon {
+ type: TransactionType.Payment;
+ merchantBaseUrl: string;
+ unclaimedPayUri?: TalerUriString;
+ info: OrderShortInfo | undefined;
+ totalRefundRaw: AmountString;
+ totalRefundEffective: AmountString;
+ refundPending: AmountString | undefined;
+ refunds: RefundInfoShort[];
+ refundQueryActive: boolean;
+ posConfirmation: string | undefined;
+ posConfirmationDeadline?: TalerProtocolTimestamp;
+ posConfirmationViaNfc?: boolean;
+ repurchaseTransactionId?: TransactionIdStr;
+ choiceIndex?: number;
+}
+
+export interface ObservedWithdrawalTransaction extends ObservedTransactionCommon {
+ type: TransactionType.Withdrawal;
+ exchangeBaseUrl: string | undefined;
+ withdrawalDetails: WithdrawalDetails;
+}
+
+export interface ObservedInternalWithdrawalTransaction extends ObservedTransactionCommon {
+ type: TransactionType.InternalWithdrawal;
exchangeBaseUrl: string;
- tosStatus: ExchangeTosStatus;
- unconfirmedKeyChange?: ExchangeKeyChangeInfo;
- exchangeUpdateStatus: ExchangeUpdateStatus;
- currencySpec: CurrencySpecification;
- /** Exchange-account request, not an independent transaction KYC status. */
- walletKycRequestedThreshold?: string;
- tosCurrentEtag?: string;
- kycHardLimit?: AmountString;
- kycSoftLimit?: AmountString;
- lastUpdateError?: ErrorInfoSummary;
+ withdrawalDetails: WithdrawalDetails;
}
-/** Complete replacement value, assembled from one committed database view. */
-export interface PeerPushCreditSnapshot {
+export interface ObservedPeerPushCreditTransaction extends ObservedTransactionCommon {
+ type: TransactionType.PeerPushCredit;
+ exchangeBaseUrl: string;
+ info: PeerInfoShort;
+}
+
+export interface ObservedPeerPullCreditTransaction extends ObservedTransactionCommon {
+ type: TransactionType.PeerPullCredit;
+ exchangeBaseUrl: string;
+ info: PeerInfoShort;
+ talerUri: string | undefined;
+}
+
+export interface ObservedPeerPushDebitTransaction extends ObservedTransactionCommon {
+ type: TransactionType.PeerPushDebit;
+ exchangeBaseUrl: string;
+ info: PeerInfoShort;
+ talerUri?: string;
+}
+
+export interface ObservedPeerPullDebitTransaction extends ObservedTransactionCommon {
+ type: TransactionType.PeerPullDebit;
+ exchangeBaseUrl: string;
+ info: PeerInfoShort;
+}
+
+export interface ObservedRefundTransaction extends ObservedTransactionCommon {
+ type: TransactionType.Refund;
+ refundedTransactionId: string;
+ paymentInfo: RefundPaymentInfo | undefined;
+ isAbortRecovery?: boolean;
+}
+
+export interface ObservedRefreshTransaction extends ObservedTransactionCommon {
+ type: TransactionType.Refresh;
+ refreshReason: RefreshReason;
+ originatingTransactionId?: string;
+ refreshInputAmount: AmountString;
+ refreshOutputAmount: AmountString;
+}
+
+export interface ObservedDepositTransaction extends ObservedTransactionCommon {
+ type: TransactionType.Deposit;
+ depositGroupId: string;
+ targetPaytoUri: string;
+ accountPub: string;
+ wireTransferDeadline: TalerProtocolTimestamp;
+ wireTransferProgress: number;
+ deposited: boolean;
+ trackingState: DepositTransactionTrackingState[];
+}
+
+export interface ObservedRecoupTransaction extends ObservedTransactionCommon {
+ type: TransactionType.Recoup;
+}
+
+export interface ObservedDenomLossTransaction extends ObservedTransactionCommon {
+ type: TransactionType.DenomLoss;
+ lossEventType: DenomLossEventType;
+ exchangeBaseUrl: string;
+}
+
+export type ObservedTransaction =
+ | ObservedPaymentTransaction
+ | ObservedWithdrawalTransaction
+ | ObservedInternalWithdrawalTransaction
+ | ObservedPeerPushCreditTransaction
+ | ObservedPeerPullCreditTransaction
+ | ObservedPeerPushDebitTransaction
+ | ObservedPeerPullDebitTransaction
+ | ObservedRefundTransaction
+ | ObservedRefreshTransaction
+ | ObservedDepositTransaction
+ | ObservedRecoupTransaction
+ | ObservedDenomLossTransaction;
+
+export interface ObservedPaymentChoices {
+ choices: ChoiceSelectionDetail[];
+ /** Default choice when one is payable, otherwise absent. */
+ defaultChoiceIndex?: number;
+ /** Whether to confirm automaticExecutableIndex without prompting. */
+ automaticExecution?: boolean;
+ automaticExecutableIndex?: number;
+}
+
+/** Latest known bank presentation. Transaction state remains authoritative. */
+export interface ObservedBankWithdrawal {
+ operationId: string;
+ status: WithdrawalOperationStatusFlag;
+ confirmTransferUrl?: string;
+ currency: string;
+ amount: AmountString | undefined;
+ editableAmount: boolean;
+ maxAmount: AmountString | undefined;
+ wireFee: AmountString | undefined;
+ defaultExchangeBaseUrl?: string;
+ editableExchange: boolean;
+}
+
+export type TransactionConfirmationUnavailableReason =
+ | PeerPushCreditConfirmationUnavailableReason
+ | "contract-unavailable";
+
+export interface TransactionSnapshotCommon {
+ exchanges: ObservedExchange[];
+}
+
+export interface PaymentSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.Payment;
+ transaction: ObservedPaymentTransaction;
+ /** Null before contract download and outside payment review. */
+ payment: ObservedPaymentChoices | null;
+ confirmation: {
+ unavailableReasons: TransactionConfirmationUnavailableReason[];
+ };
+ currentDonauInfo?: { donauBaseUrl: string };
+}
+
+export interface WithdrawalSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.Withdrawal;
+ transaction: ObservedWithdrawalTransaction;
+ bank?: ObservedBankWithdrawal;
+}
+
+export interface InternalWithdrawalSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.InternalWithdrawal;
+ transaction: ObservedInternalWithdrawalTransaction;
+}
+
+export interface PeerPushCreditSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.PeerPushCredit;
transaction: ObservedPeerPushCreditTransaction;
- exchange: PeerPushCreditExchangeSnapshot | null;
confirmation: {
- /** Empty means confirmation is available based on local knowledge.
- * Confirmation rechecks the prerequisites.
- */
unavailableReasons: PeerPushCreditConfirmationUnavailableReason[];
};
}
-/** Latest known bank presentation. Transaction state remains authoritative. */
-export type ObservedBankWithdrawal = Pick<
- WithdrawUriInfoResponse,
- | "operationId"
- | "status"
- | "confirmTransferUrl"
- | "currency"
- | "amount"
- | "editableAmount"
- | "maxAmount"
- | "wireFee"
- | "defaultExchangeBaseUrl"
- | "editableExchange"
->;
+export interface PeerPullCreditSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.PeerPullCredit;
+ transaction: ObservedPeerPullCreditTransaction;
+}
+
+export interface PeerPushDebitSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.PeerPushDebit;
+ transaction: ObservedPeerPushDebitTransaction;
+}
+
+export interface PeerPullDebitSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.PeerPullDebit;
+ transaction: ObservedPeerPullDebitTransaction;
+ confirmation: {
+ unavailableReasons: TransactionConfirmationUnavailableReason[];
+ };
+}
+
+export interface RefundSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.Refund;
+ transaction: ObservedRefundTransaction;
+}
+
+export interface RefreshSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.Refresh;
+ transaction: ObservedRefreshTransaction;
+}
+
+export interface DepositSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.Deposit;
+ transaction: ObservedDepositTransaction;
+}
+
+export interface RecoupSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.Recoup;
+ transaction: ObservedRecoupTransaction;
+}
+
+export interface DenomLossSnapshot extends TransactionSnapshotCommon {
+ type: TransactionType.DenomLoss;
+ transaction: ObservedDenomLossTransaction;
+}
+
+/** Complete replacement value, assembled from one committed database view. */
+export type TransactionSnapshot =
+ | PaymentSnapshot
+ | WithdrawalSnapshot
+ | InternalWithdrawalSnapshot
+ | PeerPushCreditSnapshot
+ | PeerPullCreditSnapshot
+ | PeerPushDebitSnapshot
+ | PeerPullDebitSnapshot
+ | RefundSnapshot
+ | RefreshSnapshot
+ | DepositSnapshot
+ | RecoupSnapshot
+ | DenomLossSnapshot;
+
+function transactionError(
+ error: TalerErrorDetail | undefined,
+): ObservedTransactionError | undefined {
+ if (!error) return undefined;
+ return {
+ code: error.code,
+ hint:
+ typeof error.hint === "string" ? error.hint.slice(0, 1024) : undefined,
+ message:
+ typeof error.message === "string"
+ ? error.message.slice(0, 1024)
+ : undefined,
+ ...((error.code === TalerErrorCode.WALLET_EXCHANGE_KEYS_NOT_ACCEPTED ||
+ error.code === TalerErrorCode.WALLET_EXCHANGE_TOS_NOT_ACCEPTED) &&
+ typeof error.exchangeBaseUrl === "string"
+ ? { exchangeBaseUrl: error.exchangeBaseUrl }
+ : {}),
+ };
+}
+
+/** Copy the public fields explicitly; diagnostics never enter the snapshot. */
+export function observedTransaction(
+ transaction: Transaction,
+): ObservedTransaction {
+ const common: ObservedTransactionCommon = {
+ transactionId: transaction.transactionId,
+ localTransactionId: transaction.localTransactionId,
+ legacy: transaction.legacy,
+ timestamp: transaction.timestamp,
+ scopes: transaction.scopes,
+ txState: transaction.txState,
+ txActions: transaction.txActions,
+ amountRaw: transaction.amountRaw,
+ amountEffective: transaction.amountEffective,
+ amountEffectiveFinal: transaction.amountEffectiveFinal,
+ kycUrl: transaction.kycUrl,
+ kycAmlReview: transaction.kycAmlReview,
+ kycAuthTransferInfo: transaction.kycAuthTransferInfo,
+ retryInfo: transaction.retryInfo,
+ error: transactionError(transaction.error),
+ abortReason: transactionError(transaction.abortReason),
+ failReason: transactionError(transaction.failReason),
+ };
+ switch (transaction.type) {
+ case TransactionType.Payment:
+ return {
+ ...common,
+ type: transaction.type,
+ merchantBaseUrl: transaction.merchantBaseUrl,
+ unclaimedPayUri: transaction.unclaimedPayUri,
+ info: transaction.info,
+ totalRefundRaw: transaction.totalRefundRaw,
+ totalRefundEffective: transaction.totalRefundEffective,
+ refundPending: transaction.refundPending,
+ refunds: transaction.refunds,
+ refundQueryActive: transaction.refundQueryActive,
+ posConfirmation: transaction.posConfirmation,
+ posConfirmationDeadline: transaction.posConfirmationDeadline,
+ posConfirmationViaNfc: transaction.posConfirmationViaNfc,
+ repurchaseTransactionId: transaction.repurchaseTransactionId,
+ choiceIndex: transaction.choiceIndex,
+ };
+ case TransactionType.Withdrawal:
+ return {
+ ...common,
+ type: transaction.type,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ withdrawalDetails: transaction.withdrawalDetails,
+ };
+ case TransactionType.InternalWithdrawal:
+ return {
+ ...common,
+ type: transaction.type,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ withdrawalDetails: transaction.withdrawalDetails,
+ };
+ case TransactionType.PeerPushCredit:
+ return {
+ ...common,
+ type: transaction.type,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ info: transaction.info,
+ };
+ case TransactionType.PeerPullCredit:
+ return {
+ ...common,
+ type: transaction.type,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ info: transaction.info,
+ talerUri: transaction.talerUri,
+ };
+ case TransactionType.PeerPushDebit:
+ return {
+ ...common,
+ type: transaction.type,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ info: transaction.info,
+ talerUri: transaction.talerUri,
+ };
+ case TransactionType.PeerPullDebit:
+ return {
+ ...common,
+ type: transaction.type,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ info: transaction.info,
+ };
+ case TransactionType.Refund:
+ return {
+ ...common,
+ type: transaction.type,
+ refundedTransactionId: transaction.refundedTransactionId,
+ paymentInfo: transaction.paymentInfo,
+ isAbortRecovery: transaction.isAbortRecovery,
+ };
+ case TransactionType.Refresh:
+ return {
+ ...common,
+ type: transaction.type,
+ refreshReason: transaction.refreshReason,
+ originatingTransactionId: transaction.originatingTransactionId,
+ refreshInputAmount: transaction.refreshInputAmount,
+ refreshOutputAmount: transaction.refreshOutputAmount,
+ };
+ case TransactionType.Deposit:
+ return {
+ ...common,
+ type: transaction.type,
+ depositGroupId: transaction.depositGroupId,
+ targetPaytoUri: transaction.targetPaytoUri,
+ accountPub: transaction.accountPub,
+ wireTransferDeadline: transaction.wireTransferDeadline,
+ wireTransferProgress: transaction.wireTransferProgress,
+ deposited: transaction.deposited,
+ trackingState: transaction.trackingState,
+ };
+ case TransactionType.Recoup:
+ return {
+ ...common,
+ type: transaction.type,
+ };
+ case TransactionType.DenomLoss:
+ return {
+ ...common,
+ type: transaction.type,
+ lossEventType: transaction.lossEventType,
+ exchangeBaseUrl: transaction.exchangeBaseUrl,
+ };
+ default:
+ return assertUnreachable(transaction);
+ }
+}
diff --git a/packages/taler-wallet-core/src/observation-deadlines.ts b/packages/taler-wallet-core/src/observation-deadlines.ts
@@ -0,0 +1,118 @@
+/*
+ * This file is part of GNU Taler
+ * (C) 2026 Taler Systems S.A.
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+import { AbsoluteTime, TalerProtocolTimestamp } from "@gnu-taler/taler-util";
+import {
+ DbProtocolTimestamp,
+ timestampProtocolFromDb,
+ WalletDenomination,
+ WalletExchangeDetails,
+} from "./db/records.js";
+import { WalletDbTransaction } from "./db/transaction.js";
+
+/** The next time a snapshot can change without a database write. */
+export class ObservationDeadlines {
+ private readonly now = AbsoluteTime.now().t_ms;
+ nextRefreshAt: number | undefined;
+
+ addProtocolTimestamp(timestamp: TalerProtocolTimestamp | undefined): void {
+ if (typeof timestamp?.t_s !== "number" || typeof this.now !== "number")
+ return;
+ // Refresh just after the boundary, including checks with inclusive endpoints.
+ const deadline = timestamp.t_s * 1000 + 1;
+ if (
+ deadline > this.now &&
+ (this.nextRefreshAt === undefined || deadline < this.nextRefreshAt)
+ )
+ this.nextRefreshAt = deadline;
+ }
+
+ addDbTimestamp(timestamp: DbProtocolTimestamp): void {
+ this.addProtocolTimestamp(timestampProtocolFromDb(timestamp));
+ }
+}
+
+/**
+ * Payment choices depend on validity windows inside the selection helpers.
+ * Track those helpers' typed database reads without extra queries. All other
+ * methods are forwarded unchanged; arbitrary record fields are never inspected.
+ */
+export function trackPaymentChoiceDeadlines(
+ tx: WalletDbTransaction,
+ deadlines: ObservationDeadlines,
+): WalletDbTransaction {
+ const denomination = (record: WalletDenomination | undefined): void => {
+ if (!record) return;
+ deadlines.addDbTimestamp(record.stampStart);
+ deadlines.addDbTimestamp(record.stampExpireWithdraw);
+ deadlines.addDbTimestamp(record.stampExpireDeposit);
+ };
+ const exchangeFees = (record: WalletExchangeDetails | undefined): void => {
+ if (!record) return;
+ for (const fees of Object.values(record.wireInfo.feesForType)) {
+ for (const fee of fees) {
+ deadlines.addProtocolTimestamp(fee.startStamp);
+ deadlines.addProtocolTimestamp(fee.endStamp);
+ }
+ }
+ // Insufficient-balance details also report whether global fees are available.
+ for (const fee of record.globalFees) {
+ deadlines.addProtocolTimestamp(fee.startDate);
+ deadlines.addProtocolTimestamp(fee.endDate);
+ }
+ };
+ const reads: Partial<WalletDbTransaction> = {
+ async getDenomination(ref) {
+ const result = await tx.getDenomination(ref);
+ denomination(result);
+ return result;
+ },
+ async getDenominationsByRefs(refs) {
+ const result = await tx.getDenominationsByRefs(refs);
+ result.forEach(denomination);
+ return result;
+ },
+ async getDenominationsByMasterPub(master) {
+ const result = await tx.getDenominationsByMasterPub(master);
+ result.forEach(denomination);
+ return result;
+ },
+ async findDenominationByFamilyFromExpiry(family, expiry, match) {
+ const result = await tx.findDenominationByFamilyFromExpiry(
+ family,
+ expiry,
+ match,
+ );
+ denomination(result);
+ return result;
+ },
+ async getTokensByIssuePubHash(hash) {
+ const result = await tx.getTokensByIssuePubHash(hash);
+ for (const token of result) {
+ deadlines.addDbTimestamp(token.validAfter);
+ deadlines.addDbTimestamp(token.validBefore);
+ }
+ return result;
+ },
+ async getExchangeDetailsByPointer(...pointer) {
+ const result = await tx.getExchangeDetailsByPointer(...pointer);
+ exchangeFees(result);
+ return result;
+ },
+ async getExchangeDetails(url) {
+ const result = await tx.getExchangeDetails(url);
+ exchangeFees(result);
+ return result;
+ },
+ };
+ return new Proxy(tx, {
+ get(target, property) {
+ if (Object.hasOwn(reads, property)) return Reflect.get(reads, property);
+ const value = Reflect.get(target, property);
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+}
diff --git a/packages/taler-wallet-core/src/observations.test.ts b/packages/taler-wallet-core/src/observations.test.ts
@@ -56,6 +56,8 @@ const transactionId = constructTransactionIdentifier({
function snapshot(): PeerPushCreditSnapshot {
return {
+ type: TransactionType.PeerPushCredit,
+ exchanges: [],
transaction: {
type: TransactionType.PeerPushCredit,
transactionId,
@@ -71,7 +73,6 @@ function snapshot(): PeerPushCreditSnapshot {
exchangeBaseUrl: "https://exchange.example/",
info: { summary: "Lunch", expiration: undefined, iconId: undefined },
},
- exchange: null,
confirmation: {
unavailableReasons: ["exchange-not-ready"],
},
@@ -92,7 +93,7 @@ function fixture() {
test("stopping during the initial read cannot emit a snapshot or retain a subscription", async () => {
const f = fixture();
const read = openPromise<PeerPushCreditSnapshot | null>();
- const registration = f.observations.registerPeerPushCredit(
+ const registration = f.observations.registerTransaction(
"view",
transactionId,
() => read.promise,
@@ -112,10 +113,8 @@ test("stopping or shutting down during an update suppresses its result", async (
const f = fixture();
const update = openPromise<PeerPushCreditSnapshot | null>();
let reads = 0;
- await f.observations.registerPeerPushCredit(
- "view",
- transactionId,
- async () => (++reads === 1 ? snapshot() : update.promise),
+ await f.observations.registerTransaction("view", transactionId, async () =>
+ ++reads === 1 ? snapshot() : update.promise,
);
f.observations.invalidate();
f.timer.advance();
@@ -133,17 +132,13 @@ test("updates during a read are serialized and read again before becoming idle",
const f = fixture();
const update = openPromise<PeerPushCreditSnapshot | null>();
let reads = 0;
- await f.observations.registerPeerPushCredit(
- "view",
- transactionId,
- async () => {
- reads++;
- if (reads === 2) return update.promise;
- const value = snapshot();
- value.transaction.info.summary = `read ${reads}`;
- return value;
- },
- );
+ await f.observations.registerTransaction("view", transactionId, async () => {
+ reads++;
+ if (reads === 2) return update.promise;
+ const value = snapshot();
+ value.transaction.info.summary = `read ${reads}`;
+ return value;
+ });
f.observations.invalidate();
f.timer.advance();
f.observations.invalidate();
@@ -167,24 +162,18 @@ test("updates during a read are serialized and read again before becoming idle",
test("initial read errors fail registration, later read errors end only that observation", async () => {
const f = fixture();
await assert.rejects(
- f.observations.registerPeerPushCredit("view", transactionId, async () => {
+ f.observations.registerTransaction("view", transactionId, async () => {
throw Error("initial error");
}),
);
assert.equal(f.notifications.length, 0);
let reads = 0;
- await f.observations.registerPeerPushCredit(
- "view",
- transactionId,
- async () => {
- if (++reads > 1) throw Error("read failed");
- return snapshot();
- },
- );
- await f.observations.registerPeerPushCredit(
- "other",
- transactionId,
- async () => snapshot(),
+ await f.observations.registerTransaction("view", transactionId, async () => {
+ if (++reads > 1) throw Error("read failed");
+ return snapshot();
+ });
+ await f.observations.registerTransaction("other", transactionId, async () =>
+ snapshot(),
);
f.observations.invalidate();
f.timer.advance();
@@ -203,7 +192,7 @@ test("proposed purse expiration schedules a refresh without a database write", a
let reads = 0;
const expiration = Math.floor(Date.now() / 1000) + 2;
try {
- await f.observations.registerPeerPushCredit(
+ await f.observations.registerTransaction(
"view",
transactionId,
async () => {
@@ -225,3 +214,33 @@ test("proposed purse expiration schedules a refresh without a database write", a
f.observations.shutdown();
}
});
+
+test("a deadline crossed during a read schedules another read", async () => {
+ const f = fixture();
+ const initial = openPromise<PeerPushCreditSnapshot>();
+ let deadline: number | undefined = Date.now() + 50;
+ let reads = 0;
+ try {
+ const registered = f.observations.registerTransaction(
+ "view",
+ transactionId,
+ async () => {
+ if (++reads === 1) return initial.promise;
+ deadline = undefined;
+ return snapshot();
+ },
+ () => deadline,
+ );
+ setDangerousTimetravel(100);
+ initial.resolve(snapshot());
+ await registered;
+ assert.equal(f.timer.pending.size, 1);
+ f.timer.advance(1);
+ await flush();
+ assert.equal(reads, 2);
+ assert.equal(f.timer.pending.size, 0);
+ } finally {
+ setDangerousTimetravel(0);
+ f.observations.shutdown();
+ }
+});
diff --git a/packages/taler-wallet-core/src/observations.ts b/packages/taler-wallet-core/src/observations.ts
@@ -11,7 +11,7 @@ import {
getErrorDetailFromException,
NotificationType,
ObservationType,
- PeerPushCreditSnapshot,
+ TransactionSnapshot,
TalerError,
TalerErrorCode,
TalerErrorDetail,
@@ -48,10 +48,11 @@ export function validateObservationId(observationId: string): void {
}
}
-interface PeerPushCreditObservation {
+interface TransactionObservation {
observationId: string;
transactionId: TransactionIdStr;
- read: () => Promise<PeerPushCreditSnapshot | null>;
+ read: () => Promise<TransactionSnapshot | null>;
+ refreshAt?: () => number | undefined;
revision: number;
lastValue?: string;
running: boolean;
@@ -61,7 +62,7 @@ interface PeerPushCreditObservation {
/** In-memory subscriptions, independent of the registering request's lifetime. */
export class WalletObservations {
- private entries = new Map<string, PeerPushCreditObservation>();
+ private entries = new Map<string, TransactionObservation>();
private stopped = false;
constructor(
@@ -69,10 +70,11 @@ export class WalletObservations {
private notify: (notification: WalletNotification) => void,
) {}
- async registerPeerPushCredit(
+ async registerTransaction(
observationId: string,
transactionId: TransactionIdStr,
- read: () => Promise<PeerPushCreditSnapshot | null>,
+ read: () => Promise<TransactionSnapshot | null>,
+ refreshAt?: () => number | undefined,
): Promise<void> {
validateObservationId(observationId);
if (this.stopped || this.entries.has(observationId)) {
@@ -82,10 +84,11 @@ export class WalletObservations {
this.stopped ? "wallet has stopped" : "observationId is already active",
);
}
- const entry: PeerPushCreditObservation = {
+ const entry: TransactionObservation = {
observationId,
transactionId,
read,
+ refreshAt,
revision: 0,
running: true,
dirty: false,
@@ -131,11 +134,11 @@ export class WalletObservations {
for (const id of this.entries.keys()) this.stop(id);
}
- private isActive(entry: PeerPushCreditObservation): boolean {
+ private isActive(entry: TransactionObservation): boolean {
return this.entries.get(entry.observationId) === entry;
}
- private schedule(entry: PeerPushCreditObservation): void {
+ private schedule(entry: TransactionObservation): void {
if (!this.isActive(entry) || entry.running) return;
entry.timer?.clear();
entry.timer = this.timers.after(0, () => {
@@ -144,7 +147,7 @@ export class WalletObservations {
});
}
- private async refresh(entry: PeerPushCreditObservation): Promise<void> {
+ private async refresh(entry: TransactionObservation): Promise<void> {
if (!this.isActive(entry)) return;
entry.running = true;
entry.dirty = false;
@@ -155,7 +158,7 @@ export class WalletObservations {
if (this.isActive(entry)) {
this.notify({
type: NotificationType.ObservationError,
- observationType: ObservationType.PeerPushCredit,
+ observationType: ObservationType.Transaction,
observationId: entry.observationId,
error: summarizeObservationError(getErrorDetailFromException(e))!,
});
@@ -168,8 +171,8 @@ export class WalletObservations {
}
private publish(
- entry: PeerPushCreditObservation,
- snapshot: PeerPushCreditSnapshot | null,
+ entry: TransactionObservation,
+ snapshot: TransactionSnapshot | null,
): void {
// Compare exactly what can appear on the wire (undefined fields omitted).
const value = canonicalJson(JSON.parse(JSON.stringify(snapshot)));
@@ -177,7 +180,7 @@ export class WalletObservations {
entry.lastValue = value;
this.notify({
type: NotificationType.ObservationSnapshot,
- observationType: ObservationType.PeerPushCredit,
+ observationType: ObservationType.Transaction,
observationId: entry.observationId,
transactionId: entry.transactionId,
revision: ++entry.revision,
@@ -189,16 +192,23 @@ export class WalletObservations {
return;
}
// Confirmation can become unavailable without a database write.
- const expiration = snapshot.transaction.info.expiration?.t_s;
+ const info =
+ "info" in snapshot.transaction ? snapshot.transaction.info : undefined;
+ const expiration =
+ info && "expiration" in info ? info.expiration?.t_s : undefined;
const now = AbsoluteTime.now().t_ms;
+ const deadline = entry.refreshAt
+ ? entry.refreshAt()
+ : typeof expiration === "number"
+ ? expiration * 1000 + 1
+ : undefined;
if (
- typeof expiration === "number" &&
+ deadline !== undefined &&
typeof now === "number" &&
- !snapshot.confirmation.unavailableReasons.includes("not-proposed") &&
- !snapshot.confirmation.unavailableReasons.includes("expired")
+ (entry.refreshAt || deadline > now)
) {
entry.timer = this.timers.after(
- Math.min(0x7fffffff, Math.max(1, expiration * 1000 - now + 1)),
+ Math.min(0x7fffffff, Math.max(1, deadline - now)),
() => {
entry.timer = undefined;
entry.dirty = true;
@@ -210,10 +220,22 @@ export class WalletObservations {
}
}
-/** All persistent inputs read by peer credit snapshots, including amount recovery. */
+/** All persistent inputs read by transaction snapshots, including amount recovery. */
const observationInputWrites = new Set<string>([
...[
"PeerPushCredit",
+ "PeerPullCredit",
+ "PeerPullDebit",
+ "PeerPushDebit",
+ "Purchase",
+ "RefundGroup",
+ "RefundItem",
+ "RefreshGroup",
+ "DepositGroup",
+ "RecoupGroup",
+ "DenomLossEvent",
+ "Token",
+ "Config",
"WithdrawalGroup",
"OperationRetry",
"Exchange",
@@ -226,6 +248,9 @@ const observationInputWrites = new Set<string>([
"CurrencyInfo",
"CurrencyInfoEntry",
"Coin",
+ "CoinAvailability",
+ "CoinHistory",
+ "Slate",
"Denomination",
"DenominationFamily",
].flatMap((name) => [`upsert${name}`, `delete${name}`]),
diff --git a/packages/taler-wallet-core/src/observe-peer-push-credit.test.ts b/packages/taler-wallet-core/src/observe-peer-push-credit.test.ts
@@ -1,855 +0,0 @@
-import { processExchangeKyc } from "./exchanges.js";
-/*
- * This file is part of GNU Taler
- * (C) 2026 Taler Systems S.A.
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import assert from "node:assert/strict";
-import { test } from "node:test";
-import {
- CancellationToken,
- encodeCrock,
- ExchangeTosStatus,
- NotificationType,
- LimitOperationType,
- ObservationType,
- openPromise,
- PeerPushCreditSnapshotNotification,
- SetTimeoutTimerAPI,
- TalerError,
- TalerErrorCode,
- TalerPreciseTimestamp,
- TransactionMajorState,
- TransactionMinorState,
- HttpStatusCode,
- TransactionType,
- WalletNotification,
-} from "@gnu-taler/taler-util";
-import { HeadersImpl, HttpRequestLibrary } from "@gnu-taler/taler-util/http";
-import {
- DbRetryInfo,
- TaskIdentifiers,
- constructTaskIdentifier,
- PendingTaskType,
-} from "./common.js";
-import { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronousWorkerFactoryPlain.js";
-import {
- ExchangeEntryDbRecordStatus,
- ExchangeEntryDbUpdateStatus,
- PeerPushCreditStatus,
- ReserveRecordStatus,
- timestampPreciseToDb,
- WalletExchangeDetails,
- WalletExchangeEntry,
- WalletPeerPushCredit,
- WalletWithdrawalGroup,
- WithdrawalGroupStatus,
- WithdrawalRecordType,
-} from "./db/records.js";
-import { runnerFactories } from "./db/testing/runners.js";
-import {
- observePeerPushCredit,
- stopObservation,
-} from "./observe-peer-push-credit.js";
-import { PeerPushCreditTransactionContext } from "./pay-peer-push-credit.js";
-import { dispatchRequestInternal } from "./requests.js";
-import { TaskSchedulerImpl } from "./shepherd.js";
-import {
- constructTransactionIdentifier,
- getTransactionById,
-} from "./transactions.js";
-import { WalletApiOperation } from "./wallet-api-types.js";
-import {
- applyRunConfigDefaults,
- getNormalWalletExecutionContext,
- InternalWalletState,
-} from "./wallet.js";
-
-const exchangeUrl = "https://exchange.example/";
-const master = encodeCrock(new Uint8Array(32));
-const oldMaster = encodeCrock(new Uint8Array(32).fill(3));
-const contractHash = encodeCrock(new Uint8Array(64).fill(2));
-const transactionId = constructTransactionIdentifier({
- tag: TransactionType.PeerPushCredit,
- peerPushCreditId: "incoming",
-});
-const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
-
-class QuietScheduler extends TaskSchedulerImpl {
- override async ensureRunning() {}
- override startShepherdTask() {}
-}
-
-async function fixture(makeRunner: (typeof runnerFactories)[number]) {
- const db = await makeRunner();
- const http = {
- async fetch() {
- throw Error("observation must not use the network");
- },
- } as unknown as HttpRequestLibrary;
- const ws = new InternalWalletState(
- db,
- () => http,
- new SetTimeoutTimerAPI(),
- new SynchronousCryptoWorkerFactoryPlain(),
- );
- ws.initWithConfig(
- applyRunConfigDefaults({
- lazyTaskLoop: true,
- testing: { skipDefaults: true },
- }),
- );
- ws.initCalled = true;
- ws.taskScheduler = new QuietScheduler(ws);
- const cts = CancellationToken.create();
- const wex = getNormalWalletExecutionContext(ws, cts.token, cts, {
- observe() {},
- });
- const stamp = timestampPreciseToDb(TalerPreciseTimestamp.now());
- const exchange: WalletExchangeEntry = {
- baseUrl: exchangeUrl,
- entryStatus: ExchangeEntryDbRecordStatus.Used,
- updateStatus: ExchangeEntryDbUpdateStatus.Ready,
- detailsPointer: {
- currency: "TESTKUDOS",
- masterPublicKey: master,
- updateClock: stamp,
- },
- tosAcceptedEtag: "v1",
- tosCurrentEtag: "v1",
- tosAcceptedTimestamp: stamp,
- lastKeysEtag: undefined,
- lastUpdate: stamp,
- nextUpdateStamp: stamp,
- nextRefreshCheckStamp: stamp,
- };
- const details: WalletExchangeDetails = {
- exchangeBaseUrl: exchangeUrl,
- masterPublicKey: master,
- currency: "TESTKUDOS",
- auditors: [],
- protocolVersionRange: "18:0:1",
- tinyAmount: "TESTKUDOS:0.01",
- reserveClosingDelay: { d_us: 1000 },
- globalFees: [],
- wireInfo: { accounts: [], feesForType: {} },
- bankComplianceLanguage: undefined,
- defaultPeerPushExpiration: undefined,
- };
- const credit: WalletPeerPushCredit = {
- peerPushCreditId: "incoming",
- exchangeBaseUrl: exchangeUrl,
- pursePub: master,
- mergePriv: master,
- contractPriv: master,
- timestamp: stamp,
- contractTermsHash: contractHash,
- status: PeerPushCreditStatus.DialogProposed,
- estimatedAmountEffective: "TESTKUDOS:4.8",
- currency: "TESTKUDOS",
- withdrawalGroupId: undefined,
- };
- await db.runReadWriteTx(async (tx) => {
- details.rowId = await tx.upsertExchangeDetails(details);
- await tx.upsertExchange(exchange);
- await tx.upsertContractTerms({
- h: contractHash,
- contractTermsRaw: {
- amount: "TESTKUDOS:5",
- summary: "Lunch",
- icon_id: "food",
- purse_expiration: { t_s: Math.floor(Date.now() / 1000) + 3600 },
- image: "large-contract-only-data".repeat(10000),
- },
- });
- await tx.upsertPeerPushCredit(credit);
- await new PeerPushCreditTransactionContext(
- wex,
- credit.peerPushCreditId,
- ).updateTransactionMeta(tx);
- });
- const notifications: WalletNotification[] = [];
- ws.addPublicNotificationListener((n) => notifications.push(n));
- function nextSnapshot(id = "view", revision?: number) {
- const result = openPromise<PeerPushCreditSnapshotNotification>();
- const cancel = ws.addPublicNotificationListener((n) => {
- if (
- n.type === NotificationType.ObservationSnapshot &&
- n.observationId === id &&
- (revision === undefined || n.revision === revision)
- ) {
- cancel();
- result.resolve(n);
- }
- });
- return result.promise;
- }
- async function observe(id = "view") {
- const next = nextSnapshot(id);
- assert.deepEqual(
- await dispatchRequestInternal(
- wex,
- WalletApiOperation.ObservePeerPushCredit,
- { transactionId, observationId: id },
- ),
- {},
- );
- return await next;
- }
- async function settle() {
- // Allow scheduled reads, their database work, and notification delivery.
- for (let i = 0; i < 4; i++) {
- await tick();
- await ws.db.runReadWriteTx(async () => {});
- }
- }
- return {
- db,
- ws,
- wex,
- cts,
- exchange,
- details,
- credit,
- notifications,
- nextSnapshot,
- observe,
- settle,
- };
-}
-
-for (const makeRunner of runnerFactories) {
- test(
- `${makeRunner.name}: database replacement refreshes observations and expired offers cannot be confirmed`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- const dump = await f.ws.db.exportDatabase();
- await f.observe();
- let next = f.nextSnapshot();
- await f.wex.runWalletDbTx(async (tx) => {
- const contract = await tx.getContractTerms(contractHash);
- assert.ok(contract);
- contract.contractTermsRaw.purse_expiration = { t_s: 1 };
- await tx.upsertContractTerms(contract);
- });
- const expired = await next;
- assert.equal(
- expired.snapshot?.transaction.txState.major,
- TransactionMajorState.Dialog,
- );
- assert.deepEqual(expired.snapshot?.confirmation, {
- unavailableReasons: ["expired"],
- });
- next = f.nextSnapshot();
- await f.ws.db.importDatabase(dump, async () => {});
- const restored = await next;
- assert.equal(restored.revision, 3);
- assert.equal(
- restored.snapshot?.confirmation.unavailableReasons.length,
- 0,
- );
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: initial snapshot uses public amounts and explicit compact fields`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- const n = await f.observe();
- assert.equal(n.type, NotificationType.ObservationSnapshot);
- assert.equal(n.observationType, ObservationType.PeerPushCredit);
- assert.equal(n.revision, 1);
- assert.equal(n.transactionId, transactionId);
- assert.equal(n.snapshot?.transaction.info.summary, "Lunch");
- assert.equal(n.snapshot?.transaction.amountRaw, "TESTKUDOS:5");
- assert.equal(n.snapshot?.transaction.amountEffective, "TESTKUDOS:4.8");
- assert.equal(
- n.snapshot?.transaction.localTransactionId,
- (await getTransactionById(f.wex, { transactionId }))
- .localTransactionId,
- );
- assert.deepEqual(n.snapshot?.confirmation, {
- unavailableReasons: [],
- });
- assert.equal(
- n.snapshot?.exchange?.tosStatus,
- ExchangeTosStatus.Accepted,
- );
- const wire = JSON.stringify(n);
- for (const excluded of [
- "stId",
- "contractTerms",
- "large-contract-only-data",
- "contractPriv",
- "mergePriv",
- "kycAccessToken",
- ])
- assert.ok(!wire.includes(excluded), excluded);
- assert.ok(wire.length < 4000);
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: related updates, equal states, rollback and deduplication`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- const first = await f.observe();
- let next = f.nextSnapshot();
- await f.wex.runWalletDbTx(async (tx) => {
- await tx.upsertExchange({ ...f.exchange, tosCurrentEtag: "v2" });
- });
- const tos = await next;
- assert.equal(tos.revision, 2);
- assert.deepEqual(
- tos.snapshot?.transaction.txState,
- first.snapshot?.transaction.txState,
- );
- assert.deepEqual(tos.snapshot?.confirmation.unavailableReasons, [
- "exchange-tos-not-accepted",
- ]);
-
- next = f.nextSnapshot();
- await f.ws.runStandaloneWalletDbTx(async (tx) => {
- await tx.upsertOperationRetry({
- id: TaskIdentifiers.forPeerPushCredit(f.credit),
- retryInfo: DbRetryInfo.reset(),
- lastError: {
- code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
- hint: "h".repeat(2000),
- message: "try again",
- details: { body: "large-error-data".repeat(10000) },
- },
- });
- });
- const errored = await next;
- assert.equal(errored.revision, 3);
- assert.equal(errored.snapshot?.transaction.error?.hint?.length, 1024);
- assert.equal(errored.snapshot?.transaction.error?.message, "try again");
- assert.ok(!JSON.stringify(errored).includes("large-error-data"));
-
- const count = f.notifications.length;
- await assert.rejects(
- f.wex.runWalletDbTx(async (tx) => {
- await tx.upsertPeerPushCredit({
- ...f.credit,
- status: PeerPushCreditStatus.Aborted,
- });
- throw Error("rollback");
- }),
- );
- await f.wex.runWalletDbTx((tx) => tx.upsertPeerPushCredit(f.credit));
- await f.settle();
- assert.equal(f.notifications.length, count);
-
- next = f.nextSnapshot();
- await f.wex.runWalletDbTx((tx) =>
- tx.deleteOperationRetry(TaskIdentifiers.forPeerPushCredit(f.credit)),
- );
- const cleared = await next;
- assert.equal(cleared.revision, 4);
- assert.equal(cleared.snapshot?.transaction.error, undefined);
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: limits, key acceptance and wallet KYC are self-contained`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- await f.observe();
- const next = f.nextSnapshot();
- await f.wex.runWalletDbTx(async (tx) => {
- const rowId = await tx.upsertReserve({
- reservePub: master,
- reservePriv: master,
- status: ReserveRecordStatus.PendingLegi,
- kycAccessToken: "wallet-kyc",
- thresholdRequested: "TESTKUDOS:10",
- });
- await tx.upsertExchange({
- ...f.exchange,
- currentMergeReserveRowId: rowId,
- supersededKeySet: {
- masterPublicKey: oldMaster,
- currency: "TESTKUDOS",
- sharesDenominations: true,
- firstSeen: f.credit.timestamp,
- },
- });
- await tx.upsertExchangeDetails({
- ...f.details,
- hardLimits: [
- {
- operation_type: LimitOperationType.merge,
- threshold: "TESTKUDOS:4",
- timeframe: { d_us: 1000000 },
- },
- ],
- });
- });
- const n = await next;
- assert.equal(n.snapshot?.exchange?.kycHardLimit, "TESTKUDOS:4");
- assert.equal(
- n.snapshot?.exchange?.unconfirmedKeyChange?.supersededMasterPub,
- oldMaster,
- );
- assert.equal(n.snapshot?.transaction.kycUrl, undefined);
- assert.deepEqual(n.snapshot?.confirmation.unavailableReasons, [
- "exchange-keys-not-accepted",
- "kyc-hard-limit",
- ]);
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: withdrawal updates refresh a credit without changing its state`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- const withdrawal: WalletWithdrawalGroup = {
- withdrawalGroupId: "withdrawal",
- wgInfo: { withdrawalType: WithdrawalRecordType.PeerPushCredit },
- secretSeed: master,
- reservePub: master,
- reservePriv: master,
- exchangeBaseUrl: exchangeUrl,
- timestampStart: f.credit.timestamp,
- status: WithdrawalGroupStatus.PendingReady,
- instructedAmount: "TESTKUDOS:5",
- denomsSel: {
- selectedDenoms: [],
- hasDenomWithAgeRestriction: false,
- totalCoinValue: "TESTKUDOS:4.8",
- totalWithdrawCost: "TESTKUDOS:5",
- },
- };
- await f.wex.runWalletDbTx(async (tx) => {
- await tx.upsertWithdrawalGroup(withdrawal);
- await tx.upsertPeerPushCredit({
- ...f.credit,
- withdrawalGroupId: "withdrawal",
- status: PeerPushCreditStatus.PendingWithdrawing,
- });
- });
- const first = await f.observe();
- const next = f.nextSnapshot();
- await f.wex.runWalletDbTx((tx) =>
- tx.upsertWithdrawalGroup({
- ...withdrawal,
- status: WithdrawalGroupStatus.PendingKyc,
- kycAccessToken: "withdraw-kyc",
- }),
- );
- const n = await next;
- assert.equal(
- first.snapshot?.transaction.txState.minor,
- TransactionMinorState.Withdraw,
- );
- assert.equal(
- n.snapshot?.transaction.txState.minor,
- TransactionMinorState.KycRequired,
- );
- assert.equal(
- n.snapshot?.transaction.kycUrl,
- `${exchangeUrl}kyc-spa/withdraw-kyc`,
- );
- assert.equal(n.revision, 2);
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: cancellation is independent and deletion ends observations`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- await f.observe("one");
- await f.observe("two");
- assert.deepEqual(
- await dispatchRequestInternal(
- f.wex,
- WalletApiOperation.StopObservation,
- { observationId: "one" },
- ),
- {},
- );
- await stopObservation(f.wex, { observationId: "one" });
- // Request cancellation must not cancel the observation.
- f.cts.cancel();
- const next = f.nextSnapshot("two");
- await f.ws.runStandaloneWalletDbTx((tx) =>
- tx.deletePeerPushCredit("incoming"),
- );
- const n = await next;
- assert.equal(n.snapshot, null);
- assert.equal(n.revision, 2);
- await f.ws.runStandaloneWalletDbTx((tx) =>
- tx.upsertPeerPushCredit(f.credit),
- );
- await f.settle();
- assert.equal(
- f.notifications.filter(
- (n) => n.type === NotificationType.ObservationSnapshot,
- ).length,
- 3,
- );
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: invalid registration, duplicate IDs and database clear`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- for (const args of [
- { transactionId, observationId: "" },
- { transactionId: "txn:payment:wrong-kind", observationId: "view" },
- {
- transactionId: "txn:peer-push-credit:missing",
- observationId: "view",
- },
- { observationId: "view" },
- ])
- await assert.rejects(
- dispatchRequestInternal(
- f.wex,
- WalletApiOperation.ObservePeerPushCredit,
- args,
- ),
- );
- await f.observe();
- await assert.rejects(
- observePeerPushCredit(f.wex, {
- transactionId,
- observationId: "view",
- }),
- (e: unknown) =>
- e instanceof TalerError &&
- e.errorDetail.code === TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
- );
- const next = f.nextSnapshot();
- await f.ws.db.clearDatabase();
- assert.equal((await next).snapshot, null);
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-
- test(
- `${makeRunner.name}: a commit during initial snapshot delivery is not missed`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- const readDone = openPromise<void>();
- const release = openPromise<void>();
- const original = f.ws.runStandaloneWalletDbTx.bind(f.ws);
- let first = true;
- f.ws.runStandaloneWalletDbTx = async (fn) => {
- const result = await original(fn);
- if (first) {
- first = false;
- readDone.resolve();
- await release.promise;
- }
- return result;
- };
- const observed = observePeerPushCredit(f.wex, {
- transactionId,
- observationId: "view",
- });
- await readDone.promise;
- await f.wex.runWalletDbTx((tx) =>
- tx.upsertPeerPushCredit({
- ...f.credit,
- status: PeerPushCreditStatus.Aborted,
- }),
- );
- const updated = f.nextSnapshot("view", 2);
- release.resolve();
- await observed;
- await updated;
- const ns = f.notifications.filter(
- (n): n is PeerPushCreditSnapshotNotification =>
- n.type === NotificationType.ObservationSnapshot,
- );
- assert.deepEqual(
- ns.map((n) => n.revision),
- [1, 2],
- );
- assert.equal(
- ns[0].snapshot?.transaction.txState.major,
- TransactionMajorState.Dialog,
- );
- assert.equal(
- ns[1].snapshot?.transaction.txState.major,
- TransactionMajorState.Aborted,
- );
- assert.equal(
- ns[1].snapshot?.transaction.amountEffective,
- "TESTKUDOS:4.8",
- );
- assert.equal(
- ns[1].snapshot?.transaction.amountEffectiveFinal,
- "TESTKUDOS:0",
- );
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-}
-
-for (const makeRunner of runnerFactories) {
- test(
- `${makeRunner.name}: active KYC state, review, links and task errors stay consistent`,
- { timeout: 10000 },
- async () => {
- const f = await fixture(makeRunner);
- try {
- let credit = {
- ...f.credit,
- status: PeerPushCreditStatus.PendingMergeKycRequired,
- kycAccessToken: "merge-token",
- kycLastAmlReview: false,
- };
- await f.wex.runWalletDbTx((tx) => tx.upsertPeerPushCredit(credit));
- let notification = await f.observe();
- assert.equal(notification.snapshot?.transaction.kycAmlReview, false);
- async function change(write: () => Promise<unknown>) {
- const next = f.nextSnapshot();
- await write();
- const previousRevision = notification.revision;
- notification = await next;
- assert.equal(notification.revision, previousRevision + 1);
- const queried = await getTransactionById(f.wex, { transactionId });
- for (const key of [
- "txState",
- "kycUrl",
- "kycAmlReview",
- "retryInfo",
- ] as const)
- assert.deepEqual(
- notification.snapshot?.transaction[key],
- queried[key],
- );
- return notification.snapshot!.transaction;
- }
- let t = await change(() =>
- f.wex.runWalletDbTx((tx) =>
- tx.upsertPeerPushCredit(
- (credit = { ...credit, kycLastAmlReview: true }),
- ),
- ),
- );
- assert.equal(t.kycAmlReview, true);
- let withdrawal: WalletWithdrawalGroup = {
- withdrawalGroupId: "withdrawal",
- wgInfo: { withdrawalType: WithdrawalRecordType.PeerPushCredit },
- secretSeed: master,
- reservePub: master,
- reservePriv: master,
- exchangeBaseUrl: exchangeUrl,
- timestampStart: credit.timestamp,
- status: WithdrawalGroupStatus.PendingReady,
- instructedAmount: "TESTKUDOS:5",
- denomsSel: {
- selectedDenoms: [],
- hasDenomWithAgeRestriction: false,
- totalCoinValue: "TESTKUDOS:4.8",
- totalWithdrawCost: "TESTKUDOS:5",
- },
- };
- t = await change(() =>
- f.wex.runWalletDbTx(async (tx) => {
- await tx.upsertWithdrawalGroup(withdrawal);
- credit = {
- ...credit,
- status: PeerPushCreditStatus.PendingWithdrawing,
- withdrawalGroupId: "withdrawal",
- };
- await tx.upsertPeerPushCredit(credit);
- }),
- );
- assert.equal(t.kycUrl, undefined);
- assert.equal(t.kycAmlReview, undefined);
- t = await change(() =>
- f.wex.runWalletDbTx((tx) =>
- tx.upsertWithdrawalGroup(
- (withdrawal = {
- ...withdrawal,
- status: WithdrawalGroupStatus.PendingKyc,
- }),
- ),
- ),
- );
- assert.equal(t.txState.minor, TransactionMinorState.KycInit);
- t = await change(() =>
- f.wex.runWalletDbTx((tx) =>
- tx.upsertWithdrawalGroup(
- (withdrawal = {
- ...withdrawal,
- kycAccessToken: "withdraw-token",
- kycLastAmlReview: true,
- }),
- ),
- ),
- );
- assert.equal(t.txState.minor, TransactionMinorState.KycRequired);
- assert.equal(t.txState.working, false);
- assert.equal(t.kycUrl, `${exchangeUrl}kyc-spa/withdraw-token`);
- t = await change(() =>
- f.wex.runWalletDbTx((tx) =>
- tx.upsertPeerPushCredit(
- (credit = {
- ...credit,
- status: PeerPushCreditStatus.SuspendedWithdrawing,
- }),
- ),
- ),
- );
- assert.equal(t.txState.major, TransactionMajorState.Suspended);
- assert.equal(t.txState.minor, TransactionMinorState.KycRequired);
- const retryId = constructTaskIdentifier({
- tag: PendingTaskType.ExchangeWalletKyc,
- exchangeBaseUrl: exchangeUrl,
- });
- let reserveId = 0;
- t = await change(() =>
- f.wex.runWalletDbTx(async (tx) => {
- await tx.upsertPeerPushCredit(
- (credit = {
- ...credit,
- status: PeerPushCreditStatus.PendingWithdrawing,
- }),
- );
- await tx.upsertWithdrawalGroup(
- (withdrawal = {
- ...withdrawal,
- status: WithdrawalGroupStatus.PendingBalanceKyc,
- }),
- );
- reserveId = await tx.upsertReserve({
- reservePub: master,
- reservePriv: master,
- status: ReserveRecordStatus.PendingLegi,
- thresholdRequested: "TESTKUDOS:10",
- kycAccessToken: "balance-token",
- amlReview: false,
- });
- await tx.upsertExchange({
- ...f.exchange,
- currentMergeReserveRowId: reserveId,
- });
- }),
- );
- assert.equal(t.kycUrl, `${exchangeUrl}kyc-spa/balance-token`);
- t = await change(() =>
- f.wex.runWalletDbTx((tx) =>
- tx.upsertOperationRetry({
- id: retryId,
- retryInfo: DbRetryInfo.reset(),
- lastError: {
- code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
- hint: "KYC connection failed",
- },
- }),
- ),
- );
- assert.equal(t.error?.hint, "KYC connection failed");
- assert.ok(t.retryInfo);
- const body = {
- aml_review: true,
- rule_gen: 1,
- access_token: "balance-token-new",
- };
- const http: HttpRequestLibrary = {
- async fetch(url, opt) {
- return {
- requestUrl: url,
- requestMethod: opt?.method ?? "GET",
- status: HttpStatusCode.Accepted,
- headers: new HeadersImpl(),
- async json() {
- return body;
- },
- async text() {
- return JSON.stringify(body);
- },
- async bytes() {
- return new TextEncoder().encode(JSON.stringify(body));
- },
- };
- },
- };
- t = await change(() =>
- processExchangeKyc({ ...f.wex, http }, exchangeUrl),
- );
- assert.equal(t.kycAmlReview, true);
- assert.equal(t.kycUrl, `${exchangeUrl}kyc-spa/balance-token-new`);
- body.aml_review = false;
- t = await change(() =>
- processExchangeKyc({ ...f.wex, http }, exchangeUrl),
- );
- assert.equal(t.kycAmlReview, false);
- t = await change(() =>
- f.wex.runWalletDbTx((tx) => tx.deleteOperationRetry(retryId)),
- );
- assert.equal(t.error, undefined);
- assert.equal(t.retryInfo, undefined);
- t = await change(() =>
- f.wex.runWalletDbTx(async (tx) => {
- const reserve = await tx.getReserve(reserveId);
- await tx.upsertReserve({
- ...reserve!,
- status: ReserveRecordStatus.Done,
- });
- }),
- );
- assert.equal(t.kycUrl, undefined);
- assert.equal(t.kycAmlReview, undefined);
- t = await change(() =>
- f.wex.runWalletDbTx((tx) =>
- tx.upsertPeerPushCredit({
- ...credit,
- status: PeerPushCreditStatus.Done,
- }),
- ),
- );
- assert.equal(t.kycUrl, undefined);
- assert.equal(t.kycAmlReview, undefined);
- } finally {
- await f.ws.shutdown();
- }
- },
- );
-}
diff --git a/packages/taler-wallet-core/src/observe-peer-push-credit.ts b/packages/taler-wallet-core/src/observe-peer-push-credit.ts
@@ -1,176 +0,0 @@
-/*
- * This file is part of GNU Taler
- * (C) 2026 Taler Systems S.A.
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import {
- Amounts,
- CancellationToken,
- EmptyObject,
- ExchangeTosStatus,
- ObservePeerPushCreditRequest,
- PeerPushCreditConfirmationUnavailableReason,
- PeerPushCreditSnapshot,
- StopObservationRequest,
- TransactionMajorState,
- TransactionMinorState,
- TransactionType,
-} from "@gnu-taler/taler-util";
-import { WalletDbTransaction } from "./db/transaction.js";
-import {
- loadReadyExchangeSummary,
- lookupExchangeByUriInTx,
-} from "./exchanges.js";
-import { getPeerCreditLimitInfo } from "./kyc.js";
-import {
- summarizeObservationError,
- validateObservationId,
-} from "./observations.js";
-import { isPurseGoneByExpiration } from "./pay-peer-common.js";
-import {
- lookupTransactionInTx,
- makeInvalidTransactionIdError,
- parseTransactionIdentifier,
-} from "./transactions.js";
-import {
- getNormalWalletExecutionContext,
- WalletExecutionContext,
-} from "./wallet.js";
-
-async function readPeerPushCreditSnapshot(
- wex: WalletExecutionContext,
- tx: WalletDbTransaction,
- transactionId: string,
-): Promise<PeerPushCreditSnapshot | null> {
- const transaction = await lookupTransactionInTx(wex, tx, { transactionId });
- if (!transaction) return null;
- if (transaction.type !== TransactionType.PeerPushCredit)
- throw makeInvalidTransactionIdError(
- transactionId,
- TransactionType.PeerPushCredit,
- );
-
- const exchange = await lookupExchangeByUriInTx(
- wex,
- tx,
- transaction.exchangeBaseUrl,
- );
- const exchangeRec = await tx.getExchange(transaction.exchangeBaseUrl);
- const ready = exchangeRec
- ? await loadReadyExchangeSummary(tx, exchangeRec)
- : undefined;
- const limits = ready
- ? getPeerCreditLimitInfo(ready, transaction.amountRaw)
- : undefined;
- const reasons: PeerPushCreditConfirmationUnavailableReason[] = [];
- if (
- transaction.txState.major !== TransactionMajorState.Dialog ||
- transaction.txState.minor !== TransactionMinorState.Proposed
- ) {
- reasons.push("not-proposed");
- } else {
- if (
- transaction.info.expiration &&
- isPurseGoneByExpiration(transaction.info.expiration)
- )
- reasons.push("expired");
- if (!ready) reasons.push("exchange-not-ready");
- if (exchange?.unconfirmedKeyChange)
- reasons.push("exchange-keys-not-accepted");
- if (
- exchange &&
- wex.ws.refcntIgnoreTos === 0 &&
- exchange.tosStatus !== ExchangeTosStatus.Accepted &&
- exchange.tosStatus !== ExchangeTosStatus.MissingTos
- )
- reasons.push("exchange-tos-not-accepted");
- if (
- limits?.kycHardLimit &&
- Amounts.cmp(transaction.amountRaw, limits.kycHardLimit) > 0
- )
- reasons.push("kyc-hard-limit");
- }
-
- return {
- transaction: {
- type: transaction.type,
- transactionId: transaction.transactionId,
- localTransactionId: transaction.localTransactionId,
- legacy: transaction.legacy,
- timestamp: transaction.timestamp,
- scopes: transaction.scopes,
- txState: transaction.txState,
- txActions: transaction.txActions,
- amountRaw: transaction.amountRaw,
- amountEffective: transaction.amountEffective,
- amountEffectiveFinal: transaction.amountEffectiveFinal,
- info: transaction.info,
- exchangeBaseUrl: transaction.exchangeBaseUrl,
- kycUrl: transaction.kycUrl,
- kycAmlReview: transaction.kycAmlReview,
- retryInfo: transaction.retryInfo,
- error: summarizeObservationError(transaction.error),
- abortReason: summarizeObservationError(transaction.abortReason),
- failReason: summarizeObservationError(transaction.failReason),
- },
- exchange: exchange
- ? {
- exchangeBaseUrl: exchange.exchangeBaseUrl,
- tosStatus: exchange.tosStatus,
- tosCurrentEtag: exchangeRec?.tosCurrentEtag,
- unconfirmedKeyChange: exchange.unconfirmedKeyChange,
- exchangeUpdateStatus: exchange.exchangeUpdateStatus,
- currencySpec: exchange.currencySpec,
- walletKycRequestedThreshold: exchange.walletKycRequestedThreshold,
- kycHardLimit: limits?.kycHardLimit,
- kycSoftLimit: limits?.kycSoftLimit,
- lastUpdateError: summarizeObservationError(
- exchange.lastUpdateErrorInfo?.error,
- ),
- }
- : null,
- confirmation: {
- unavailableReasons: reasons,
- },
- };
-}
-
-export async function observePeerPushCredit(
- wex: WalletExecutionContext,
- req: ObservePeerPushCreditRequest,
-): Promise<EmptyObject> {
- const parsed = parseTransactionIdentifier(req.transactionId);
- if (parsed?.tag !== TransactionType.PeerPushCredit)
- throw makeInvalidTransactionIdError(
- req.transactionId,
- TransactionType.PeerPushCredit,
- );
- // An observation outlives its request and must not retain its progress or
- // cancellation context. All reads use the wallet's current admitted database.
- const ws = wex.ws;
- const reader = getNormalWalletExecutionContext(
- ws,
- CancellationToken.CONTINUE,
- undefined,
- { observe() {} },
- );
- await ws.observations.registerPeerPushCredit(
- req.observationId,
- req.transactionId,
- () =>
- ws.runStandaloneWalletDbTx((tx) =>
- readPeerPushCreditSnapshot(reader, tx, req.transactionId),
- ),
- );
- return {};
-}
-
-export async function stopObservation(
- wex: WalletExecutionContext,
- req: StopObservationRequest,
-): Promise<EmptyObject> {
- validateObservationId(req.observationId);
- wex.ws.observations.stop(req.observationId);
- return {};
-}
diff --git a/packages/taler-wallet-core/src/observe-transaction.test.ts b/packages/taler-wallet-core/src/observe-transaction.test.ts
@@ -0,0 +1,1560 @@
+import { processExchangeKyc } from "./exchanges.js";
+/*
+ * This file is part of GNU Taler
+ * (C) 2026 Taler Systems S.A.
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ CancellationToken,
+ encodeCrock,
+ ExchangeTosStatus,
+ NotificationType,
+ LimitOperationType,
+ ObservationType,
+ openPromise,
+ TransactionSnapshotNotification as GenericTransactionSnapshotNotification,
+ PeerPushCreditSnapshot,
+ SetTimeoutTimerAPI,
+ TalerError,
+ TalerErrorCode,
+ TalerPreciseTimestamp,
+ TransactionMajorState,
+ TransactionMinorState,
+ HttpStatusCode,
+ TransactionType,
+ TransactionIdStr,
+ WalletNotification,
+} from "@gnu-taler/taler-util";
+import { HeadersImpl, HttpRequestLibrary } from "@gnu-taler/taler-util/http";
+import {
+ DbRetryInfo,
+ TaskIdentifiers,
+ constructTaskIdentifier,
+ PendingTaskType,
+} from "./common.js";
+import { SynchronousCryptoWorkerFactoryPlain } from "./crypto/workers/synchronousWorkerFactoryPlain.js";
+import {
+ ExchangeEntryDbRecordStatus,
+ ExchangeEntryDbUpdateStatus,
+ PeerPushCreditStatus,
+ ReserveRecordStatus,
+ timestampPreciseToDb,
+ WalletExchangeDetails,
+ WalletExchangeEntry,
+ WalletPeerPushCredit,
+ WalletWithdrawalGroup,
+ WithdrawalGroupStatus,
+ WithdrawalRecordType,
+} from "./db/records.js";
+import { runnerFactories } from "./db/testing/runners.js";
+import {
+ observeTransaction,
+ stopObservation,
+ readTransactionSnapshot,
+} from "./observe-transaction.js";
+import { PeerPushCreditTransactionContext } from "./pay-peer-push-credit.js";
+import { dispatchRequestInternal } from "./requests.js";
+import { TaskSchedulerImpl } from "./shepherd.js";
+import {
+ constructTransactionIdentifier,
+ parseTransactionIdentifier,
+ getTransactionById,
+} from "./transactions.js";
+import { WalletApiOperation } from "./wallet-api-types.js";
+import {
+ applyRunConfigDefaults,
+ getNormalWalletExecutionContext,
+ InternalWalletState,
+} from "./wallet.js";
+
+interface TransactionSnapshotNotification extends GenericTransactionSnapshotNotification {
+ snapshot: PeerPushCreditSnapshot | null;
+}
+
+const exchangeUrl = "https://exchange.example/";
+const master = encodeCrock(new Uint8Array(32));
+const oldMaster = encodeCrock(new Uint8Array(32).fill(3));
+const contractHash = encodeCrock(new Uint8Array(64).fill(2));
+const transactionId = constructTransactionIdentifier({
+ tag: TransactionType.PeerPushCredit,
+ peerPushCreditId: "incoming",
+});
+const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+class QuietScheduler extends TaskSchedulerImpl {
+ override async ensureRunning() {}
+ override startShepherdTask() {}
+}
+
+async function fixture(makeRunner: (typeof runnerFactories)[number]) {
+ const db = await makeRunner();
+ const http = {
+ async fetch() {
+ throw Error("observation must not use the network");
+ },
+ } as unknown as HttpRequestLibrary;
+ const ws = new InternalWalletState(
+ db,
+ () => http,
+ new SetTimeoutTimerAPI(),
+ new SynchronousCryptoWorkerFactoryPlain(),
+ );
+ ws.initWithConfig(
+ applyRunConfigDefaults({
+ lazyTaskLoop: true,
+ testing: { skipDefaults: true },
+ }),
+ );
+ ws.initCalled = true;
+ ws.taskScheduler = new QuietScheduler(ws);
+ const cts = CancellationToken.create();
+ const wex = getNormalWalletExecutionContext(ws, cts.token, cts, {
+ observe() {},
+ });
+ const stamp = timestampPreciseToDb(TalerPreciseTimestamp.now());
+ const exchange: WalletExchangeEntry = {
+ baseUrl: exchangeUrl,
+ entryStatus: ExchangeEntryDbRecordStatus.Used,
+ updateStatus: ExchangeEntryDbUpdateStatus.Ready,
+ detailsPointer: {
+ currency: "TESTKUDOS",
+ masterPublicKey: master,
+ updateClock: stamp,
+ },
+ tosAcceptedEtag: "v1",
+ tosCurrentEtag: "v1",
+ tosAcceptedTimestamp: stamp,
+ lastKeysEtag: undefined,
+ lastUpdate: stamp,
+ nextUpdateStamp: stamp,
+ nextRefreshCheckStamp: stamp,
+ };
+ const details: WalletExchangeDetails = {
+ exchangeBaseUrl: exchangeUrl,
+ masterPublicKey: master,
+ currency: "TESTKUDOS",
+ auditors: [],
+ protocolVersionRange: "18:0:1",
+ tinyAmount: "TESTKUDOS:0.01",
+ reserveClosingDelay: { d_us: 1000 },
+ globalFees: [],
+ wireInfo: { accounts: [], feesForType: {} },
+ bankComplianceLanguage: undefined,
+ defaultPeerPushExpiration: undefined,
+ };
+ const credit: WalletPeerPushCredit = {
+ peerPushCreditId: "incoming",
+ exchangeBaseUrl: exchangeUrl,
+ pursePub: master,
+ mergePriv: master,
+ contractPriv: master,
+ timestamp: stamp,
+ contractTermsHash: contractHash,
+ status: PeerPushCreditStatus.DialogProposed,
+ estimatedAmountEffective: "TESTKUDOS:4.8",
+ currency: "TESTKUDOS",
+ withdrawalGroupId: undefined,
+ };
+ await db.runReadWriteTx(async (tx) => {
+ details.rowId = await tx.upsertExchangeDetails(details);
+ await tx.upsertExchange(exchange);
+ await tx.upsertContractTerms({
+ h: contractHash,
+ contractTermsRaw: {
+ amount: "TESTKUDOS:5",
+ summary: "Lunch",
+ icon_id: "food",
+ purse_expiration: { t_s: Math.floor(Date.now() / 1000) + 3600 },
+ image: "large-contract-only-data".repeat(10000),
+ },
+ });
+ await tx.upsertPeerPushCredit(credit);
+ await new PeerPushCreditTransactionContext(
+ wex,
+ credit.peerPushCreditId,
+ ).updateTransactionMeta(tx);
+ });
+ const notifications: WalletNotification[] = [];
+ ws.addPublicNotificationListener((n) => notifications.push(n));
+ function nextSnapshot(id = "view", revision?: number, deleted = false) {
+ const result = openPromise<TransactionSnapshotNotification>();
+ const cancel = ws.addPublicNotificationListener((n) => {
+ if (
+ n.type === NotificationType.ObservationError &&
+ n.observationId === id
+ ) {
+ cancel();
+ result.reject(new Error(JSON.stringify(n.error)));
+ }
+ if (
+ n.type === NotificationType.ObservationSnapshot &&
+ n.observationId === id &&
+ (revision === undefined || n.revision === revision) &&
+ (!deleted || n.snapshot === null)
+ ) {
+ cancel();
+ result.resolve(n as TransactionSnapshotNotification);
+ }
+ });
+ return result.promise;
+ }
+ async function observe(id = "view") {
+ const next = nextSnapshot(id);
+ assert.deepEqual(
+ await dispatchRequestInternal(
+ wex,
+ WalletApiOperation.ObserveTransaction,
+ { transactionId, observationId: id },
+ ),
+ {},
+ );
+ return await next;
+ }
+ async function settle() {
+ // Allow scheduled reads, their database work, and notification delivery.
+ for (let i = 0; i < 4; i++) {
+ await tick();
+ await ws.db.runReadWriteTx(async () => {});
+ }
+ }
+ return {
+ db,
+ ws,
+ wex,
+ cts,
+ exchange,
+ details,
+ credit,
+ notifications,
+ nextSnapshot,
+ observe,
+ settle,
+ };
+}
+
+for (const makeRunner of runnerFactories) {
+ test(
+ `${makeRunner.name}: database replacement refreshes observations and expired offers cannot be confirmed`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const dump = await f.ws.db.exportDatabase();
+ await f.observe();
+ let next = f.nextSnapshot();
+ await f.wex.runWalletDbTx(async (tx) => {
+ const contract = await tx.getContractTerms(contractHash);
+ assert.ok(contract);
+ contract.contractTermsRaw.purse_expiration = { t_s: 1 };
+ await tx.upsertContractTerms(contract);
+ });
+ const expired = await next;
+ assert.equal(
+ expired.snapshot?.transaction.txState.major,
+ TransactionMajorState.Dialog,
+ );
+ assert.deepEqual(expired.snapshot?.confirmation, {
+ unavailableReasons: ["expired"],
+ });
+ next = f.nextSnapshot();
+ await f.ws.db.importDatabase(dump, async () => {});
+ const restored = await next;
+ assert.equal(restored.revision, 3);
+ assert.equal(
+ restored.snapshot?.confirmation.unavailableReasons.length,
+ 0,
+ );
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: initial snapshot uses public amounts and explicit compact fields`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const n = await f.observe();
+ assert.equal(n.type, NotificationType.ObservationSnapshot);
+ assert.equal(n.observationType, ObservationType.Transaction);
+ assert.equal(n.revision, 1);
+ assert.equal(n.transactionId, transactionId);
+ assert.equal(n.snapshot?.transaction.info.summary, "Lunch");
+ assert.equal(n.snapshot?.transaction.amountRaw, "TESTKUDOS:5");
+ assert.equal(n.snapshot?.transaction.amountEffective, "TESTKUDOS:4.8");
+ assert.equal(
+ n.snapshot?.transaction.localTransactionId,
+ (await getTransactionById(f.wex, { transactionId }))
+ .localTransactionId,
+ );
+ assert.deepEqual(n.snapshot?.confirmation, {
+ unavailableReasons: [],
+ });
+ assert.equal(
+ n.snapshot?.exchanges[0]?.tosStatus,
+ ExchangeTosStatus.Accepted,
+ );
+ const wire = JSON.stringify(n);
+ for (const excluded of [
+ "stId",
+ "contractTerms",
+ "large-contract-only-data",
+ "contractPriv",
+ "mergePriv",
+ "kycAccessToken",
+ ])
+ assert.ok(!wire.includes(excluded), excluded);
+ assert.ok(wire.length < 4000);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: related updates, equal states, rollback and deduplication`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const first = await f.observe();
+ let next = f.nextSnapshot();
+ await f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertExchange({ ...f.exchange, tosCurrentEtag: "v2" });
+ });
+ const tos = await next;
+ assert.equal(tos.revision, 2);
+ assert.deepEqual(
+ tos.snapshot?.transaction.txState,
+ first.snapshot?.transaction.txState,
+ );
+ assert.deepEqual(tos.snapshot?.confirmation.unavailableReasons, [
+ "exchange-tos-not-accepted",
+ ]);
+
+ next = f.nextSnapshot();
+ await f.ws.runStandaloneWalletDbTx(async (tx) => {
+ await tx.upsertOperationRetry({
+ id: TaskIdentifiers.forPeerPushCredit(f.credit),
+ retryInfo: DbRetryInfo.reset(),
+ lastError: {
+ code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
+ hint: "h".repeat(2000),
+ message: "try again",
+ details: { body: "large-error-data".repeat(10000) },
+ },
+ });
+ });
+ const errored = await next;
+ assert.equal(errored.revision, 3);
+ assert.equal(errored.snapshot?.transaction.error?.hint?.length, 1024);
+ assert.equal(errored.snapshot?.transaction.error?.message, "try again");
+ assert.ok(!JSON.stringify(errored).includes("large-error-data"));
+
+ const count = f.notifications.length;
+ await assert.rejects(
+ f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertPeerPushCredit({
+ ...f.credit,
+ status: PeerPushCreditStatus.Aborted,
+ });
+ throw Error("rollback");
+ }),
+ );
+ await f.wex.runWalletDbTx((tx) => tx.upsertPeerPushCredit(f.credit));
+ await f.settle();
+ assert.equal(f.notifications.length, count);
+
+ next = f.nextSnapshot();
+ await f.wex.runWalletDbTx((tx) =>
+ tx.deleteOperationRetry(TaskIdentifiers.forPeerPushCredit(f.credit)),
+ );
+ const cleared = await next;
+ assert.equal(cleared.revision, 4);
+ assert.equal(cleared.snapshot?.transaction.error, undefined);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: limits, key acceptance and wallet KYC are self-contained`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ await f.observe();
+ const next = f.nextSnapshot();
+ await f.wex.runWalletDbTx(async (tx) => {
+ const rowId = await tx.upsertReserve({
+ reservePub: master,
+ reservePriv: master,
+ status: ReserveRecordStatus.PendingLegi,
+ kycAccessToken: "wallet-kyc",
+ thresholdRequested: "TESTKUDOS:10",
+ });
+ await tx.upsertExchange({
+ ...f.exchange,
+ currentMergeReserveRowId: rowId,
+ supersededKeySet: {
+ masterPublicKey: oldMaster,
+ currency: "TESTKUDOS",
+ sharesDenominations: true,
+ firstSeen: f.credit.timestamp,
+ },
+ });
+ await tx.upsertExchangeDetails({
+ ...f.details,
+ hardLimits: [
+ {
+ operation_type: LimitOperationType.merge,
+ threshold: "TESTKUDOS:4",
+ timeframe: { d_us: 1000000 },
+ },
+ ],
+ });
+ });
+ const n = await next;
+ assert.equal(n.snapshot?.exchanges[0]?.kycHardLimit, "TESTKUDOS:4");
+ assert.equal(
+ n.snapshot?.exchanges[0]?.unconfirmedKeyChange?.supersededMasterPub,
+ oldMaster,
+ );
+ assert.equal(n.snapshot?.transaction.kycUrl, undefined);
+ assert.deepEqual(n.snapshot?.confirmation.unavailableReasons, [
+ "exchange-keys-not-accepted",
+ "kyc-hard-limit",
+ ]);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: withdrawal updates refresh a credit without changing its state`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const withdrawal: WalletWithdrawalGroup = {
+ withdrawalGroupId: "withdrawal",
+ wgInfo: { withdrawalType: WithdrawalRecordType.PeerPushCredit },
+ secretSeed: master,
+ reservePub: master,
+ reservePriv: master,
+ exchangeBaseUrl: exchangeUrl,
+ timestampStart: f.credit.timestamp,
+ status: WithdrawalGroupStatus.PendingReady,
+ instructedAmount: "TESTKUDOS:5",
+ denomsSel: {
+ selectedDenoms: [],
+ hasDenomWithAgeRestriction: false,
+ totalCoinValue: "TESTKUDOS:4.8",
+ totalWithdrawCost: "TESTKUDOS:5",
+ },
+ };
+ await f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertWithdrawalGroup(withdrawal);
+ await tx.upsertPeerPushCredit({
+ ...f.credit,
+ withdrawalGroupId: "withdrawal",
+ status: PeerPushCreditStatus.PendingWithdrawing,
+ });
+ });
+ const first = await f.observe();
+ const next = f.nextSnapshot();
+ await f.wex.runWalletDbTx((tx) =>
+ tx.upsertWithdrawalGroup({
+ ...withdrawal,
+ status: WithdrawalGroupStatus.PendingKyc,
+ kycAccessToken: "withdraw-kyc",
+ }),
+ );
+ const n = await next;
+ assert.equal(
+ first.snapshot?.transaction.txState.minor,
+ TransactionMinorState.Withdraw,
+ );
+ assert.equal(
+ n.snapshot?.transaction.txState.minor,
+ TransactionMinorState.KycRequired,
+ );
+ assert.equal(
+ n.snapshot?.transaction.kycUrl,
+ `${exchangeUrl}kyc-spa/withdraw-kyc`,
+ );
+ assert.equal(n.revision, 2);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: cancellation is independent and deletion ends observations`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ await f.observe("one");
+ await f.observe("two");
+ assert.deepEqual(
+ await dispatchRequestInternal(
+ f.wex,
+ WalletApiOperation.StopObservation,
+ { observationId: "one" },
+ ),
+ {},
+ );
+ await stopObservation(f.wex, { observationId: "one" });
+ // Request cancellation must not cancel the observation.
+ f.cts.cancel();
+ const next = f.nextSnapshot("two");
+ await f.ws.runStandaloneWalletDbTx((tx) =>
+ tx.deletePeerPushCredit("incoming"),
+ );
+ const n = await next;
+ assert.equal(n.snapshot, null);
+ assert.equal(n.revision, 2);
+ await f.ws.runStandaloneWalletDbTx((tx) =>
+ tx.upsertPeerPushCredit(f.credit),
+ );
+ await f.settle();
+ assert.equal(
+ f.notifications.filter(
+ (n) => n.type === NotificationType.ObservationSnapshot,
+ ).length,
+ 3,
+ );
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: invalid registration, duplicate IDs and database clear`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ for (const args of [
+ { transactionId, observationId: "" },
+ { transactionId: "txn:payment:wrong-kind", observationId: "view" },
+ {
+ transactionId: "txn:peer-push-credit:missing",
+ observationId: "view",
+ },
+ { observationId: "view" },
+ ])
+ await assert.rejects(
+ dispatchRequestInternal(
+ f.wex,
+ WalletApiOperation.ObserveTransaction,
+ args,
+ ),
+ );
+ await f.observe();
+ await assert.rejects(
+ observeTransaction(f.wex, {
+ transactionId,
+ observationId: "view",
+ }),
+ (e: unknown) =>
+ e instanceof TalerError &&
+ e.errorDetail.code === TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ );
+ const next = f.nextSnapshot();
+ await f.ws.db.clearDatabase();
+ assert.equal((await next).snapshot, null);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+
+ test(
+ `${makeRunner.name}: a commit during initial snapshot delivery is not missed`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const readDone = openPromise<void>();
+ const release = openPromise<void>();
+ const original = f.ws.runStandaloneWalletDbTx.bind(f.ws);
+ let first = true;
+ f.ws.runStandaloneWalletDbTx = async (fn) => {
+ const result = await original(fn);
+ if (first) {
+ first = false;
+ readDone.resolve();
+ await release.promise;
+ }
+ return result;
+ };
+ const observed = observeTransaction(f.wex, {
+ transactionId,
+ observationId: "view",
+ });
+ await readDone.promise;
+ await f.wex.runWalletDbTx((tx) =>
+ tx.upsertPeerPushCredit({
+ ...f.credit,
+ status: PeerPushCreditStatus.Aborted,
+ }),
+ );
+ const updated = f.nextSnapshot("view", 2);
+ release.resolve();
+ await observed;
+ await updated;
+ const ns = f.notifications.filter(
+ (n): n is TransactionSnapshotNotification =>
+ n.type === NotificationType.ObservationSnapshot,
+ );
+ assert.deepEqual(
+ ns.map((n) => n.revision),
+ [1, 2],
+ );
+ assert.equal(
+ ns[0].snapshot?.transaction.txState.major,
+ TransactionMajorState.Dialog,
+ );
+ assert.equal(
+ ns[1].snapshot?.transaction.txState.major,
+ TransactionMajorState.Aborted,
+ );
+ assert.equal(
+ ns[1].snapshot?.transaction.amountEffective,
+ "TESTKUDOS:4.8",
+ );
+ assert.equal(
+ ns[1].snapshot?.transaction.amountEffectiveFinal,
+ "TESTKUDOS:0",
+ );
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+}
+
+for (const makeRunner of runnerFactories) {
+ test(
+ `${makeRunner.name}: active KYC state, review, links and task errors stay consistent`,
+ { timeout: 10000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ let credit = {
+ ...f.credit,
+ status: PeerPushCreditStatus.PendingMergeKycRequired,
+ kycAccessToken: "merge-token",
+ kycLastAmlReview: false,
+ };
+ await f.wex.runWalletDbTx((tx) => tx.upsertPeerPushCredit(credit));
+ let notification = await f.observe();
+ assert.equal(notification.snapshot?.transaction.kycAmlReview, false);
+ async function change(write: () => Promise<unknown>) {
+ const next = f.nextSnapshot();
+ await write();
+ const previousRevision = notification.revision;
+ notification = await next;
+ assert.equal(notification.revision, previousRevision + 1);
+ const queried = await getTransactionById(f.wex, { transactionId });
+ for (const key of [
+ "txState",
+ "kycUrl",
+ "kycAmlReview",
+ "retryInfo",
+ ] as const)
+ assert.deepEqual(
+ notification.snapshot?.transaction[key],
+ queried[key],
+ );
+ return notification.snapshot!.transaction;
+ }
+ let t = await change(() =>
+ f.wex.runWalletDbTx((tx) =>
+ tx.upsertPeerPushCredit(
+ (credit = { ...credit, kycLastAmlReview: true }),
+ ),
+ ),
+ );
+ assert.equal(t.kycAmlReview, true);
+ let withdrawal: WalletWithdrawalGroup = {
+ withdrawalGroupId: "withdrawal",
+ wgInfo: { withdrawalType: WithdrawalRecordType.PeerPushCredit },
+ secretSeed: master,
+ reservePub: master,
+ reservePriv: master,
+ exchangeBaseUrl: exchangeUrl,
+ timestampStart: credit.timestamp,
+ status: WithdrawalGroupStatus.PendingReady,
+ instructedAmount: "TESTKUDOS:5",
+ denomsSel: {
+ selectedDenoms: [],
+ hasDenomWithAgeRestriction: false,
+ totalCoinValue: "TESTKUDOS:4.8",
+ totalWithdrawCost: "TESTKUDOS:5",
+ },
+ };
+ t = await change(() =>
+ f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertWithdrawalGroup(withdrawal);
+ credit = {
+ ...credit,
+ status: PeerPushCreditStatus.PendingWithdrawing,
+ withdrawalGroupId: "withdrawal",
+ };
+ await tx.upsertPeerPushCredit(credit);
+ }),
+ );
+ assert.equal(t.kycUrl, undefined);
+ assert.equal(t.kycAmlReview, undefined);
+ t = await change(() =>
+ f.wex.runWalletDbTx((tx) =>
+ tx.upsertWithdrawalGroup(
+ (withdrawal = {
+ ...withdrawal,
+ status: WithdrawalGroupStatus.PendingKyc,
+ }),
+ ),
+ ),
+ );
+ assert.equal(t.txState.minor, TransactionMinorState.KycInit);
+ t = await change(() =>
+ f.wex.runWalletDbTx((tx) =>
+ tx.upsertWithdrawalGroup(
+ (withdrawal = {
+ ...withdrawal,
+ kycAccessToken: "withdraw-token",
+ kycLastAmlReview: true,
+ }),
+ ),
+ ),
+ );
+ assert.equal(t.txState.minor, TransactionMinorState.KycRequired);
+ assert.equal(t.txState.working, false);
+ assert.equal(t.kycUrl, `${exchangeUrl}kyc-spa/withdraw-token`);
+ t = await change(() =>
+ f.wex.runWalletDbTx((tx) =>
+ tx.upsertPeerPushCredit(
+ (credit = {
+ ...credit,
+ status: PeerPushCreditStatus.SuspendedWithdrawing,
+ }),
+ ),
+ ),
+ );
+ assert.equal(t.txState.major, TransactionMajorState.Suspended);
+ assert.equal(t.txState.minor, TransactionMinorState.KycRequired);
+ const retryId = constructTaskIdentifier({
+ tag: PendingTaskType.ExchangeWalletKyc,
+ exchangeBaseUrl: exchangeUrl,
+ });
+ let reserveId = 0;
+ t = await change(() =>
+ f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertPeerPushCredit(
+ (credit = {
+ ...credit,
+ status: PeerPushCreditStatus.PendingWithdrawing,
+ }),
+ );
+ await tx.upsertWithdrawalGroup(
+ (withdrawal = {
+ ...withdrawal,
+ status: WithdrawalGroupStatus.PendingBalanceKyc,
+ }),
+ );
+ reserveId = await tx.upsertReserve({
+ reservePub: master,
+ reservePriv: master,
+ status: ReserveRecordStatus.PendingLegi,
+ thresholdRequested: "TESTKUDOS:10",
+ kycAccessToken: "balance-token",
+ amlReview: false,
+ });
+ await tx.upsertExchange({
+ ...f.exchange,
+ currentMergeReserveRowId: reserveId,
+ });
+ }),
+ );
+ assert.equal(t.kycUrl, `${exchangeUrl}kyc-spa/balance-token`);
+ t = await change(() =>
+ f.wex.runWalletDbTx((tx) =>
+ tx.upsertOperationRetry({
+ id: retryId,
+ retryInfo: DbRetryInfo.reset(),
+ lastError: {
+ code: TalerErrorCode.WALLET_UNEXPECTED_EXCEPTION,
+ hint: "KYC connection failed",
+ },
+ }),
+ ),
+ );
+ assert.equal(t.error?.hint, "KYC connection failed");
+ assert.ok(t.retryInfo);
+ const body = {
+ aml_review: true,
+ rule_gen: 1,
+ access_token: "balance-token-new",
+ };
+ const http: HttpRequestLibrary = {
+ async fetch(url, opt) {
+ return {
+ requestUrl: url,
+ requestMethod: opt?.method ?? "GET",
+ status: HttpStatusCode.Accepted,
+ headers: new HeadersImpl(),
+ async json() {
+ return body;
+ },
+ async text() {
+ return JSON.stringify(body);
+ },
+ async bytes() {
+ return new TextEncoder().encode(JSON.stringify(body));
+ },
+ };
+ },
+ };
+ t = await change(() =>
+ processExchangeKyc({ ...f.wex, http }, exchangeUrl),
+ );
+ assert.equal(t.kycAmlReview, true);
+ assert.equal(t.kycUrl, `${exchangeUrl}kyc-spa/balance-token-new`);
+ body.aml_review = false;
+ t = await change(() =>
+ processExchangeKyc({ ...f.wex, http }, exchangeUrl),
+ );
+ assert.equal(t.kycAmlReview, false);
+ t = await change(() =>
+ f.wex.runWalletDbTx((tx) => tx.deleteOperationRetry(retryId)),
+ );
+ assert.equal(t.error, undefined);
+ assert.equal(t.retryInfo, undefined);
+ t = await change(() =>
+ f.wex.runWalletDbTx(async (tx) => {
+ const reserve = await tx.getReserve(reserveId);
+ await tx.upsertReserve({
+ ...reserve!,
+ status: ReserveRecordStatus.Done,
+ });
+ }),
+ );
+ assert.equal(t.kycUrl, undefined);
+ assert.equal(t.kycAmlReview, undefined);
+ t = await change(() =>
+ f.wex.runWalletDbTx((tx) =>
+ tx.upsertPeerPushCredit({
+ ...credit,
+ status: PeerPushCreditStatus.Done,
+ }),
+ ),
+ );
+ assert.equal(t.kycUrl, undefined);
+ assert.equal(t.kycAmlReview, undefined);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+}
+
+for (const makeRunner of runnerFactories) {
+ test(
+ `${makeRunner.name}: generic snapshots cover every transaction type without writes or network`,
+ { timeout: 15000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const R = await import("./db/records.js");
+ const U = await import("@gnu-taler/taler-util");
+ const stamp = f.credit.timestamp;
+ const peer = {
+ exchangeBaseUrl: exchangeUrl,
+ contractTermsHash: contractHash,
+ contractPriv: master,
+ contractPub: master,
+ pursePub: master,
+ pursePriv: master,
+ mergePub: master,
+ mergePriv: master,
+ contractEncNonce: master,
+ };
+ const withdrawal: WalletWithdrawalGroup = {
+ withdrawalGroupId: "manual",
+ wgInfo: { withdrawalType: WithdrawalRecordType.BankManual },
+ secretSeed: master,
+ reservePub: master,
+ reservePriv: master,
+ exchangeBaseUrl: exchangeUrl,
+ timestampStart: stamp,
+ status: WithdrawalGroupStatus.PendingReady,
+ instructedAmount: "TESTKUDOS:5",
+ denomsSel: {
+ selectedDenoms: [],
+ hasDenomWithAgeRestriction: false,
+ totalCoinValue: "TESTKUDOS:4.8",
+ totalWithdrawCost: "TESTKUDOS:5",
+ },
+ };
+ await f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertWithdrawalGroup(withdrawal);
+ await tx.upsertWithdrawalGroup({
+ ...withdrawal,
+ withdrawalGroupId: "internal",
+ wgInfo: { withdrawalType: WithdrawalRecordType.PeerPushCredit },
+ });
+ await tx.upsertRefreshGroup({
+ refreshGroupId: "refresh",
+ currency: "TESTKUDOS",
+ reason: U.RefreshReason.Manual,
+ operationStatus: R.RefreshOperationStatus.Pending,
+ oldCoinPubs: [],
+ inputPerCoin: [],
+ expectedOutputPerCoin: [],
+ statusPerCoin: [],
+ refundRequests: {},
+ timestampCreated: stamp,
+ timestampFinished: undefined,
+ });
+ await tx.upsertRecoupGroup({
+ recoupGroupId: "recoup",
+ exchangeBaseUrl: exchangeUrl,
+ operationStatus: R.RecoupOperationStatus.Pending,
+ timestampStarted: stamp,
+ timestampFinished: undefined,
+ coinPubs: [],
+ recoupFinishedPerCoin: [],
+ scheduleRefreshCoins: [],
+ });
+ await tx.upsertDenomLossEvent({
+ denomLossEventId: "loss",
+ currency: "TESTKUDOS",
+ denomPubHashes: [],
+ status: R.DenomLossStatus.Done,
+ timestampCreated: stamp,
+ amount: "TESTKUDOS:1",
+ eventType: U.DenomLossEventType.DenomExpired,
+ exchangeBaseUrl: exchangeUrl,
+ });
+ await tx.upsertRefundGroup({
+ refundGroupId: "refund",
+ proposalId: "payment",
+ status: R.RefundGroupStatus.Pending,
+ timestampCreated: stamp,
+ amountRaw: "TESTKUDOS:1",
+ amountEffective: "TESTKUDOS:0.9",
+ });
+ await tx.upsertPeerPushDebit({
+ ...peer,
+ amount: "TESTKUDOS:5",
+ totalCost: "TESTKUDOS:5.1",
+ status: R.PeerPushDebitStatus.PendingReady,
+ timestampCreated: stamp,
+ purseExpiration: R.timestampProtocolToDb({ t_s: 2000000000 }),
+ });
+ await tx.upsertPeerPullCredit({
+ ...peer,
+ amount: "TESTKUDOS:5",
+ estimatedAmountEffective: "TESTKUDOS:4.8",
+ mergeTimestamp: stamp,
+ mergeReserveRowId: 1,
+ withdrawalGroupId: undefined,
+ status: R.PeerPullPaymentCreditStatus.PendingReady,
+ });
+ await tx.upsertPeerPullDebit({
+ ...peer,
+ peerPullDebitId: "pull",
+ amount: "TESTKUDOS:5",
+ totalCostEstimated: "TESTKUDOS:5.1",
+ timestampCreated: stamp,
+ status: R.PeerPullDebitRecordStatus.Done,
+ });
+ await tx.upsertPurchase({
+ proposalId: "payment",
+ merchantBaseUrl: "https://merchant.example/",
+ orderId: "order",
+ noncePriv: master,
+ noncePub: master,
+ secretSeed: master,
+ timestamp: stamp,
+ purchaseStatus: R.PurchaseStatus.PendingDownloadingProposal,
+ shared: false,
+ createdFromShared: false,
+ } as import("./db/records.js").WalletPurchase);
+ await tx.upsertDepositGroup({
+ depositGroupId: "deposit",
+ currency: "TESTKUDOS",
+ operationStatus: R.DepositOperationStatus.Finished,
+ timestampCreated: stamp,
+ wireTransferDeadline: R.timestampProtocolToDb({ t_s: 2000000000 }),
+ wire: {
+ payto_uri: "payto://iban/DE76500202009817493529",
+ salt: master,
+ },
+ merchantPub: master,
+ merchantPriv: master,
+ noncePub: master,
+ noncePriv: master,
+ contractTermsHash: master,
+ amount: "TESTKUDOS:5",
+ counterpartyEffectiveDepositAmount: "TESTKUDOS:5",
+ totalPayCost: "TESTKUDOS:5.1",
+ infoPerExchange: {},
+ } as import("./db/records.js").WalletDepositGroup);
+ });
+ const ids = [
+ transactionId,
+ "txn:withdrawal:manual",
+ "txn:internal-withdrawal:internal",
+ "txn:refresh:refresh",
+ "txn:recoup:recoup",
+ "txn:denom-loss:loss",
+ "txn:refund:refund",
+ `txn:peer-push-debit:${master}`,
+ `txn:peer-pull-credit:${master}`,
+ "txn:peer-pull-debit:pull",
+ "txn:payment:payment",
+ "txn:deposit:deposit",
+ ];
+ const before = await f.ws.db.exportDatabase();
+ for (const id of ids) {
+ await observeTransaction(f.wex, {
+ transactionId: id as TransactionIdStr,
+ observationId: id,
+ });
+ await f.settle();
+ const notification = f.notifications.find(
+ (n) =>
+ n.type === U.NotificationType.ObservationSnapshot &&
+ n.observationId === id,
+ );
+ assert.ok(
+ notification?.type === U.NotificationType.ObservationSnapshot &&
+ notification.snapshot,
+ id,
+ );
+ assert.equal(
+ notification.snapshot.type,
+ parseTransactionIdentifier(id)?.tag,
+ );
+ assert.equal(notification.snapshot.transaction.transactionId, id);
+ const wire = JSON.stringify(notification.snapshot);
+ for (const key of [
+ '"stId"',
+ '"kycAccessToken"',
+ '"kycPaytoHash"',
+ '"contractTerms"',
+ '"contractPriv"',
+ ])
+ assert.ok(!wire.includes(key), key);
+ }
+ assert.deepEqual(await f.ws.db.exportDatabase(), before);
+ let nextPayment = f.nextSnapshot("txn:payment:payment");
+ // Downloaded payment choices and configuration must update without a public state transition.
+ const now = Math.floor(Date.now() / 1000);
+ await f.wex.runWalletDbTx(async (tx) => {
+ const purchase = await tx.getPurchase("payment");
+ assert.ok(purchase);
+ purchase.download = {
+ contractTermsHash: master,
+ contractTermsMerchantSig: master,
+ currency: "TESTKUDOS",
+ };
+ purchase.purchaseStatus = R.PurchaseStatus.DialogProposed;
+ await tx.upsertContractTerms({
+ h: master,
+ contractTermsRaw: {
+ version: 0,
+ amount: "TESTKUDOS:0",
+ max_fee: "TESTKUDOS:0",
+ order_id: "order",
+ nonce: master,
+ merchant_base_url: purchase.merchantBaseUrl,
+ h_wire: master,
+ wire_method: "iban",
+ summary: "Free item",
+ fulfillment_message: "Enjoy",
+ pay_deadline: { t_s: now + 300 },
+ refund_deadline: { t_s: now + 600 },
+ wire_transfer_deadline: { t_s: now + 86400 },
+ timestamp: { t_s: now },
+ merchant: { name: "test" },
+ merchant_pub: master,
+ exchanges: [],
+ },
+ });
+ await tx.upsertPurchase(purchase);
+ });
+ await f.settle();
+ await nextPayment;
+ const latestPayment = () =>
+ f.notifications
+ .filter(
+ (n): n is GenericTransactionSnapshotNotification =>
+ n.type === U.NotificationType.ObservationSnapshot &&
+ n.observationId === "txn:payment:payment",
+ )
+ .at(-1)!;
+ const payment = latestPayment();
+ assert.ok(payment.snapshot?.type === U.TransactionType.Payment);
+ assert.equal(
+ payment.snapshot.payment?.choices[0].status,
+ U.ChoiceSelectionDetailType.PaymentPossible,
+ );
+ assert.deepEqual(payment.snapshot.confirmation.unavailableReasons, []);
+ assert.ok(
+ !JSON.stringify(payment.snapshot).includes('"contractTerms"'),
+ );
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await f.wex.runWalletDbTx((tx) =>
+ tx.upsertConfig({
+ key: R.ConfigRecordKey.DonauConfig,
+ value: {
+ donauBaseUrl: "https://donau.example/",
+ donauTaxId: "tax-id",
+ donauTaxIdHash: master,
+ donauSalt: master,
+ },
+ }),
+ );
+ await f.settle();
+ await nextPayment;
+ const configured = latestPayment();
+ assert.ok(!JSON.stringify(configured.snapshot).includes("taxPayerId"));
+ assert.ok(configured.revision > payment.revision);
+ assert.ok(configured.snapshot?.type === U.TransactionType.Payment);
+ assert.deepEqual(
+ configured.snapshot.transaction.txState,
+ payment.snapshot.transaction.txState,
+ );
+ assert.equal(
+ configured.snapshot.currentDonauInfo?.donauBaseUrl,
+ "https://donau.example/",
+ );
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await f.wex.runWalletDbTx(async (tx) => {
+ const ct = await tx.getContractTerms(master);
+ assert.ok(ct);
+ ct.contractTermsRaw.pay_deadline = { t_s: 1 };
+ await tx.upsertContractTerms(ct);
+ });
+ await f.settle();
+ await nextPayment;
+ const expiredPayment = latestPayment().snapshot;
+ assert.ok(expiredPayment?.type === U.TransactionType.Payment);
+ assert.deepEqual(expiredPayment.confirmation.unavailableReasons, [
+ "expired",
+ ]);
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await f.wex.runWalletDbTx(async (tx) => {
+ const ct = await tx.getContractTerms(master);
+ assert.ok(ct);
+ ct.contractTermsRaw.pay_deadline = { t_s: now + 300 };
+ ct.contractTermsRaw.amount = "TESTKUDOS:5";
+ ct.contractTermsRaw.exchanges = [
+ { url: exchangeUrl, master_pub: master, priority: 0 },
+ ];
+ await tx.upsertContractTerms(ct);
+ const details: WalletExchangeDetails = {
+ ...f.details,
+ wireInfo: {
+ accounts: [
+ {
+ payto_uri: "payto://iban/DE76500202009817493529",
+ master_sig: master,
+ credit_restrictions: [],
+ debit_restrictions: [],
+ },
+ ],
+ feesForType: {
+ iban: [
+ {
+ wireFee: "TESTKUDOS:0",
+ closingFee: "TESTKUDOS:0",
+ startStamp: { t_s: now - 60 },
+ endStamp: { t_s: now + 3600 },
+ sig: master,
+ },
+ ],
+ },
+ },
+ };
+ await tx.upsertExchangeDetails(details);
+ });
+ await nextPayment;
+ const unpaid = latestPayment().snapshot;
+ assert.ok(unpaid?.type === U.TransactionType.Payment);
+ assert.equal(
+ unpaid.payment?.choices[0].status,
+ U.ChoiceSelectionDetailType.InsufficientBalance,
+ );
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await f.wex.runWalletDbTx(async (tx) => {
+ await tx.upsertDenomination({
+ exchangeBaseUrl: exchangeUrl,
+ exchangeMasterPub: master,
+ denomPubHash: master,
+ denomPub: {
+ cipher: U.DenomKeyType.Rsa,
+ rsa_public_key: master,
+ age_mask: 0,
+ },
+ currency: "TESTKUDOS",
+ value: "TESTKUDOS:5",
+ fees: {
+ feeWithdraw: "TESTKUDOS:0",
+ feeDeposit: "TESTKUDOS:0",
+ feeRefresh: "TESTKUDOS:0",
+ feeRefund: "TESTKUDOS:0",
+ },
+ stampStart: R.timestampProtocolToDb({ t_s: now - 60 }),
+ stampExpireWithdraw: R.timestampProtocolToDb({ t_s: now + 3600 }),
+ stampExpireDeposit: R.timestampProtocolToDb({ t_s: now + 7200 }),
+ stampExpireLegal: R.timestampProtocolToDb({ t_s: now + 10800 }),
+ isOffered: true,
+ isLost: false,
+ isRevoked: false,
+ masterSig: master,
+ verificationStatus: R.DenominationVerificationStatus.VerifiedGood,
+ });
+ await tx.upsertCoin({
+ coinPub: master,
+ coinPriv: master,
+ denomPubHash: master,
+ denomSig: { cipher: U.DenomKeyType.Rsa, rsa_signature: master },
+ exchangeBaseUrl: exchangeUrl,
+ exchangeMasterPub: master,
+ blindingKey: master,
+ exchangeWithdrawValues: { cipher: "RSA" },
+ coinEvHash: master,
+ status: U.CoinStatus.Fresh,
+ visible: 1,
+ maxAge: 0,
+ ageCommitmentProof: undefined,
+ coinSource: {
+ type: R.CoinSourceType.Withdraw,
+ withdrawalGroupId: "",
+ coinIndex: 0,
+ reservePub: master,
+ },
+ });
+ await tx.upsertCoinAvailability({
+ currency: "TESTKUDOS",
+ value: "TESTKUDOS:5",
+ denomPubHash: master,
+ exchangeBaseUrl: exchangeUrl,
+ exchangeMasterPub: master,
+ maxAge: 0,
+ freshCoinCount: 1,
+ visibleCoinCount: 1,
+ hasFreshCoins: 1,
+ });
+ });
+ await nextPayment;
+ const affordable = latestPayment().snapshot;
+ assert.ok(affordable?.type === U.TransactionType.Payment);
+ assert.deepEqual(
+ affordable.transaction.txState,
+ unpaid.transaction.txState,
+ );
+ assert.equal(
+ affordable.payment?.choices[0].status,
+ U.ChoiceSelectionDetailType.PaymentPossible,
+ JSON.stringify(affordable.payment),
+ );
+ // Validity changes must refresh choices even when the task loop is idle.
+ const depositExpiry = Math.floor(Date.now() / 1000) + 2;
+ await f.wex.runWalletDbTx(async (tx) => {
+ const denomination = await tx.getDenomination({
+ exchangeMasterPub: master,
+ denomPubHash: master,
+ });
+ assert.ok(denomination);
+ denomination.stampExpireDeposit = R.timestampProtocolToDb({
+ t_s: depositExpiry,
+ });
+ await tx.upsertDenomination(denomination);
+ });
+ await f.settle();
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await new Promise((resolve) =>
+ setTimeout(
+ resolve,
+ Math.max(0, depositExpiry * 1000 - Date.now()) + 50,
+ ),
+ );
+ await nextPayment;
+ assert.equal(latestPayment().snapshot?.type, U.TransactionType.Payment);
+ const expiredCoins = latestPayment().snapshot;
+ assert.ok(expiredCoins?.type === U.TransactionType.Payment);
+ assert.equal(
+ expiredCoins.payment?.choices[0].status,
+ U.ChoiceSelectionDetailType.InsufficientBalance,
+ );
+
+ // Diagnostic fee availability also changes without a database write.
+ const feeStart = Math.floor(Date.now() / 1000) + 2;
+ await f.wex.runWalletDbTx(async (tx) => {
+ const details = await tx.getExchangeDetailsByPointer(
+ exchangeUrl,
+ "TESTKUDOS",
+ master,
+ );
+ assert.ok(details);
+ details.globalFees = [
+ {
+ startDate: { t_s: feeStart },
+ endDate: { t_s: now + 3600 },
+ historyFee: "TESTKUDOS:0",
+ accountFee: "TESTKUDOS:0",
+ purseFee: "TESTKUDOS:0",
+ historyTimeout: { d_us: 1000000 },
+ purseTimeout: { d_us: 1000000 },
+ purseLimit: 5,
+ signature: master,
+ },
+ ];
+ await tx.upsertExchangeDetails(details);
+ });
+ await f.settle();
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await new Promise((resolve) =>
+ setTimeout(resolve, Math.max(0, feeStart * 1000 - Date.now()) + 50),
+ );
+ await nextPayment;
+ const availableFees = latestPayment().snapshot;
+ assert.ok(availableFees?.type === U.TransactionType.Payment);
+ const feeChoice = availableFees.payment?.choices[0];
+ assert.ok(
+ feeChoice?.status === U.ChoiceSelectionDetailType.InsufficientBalance,
+ );
+ assert.equal(
+ feeChoice.balanceDetails?.perExchange[exchangeUrl].missingGlobalFees,
+ false,
+ );
+
+ // A future wire-fee period can make the same coins usable again.
+ const wireStart = Math.floor(Date.now() / 1000) + 2;
+ await f.wex.runWalletDbTx(async (tx) => {
+ const denomination = await tx.getDenomination({
+ exchangeMasterPub: master,
+ denomPubHash: master,
+ });
+ assert.ok(denomination);
+ denomination.stampExpireDeposit = R.timestampProtocolToDb({
+ t_s: now + 7200,
+ });
+ await tx.upsertDenomination(denomination);
+ const details = await tx.getExchangeDetailsByPointer(
+ exchangeUrl,
+ "TESTKUDOS",
+ master,
+ );
+ assert.ok(details);
+ details.wireInfo.feesForType.iban[0].startStamp = { t_s: wireStart };
+ await tx.upsertExchangeDetails(details);
+ });
+ await f.settle();
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await new Promise((resolve) =>
+ setTimeout(resolve, Math.max(0, wireStart * 1000 - Date.now()) + 50),
+ );
+ await nextPayment;
+ const validWire = latestPayment().snapshot;
+ assert.ok(validWire?.type === U.TransactionType.Payment);
+ assert.equal(
+ validWire.payment?.choices[0].status,
+ U.ChoiceSelectionDetailType.PaymentPossible,
+ );
+
+ const payDeadline = Math.floor(Date.now() / 1000) + 2;
+ await f.wex.runWalletDbTx(async (tx) => {
+ const contract = await tx.getContractTerms(master);
+ assert.ok(contract);
+ contract.contractTermsRaw.pay_deadline = { t_s: payDeadline };
+ await tx.upsertContractTerms(contract);
+ });
+ await f.settle();
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await new Promise((resolve) =>
+ setTimeout(
+ resolve,
+ Math.max(0, payDeadline * 1000 - Date.now()) + 50,
+ ),
+ );
+ await nextPayment;
+ const timedOut = latestPayment().snapshot;
+ assert.ok(timedOut?.type === U.TransactionType.Payment);
+ assert.deepEqual(timedOut.confirmation.unavailableReasons, ["expired"]);
+
+ nextPayment = f.nextSnapshot("txn:payment:payment");
+ await f.wex.runWalletDbTx(async (tx) => {
+ const p = await tx.getPurchase("payment");
+ assert.ok(p);
+ p.purchaseStatus = R.PurchaseStatus.DialogUnclaimed;
+ await tx.upsertPurchase(p);
+ });
+ await nextPayment;
+ const handedOff = latestPayment().snapshot;
+ assert.ok(handedOff?.type === TransactionType.Payment);
+ assert.deepEqual(handedOff.confirmation.unavailableReasons, [
+ "not-proposed",
+ ]);
+ // Existing bank fields are persisted by both backends, including after reopening the transaction.
+ await f.wex.runWalletDbTx((tx) =>
+ tx.upsertWithdrawalGroup({
+ ...withdrawal,
+ withdrawalGroupId: "bank",
+ wgInfo: {
+ withdrawalType: R.WithdrawalRecordType.BankIntegrated,
+ bankInfo: {
+ talerWithdrawUri: "taler://withdraw/bank.example/op",
+ confirmUrl: "https://bank.example/confirm",
+ timestampReserveInfoPosted: undefined,
+ timestampBankConfirmed: undefined,
+ currency: "TESTKUDOS",
+ wireTypes: ["iban"],
+ presentation: {
+ operationId: "op",
+ status: "pending",
+ currency: "TESTKUDOS",
+ amount: "TESTKUDOS:5",
+ editableAmount: false,
+ editableExchange: true,
+ maxAmount: undefined,
+ wireFee: undefined,
+ },
+ },
+ },
+ }),
+ );
+ await observeTransaction(f.wex, {
+ transactionId: "txn:withdrawal:bank" as TransactionIdStr,
+ observationId: "bank",
+ });
+ await f.settle();
+ const bank = f.notifications.find(
+ (n) =>
+ n.type === U.NotificationType.ObservationSnapshot &&
+ n.observationId === "bank",
+ );
+ assert.ok(
+ bank?.type === U.NotificationType.ObservationSnapshot &&
+ bank.snapshot?.type === U.TransactionType.Withdrawal,
+ );
+ assert.equal(bank.snapshot.bank?.status, "pending");
+ const deleted = new Promise<void>((resolve) => {
+ f.ws.addPublicNotificationListener((n) => {
+ if (
+ n.type === U.NotificationType.ObservationSnapshot &&
+ n.observationId === "txn:refund:refund" &&
+ n.snapshot === null
+ )
+ resolve();
+ });
+ });
+ await f.wex.runWalletDbTx((tx) => tx.deleteRefundGroup("refund"));
+ await f.settle();
+ await deleted;
+ const deletedPayment = f.nextSnapshot(
+ "txn:payment:payment",
+ undefined,
+ true,
+ );
+ await f.wex.runWalletDbTx((tx) => tx.deletePurchase("payment"));
+ assert.equal((await deletedPayment).snapshot, null);
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+}
+
+for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: invoice observations retain the preparation estimate without checking affordability`, async () => {
+ const f = await fixture(makeRunner);
+ const { PeerPullDebitRecordStatus } = await import("./db/records.js");
+ try {
+ // No spendable coins or current purse balance are needed to present the invoice.
+ await f.wex.runWalletDbTx((tx) =>
+ tx.upsertPeerPullDebit({
+ peerPullDebitId: "review",
+ exchangeBaseUrl: exchangeUrl,
+ contractTermsHash: contractHash,
+ contractPriv: master,
+ pursePub: master,
+ amount: "TESTKUDOS:5",
+ totalCostEstimated: "TESTKUDOS:5.2",
+ timestampCreated: f.credit.timestamp,
+ status: PeerPullDebitRecordStatus.DialogProposed,
+ }),
+ );
+ const read = () =>
+ f.wex.runWalletDbTx((tx) =>
+ readTransactionSnapshot(f.wex, tx, "txn:peer-pull-debit:review"),
+ );
+ const snapshot = await read();
+ assert.ok(snapshot?.type === TransactionType.PeerPullDebit);
+ assert.equal(snapshot.transaction.amountRaw, "TESTKUDOS:5");
+ assert.equal(snapshot.transaction.amountEffective, "TESTKUDOS:5.2");
+ assert.deepEqual(snapshot.confirmation.unavailableReasons, []);
+ assert.equal("preview" in snapshot, false);
+
+ await f.wex.runWalletDbTx(async (tx) => {
+ const contract = await tx.getContractTerms(contractHash);
+ assert.ok(contract);
+ contract.contractTermsRaw.purse_expiration = { t_s: 1 };
+ await tx.upsertContractTerms(contract);
+ });
+ const expired = await read();
+ assert.ok(expired?.type === TransactionType.PeerPullDebit);
+ assert.deepEqual(expired.confirmation.unavailableReasons, ["expired"]);
+ assert.equal(expired.transaction.amountEffective, "TESTKUDOS:5.2");
+ } finally {
+ await f.ws.shutdown();
+ }
+ });
+}
+
+for (const makeRunner of runnerFactories) {
+ test(
+ `${makeRunner.name}: peer confirmation expires without a database write`,
+ { timeout: 5000 },
+ async () => {
+ const f = await fixture(makeRunner);
+ try {
+ const expiration = Math.floor(Date.now() / 1000) + 2;
+ await f.wex.runWalletDbTx(async (tx) => {
+ const contract = await tx.getContractTerms(contractHash);
+ assert.ok(contract);
+ contract.contractTermsRaw.purse_expiration = { t_s: expiration };
+ await tx.upsertContractTerms(contract);
+ });
+ const initial = await f.observe();
+ assert.deepEqual(initial.snapshot?.confirmation.unavailableReasons, []);
+ const expired = f.nextSnapshot("view", 2);
+ await new Promise((resolve) =>
+ setTimeout(resolve, Math.max(0, expiration * 1000 - Date.now()) + 50),
+ );
+ assert.deepEqual(
+ (await expired).snapshot?.confirmation.unavailableReasons,
+ ["expired"],
+ );
+ } finally {
+ await f.ws.shutdown();
+ }
+ },
+ );
+}
diff --git a/packages/taler-wallet-core/src/observe-transaction.ts b/packages/taler-wallet-core/src/observe-transaction.ts
@@ -0,0 +1,444 @@
+/*
+ * This file is part of GNU Taler
+ * (C) 2026 Taler Systems S.A.
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+import {
+ AbsoluteTime,
+ Amounts,
+ assertUnreachable,
+ CancellationToken,
+ EmptyObject,
+ ExchangeTosStatus,
+ ObservedExchange,
+ ObservedPaymentTransaction,
+ ObservedPeerPullDebitTransaction,
+ ObservedPeerPushCreditTransaction,
+ ObservedTransaction,
+ ObservedTransactionCommon,
+ ObservedWithdrawalTransaction,
+ ObserveTransactionRequest,
+ observedTransaction,
+ PaymentSnapshot,
+ PeerPushCreditConfirmationUnavailableReason,
+ ScopeType,
+ StopObservationRequest,
+ Transaction,
+ TransactionConfirmationUnavailableReason,
+ TransactionMajorState,
+ TransactionMinorState,
+ TransactionSnapshot,
+ TransactionType,
+ WithdrawalSnapshot,
+} from "@gnu-taler/taler-util";
+import {
+ ConfigRecordKey,
+ WithdrawalRecordType,
+ timestampPreciseFromDb,
+} from "./db/records.js";
+import { WalletDbTransaction } from "./db/transaction.js";
+import {
+ loadReadyExchangeSummary,
+ lookupExchangeByUriInTx,
+} from "./exchanges.js";
+import { getPeerCreditLimitInfo } from "./kyc.js";
+import {
+ ObservationDeadlines,
+ trackPaymentChoiceDeadlines,
+} from "./observation-deadlines.js";
+import {
+ summarizeObservationError,
+ validateObservationId,
+} from "./observations.js";
+import { getChoicesForPaymentInTx } from "./pay-merchant.js";
+import { isPurseGoneByExpiration } from "./pay-peer-common.js";
+import {
+ lookupTransactionInTx,
+ maybeTaskFromTransaction,
+ makeInvalidTransactionIdError,
+ parseTransactionIdentifier,
+} from "./transactions.js";
+import {
+ getNormalWalletExecutionContext,
+ WalletExecutionContext,
+} from "./wallet.js";
+
+/** Assemble every variant from the same committed database view. */
+export async function readTransactionSnapshot(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ transactionId: string,
+ deadlines = new ObservationDeadlines(),
+): Promise<TransactionSnapshot | null> {
+ const fullTransaction = await lookupTransactionInTx(wex, tx, {
+ transactionId,
+ });
+ if (!fullTransaction) return null;
+ applyPeerExpiration(fullTransaction, deadlines);
+ await addRetryInfo(tx, fullTransaction);
+ const exchanges = await readTransactionExchanges(wex, tx, fullTransaction);
+ const transaction = observedTransaction(fullTransaction);
+
+ // Keep the outer discriminator and projected transaction paired explicitly.
+ // Only the variants with additional presentation data need another reader.
+ switch (transaction.type) {
+ case TransactionType.Payment:
+ return readPaymentSnapshot(wex, tx, transaction, exchanges, deadlines);
+ case TransactionType.Withdrawal:
+ return readWithdrawalSnapshot(tx, transaction, exchanges);
+ case TransactionType.PeerPushCredit:
+ return {
+ ...makeSnapshotBase(transaction, exchanges),
+ confirmation: await readPeerConfirmation(
+ wex,
+ tx,
+ transaction,
+ exchanges,
+ ),
+ };
+ case TransactionType.PeerPullDebit:
+ return {
+ ...makeSnapshotBase(transaction, exchanges),
+ confirmation: await readPeerConfirmation(
+ wex,
+ tx,
+ transaction,
+ exchanges,
+ ),
+ };
+ case TransactionType.PeerPullCredit:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.PeerPushDebit:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.InternalWithdrawal:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.Deposit:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.Refund:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.Refresh:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.Recoup:
+ return makeSnapshotBase(transaction, exchanges);
+ case TransactionType.DenomLoss:
+ return makeSnapshotBase(transaction, exchanges);
+ default:
+ return assertUnreachable(transaction);
+ }
+}
+
+/** Keep the outer discriminator paired with the observed transaction. */
+function makeSnapshotBase<T extends ObservedTransaction>(
+ transaction: T,
+ exchanges: ObservedExchange[],
+): {
+ type: T["type"];
+ transaction: T;
+ exchanges: ObservedExchange[];
+} {
+ return {
+ type: transaction.type,
+ transaction,
+ exchanges,
+ };
+}
+
+function applyPeerExpiration(
+ transaction: Transaction,
+ deadlines: ObservationDeadlines,
+): void {
+ switch (transaction.type) {
+ case TransactionType.PeerPushCredit:
+ case TransactionType.PeerPullDebit:
+ deadlines.addProtocolTimestamp(transaction.info.expiration);
+ break;
+ case TransactionType.PeerPullCredit:
+ case TransactionType.PeerPushDebit:
+ deadlines.addProtocolTimestamp(transaction.info.expiration);
+ // Link availability can expire before the task persists a state transition.
+ if (
+ transaction.info.expiration &&
+ isPurseGoneByExpiration(transaction.info.expiration)
+ )
+ transaction.talerUri = undefined;
+ break;
+ }
+}
+
+async function addRetryInfo(
+ tx: WalletDbTransaction,
+ transaction: Transaction,
+): Promise<void> {
+ if (!transaction.error || transaction.retryInfo) return;
+ const taskId = maybeTaskFromTransaction(transaction.transactionId);
+ if (!taskId) return;
+ const retry = await tx.getOperationRetry(taskId);
+ if (retry?.lastError?.code === transaction.error.code) {
+ transaction.retryInfo = {
+ retryCounter: retry.retryInfo.retryCounter,
+ nextRetry: timestampPreciseFromDb(retry.retryInfo.nextRetry),
+ };
+ }
+}
+
+async function purchaseExchangeUrls(
+ tx: WalletDbTransaction,
+ proposalId: string,
+): Promise<string[]> {
+ const purchase = await tx.getPurchase(proposalId);
+ const contract = purchase?.download
+ ? await tx.getContractTerms(purchase.download.contractTermsHash)
+ : undefined;
+ const urls = [...(purchase?.exchanges ?? [])];
+ for (const exchange of contract?.contractTermsRaw.exchanges ?? [])
+ urls.push(exchange.url);
+ return urls;
+}
+
+/** Exchanges can be relevant before they have appeared in transaction scopes. */
+async function transactionExchangeUrls(
+ tx: WalletDbTransaction,
+ transaction: Transaction,
+): Promise<Set<string>> {
+ const urls = new Set<string>();
+ if ("exchangeBaseUrl" in transaction && transaction.exchangeBaseUrl)
+ urls.add(transaction.exchangeBaseUrl);
+ for (const scope of transaction.scopes)
+ if (
+ scope.type === ScopeType.Exchange ||
+ scope.type === ScopeType.ExchangeLegacyKeys
+ )
+ urls.add(scope.url);
+
+ const id = parseTransactionIdentifier(transaction.transactionId);
+ switch (id?.tag) {
+ case TransactionType.Payment:
+ for (const url of await purchaseExchangeUrls(tx, id.proposalId))
+ urls.add(url);
+ break;
+ case TransactionType.Refund: {
+ const refund = await tx.getRefundGroup(id.refundGroupId);
+ if (refund)
+ for (const url of await purchaseExchangeUrls(tx, refund.proposalId))
+ urls.add(url);
+ break;
+ }
+ case TransactionType.Deposit: {
+ const deposit = await tx.getDepositGroup(id.depositGroupId);
+ for (const url of Object.keys(deposit?.infoPerExchange ?? {}))
+ urls.add(url);
+ break;
+ }
+ case TransactionType.Refresh: {
+ const refresh = await tx.getRefreshGroup(id.refreshGroupId);
+ for (const url of Object.keys(refresh?.infoPerExchange ?? {}))
+ urls.add(url);
+ break;
+ }
+ case TransactionType.Recoup: {
+ const recoup = await tx.getRecoupGroup(id.recoupGroupId);
+ if (recoup) urls.add(recoup.exchangeBaseUrl);
+ break;
+ }
+ }
+ return urls;
+}
+
+async function readTransactionExchanges(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ transaction: Transaction,
+): Promise<ObservedExchange[]> {
+ const exchanges: ObservedExchange[] = [];
+ for (const url of await transactionExchangeUrls(tx, transaction)) {
+ const exchange = await lookupExchangeByUriInTx(wex, tx, url);
+ if (!exchange) continue;
+ const record = await tx.getExchange(url);
+ let limits: ReturnType<typeof getPeerCreditLimitInfo> | undefined;
+ if (
+ record &&
+ (transaction.type === TransactionType.PeerPushCredit ||
+ transaction.type === TransactionType.PeerPullCredit)
+ ) {
+ const ready = await loadReadyExchangeSummary(tx, record);
+ if (ready) limits = getPeerCreditLimitInfo(ready, transaction.amountRaw);
+ }
+ exchanges.push({
+ exchangeBaseUrl: url,
+ tosStatus: exchange.tosStatus,
+ tosCurrentEtag: record?.tosCurrentEtag,
+ unconfirmedKeyChange: exchange.unconfirmedKeyChange,
+ exchangeUpdateStatus: exchange.exchangeUpdateStatus,
+ currencySpec: exchange.currencySpec,
+ walletKycRequestedThreshold: exchange.walletKycRequestedThreshold,
+ kycHardLimit: limits?.kycHardLimit,
+ kycSoftLimit: limits?.kycSoftLimit,
+ lastUpdateError: summarizeObservationError(
+ exchange.lastUpdateErrorInfo?.error,
+ ),
+ });
+ }
+ return exchanges.sort((a, b) =>
+ a.exchangeBaseUrl.localeCompare(b.exchangeBaseUrl),
+ );
+}
+
+function isProposed(transaction: ObservedTransactionCommon): boolean {
+ return (
+ transaction.txState.major === TransactionMajorState.Dialog &&
+ transaction.txState.minor === TransactionMinorState.Proposed
+ );
+}
+
+async function readPeerConfirmation(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ transaction:
+ | ObservedPeerPushCreditTransaction
+ | ObservedPeerPullDebitTransaction,
+ exchanges: ObservedExchange[],
+): Promise<{
+ unavailableReasons: PeerPushCreditConfirmationUnavailableReason[];
+}> {
+ if (!isProposed(transaction)) return { unavailableReasons: ["not-proposed"] };
+ const reasons: PeerPushCreditConfirmationUnavailableReason[] = [];
+ if (
+ transaction.info.expiration &&
+ isPurseGoneByExpiration(transaction.info.expiration)
+ )
+ reasons.push("expired");
+ const record = await tx.getExchange(transaction.exchangeBaseUrl);
+ if (!record || !(await loadReadyExchangeSummary(tx, record)))
+ reasons.push("exchange-not-ready");
+ const exchange = exchanges.find(
+ (e) => e.exchangeBaseUrl === transaction.exchangeBaseUrl,
+ );
+ if (exchange?.unconfirmedKeyChange)
+ reasons.push("exchange-keys-not-accepted");
+ if (
+ exchange &&
+ wex.ws.refcntIgnoreTos === 0 &&
+ exchange.tosStatus !== ExchangeTosStatus.Accepted &&
+ exchange.tosStatus !== ExchangeTosStatus.MissingTos
+ )
+ reasons.push("exchange-tos-not-accepted");
+ if (
+ transaction.type === TransactionType.PeerPushCredit &&
+ exchange?.kycHardLimit &&
+ Amounts.cmp(transaction.amountRaw, exchange.kycHardLimit) > 0
+ )
+ reasons.push("kyc-hard-limit");
+ return { unavailableReasons: reasons };
+}
+
+async function readPaymentSnapshot(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ transaction: ObservedPaymentTransaction,
+ exchanges: ObservedExchange[],
+ deadlines: ObservationDeadlines,
+): Promise<PaymentSnapshot> {
+ // Completed payments retain their selected amounts. Only dialogs need choices.
+ const payment =
+ transaction.info &&
+ transaction.txState.major === TransactionMajorState.Dialog
+ ? await getChoicesForPaymentInTx(
+ wex,
+ trackPaymentChoiceDeadlines(tx, deadlines),
+ transaction.transactionId,
+ )
+ : undefined;
+ const reasons: TransactionConfirmationUnavailableReason[] = [];
+ if (payment)
+ deadlines.addProtocolTimestamp(payment.contractTerms.pay_deadline);
+ if (!isProposed(transaction)) reasons.push("not-proposed");
+ else if (!payment) reasons.push("contract-unavailable");
+ else if (
+ AbsoluteTime.isExpired(
+ AbsoluteTime.fromProtocolTimestamp(payment.contractTerms.pay_deadline),
+ )
+ )
+ reasons.push("expired");
+ const config = await tx.getConfig(ConfigRecordKey.DonauConfig);
+ return {
+ ...makeSnapshotBase(transaction, exchanges),
+ payment: payment
+ ? {
+ choices: payment.choices,
+ defaultChoiceIndex: payment.defaultChoiceIndex,
+ automaticExecution: payment.automaticExecution,
+ automaticExecutableIndex: payment.automaticExecutableIndex,
+ }
+ : null,
+ confirmation: { unavailableReasons: reasons },
+ currentDonauInfo: config
+ ? { donauBaseUrl: config.value.donauBaseUrl }
+ : undefined,
+ };
+}
+
+async function readWithdrawalSnapshot(
+ tx: WalletDbTransaction,
+ transaction: ObservedWithdrawalTransaction,
+ exchanges: ObservedExchange[],
+): Promise<WithdrawalSnapshot> {
+ const id = parseTransactionIdentifier(transaction.transactionId);
+ const withdrawal =
+ id?.tag === TransactionType.Withdrawal
+ ? await tx.getWithdrawalGroup(id.withdrawalGroupId)
+ : undefined;
+ const bank =
+ withdrawal?.wgInfo.withdrawalType === WithdrawalRecordType.BankIntegrated
+ ? withdrawal.wgInfo.bankInfo.presentation
+ : undefined;
+ return {
+ ...makeSnapshotBase(transaction, exchanges),
+ bank,
+ };
+}
+
+export async function observeTransaction(
+ wex: WalletExecutionContext,
+ req: ObserveTransactionRequest,
+): Promise<EmptyObject> {
+ const parsed = parseTransactionIdentifier(req.transactionId);
+ if (!parsed) throw makeInvalidTransactionIdError(req.transactionId);
+ // An observation outlives its request and must not retain its progress or
+ // cancellation context. All reads use the wallet's current admitted database.
+ const ws = wex.ws;
+ const reader = getNormalWalletExecutionContext(
+ ws,
+ CancellationToken.CONTINUE,
+ undefined,
+ { observe() {} },
+ );
+ let deadline: number | undefined;
+ await ws.observations.registerTransaction(
+ req.observationId,
+ req.transactionId,
+ () =>
+ ws.runStandaloneWalletDbTx(async (tx) => {
+ const deadlines = new ObservationDeadlines();
+ const snapshot = await readTransactionSnapshot(
+ reader,
+ tx,
+ req.transactionId,
+ deadlines,
+ );
+ deadline = deadlines.nextRefreshAt;
+ return snapshot;
+ }),
+ () => deadline,
+ );
+ return {};
+}
+
+export async function stopObservation(
+ wex: WalletExecutionContext,
+ req: StopObservationRequest,
+): Promise<EmptyObject> {
+ validateObservationId(req.observationId);
+ wex.ws.observations.stop(req.observationId);
+ return {};
+}
diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts
@@ -23,10 +23,7 @@
/**
* Imports.
*/
-import {
- observePeerPushCredit,
- stopObservation,
-} from "./observe-peer-push-credit.js";
+import { observeTransaction, stopObservation } from "./observe-transaction.js";
import {
AbortTransactionRequest,
AcceptBankIntegratedWithdrawalRequest,
@@ -241,7 +238,7 @@ import {
codecForPreparePayRequest,
codecForPreparePayTemplateRequest,
codecForPreparePeerPullPaymentRequest,
- codecForObservePeerPushCreditRequest,
+ codecForObserveTransactionRequest,
codecForStopObservationRequest,
codecForPreparePeerPushCreditRequest,
codecForPrepareRefundRequest,
@@ -3103,9 +3100,9 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = {
codec: codecForInitiatePeerPushDebitRequest(),
handler: initiatePeerPushDebit,
},
- [WalletApiOperation.ObservePeerPushCredit]: {
- codec: codecForObservePeerPushCreditRequest(),
- handler: observePeerPushCredit,
+ [WalletApiOperation.ObserveTransaction]: {
+ codec: codecForObserveTransactionRequest(),
+ handler: observeTransaction,
},
[WalletApiOperation.StopObservation]: {
codec: codecForStopObservationRequest(),
diff --git a/packages/taler-wallet-core/src/transaction-reasons.test.ts b/packages/taler-wallet-core/src/transaction-reasons.test.ts
@@ -339,6 +339,57 @@ for (const makeRunner of runnerFactories) {
}
});
+ test(`${makeRunner.name}: reserve registration publishes the bank result and confirmation link`, async () => {
+ const f = await fixture();
+ try {
+ for (const status of ["selected", "confirmed", "aborted"] as const) {
+ const group = withdrawal(WithdrawalGroupStatus.PendingRegisteringBank);
+ assert.ok(
+ group.wgInfo.withdrawalType === WithdrawalRecordType.BankIntegrated,
+ );
+ group.wgInfo.bankInfo.presentation = {
+ operationId: "operation",
+ status: "pending",
+ currency: "TESTKUDOS",
+ editableAmount: false,
+ editableExchange: true,
+ amount: "TESTKUDOS:1",
+ maxAmount: undefined,
+ wireFee: undefined,
+ };
+ await f.db.runReadWriteTx((tx) => tx.upsertWithdrawalGroup(group));
+ const confirmUrl =
+ status === "selected" ? "https://bank.example/confirm" : undefined;
+ f.reply(200, {
+ status,
+ confirm_transfer_url: confirmUrl,
+ wire_types: [],
+ amount: "TESTKUDOS:1",
+ });
+ await processWithdrawalGroup(f.wex, "reason-withdrawal");
+ const { readTransactionSnapshot } =
+ await import("./observe-transaction.js");
+ const snapshot = await f.db.runReadWriteTx((tx) =>
+ readTransactionSnapshot(
+ f.wex,
+ tx,
+ "txn:withdrawal:reason-withdrawal",
+ ),
+ );
+ assert.ok(snapshot?.type === TransactionType.Withdrawal);
+ assert.equal(snapshot.bank?.status, status);
+ assert.equal(snapshot.bank?.confirmTransferUrl, confirmUrl);
+ assert.ok(
+ snapshot.transaction.withdrawalDetails.type ===
+ "taler-bank-integration-api",
+ );
+ if (status === "confirmed")
+ assert.equal(snapshot.transaction.withdrawalDetails.confirmed, true);
+ }
+ } finally {
+ await f.db.close();
+ }
+ });
test(`${makeRunner.name}: bank rejection details and manual withdrawal failures reach history`, async () => {
const f = await fixture();
try {
diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts
@@ -170,7 +170,7 @@ import {
PreparePayV2Result,
PreparePeerPullDebitRequest,
PreparePeerPullDebitResponse,
- ObservePeerPushCreditRequest,
+ ObserveTransactionRequest,
StopObservationRequest,
PreparePeerPushCreditRequest,
PreparePeerPushCreditResponse,
@@ -351,7 +351,7 @@ export enum WalletApiOperation {
// P2P Payments
- ObservePeerPushCredit = "observePeerPushCredit",
+ ObserveTransaction = "observeTransaction",
StopObservation = "stopObservation",
PreparePeerPushCredit = "preparePeerPushCredit",
CheckPeerPushDebit = "checkPeerPushDebit",
@@ -1394,10 +1394,10 @@ export type PreparePeerPushCreditOp = {
response: PreparePeerPushCreditResponse;
};
-/** Observe an existing incoming peer push payment. All snapshots are notifications. */
-export type ObservePeerPushCreditOp = {
- op: WalletApiOperation.ObservePeerPushCredit;
- request: ObservePeerPushCreditRequest;
+/** Observe an existing transaction of any type. All snapshots are notifications. */
+export type ObserveTransactionOp = {
+ op: WalletApiOperation.ObserveTransaction;
+ request: ObserveTransactionRequest;
response: EmptyObject;
};
@@ -1997,7 +1997,7 @@ export const walletApiExpectedErrors = {
// --- Peer-to-peer -------------------------------------------------------
- [WalletApiOperation.ObservePeerPushCredit]: [
+ [WalletApiOperation.ObserveTransaction]: [
TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
TalerErrorCode.WALLET_TRANSACTION_NOT_FOUND,
],
@@ -2233,7 +2233,7 @@ export type WalletOperations = {
[WalletApiOperation.CheckPeerPushDebit]: CheckPeerPushDebitOp;
[WalletApiOperation.CheckPeerPushDebitV2]: CheckPeerPushDebitV2Op;
[WalletApiOperation.InitiatePeerPushDebit]: InitiatePeerPushDebitOp;
- [WalletApiOperation.ObservePeerPushCredit]: ObservePeerPushCreditOp;
+ [WalletApiOperation.ObserveTransaction]: ObserveTransactionOp;
[WalletApiOperation.StopObservation]: StopObservationOp;
[WalletApiOperation.PreparePeerPushCredit]: PreparePeerPushCreditOp;
[WalletApiOperation.ConfirmPeerPushCredit]: ConfirmPeerPushCreditOp;