taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit b294961132e9d03b6f5b6c95d10dc503c9b06d0f
parent 7ed881015f662b2b6b58012d99776b718662d4ca
Author: Florian Dold <dold@taler.net>
Date:   Tue, 10 Nov 2026 16:22:02 +0100

wallet-core: implement and document observePeerPushCredit

Diffstat:
Adoc/wallet-observations.md | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/README.md | 3+++
Mpackages/taler-wallet-core/src/exchanges.ts | 63++++++++++++++++++++++++++++++++++++---------------------------
Apackages/taler-wallet-core/src/observe-peer-push-credit.test.ts | 855+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/taler-wallet-core/src/observe-peer-push-credit.ts | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/requests.test.ts | 11+++++++++++
Mpackages/taler-wallet-core/src/requests.ts | 15+++++++++++++++
Mpackages/taler-wallet-core/src/transactions.ts | 72+++++++++++++++++++++++++++---------------------------------------------
Mpackages/taler-wallet-core/src/wallet-api-types.ts | 27+++++++++++++++++++++++++++
9 files changed, 1295 insertions(+), 72 deletions(-)

diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md @@ -0,0 +1,145 @@ +# Wallet 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. + +## Register and receive + +Install the notification listener before making this request: + +```json +{ + "id": "101", + "operation": "observePeerPushCredit", + "args": { + "transactionId": "txn:peer-push-credit:example", + "observationId": "receive-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: + +```typescript +interface PeerPushCreditSnapshotNotification { + type: "observation-snapshot"; + observationType: "peer-push-credit"; + observationId: string; + revision: number; + transactionId: string; + snapshot: PeerPushCreditSnapshot | 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. diff --git a/packages/taler-wallet-core/README.md b/packages/taler-wallet-core/README.md @@ -2,3 +2,6 @@ This package implements `taler-wallet-core`, the main logic and storage for the GNU Taler wallet. + +See [wallet snapshot observations](../../doc/wallet-observations.md) for the +notification-based API for observing incoming peer push payments. diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -827,36 +827,45 @@ export async function getExchangeDetailsInTx( }; } +/** Read exchange presentation data without opening another transaction. */ +export async function lookupExchangeByUriInTx( + wex: WalletExecutionContext, + tx: WalletDbTransaction, + exchangeBaseUrl: string, +): Promise<ExchangeListItem | undefined> { + const exchangeRec = await tx.getExchange(exchangeBaseUrl); + if (!exchangeRec) { + return undefined; + } + const exchangeDetails = await getExchangeRecordsInternal( + tx, + exchangeRec.baseUrl, + ); + const opRetryRecord = await tx.getOperationRetry( + TaskIdentifiers.forExchangeUpdate(exchangeRec), + ); + let reserveRec: WalletReserve | undefined = undefined; + if (exchangeRec.currentMergeReserveRowId != null) { + reserveRec = await tx.getReserve(exchangeRec.currentMergeReserveRowId); + checkDbInvariant(!!reserveRec, "reserve record not found"); + } + return await makeExchangeListItem( + wex, + tx, + exchangeRec, + exchangeDetails, + reserveRec, + opRetryRecord?.lastError, + ); +} + export async function lookupExchangeByUri( wex: WalletExecutionContext, req: GetExchangeEntryByUrlRequest, ): Promise<ExchangeListItem> { - const res = await wex.runWalletDbTx(async (tx) => { - const exchangeRec = await tx.getExchange(req.exchangeBaseUrl); - if (!exchangeRec) { - return undefined; - } - const exchangeDetails = await getExchangeRecordsInternal( - tx, - exchangeRec.baseUrl, - ); - const opRetryRecord = await tx.getOperationRetry( - TaskIdentifiers.forExchangeUpdate(exchangeRec), - ); - let reserveRec: WalletReserve | undefined = undefined; - if (exchangeRec.currentMergeReserveRowId != null) { - reserveRec = await tx.getReserve(exchangeRec.currentMergeReserveRowId); - checkDbInvariant(!!reserveRec, "reserve record not found"); - } - return await makeExchangeListItem( - wex, - tx, - exchangeRec, - exchangeDetails, - reserveRec, - opRetryRecord?.lastError, - ); - }); + const res = await wex.runWalletDbTx((tx) => + lookupExchangeByUriInTx(wex, tx, req.exchangeBaseUrl), + ); if (!res) { throw TalerError.fromDetail( TalerErrorCode.WALLET_EXCHANGE_ENTRY_NOT_FOUND, @@ -2236,7 +2245,7 @@ function constructReadyExchangeSummary( }; } -async function loadReadyExchangeSummary( +export async function loadReadyExchangeSummary( tx: WalletDbTransaction, exchangeRec: WalletExchangeEntry, ): Promise<ReadyExchangeSummary | undefined> { 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 @@ -0,0 +1,855 @@ +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 @@ -0,0 +1,176 @@ +/* + * 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/requests.test.ts b/packages/taler-wallet-core/src/requests.test.ts @@ -358,6 +358,7 @@ interface TestContext { wex: WalletExecutionContext; getStoredRecord(): ConfigRecord | undefined; getReloadCount(): number; + getObservationInvalidations(): number; } function makeTestContext(options?: { @@ -366,6 +367,7 @@ function makeTestContext(options?: { }): TestContext { let storedRecord: ConfigRecord | undefined; let reloadCount = 0; + let observationInvalidations = 0; const tx = { async upsertConfig(record: ConfigRecord): Promise<void> { if (options?.failWrite) { @@ -381,6 +383,13 @@ function makeTestContext(options?: { }, } as WalletDbTransaction; const wex = { + ws: { + observations: { + invalidate() { + observationInvalidations++; + }, + }, + }, async runWalletDbTx<T>( f: (tx: WalletDbTransaction) => Promise<T>, ): Promise<T> { @@ -396,6 +405,7 @@ function makeTestContext(options?: { wex, getStoredRecord: () => storedRecord, getReloadCount: () => reloadCount, + getObservationInvalidations: () => observationInvalidations, }; } @@ -410,6 +420,7 @@ test("application-resumed hint reports healthy DB operations", async () => { }); assert.strictEqual(ctx.getStoredRecord()?.key, ConfigRecordKey.LastResumed); assert.strictEqual(ctx.getReloadCount(), 1); + assert.strictEqual(ctx.getObservationInvalidations(), 1); }); test("application-resumed hint reports DB failures independently", async () => { diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -24,6 +24,10 @@ * Imports. */ import { + observePeerPushCredit, + stopObservation, +} from "./observe-peer-push-credit.js"; +import { AbortTransactionRequest, AcceptBankIntegratedWithdrawalRequest, AcceptManualWithdrawalRequest, @@ -237,6 +241,8 @@ import { codecForPreparePayRequest, codecForPreparePayTemplateRequest, codecForPreparePeerPullPaymentRequest, + codecForObservePeerPushCreditRequest, + codecForStopObservationRequest, codecForPreparePeerPushCreditRequest, codecForPrepareRefundRequest, codecForPrepareWithdrawExchangeRequest, @@ -2239,6 +2245,7 @@ export async function handleHintApplicationResumed( req: EmptyObject, ): Promise<HintApplicationResumedResponse> { logger.info("handling hintApplicationResumed"); + wex.ws.observations.invalidate(); let dbWriteHealthy = false; try { @@ -3096,6 +3103,14 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { codec: codecForInitiatePeerPushDebitRequest(), handler: initiatePeerPushDebit, }, + [WalletApiOperation.ObservePeerPushCredit]: { + codec: codecForObservePeerPushCreditRequest(), + handler: observePeerPushCredit, + }, + [WalletApiOperation.StopObservation]: { + codec: codecForStopObservationRequest(), + handler: stopObservation, + }, [WalletApiOperation.PreparePeerPushCredit]: { codec: codecForPreparePeerPushCreditRequest(), handler: preparePeerPushCredit, diff --git a/packages/taler-wallet-core/src/transactions.ts b/packages/taler-wallet-core/src/transactions.ts @@ -200,55 +200,37 @@ export function makeTransactionActionUnsupportedError( ); } +/** Resolve the same public view for requests and observations in a caller's transaction. */ +export async function lookupTransactionInTx( + wex: WalletExecutionContext, + tx: WalletDbTransaction, + req: TransactionByIdRequest, +): Promise<Transaction | undefined> { + const ctx = await getContextForTransaction(wex, req.transactionId); + const details = await ctx.lookupFullTransaction(tx, { + includeContractTerms: req.includeContractTerms, + }); + if (!details) return undefined; + const amounts = await withTransactionAmounts(tx, details); + const meta = await tx.getTransactionMeta(req.transactionId); + const localIdent = ( + await tx.getLocalTransactionIdentifiers([req.transactionId]) + ).get(req.transactionId); + return withLocalTransactionIdentifier( + withMaterializedLegacyScopes(amounts, meta), + localIdent, + ); +} + export async function getTransactionById( wex: WalletExecutionContext, req: TransactionByIdRequest, ): Promise<Transaction> { - const parsedTx = parseTransactionIdentifier(req.transactionId); - - if (!parsedTx) { - throw makeInvalidTransactionIdError(req.transactionId); - } - - switch (parsedTx.tag) { - case TransactionType.InternalWithdrawal: - case TransactionType.Withdrawal: - case TransactionType.DenomLoss: - case TransactionType.Recoup: - case TransactionType.PeerPushDebit: - case TransactionType.PeerPushCredit: - case TransactionType.Refresh: - case TransactionType.PeerPullCredit: - case TransactionType.Payment: - case TransactionType.Deposit: - case TransactionType.PeerPullDebit: - case TransactionType.Refund: { - const ctx = await getContextForTransaction(wex, req.transactionId); - const result = await wex.runWalletDbTx(async (tx) => ({ - txDetails: await (async () => { - const details = await ctx.lookupFullTransaction(tx, { - includeContractTerms: req.includeContractTerms, - }); - return details && withTransactionAmounts(tx, details); - })(), - txMeta: await tx.getTransactionMeta(req.transactionId), - localIdent: ( - await tx.getLocalTransactionIdentifiers([req.transactionId]) - ).get(req.transactionId), - })); - if (!result.txDetails) { - throw TalerError.fromDetail( - TalerErrorCode.WALLET_TRANSACTION_NOT_FOUND, - { transactionId: req.transactionId }, - `transaction ${req.transactionId} not found`, - ); - } - return withLocalTransactionIdentifier( - withMaterializedLegacyScopes(result.txDetails, result.txMeta), - result.localIdent, - ); - } - } + const result = await wex.runWalletDbTx((tx) => + lookupTransactionInTx(wex, tx, req), + ); + if (!result) throw makeTransactionNotFoundError(req.transactionId); + return result; } function withMaterializedLegacyScopes( diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts @@ -170,6 +170,8 @@ import { PreparePayV2Result, PreparePeerPullDebitRequest, PreparePeerPullDebitResponse, + ObservePeerPushCreditRequest, + StopObservationRequest, PreparePeerPushCreditRequest, PreparePeerPushCreditResponse, PrepareRefundRequest, @@ -349,6 +351,8 @@ export enum WalletApiOperation { // P2P Payments + ObservePeerPushCredit = "observePeerPushCredit", + StopObservation = "stopObservation", PreparePeerPushCredit = "preparePeerPushCredit", CheckPeerPushDebit = "checkPeerPushDebit", CheckPeerPushDebitV2 = "checkPeerPushDebitV2", @@ -1390,6 +1394,20 @@ export type PreparePeerPushCreditOp = { response: PreparePeerPushCreditResponse; }; +/** Observe an existing incoming peer push payment. All snapshots are notifications. */ +export type ObservePeerPushCreditOp = { + op: WalletApiOperation.ObservePeerPushCredit; + request: ObservePeerPushCreditRequest; + response: EmptyObject; +}; + +/** End an observation without changing the observed transaction. */ +export type StopObservationOp = { + op: WalletApiOperation.StopObservation; + request: StopObservationRequest; + response: EmptyObject; +}; + /** * Accept an incoming peer push payment. */ @@ -1979,6 +1997,13 @@ export const walletApiExpectedErrors = { // --- Peer-to-peer ------------------------------------------------------- + [WalletApiOperation.ObservePeerPushCredit]: [ + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + TalerErrorCode.WALLET_TRANSACTION_NOT_FOUND, + ], + [WalletApiOperation.StopObservation]: [ + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + ], [WalletApiOperation.PreparePeerPushCredit]: [ TalerErrorCode.WALLET_PEER_CONTRACT_NOT_FOUND, TalerErrorCode.WALLET_PEER_PUSH_CREDIT_PURSE_GONE, @@ -2208,6 +2233,8 @@ export type WalletOperations = { [WalletApiOperation.CheckPeerPushDebit]: CheckPeerPushDebitOp; [WalletApiOperation.CheckPeerPushDebitV2]: CheckPeerPushDebitV2Op; [WalletApiOperation.InitiatePeerPushDebit]: InitiatePeerPushDebitOp; + [WalletApiOperation.ObservePeerPushCredit]: ObservePeerPushCreditOp; + [WalletApiOperation.StopObservation]: StopObservationOp; [WalletApiOperation.PreparePeerPushCredit]: PreparePeerPushCreditOp; [WalletApiOperation.ConfirmPeerPushCredit]: ConfirmPeerPushCreditOp; [WalletApiOperation.CheckPeerPullCredit]: CheckPeerPullCreditOp;