wallet-observations.md (17306B)
1 # Wallet transaction snapshot observations 2 3 Wallet observations provide complete, consistent snapshots for a UI view, 4 implementing https://bugs.gnunet.org/view?id=11794. `observeTransaction` supports 5 all transaction types. Preparation remains a separate operation and supplies the 6 transaction ID to observe. 7 8 ## Watching a view 9 10 Use `createWalletObservationClient` from `@gnu-taler/taler-wallet-core` with a 11 connection that exposes its RPC client, notifications and current connection 12 status. `watchTransaction`, `watchBalanceRefreshInfo` and `watchUserAttention` 13 return a handle synchronously, including while registration is pending. 14 15 ```typescript 16 const observations = createWalletObservationClient(connection); 17 const watch = observations.watchTransaction(transactionId, (view) => { 18 renderTransaction(view); 19 setConfirmEnabled(view.status === "ready" && canConfirm(view.snapshot)); 20 }); 21 22 // Retry a failed view or release it when its screen closes. 23 retryButton.onclick = () => watch.retry(); 24 onScreenClose(() => watch.dispose()); 25 ``` 26 27 A connected watch starts loading and becomes ready on its first snapshot. While loading, 28 disconnected or failed, it can retain the previous snapshot for display. 29 Reconnecting or losing a lease starts a new registration and waits for its first 30 snapshot. Deletion is terminal. 31 32 ## Register and receive 33 34 Install the notification listener before making this request: 35 36 ```json 37 { 38 "id": "101", 39 "operation": "observeTransaction", 40 "args": { 41 "transactionId": "txn:payment:example", 42 "observationId": "payment-screen-17", 43 "lease": true 44 } 45 } 46 ``` 47 48 The response is `{}`. The initial snapshot arrives through the notification 49 channel and may precede the response. Registration validates the ID and record's 50 existence. Failed registration leaves no observation behind. 51 52 ```typescript 53 interface TransactionSnapshotNotification { 54 type: "observation-snapshot"; 55 observationType: "transaction"; 56 observationId: string; 57 revision: number; 58 transactionId: string; 59 snapshot: TransactionSnapshot | null; 60 } 61 ``` 62 63 `TransactionSnapshot` is a discriminated union: narrow `snapshot.type` to access 64 its typed `transaction` and domain fields. `transaction.type` matches the outer 65 discriminator. Every variant contains an `exchanges` array of relevant cached 66 exchange summaries; missing exchange records do not prevent viewing a transaction. 67 68 Revision 1 is the initial snapshot. Revisions increase only when the snapshot 69 changes. Replace the previous snapshot in full, including clearing optional 70 fields that disappeared. Ignore revisions no newer than the last applied one. 71 Revisions belong to one observation, not the database. Updates can be coalesced: 72 this is a current-state view, not an event log. 73 74 ## Snapshot contents 75 76 Every transaction includes public identifiers, timestamps, scopes, state, actions, 77 amounts, and its type-specific presentation. `amountEffective` preserves the 78 initial estimate; `amountEffectiveFinal`, when available, describes the settled 79 balance effect. Full diagnostics and contract documents remain separate reads. 80 Explicit observation interfaces list the public fields, and the projection 81 copies them individually. New diagnostic fields do not automatically enter 82 snapshots. 83 84 | Type | Additional presentation | 85 | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 86 | `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. | 87 | `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. | 88 | `deposit` | Submission status, wire-transfer progress and tracking, KYC authentication instructions, and recovery amounts. | 89 | `peer-push-credit` | Confirmation blockers; the relevant exchange summary is in `exchanges`. | 90 | `peer-pull-credit` | Invoice link, expiration, active peer/withdrawal/balance-KYC state and errors. | 91 | `peer-pull-debit` | Confirmation blockers for transaction state, expiration and exchange prerequisites. Amounts retain the estimate recorded during preparation. | 92 | `peer-push-debit` | Share link, collection/cancellation state, expiration and recovery amounts. | 93 | `refund`, `refresh`, `recoup`, `denom-loss` | Public transaction details, amounts, supported actions and compact errors. | 94 | `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. | 95 96 Confirmation availability is based on local knowledge. Merchant choices retain 97 individual affordability results. Confirmation requests remain authoritative and 98 recheck prerequisites and remote state. Observation does not reserve coins or 99 predict future KYC decisions. Peer-invoice observations preserve the preparation 100 estimate; confirmation checks the current purse balance and selects available 101 coins. An expired peer link is omitted even if persisted transaction processing 102 has not yet caught up. 103 104 Exchange summaries contain terms status/ETag, key-change information, update 105 status, currency display specification, and compact update errors. Peer credits 106 also expose known soft/hard limits. These are cached limits; the account-level 107 `walletKycRequestedThreshold` must not independently trigger a transaction KYC 108 prompt. 109 110 Errors and failure/abort reasons contain `code`, `hint`, and `message`, with 111 text limited to 1024 characters. Transaction key-change and terms errors also 112 retain `exchangeBaseUrl` so the UI can offer the relevant recovery action. Internal state IDs, standalone KYC access tokens 113 and payto hashes are omitted. Actionable KYC URLs and transfer instructions remain 114 available. Fetch `getTransactionById` for full diagnostics. 115 116 `txState` is authoritative for active KYC, including an associated withdrawal. 117 `kycUrl` and `kycAmlReview` describe the active requirement only. True means the 118 exchange reports waiting for review; false does not rule out an undisclosed 119 review. An absent field means unknown or inapplicable. `retryInfo`, when present, 120 belongs to the operation supplying the error, and disappears with that error. 121 122 ## Lifetime and failures 123 124 Observation IDs are caller-generated, nonempty strings of at most 256 characters, 125 unique across the wallet instance. Reusing an active ID is an API error. Multiple 126 observations of the same transaction are independent. 127 128 `lease: true` on any of the three observe requests starts a five-minute lease 129 before the first read. Only an explicit renewal extends it. For example, 130 `renewObservations({ observationIds: ["a", "b"] })` returning 131 `{ missingObservationIds: ["a"] }` means that only `b` was renewed. An 132 unknown, expired or unleased ID is reported as missing. Expiry removes the 133 registration and its timers, suppresses pending reads and emits 134 `observation-ended` with reason `lease-expired`. A suspended host applies the 135 same deadline when it resumes. Omitting `lease` retains the original lifetime, 136 so losing a stop can leave a raw registration in memory until wallet shutdown. 137 138 The client probes each connected host with an empty renewal batch before 139 registering, then renews its active IDs together once a minute. Disposing a 140 watch removes it from that batch immediately. A lost stop or a crashed tab 141 therefore leaves at most the remainder of one lease once the host can run. 142 A live client continues renewing a handle until it is disposed or terminates. 143 144 Call `stopObservation({ observationId })` when closing a view. It is idempotent 145 and cancels observation, not transaction processing. Remove the UI routing entry 146 before stopping because notifications already queued on the transport can still 147 arrive. Stopped observations cannot publish new in-flight reads. 148 149 Completed, failed and aborted transactions remain observable. Deletion emits one 150 final notification with `snapshot: null` and ends the observation. Database import 151 or clear refreshes observations against the committed replacement. Shutdown 152 forgets observations; reconnecting clients register with fresh IDs. 153 154 A later snapshot-read failure emits `observation-error` with the observation ID, 155 `observationType: "transaction"`, and a compact error, then ends the observation. 156 This is a subscription failure, not a transaction failure. Initial read failures 157 are request errors. Retry uses a fresh observation ID. 158 159 ## Consistency and time 160 161 Register before reading the initial snapshot. Assemble transaction, choices, 162 exchange and prerequisite data in one database transaction, without network 163 requests or persistent writes. Each observation reads committed state and runs 164 one read at a time. A change during a read schedules another read. The registry 165 publishes a revision only when the snapshot changes. 166 167 Transaction, exchange, balance and Donau change notifications invalidate 168 transaction views. Token writes also invalidate them after commit. Snapshot 169 readers track purse and payment expiry, token and fee validity, and the effective 170 withdrawal cutoff for denominations used to give change. A cached refresh cost 171 retains its next eligibility boundary so a second view can schedule the same 172 update. 173 174 Bank preparation initializes cached bank presentation. Existing withdrawal tasks 175 update it from both status reads and reserve-registration responses; observations 176 never perform bank requests. The transaction state takes precedence over cached 177 bank presentation, including when the exchange finds the reserve already funded. 178 Older records acquire this optional presentation when prepared again. 179 180 ## Web UI and migration 181 182 The generic controller and `useTransactionObservation` retain explicit `loading`, 183 `ready`, `disconnected`, `failed`, and `deleted` states. Loading, disconnect and 184 failure may retain the last snapshot, but confirmation requires a fresh ready 185 snapshot. Failure offers retry; deletion is terminal. Changing connection or 186 transaction rejects late deliveries and discards the previous target's value. 187 188 Transaction details, merchant review/results, peer receive/pay/share, and withdrawal 189 tracking consume observations. Full merchant documents are loaded separately when 190 the contract hash becomes available or changes. Failed document reads can be retried 191 and are retried after reconnecting. Preparation owns peer documents; 192 its amounts/status do not substitute for an observed review. Request progress, 193 durability checks, action errors and fulfillment navigation remain separate from 194 subscription state. The extension delivers observations to the registering port 195 and stops them when the port disconnects. The PWA broadcasts wallet notifications 196 to all its tabs. Each client matches updates by `observationId`. Only the 197 registering tab can renew or stop its observations. If that tab disappears, 198 wallet-core expires its leased observations. The PWA uses a Web Lock to elect 199 the database owner and assumes trusted wallet code on the same origin. 200 201 `observePeerPushCredit` and its `observationType: "peer-push-credit"` notification 202 have been removed. Consumers must call `observeTransaction`, accept 203 `observationType: "transaction"`, and narrow `snapshot.type`. `stopObservation` 204 is idempotent. Transaction lists and balances retain their 205 existing query/notification behavior. 206 207 ## User attention 208 209 The web wallet labels the inbox **Notifications**. A home screen can subscribe to 210 the wallet-core `user-attention-changed` event and call 211 `getUserAttentionSummary({})` to get `{ unreadCount }`. Read the summary on 212 initial connection, reconnection and after each event. The event also fires 213 when an item reaches its expiry while the wallet is running. Attention changes 214 are independent of balance changes. 215 216 An inbox can call `getUserAttention({})` for a single snapshot, or 217 `observeUserAttention({ observationId })` to receive snapshots with 218 `observationType: "user-attention"`. The snapshot contains `items` in 219 newest-first order and their `unreadCount`. Register and stop the observation 220 using the same lifecycle as a transaction view. 221 222 Each item has a stable `attentionId` for that occurrence. Call 223 `markUserAttentionRead({ attentionId })` to set its `readAt` timestamp. Show 224 a dismiss action when `dismissible` is true and call 225 `dismissUserAttention({ attentionId })`. An item with `expiresAt` leaves the 226 inbox at that time. Warnings about exchange terms, exchange master keys, 227 exchange currencies, and blocked refreshes leave the inbox when their 228 underlying conditions resolve. When accepting 229 exchange terms, pass the displayed ETag as `expectedEtag` to 230 `setExchangeTosAccepted` so the user accepts the version they reviewed. 231 When confirming an exchange identity change, pass the displayed 232 `currentMasterPub` and `currentCurrency` to `confirmExchangeKeyChange`. 233 If either has changed, the warning stays pending for review. 234 235 `markAllUserAttentionRead({})` marks every active unread occurrence as read. 236 `clearReadUserAttention({})` dismisses every active occurrence that is both 237 read and dismissible. Read condition-based warnings stay visible until their 238 conditions resolve. Each operation returns `{}` and emits one 239 `user-attention-changed` event when it changes the inbox. 240 241 In developer mode, open `taler://dev-experiment/show-user-attention` to 242 create four sample items. Three start unread and the sample coin conflict 243 expires after one minute. Run it again to reset the samples, or open 244 `taler://dev-experiment/clear-user-attention` to remove them. Both 245 experiments preserve genuine items and the refresh setting.