@bsv/expo-wallet-toolbox 0.20.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +147 -0
- package/README.md +78 -13
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletContext.tsx +166 -219
- package/core/demo/demoAssets.ts +8 -10
- package/core/demo/demoLedger.ts +32 -38
- package/core/demo/demoMandalaRuntime.ts +67 -49
- package/core/demo/index.ts +1 -1
- package/core/directpay/DirectPayManager.ts +148 -29
- package/core/directpay/DirectPayProvider.tsx +11 -2
- package/core/directpay/payFlow.ts +10 -1
- package/core/directpay/settings.ts +56 -9
- package/core/directpay/types.ts +11 -2
- package/core/directpay/webrtpay.ts +4 -0
- package/core/i18n/translations.tsx +185 -84
- package/core/index.ts +55 -37
- package/core/localpay/build.ts +110 -569
- package/core/localpay/codec.ts +190 -93
- package/core/localpay/pending.ts +217 -202
- package/core/localpay/session.ts +99 -25
- package/core/localpay/types.ts +6 -5
- package/core/localpay/verify.ts +118 -173
- package/core/mandala/abortGuard.ts +97 -120
- package/core/mandala/accessPolicy.ts +133 -0
- package/core/mandala/assets.ts +370 -0
- package/core/mandala/colorGuard.ts +178 -0
- package/core/mandala/colorModule.ts +82 -0
- package/core/mandala/createRuntime.ts +483 -2392
- package/core/mandala/handle.ts +694 -0
- package/core/mandala/kvStore.ts +105 -0
- package/core/mandala/nearby.ts +185 -0
- package/core/mandala/receipt.ts +121 -0
- package/core/mandala/runtime.ts +166 -312
- package/core/mandala/settle.ts +540 -0
- package/core/mandala/transferJournal.ts +395 -0
- package/core/mandala/types.ts +61 -311
- package/core/networks.ts +5 -5
- package/core/offline/cancelParked.ts +80 -63
- package/core/offline/payerHold.ts +52 -118
- package/core/parsePeerPayURI.ts +25 -12
- package/core/pay/rails/direct.ts +6 -2
- package/core/pay/rails/handle.ts +15 -14
- package/core/pay/rails/index.ts +5 -3
- package/core/pay/rails/nearby.ts +25 -87
- package/core/profiles/assertProfileEmpty.ts +19 -10
- package/core/services/vault/guard.ts +5 -4
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/package.json +6 -5
- package/ui/components/pay/AssetPicker.tsx +2 -2
- package/ui/components/pay/HandleReceive.tsx +10 -4
- package/ui/components/pay/NearbyFlow.tsx +324 -239
- package/ui/components/pay/RequestHub.tsx +10 -0
- package/ui/components/pay/UniversalSend.tsx +31 -28
- package/ui/components/pay/useRecipientInput.ts +2 -2
- package/ui/components/ui/PermissionSheet.tsx +94 -160
- package/ui/components/ui/colorPrompt.ts +236 -0
- package/ui/components/wallet/AmountInput.tsx +9 -6
- package/ui/components/wallet/AssetAmount.tsx +6 -6
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ContactActivityList.tsx +10 -13
- package/ui/components/wallet/tokenEviction.ts +9 -9
- package/ui/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +1 -1
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- package/ui/screens/WalletHomeScreen.tsx +40 -14
- package/ui/screens/tokenRowTitle.ts +28 -15
- package/ui/tokenFormat.ts +133 -69
- package/ui/tokenStatus.ts +5 -8
- package/core/localpay/settlementAck.ts +0 -155
- package/core/mandala/basketMigration.ts +0 -166
- package/core/mandala/bundle.ts +0 -244
- package/core/mandala/drain.ts +0 -754
- package/core/mandala/inboxPrehold.ts +0 -193
- package/core/mandala/permissionModule.ts +0 -931
- package/core/mandala/resendTransfer.ts +0 -178
- package/core/mandala/settlementStore.ts +0 -434
- package/core/mandala/token.ts +0 -45
- package/core/offline/tokenFrames.ts +0 -197
package/core/demo/demoLedger.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The demo wallet's whole world: one mutable, in-memory ledger.
|
|
3
3
|
*
|
|
4
|
-
* DEV-ONLY. Holds a BSV balance with its action history and
|
|
5
|
-
* balance per demo stablecoin with its settlement history, and mutates both
|
|
4
|
+
* DEV-ONLY. Holds a BSV balance with its action history and an exact token
|
|
5
|
+
* unit balance per demo stablecoin with its settlement history, and mutates both
|
|
6
6
|
* when the UI "sends". Nothing here touches SQLite, the keychain, an overlay
|
|
7
7
|
* or the network, so a demo send can never become a real one — and everything
|
|
8
8
|
* is gone at reload, which is what makes the mode safe to hand to someone.
|
|
9
9
|
*
|
|
10
|
-
* Figures are integers throughout (satoshis, token
|
|
11
|
-
* reason `ui/tokenFormat.ts` is: a float balance prints
|
|
12
|
-
* owned.
|
|
10
|
+
* Figures are integers throughout (satoshis as numbers, token units as
|
|
11
|
+
* `bigint`) for the same reason `ui/tokenFormat.ts` is: a float balance prints
|
|
12
|
+
* money that is not owned.
|
|
13
13
|
*/
|
|
14
14
|
import type { TokenActivityRow, TokenActivityStatus } from '../mandala/runtime'
|
|
15
15
|
import type { WalletAction } from '@bsv/sdk'
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
DEMO_CHF,
|
|
18
18
|
DEMO_COUNTERPARTIES,
|
|
19
19
|
DEMO_OPENING_SATS,
|
|
20
|
-
|
|
20
|
+
DEMO_OPENING_TOKEN_UNITS,
|
|
21
21
|
DEMO_USD,
|
|
22
22
|
demoAssetById
|
|
23
23
|
} from './demoAssets'
|
|
@@ -32,7 +32,7 @@ export type DemoAction = WalletAction & {
|
|
|
32
32
|
interface DemoState {
|
|
33
33
|
satoshis: number
|
|
34
34
|
actions: DemoAction[]
|
|
35
|
-
|
|
35
|
+
tokenUnits: Record<string, bigint>
|
|
36
36
|
tokenActivity: TokenActivityRow[]
|
|
37
37
|
}
|
|
38
38
|
|
|
@@ -70,14 +70,14 @@ function bsvAction(over: Partial<DemoAction> & { satoshis: number; description:
|
|
|
70
70
|
function tokenRow(
|
|
71
71
|
assetId: string,
|
|
72
72
|
role: 'sent' | 'received',
|
|
73
|
-
|
|
73
|
+
units: bigint,
|
|
74
74
|
at: string,
|
|
75
75
|
counterpartyKey?: string,
|
|
76
76
|
status: TokenActivityStatus = 'settled'
|
|
77
77
|
): TokenActivityRow {
|
|
78
78
|
const asset = demoAssetById(assetId)
|
|
79
79
|
if (!asset) throw new Error(`demo: unknown assetId ${assetId}`)
|
|
80
|
-
return { txid: demoTxid(), role, asset,
|
|
80
|
+
return { txid: demoTxid(), role, asset, units, counterpartyKey, status, at, rail: 'handle' }
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
/**
|
|
@@ -98,16 +98,16 @@ function seed(): DemoState {
|
|
|
98
98
|
bsvAction({ satoshis: 15_000_000, description: `From ${lena.name}`, created_at: daysAgo(2, 13) }),
|
|
99
99
|
bsvAction({ satoshis: -1_000_000, description: 'Lunch', created_at: daysAgo(0, 12) })
|
|
100
100
|
],
|
|
101
|
-
|
|
101
|
+
tokenUnits: { ...DEMO_OPENING_TOKEN_UNITS },
|
|
102
102
|
tokenActivity: [
|
|
103
|
-
tokenRow(DEMO_USD.assetId, 'received',
|
|
104
|
-
tokenRow(DEMO_CHF.assetId, 'received',
|
|
105
|
-
tokenRow(DEMO_USD.assetId, 'sent',
|
|
106
|
-
tokenRow(DEMO_CHF.assetId, 'sent',
|
|
107
|
-
tokenRow(DEMO_USD.assetId, 'received',
|
|
108
|
-
tokenRow(DEMO_CHF.assetId, 'received',
|
|
103
|
+
tokenRow(DEMO_USD.assetId, 'received', 50_000n, daysAgo(16, 11), sofia.key),
|
|
104
|
+
tokenRow(DEMO_CHF.assetId, 'received', 40_000n, daysAgo(13, 15), lena.key),
|
|
105
|
+
tokenRow(DEMO_USD.assetId, 'sent', 12_500n, daysAgo(9, 19), store.key),
|
|
106
|
+
tokenRow(DEMO_CHF.assetId, 'sent', 7_450n, daysAgo(6, 12), marco.key),
|
|
107
|
+
tokenRow(DEMO_USD.assetId, 'received', 86_500n, daysAgo(3, 14), marco.key),
|
|
108
|
+
tokenRow(DEMO_CHF.assetId, 'received', 53_500n, daysAgo(1, 17), sofia.key),
|
|
109
109
|
// One row mid-flight, so the "settling" copy has something to render.
|
|
110
|
-
tokenRow(DEMO_USD.assetId, 'sent',
|
|
110
|
+
tokenRow(DEMO_USD.assetId, 'sent', 2_000n, daysAgo(0, 11), lena.key, 'settling')
|
|
111
111
|
]
|
|
112
112
|
}
|
|
113
113
|
}
|
|
@@ -148,8 +148,8 @@ export function demoTotalActions(): number {
|
|
|
148
148
|
return state.actions.length
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
-
export function
|
|
152
|
-
return state.
|
|
151
|
+
export function demoTokenUnits(assetId: string): bigint {
|
|
152
|
+
return state.tokenUnits[assetId] ?? 0n
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
export function demoTokenActivity(limit?: number): TokenActivityRow[] {
|
|
@@ -157,11 +157,11 @@ export function demoTokenActivity(limit?: number): TokenActivityRow[] {
|
|
|
157
157
|
return limit == null ? sorted : sorted.slice(0, limit)
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
/**
|
|
161
|
-
export function
|
|
160
|
+
/** Units received but not yet settled — what the UI shows as pending. */
|
|
161
|
+
export function demoOfflineUnits(assetId: string): bigint {
|
|
162
162
|
return state.tokenActivity
|
|
163
163
|
.filter(r => r.asset.assetId === assetId && r.role === 'received' && r.status === 'settling')
|
|
164
|
-
.reduce((sum, r) => sum + r.
|
|
164
|
+
.reduce((sum, r) => sum + r.units, 0n)
|
|
165
165
|
}
|
|
166
166
|
|
|
167
167
|
// ── writes ─────────────────────────────────────────────────────────────
|
|
@@ -194,16 +194,15 @@ export function demoReceiveBsv(satoshis: number, description: string): DemoActio
|
|
|
194
194
|
}
|
|
195
195
|
|
|
196
196
|
/** Spend a token. Returns the new row, or null when the balance cannot cover it. */
|
|
197
|
-
export function demoSendToken(assetId: string,
|
|
197
|
+
export function demoSendToken(assetId: string, units: bigint, counterpartyKey?: string): TokenActivityRow | null {
|
|
198
198
|
if (!demoAssetById(assetId)) return null
|
|
199
|
-
if (
|
|
200
|
-
const held =
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const row = tokenRow(assetId, 'sent', amount, new Date().toISOString(), counterpartyKey, 'settled')
|
|
199
|
+
if (typeof units !== 'bigint' || units <= 0n) return null
|
|
200
|
+
const held = demoTokenUnits(assetId)
|
|
201
|
+
if (units > held) return null
|
|
202
|
+
const row = tokenRow(assetId, 'sent', units, new Date().toISOString(), counterpartyKey, 'settled')
|
|
204
203
|
state = {
|
|
205
204
|
...state,
|
|
206
|
-
|
|
205
|
+
tokenUnits: { ...state.tokenUnits, [assetId]: held - units },
|
|
207
206
|
tokenActivity: [...state.tokenActivity, row]
|
|
208
207
|
}
|
|
209
208
|
notify()
|
|
@@ -211,18 +210,13 @@ export function demoSendToken(assetId: string, baseUnits: number, counterpartyKe
|
|
|
211
210
|
}
|
|
212
211
|
|
|
213
212
|
/** Receive a token — for demonstrating an incoming payment on cue. */
|
|
214
|
-
export function demoReceiveToken(
|
|
215
|
-
assetId: string,
|
|
216
|
-
baseUnits: number,
|
|
217
|
-
counterpartyKey?: string
|
|
218
|
-
): TokenActivityRow | null {
|
|
213
|
+
export function demoReceiveToken(assetId: string, units: bigint, counterpartyKey?: string): TokenActivityRow | null {
|
|
219
214
|
if (!demoAssetById(assetId)) return null
|
|
220
|
-
if (
|
|
221
|
-
const
|
|
222
|
-
const row = tokenRow(assetId, 'received', amount, new Date().toISOString(), counterpartyKey, 'settled')
|
|
215
|
+
if (typeof units !== 'bigint' || units <= 0n) return null
|
|
216
|
+
const row = tokenRow(assetId, 'received', units, new Date().toISOString(), counterpartyKey, 'settled')
|
|
223
217
|
state = {
|
|
224
218
|
...state,
|
|
225
|
-
|
|
219
|
+
tokenUnits: { ...state.tokenUnits, [assetId]: demoTokenUnits(assetId) + units },
|
|
226
220
|
tokenActivity: [...state.tokenActivity, row]
|
|
227
221
|
}
|
|
228
222
|
notify()
|
|
@@ -2,52 +2,69 @@
|
|
|
2
2
|
* A `MandalaRuntime` backed entirely by the demo ledger.
|
|
3
3
|
*
|
|
4
4
|
* DEV-ONLY. Implements the members the UI actually reads or calls; everything
|
|
5
|
-
* else on the interface is
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* else on the interface is settlement machinery that has nothing to settle
|
|
6
|
+
* here, so it answers "nothing happened" rather than throwing — a demo must
|
|
7
|
+
* never crash on a background tick.
|
|
8
8
|
*
|
|
9
9
|
* `endpoints` deliberately carries the `.invalid` demo overlay rather than the
|
|
10
10
|
* configured one: if any code path ever did try to settle one of these rows,
|
|
11
|
-
* it must fail to resolve rather than reach a real issuer.
|
|
11
|
+
* it must fail to resolve rather than reach a real issuer. The journal refuses
|
|
12
|
+
* every call for the same reason.
|
|
12
13
|
*/
|
|
13
|
-
import type {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
} from './
|
|
14
|
+
import type {
|
|
15
|
+
MandalaRuntime,
|
|
16
|
+
TokenAssetInfo,
|
|
17
|
+
TokenAssetStatus,
|
|
18
|
+
TokenBalance,
|
|
19
|
+
TokenSendResult
|
|
20
|
+
} from '../mandala/runtime'
|
|
21
|
+
import type { TransferJournal } from '../mandala/transferJournal'
|
|
22
|
+
import { DEMO_ASSETS, DEMO_OVERLAY_KEY, DEMO_OVERLAY_URL } from './demoAssets'
|
|
23
|
+
import { demoOfflineUnits, demoSendToken, demoTokenActivity, demoTokenUnits, subscribeDemoLedger } from './demoLedger'
|
|
24
|
+
|
|
25
|
+
const DEMO_MESSAGEBOX_URL = 'https://messagebox.demo.invalid'
|
|
22
26
|
|
|
23
27
|
function statusFor(): TokenAssetStatus {
|
|
24
28
|
return {
|
|
25
29
|
paused: false,
|
|
26
|
-
|
|
30
|
+
frozenUnits: 0n,
|
|
27
31
|
selfAdmitted: true,
|
|
28
32
|
recipientAdmitted: async () => true,
|
|
29
33
|
metadataResolved: true,
|
|
30
|
-
messageBoxUrl:
|
|
34
|
+
messageBoxUrl: DEMO_MESSAGEBOX_URL
|
|
31
35
|
}
|
|
32
36
|
}
|
|
33
37
|
|
|
34
38
|
function balanceFor(asset: TokenAssetInfo): TokenBalance {
|
|
39
|
+
const units = demoTokenUnits(asset.assetId)
|
|
40
|
+
const offline = demoOfflineUnits(asset.assetId)
|
|
41
|
+
return { asset, units, offlineUnits: offline > units ? units : offline }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function demoJournal(): TransferJournal {
|
|
45
|
+
const refuse = async (): Promise<never> => {
|
|
46
|
+
throw new Error('demo mode has no color_transfers journal')
|
|
47
|
+
}
|
|
35
48
|
return {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
49
|
+
get: refuse,
|
|
50
|
+
getByReference: refuse,
|
|
51
|
+
list: refuse,
|
|
52
|
+
insert: refuse,
|
|
53
|
+
advance: refuse,
|
|
54
|
+
setDelivered: refuse,
|
|
55
|
+
statesOf: refuse
|
|
39
56
|
}
|
|
40
57
|
}
|
|
41
58
|
|
|
42
59
|
export function createDemoMandalaRuntime(): MandalaRuntime {
|
|
43
|
-
const runtime = {
|
|
60
|
+
const runtime: MandalaRuntime = {
|
|
44
61
|
available: true,
|
|
45
62
|
endpoints: {
|
|
46
|
-
overlayUrl:
|
|
47
|
-
overlayIdentityKey:
|
|
48
|
-
messageBoxUrl:
|
|
63
|
+
overlayUrl: DEMO_OVERLAY_URL,
|
|
64
|
+
overlayIdentityKey: DEMO_OVERLAY_KEY,
|
|
65
|
+
messageBoxUrl: DEMO_MESSAGEBOX_URL
|
|
49
66
|
},
|
|
50
|
-
|
|
67
|
+
journal: demoJournal(),
|
|
51
68
|
|
|
52
69
|
// ── what the UI reads ───────────────────────────────────────────
|
|
53
70
|
listAssets: async () => DEMO_ASSETS,
|
|
@@ -56,41 +73,42 @@ export function createDemoMandalaRuntime(): MandalaRuntime {
|
|
|
56
73
|
stuck: async () => [],
|
|
57
74
|
assetStatus: async () => statusFor(),
|
|
58
75
|
refreshAssetStatus: async () => statusFor(),
|
|
76
|
+
rememberDeploy: async () => {},
|
|
59
77
|
recipientRefusal: () => null,
|
|
60
78
|
subscribe: subscribeDemoLedger,
|
|
61
79
|
|
|
62
80
|
// ── what the UI calls ───────────────────────────────────────────
|
|
63
|
-
sendToHandle: async (args: {
|
|
64
|
-
|
|
81
|
+
sendToHandle: async (args: {
|
|
82
|
+
assetId: string
|
|
83
|
+
recipientIdentityKey: string
|
|
84
|
+
units: bigint
|
|
85
|
+
}): Promise<TokenSendResult> => {
|
|
86
|
+
const row = demoSendToken(args.assetId, args.units, args.recipientIdentityKey)
|
|
65
87
|
if (!row) {
|
|
66
|
-
return {
|
|
67
|
-
kind: 'refused' as const,
|
|
68
|
-
code: 'ERR_INSUFFICIENT_FUNDS',
|
|
69
|
-
message: 'Not enough balance in demo mode.'
|
|
70
|
-
}
|
|
88
|
+
return { kind: 'refused', code: 'ERR_INSUFFICIENT_FUNDS', message: 'Not enough balance in demo mode.' }
|
|
71
89
|
}
|
|
72
|
-
return { kind: 'sent'
|
|
90
|
+
return { kind: 'sent', txid: row.txid, settled: true, notified: true }
|
|
73
91
|
},
|
|
74
92
|
receiveFromInbox: async () => ({ credited: 0, failed: 0 }),
|
|
75
|
-
settleNow: async () => '
|
|
76
|
-
|
|
93
|
+
settleNow: async () => 'settled',
|
|
94
|
+
resendTransfer: async () => 'unavailable',
|
|
77
95
|
|
|
78
96
|
// ── machinery with nothing to do ────────────────────────────────
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
97
|
+
settleAll: async () => 0,
|
|
98
|
+
reviewTokenHoldings: async () => ({ settled: 0, refused: 0, pending: 0, unreachable: false }),
|
|
99
|
+
isHandoverAdmitted: async () => undefined,
|
|
100
|
+
reconcileHeld: async () => {},
|
|
101
|
+
tick: async () => {},
|
|
102
|
+
nearby: {
|
|
103
|
+
handover: async () => {
|
|
104
|
+
throw new Error('demo mode does not build nearby token payments')
|
|
105
|
+
},
|
|
106
|
+
onHandedOver: async () => {},
|
|
107
|
+
accept: async () => {
|
|
108
|
+
throw new Error('demo mode does not receive nearby token payments')
|
|
109
|
+
},
|
|
110
|
+
onReceived: async () => {}
|
|
111
|
+
}
|
|
88
112
|
}
|
|
89
|
-
|
|
90
|
-
// The remaining members are injection points for machinery demo mode never
|
|
91
|
-
// starts (the drain, the nearby build, the frame verifier, the pending
|
|
92
|
-
// queue). Casting rather than stubbing each one keeps this file honest about
|
|
93
|
-
// the fact that nothing here is a real settlement path — the same approach
|
|
94
|
-
// `__tests__/__mocks__/fakeMandalaRuntime.ts` takes.
|
|
95
|
-
return runtime as unknown as MandalaRuntime
|
|
113
|
+
return runtime
|
|
96
114
|
}
|
package/core/demo/index.ts
CHANGED
|
@@ -5,8 +5,14 @@
|
|
|
5
5
|
* `DirectPayProvider` starts it once a wallet is built and stops it when the wallet goes. While
|
|
6
6
|
* a wallet is open there is always a client, so this wallet can dial others. Dialing and
|
|
7
7
|
* receiving by identity key need a signaler, chosen in the device settings: a relay server (the
|
|
8
|
-
* default) or the message box. Receiving is on when the user left it on
|
|
9
|
-
* foreground
|
|
8
|
+
* default) or the message box. Receiving is on when the user left it on, the app is in the
|
|
9
|
+
* foreground and the Receive screen is showing ({@link DirectPayManager.openReceiveScreen}; the
|
|
10
|
+
* user's decision, 2026-10-21): the rest of the time this wallet answers no dial, so nobody can
|
|
11
|
+
* learn its address or that it is open, and payers use the message box. Opening and closing the
|
|
12
|
+
* screen starts and stops receiving on the same client, so a payment being sent is not cut off.
|
|
13
|
+
* Payments are taken into the wallet at once (`receive.ts`). Live sessions carry payments only
|
|
14
|
+
* (no payment request handler is given), and an authenticated peer may send at most
|
|
15
|
+
* MAX_LIVE_MESSAGE_BYTES (a 1 MB transaction). Through a relay,
|
|
10
16
|
* receiving follows the relay connection, which reconnects by itself, and every connection may
|
|
11
17
|
* use the short-lived TURN servers the relay hands out.
|
|
12
18
|
*
|
|
@@ -45,7 +51,7 @@
|
|
|
45
51
|
import i18n from '../i18n/translations'
|
|
46
52
|
import type { KVStorage } from '../localpay/pending'
|
|
47
53
|
import { classifyCreditError, type CreditFailureKind } from '../pay/creditErrors'
|
|
48
|
-
import { iceServersFrom } from './settings'
|
|
54
|
+
import { iceServersFrom, MAX_LIVE_MESSAGE_BYTES, onlyOwnStun } from './settings'
|
|
49
55
|
import {
|
|
50
56
|
receiveDirectPayment,
|
|
51
57
|
retryKeptDirectPayments,
|
|
@@ -202,6 +208,14 @@ export class DirectPayManager {
|
|
|
202
208
|
private _foreground: boolean
|
|
203
209
|
/** The last relay connection failed and has not come online since (see {@link signalingDown}). */
|
|
204
210
|
private _relayDown = false
|
|
211
|
+
/** Receive screens showing now (see {@link openReceiveScreen}). */
|
|
212
|
+
private _receiveScreens = 0
|
|
213
|
+
/** The current client answers dials: set by {@link _beginReceiving}, cleared by {@link _endReceiving} and teardown. */
|
|
214
|
+
private _receiving = false
|
|
215
|
+
/** Bumped whenever receiving starts or ends; a start that is no longer current changes nothing. */
|
|
216
|
+
private _receiveRun = 0
|
|
217
|
+
/** Undone when receiving ends: the relay start timer, the relay retry. */
|
|
218
|
+
private _receiveCleanups: Array<() => void> = []
|
|
205
219
|
|
|
206
220
|
private readonly _deps: DirectPayManagerDeps
|
|
207
221
|
|
|
@@ -288,6 +302,24 @@ export class DirectPayManager {
|
|
|
288
302
|
}
|
|
289
303
|
}
|
|
290
304
|
|
|
305
|
+
/**
|
|
306
|
+
* The Receive screen is showing: while at least one is, receiving is on (when the settings
|
|
307
|
+
* turn it on and the app is in the foreground). Returns the function to call when it stops
|
|
308
|
+
* showing; calling it again does nothing. Works with no wallet open: receiving then starts
|
|
309
|
+
* with the wallet.
|
|
310
|
+
*/
|
|
311
|
+
openReceiveScreen = (): (() => void) => {
|
|
312
|
+
this._receiveScreens++
|
|
313
|
+
if (this._receiveScreens === 1) this._receiveScreenChanged()
|
|
314
|
+
let open = true
|
|
315
|
+
return () => {
|
|
316
|
+
if (!open) return
|
|
317
|
+
open = false
|
|
318
|
+
this._receiveScreens--
|
|
319
|
+
if (this._receiveScreens === 0) this._receiveScreenChanged()
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
291
323
|
/** Closes the client and signaler. The snapshot clears at once; never rejects. */
|
|
292
324
|
async stop(): Promise<void> {
|
|
293
325
|
this._stopRetries()
|
|
@@ -337,7 +369,7 @@ export class DirectPayManager {
|
|
|
337
369
|
let failures = 0
|
|
338
370
|
const polled = (pollError?: unknown) => {
|
|
339
371
|
failures = pollError === undefined ? 0 : failures + 1
|
|
340
|
-
this._messageBoxPolled(generation,
|
|
372
|
+
this._messageBoxPolled(generation, failures, pollError)
|
|
341
373
|
}
|
|
342
374
|
signaler = new webrtpay.MessageBoxSignaler(watchingPolls(o.peerPayClient, polled), {
|
|
343
375
|
host: o.messageBoxUrl || undefined,
|
|
@@ -354,6 +386,10 @@ export class DirectPayManager {
|
|
|
354
386
|
iceServers: iceServersFrom(o.settings),
|
|
355
387
|
...(o.RTCPeerConnection !== undefined && { RTCPeerConnection: o.RTCPeerConnection })
|
|
356
388
|
},
|
|
389
|
+
// Live sessions carry a payment and its ack: an authenticated peer may send this wallet
|
|
390
|
+
// no more than a payment with a 1 MB transaction (larger ones go by message box).
|
|
391
|
+
maxMessageBytes: MAX_LIVE_MESSAGE_BYTES,
|
|
392
|
+
limits: { maxMessageBytes: MAX_LIVE_MESSAGE_BYTES },
|
|
357
393
|
// Once the recipient has answered, give the link 10 s (the package default is 6 s): a
|
|
358
394
|
// slow STUN or TURN answer on a phone network otherwise ends a payment the recipient is
|
|
359
395
|
// online for.
|
|
@@ -362,7 +398,7 @@ export class DirectPayManager {
|
|
|
362
398
|
// client's life: it reuses live credentials.
|
|
363
399
|
...(relay &&
|
|
364
400
|
!fallback && {
|
|
365
|
-
iceServersProvider: relay.turnProvider(),
|
|
401
|
+
iceServersProvider: ownStunOnly(relay.turnProvider()),
|
|
366
402
|
onIceServersProviderError: (e: unknown) =>
|
|
367
403
|
console.warn("[DirectPayManager] Connecting without the relay's TURN servers:", messageOf(e))
|
|
368
404
|
})
|
|
@@ -388,37 +424,115 @@ export class DirectPayManager {
|
|
|
388
424
|
background: !this._foreground
|
|
389
425
|
})
|
|
390
426
|
if (!receive || !client) return
|
|
427
|
+
await this._beginReceiving(generation, o, client, relay, fallback, closing)
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Receiving is on: the user's switch, the app in the foreground, and a Receive screen showing. */
|
|
431
|
+
private _receives(o: DirectPayStartOptions): boolean {
|
|
432
|
+
return o.settings.receiveEnabled && this._foreground && this._receiveScreens > 0
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* A Receive screen opened or the last one closed: starts or stops receiving on the current
|
|
437
|
+
* client, without replacing it (a payment being sent keeps its connection).
|
|
438
|
+
*/
|
|
439
|
+
private _receiveScreenChanged(): void {
|
|
440
|
+
const started = this._started
|
|
441
|
+
const client = this._snapshot.client
|
|
442
|
+
if (!started || !client) return
|
|
443
|
+
const want = this._receives(started.options)
|
|
444
|
+
if (want === this._receiving) return
|
|
445
|
+
if (!want) {
|
|
446
|
+
this._endReceiving()
|
|
447
|
+
return
|
|
448
|
+
}
|
|
449
|
+
// A setup problem (no relay address, no message box) leaves nothing to receive through.
|
|
450
|
+
if (this._snapshot.via === null || this._snapshot.notice) return
|
|
451
|
+
const fallback = this._snapshot.relayUnreachable
|
|
452
|
+
this._update({ status: 'starting', error: '' })
|
|
453
|
+
// On the message box after a fallback, `started.relay` is only the relay being retried.
|
|
454
|
+
void this._beginReceiving(
|
|
455
|
+
this._generation,
|
|
456
|
+
started.options,
|
|
457
|
+
client,
|
|
458
|
+
fallback ? null : started.relay,
|
|
459
|
+
fallback,
|
|
460
|
+
Promise.resolve()
|
|
461
|
+
)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Starts receiving on `client`: with the relay, the fallback to the message box when it is not
|
|
466
|
+
* online in time; on that fallback, the relay retry; then the client listens.
|
|
467
|
+
*/
|
|
468
|
+
private async _beginReceiving(
|
|
469
|
+
generation: number,
|
|
470
|
+
o: DirectPayStartOptions,
|
|
471
|
+
client: DirectPayClientLike,
|
|
472
|
+
relay: RelaySignalerLike | null,
|
|
473
|
+
fallback: boolean,
|
|
474
|
+
closing: Promise<void>
|
|
475
|
+
): Promise<void> {
|
|
476
|
+
this._receiving = true
|
|
477
|
+
const run = ++this._receiveRun
|
|
391
478
|
if (relay && !fallback && o.peerPayClient) {
|
|
392
479
|
// Not online through the relay in time: receive through the message box meanwhile.
|
|
393
480
|
const timer = setTimeout(() => {
|
|
394
|
-
if (generation === this._generation && this._snapshot.status !== 'online') {
|
|
481
|
+
if (generation === this._generation && run === this._receiveRun && this._snapshot.status !== 'online') {
|
|
395
482
|
this._fallBack(generation, o, 'it did not accept this wallet in time')
|
|
396
483
|
}
|
|
397
484
|
}, RELAY_START_MS)
|
|
398
|
-
this.
|
|
485
|
+
this._receiveCleanups.push(() => clearTimeout(timer))
|
|
399
486
|
}
|
|
400
487
|
if (fallback) this._retryRelayLater(generation, o)
|
|
401
488
|
|
|
402
489
|
// The previous client stops listening first, so two never answer the same offer.
|
|
403
490
|
await closing
|
|
404
|
-
if (generation !== this._generation) return
|
|
491
|
+
if (generation !== this._generation || run !== this._receiveRun) return
|
|
405
492
|
try {
|
|
493
|
+
// onPayment only: payment requests sent over a live session are dropped unanswered.
|
|
406
494
|
await client.startReceiving({
|
|
407
495
|
onPayment: (p, ctx) => this._onPayment(o, p, ctx.note),
|
|
408
496
|
onError: e => console.warn('[DirectPayManager] Inbound direct payment session failed:', messageOf(e))
|
|
409
497
|
})
|
|
410
498
|
// The status follows the relay's connection (_relayChanged) or the message box's polls
|
|
411
|
-
// (_messageBoxPolled), so it says online only once receiving works.
|
|
499
|
+
// (_messageBoxPolled), so it says online only once receiving works. A stop asked for
|
|
500
|
+
// meanwhile has already called stopReceiving, which runs after this start.
|
|
412
501
|
} catch (e) {
|
|
413
|
-
if (generation === this._generation) {
|
|
502
|
+
if (generation === this._generation && run === this._receiveRun) {
|
|
414
503
|
this._update({ status: 'error', error: `Direct payments cannot be received: ${messageOf(e)}` })
|
|
415
504
|
}
|
|
416
505
|
}
|
|
417
506
|
}
|
|
418
507
|
|
|
419
|
-
/**
|
|
420
|
-
|
|
421
|
-
|
|
508
|
+
/**
|
|
509
|
+
* The last Receive screen closed: the client stops answering dials (sessions already open run
|
|
510
|
+
* to their end), the relay retry stops, and the status is `off`. The client stays, for sending.
|
|
511
|
+
*/
|
|
512
|
+
private _endReceiving(): void {
|
|
513
|
+
if (!this._receiving) return
|
|
514
|
+
this._receiving = false
|
|
515
|
+
this._receiveRun++
|
|
516
|
+
this._runReceiveCleanups()
|
|
517
|
+
clearTimeout(this._stableTimer)
|
|
518
|
+
this._stableTimer = undefined
|
|
519
|
+
const client = this._snapshot.client
|
|
520
|
+
if (client) {
|
|
521
|
+
void client.stopReceiving().catch(e => console.warn('[DirectPayManager] Could not stop receiving:', messageOf(e)))
|
|
522
|
+
}
|
|
523
|
+
this._update({ status: 'off', error: '' })
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
private _runReceiveCleanups(): void {
|
|
527
|
+
const cleanups = this._receiveCleanups
|
|
528
|
+
this._receiveCleanups = []
|
|
529
|
+
for (const fn of cleanups) {
|
|
530
|
+
try {
|
|
531
|
+
fn()
|
|
532
|
+
} catch (e) {
|
|
533
|
+
console.warn('[DirectPayManager] Cleanup failed:', messageOf(e))
|
|
534
|
+
}
|
|
535
|
+
}
|
|
422
536
|
}
|
|
423
537
|
|
|
424
538
|
/** Receiving through the relay failed: receive through the message box, retrying the relay. */
|
|
@@ -438,10 +552,11 @@ export class DirectPayManager {
|
|
|
438
552
|
*/
|
|
439
553
|
private _retryRelayLater(generation: number, o: DirectPayStartOptions): void {
|
|
440
554
|
const wait = Math.min(RELAY_RETRY_FIRST_MS * 2 ** Math.max(0, this._fallbacks - 1), RELAY_RETRY_MAX_MS)
|
|
555
|
+
let retry: RelaySignalerLike | null = null
|
|
441
556
|
const timer = setTimeout(() => {
|
|
442
557
|
const started = this._started
|
|
443
558
|
if (generation !== this._generation || !started) return
|
|
444
|
-
|
|
559
|
+
retry = new this._deps.webrtpay.RelaySignaler({
|
|
445
560
|
url: o.settings.relayUrl,
|
|
446
561
|
wallet: o.wallet,
|
|
447
562
|
originator: o.originator,
|
|
@@ -456,18 +571,14 @@ export class DirectPayManager {
|
|
|
456
571
|
/* closed */
|
|
457
572
|
})
|
|
458
573
|
}, wait)
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
started.unsubscribe = () => {
|
|
468
|
-
fn()
|
|
469
|
-
unsubscribe()
|
|
470
|
-
}
|
|
574
|
+
// Receiving ended: the retry's relay connection (which makes this wallet look online) closes.
|
|
575
|
+
this._receiveCleanups.push(() => {
|
|
576
|
+
clearTimeout(timer)
|
|
577
|
+
const started = this._started
|
|
578
|
+
if (!retry) return
|
|
579
|
+
if (started?.relay === retry) started.relay = null
|
|
580
|
+
void retry.close().catch(() => {})
|
|
581
|
+
})
|
|
471
582
|
}
|
|
472
583
|
|
|
473
584
|
/** The relay being retried accepted this wallet: receiving moves back to it. */
|
|
@@ -497,7 +608,7 @@ export class DirectPayManager {
|
|
|
497
608
|
if (generation !== this._generation) return
|
|
498
609
|
if (state === 'online') this._relayDown = false
|
|
499
610
|
else if (state === 'offline' && e) this._relayDown = true
|
|
500
|
-
if (!this.
|
|
611
|
+
if (!this._receiving) return
|
|
501
612
|
// Online long enough: the next fallback retries the relay after the shortest wait again.
|
|
502
613
|
if (state === 'online' && this._stableTimer === undefined) {
|
|
503
614
|
this._stableTimer = setTimeout(() => {
|
|
@@ -522,8 +633,8 @@ export class DirectPayManager {
|
|
|
522
633
|
* worked, and `error` after {@link POLL_FAILURES_SHOWN} failures in a row (the signaler keeps
|
|
523
634
|
* polling, and the status recovers by itself).
|
|
524
635
|
*/
|
|
525
|
-
private _messageBoxPolled(generation: number,
|
|
526
|
-
if (generation !== this._generation || !
|
|
636
|
+
private _messageBoxPolled(generation: number, failures: number, error: unknown): void {
|
|
637
|
+
if (generation !== this._generation || !this._receiving) return
|
|
527
638
|
if (failures === 0) this._update({ status: 'online', error: '' })
|
|
528
639
|
else if (failures >= POLL_FAILURES_SHOWN) {
|
|
529
640
|
this._update({
|
|
@@ -702,6 +813,9 @@ export class DirectPayManager {
|
|
|
702
813
|
/** Detaches the current client and signaler; returns their closing (never rejects). */
|
|
703
814
|
private _teardown(): Promise<void> {
|
|
704
815
|
this._generation++
|
|
816
|
+
this._receiving = false
|
|
817
|
+
this._receiveRun++
|
|
818
|
+
this._runReceiveCleanups()
|
|
705
819
|
clearTimeout(this._stableTimer)
|
|
706
820
|
this._stableTimer = undefined
|
|
707
821
|
this._relayDown = false
|
|
@@ -745,6 +859,11 @@ export class DirectPayManager {
|
|
|
745
859
|
*/
|
|
746
860
|
export const signalBox = (chain: string) => (chain === 'main' ? 'webrtpay_signals' : `webrtpay_signals_${chain}`)
|
|
747
861
|
|
|
862
|
+
/** The relay's TURN servers without the STUN servers its answer names (see onlyOwnStun). */
|
|
863
|
+
function ownStunOnly<T extends { urls: string | string[] }>(provider: () => Promise<T[]>): () => Promise<T[]> {
|
|
864
|
+
return async () => onlyOwnStun(await provider())
|
|
865
|
+
}
|
|
866
|
+
|
|
748
867
|
/**
|
|
749
868
|
* The message box client as the signaler sees it: the same calls, with each listing (a poll)
|
|
750
869
|
* reported to `polled`, with its error when it failed. The live websocket calls and the host
|
|
@@ -71,6 +71,11 @@ export interface DirectPayContextValue {
|
|
|
71
71
|
* `NotSentError` when it stopped before the payment was made.
|
|
72
72
|
*/
|
|
73
73
|
sendDirect: (args: DirectPaySendArgs) => Promise<DirectSendResult>
|
|
74
|
+
/**
|
|
75
|
+
* The Receive screen is showing: live payments are answered only while it is (see
|
|
76
|
+
* `DirectPayManager.openReceiveScreen`). Returns the function to call when it stops showing.
|
|
77
|
+
*/
|
|
78
|
+
openReceiveScreen: () => () => void
|
|
74
79
|
}
|
|
75
80
|
|
|
76
81
|
const OFF_SNAPSHOT: DirectPaySnapshot = {
|
|
@@ -88,6 +93,8 @@ const unavailable = async (): Promise<never> => {
|
|
|
88
93
|
throw new NotSentError('Direct payments are not available', 'not configured')
|
|
89
94
|
}
|
|
90
95
|
|
|
96
|
+
const noReceiveScreen = () => () => {}
|
|
97
|
+
|
|
91
98
|
const DirectPayContext = createContext<DirectPayContextValue>({
|
|
92
99
|
available: false,
|
|
93
100
|
snapshot: OFF_SNAPSHOT,
|
|
@@ -96,7 +103,8 @@ const DirectPayContext = createContext<DirectPayContextValue>({
|
|
|
96
103
|
saveSettings: unavailable,
|
|
97
104
|
reload: async () => {},
|
|
98
105
|
canSendDirect: false,
|
|
99
|
-
sendDirect: unavailable
|
|
106
|
+
sendDirect: unavailable,
|
|
107
|
+
openReceiveScreen: () => () => {}
|
|
100
108
|
})
|
|
101
109
|
|
|
102
110
|
export const useDirectPay = (): DirectPayContextValue => useContext(DirectPayContext)
|
|
@@ -303,7 +311,8 @@ export const DirectPayProvider: React.FC<{ children: React.ReactNode; onToast?:
|
|
|
303
311
|
saveSettings,
|
|
304
312
|
reload,
|
|
305
313
|
canSendDirect,
|
|
306
|
-
sendDirect
|
|
314
|
+
sendDirect,
|
|
315
|
+
openReceiveScreen: manager ? manager.openReceiveScreen : noReceiveScreen
|
|
307
316
|
}),
|
|
308
317
|
[manager, snapshot, settings, saveSettings, reload, canSendDirect, sendDirect]
|
|
309
318
|
)
|