@bsv/expo-wallet-toolbox 0.17.0 → 0.19.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.
@@ -25,6 +25,7 @@ import {
25
25
  TouchableOpacity,
26
26
  View
27
27
  } from 'react-native'
28
+ import { useDirectPay } from '../../../core/directpay/DirectPayProvider'
28
29
  import { useTranslation } from 'react-i18next'
29
30
  import { PeerPayClient, type IncomingPayment } from '@bsv/message-box-client'
30
31
  import { type DisplayableIdentity } from '@bsv/sdk'
@@ -48,6 +49,7 @@ import { makeCreditClassifier } from '../../../core/pay/creditErrors'
48
49
  import { satoshisFromToken } from '../../../core/pay/tokenAmount'
49
50
  import { userFacingPayError } from '../../../core/pay/userError'
50
51
  import { creditInboxOnce, type CreditInboxResult } from '../../../core/pay/creditInbox'
52
+ import { inboxSeenStore } from '../../../core/directpay/receive'
51
53
  import { setReceiveInboxFocused } from '../../../core/pay/receiveFocus'
52
54
  import { TaskCreditInbox } from '../../../core/monitor/TaskCreditInbox'
53
55
  import { useOnline } from '../../hooks/useOnline'
@@ -407,6 +409,7 @@ export default function HandleReceive({
407
409
  }: HandleReceiveProps = {}) {
408
410
  const { t } = useTranslation()
409
411
  const { colors } = useTheme()
412
+ const directPay = useDirectPay()
410
413
  const Ionicons = loadIonicons()
411
414
  const QRCode = loadQRCode()
412
415
  const { useFocusEffect } = loadExpoRouter()
@@ -547,16 +550,20 @@ export default function HandleReceive({
547
550
  [selectedNetwork]
548
551
  )
549
552
 
553
+ // With direct payments on, a payment that arrived live as well is credited,
554
+ // and celebrated, once (see core/directpay/receive.ts).
555
+ const seen = useMemo(() => inboxSeenStore(identityKey, selectedNetwork), [identityKey, selectedNetwork])
556
+
550
557
  const internalize = useCallback(
551
558
  async (payment: IncomingPayment) => {
552
559
  const client = peerPayClient
553
560
  if (!client || !wallet) throw new Error(t('wallet_not_ready'))
554
- await internalizeIncoming(wallet as any, client, adminOriginator, payment, repairBeef)
561
+ return await internalizeIncoming(wallet as any, client, adminOriginator, payment, repairBeef, seen)
555
562
  },
556
- [peerPayClient, wallet, adminOriginator, t, repairBeef]
563
+ [peerPayClient, wallet, adminOriginator, t, repairBeef, seen]
557
564
  )
558
565
 
559
- const applyCreditResult = useCallback((outcome: CreditInboxResult) => {
566
+ const applyCreditResult = useCallback((outcome: CreditInboxResult, duplicates: ReadonlySet<string> = new Set()) => {
560
567
  TaskCreditInbox.lastAttentionCount = outcome.attentionCount
561
568
  attemptsRef.current = outcome.attempts
562
569
  setAttempts(outcome.attempts)
@@ -568,7 +575,10 @@ export default function HandleReceive({
568
575
  // looked at — and whether it landed is the one thing a payee must never
569
576
  // be left unsure about. Everything not left in the attempt map was
570
577
  // credited, so that is what the figure sums.
571
- const credited = outcome.payments.filter(p => !outcome.attempts[String(p.messageId)])
578
+ // A duplicate (taken live first) left the box but was celebrated then.
579
+ const credited = outcome.payments.filter(
580
+ p => !outcome.attempts[String(p.messageId)] && !duplicates.has(String(p.messageId))
581
+ )
572
582
  setReceived({
573
583
  amount: credited.reduce((sum, p) => sum + (satoshisFromToken(p.token)?.satoshis ?? 0), 0),
574
584
  count: outcome.accepted
@@ -584,15 +594,20 @@ export default function HandleReceive({
584
594
  getOnline: () => online,
585
595
  peekLastMissHeight
586
596
  })
597
+ const duplicates = new Set<string>()
587
598
  const outcome = await creditInboxOnce({
588
599
  client,
589
600
  messageBoxUrl,
590
601
  storage: storage ?? undefined,
591
602
  force,
592
603
  classify,
593
- accept: payment => acceptWithRetry(client, messageBoxUrl, payment, internalize)
604
+ accept: async payment => {
605
+ const credited = await acceptWithRetry(client, messageBoxUrl, payment, internalize)
606
+ if (credited === 'duplicate') duplicates.add(String(payment.messageId))
607
+ return credited
608
+ }
594
609
  })
595
- applyCreditResult(outcome)
610
+ applyCreditResult(outcome, duplicates)
596
611
  return outcome
597
612
  },
598
613
  [peerPayClient, messageBoxUrl, storage, online, peekLastMissHeight, internalize, applyCreditResult]
@@ -935,6 +950,34 @@ export default function HandleReceive({
935
950
  // Scrolls, because a 240pt QR plus the inbox overflows a small screen and a
936
951
  // note being edited puts the keyboard over the row that owns it.
937
952
  <ScrollView contentContainerStyle={styles.container} keyboardShouldPersistTaps="handled">
953
+ {/* Live payments: whether this wallet can be paid directly while the app is open. Only in a
954
+ build that offers them, and only for BSV (a token always arrives by message box). */}
955
+ {directPay.available && !asset && (
956
+ <View
957
+ style={[styles.liveCard, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
958
+ accessibilityLiveRegion="polite"
959
+ >
960
+ <View
961
+ style={[
962
+ styles.liveDot,
963
+ {
964
+ backgroundColor:
965
+ directPay.live.tone === 'on'
966
+ ? colors.success
967
+ : directPay.live.tone === 'error'
968
+ ? colors.error
969
+ : directPay.live.tone === 'connecting'
970
+ ? colors.warning
971
+ : colors.separator
972
+ }
973
+ ]}
974
+ />
975
+ <View style={styles.liveText}>
976
+ <Text style={[styles.liveTitle, { color: colors.textPrimary }]}>{t(directPay.live.titleKey)}</Text>
977
+ <Text style={[styles.liveBody, { color: colors.textSecondary }]}>{t(directPay.live.bodyKey)}</Text>
978
+ </View>
979
+ </View>
980
+ )}
938
981
  {/* Your handle. The QR is the focal element — it is the thing physically
939
982
  held up to another device. */}
940
983
  {/* The figure the code asks for, as its price. Only when one was named. */}
@@ -1058,6 +1101,19 @@ export default function HandleReceive({
1058
1101
  }
1059
1102
 
1060
1103
  const styles = StyleSheet.create({
1104
+ liveCard: {
1105
+ flexDirection: 'row',
1106
+ alignItems: 'flex-start',
1107
+ gap: 10,
1108
+ padding: 14,
1109
+ borderRadius: 14,
1110
+ borderWidth: StyleSheet.hairlineWidth,
1111
+ marginBottom: 16
1112
+ },
1113
+ liveDot: { width: 10, height: 10, borderRadius: 5, marginTop: 5 },
1114
+ liveText: { flex: 1 },
1115
+ liveTitle: { fontSize: 15, fontWeight: '600' },
1116
+ liveBody: { fontSize: 13, marginTop: 2 },
1061
1117
  container: {
1062
1118
  paddingHorizontal: spacing.lg,
1063
1119
  paddingTop: spacing.lg
@@ -25,6 +25,9 @@ import AmountDisplay from '../wallet/AmountDisplay'
25
25
  import { showAlert } from '../ui/AlertCard'
26
26
  import { showChoiceSheet } from '../ui/ChoiceSheet'
27
27
  import { promptCheckWallet } from '../../screens/WalletCheckScreen'
28
+ import { useDirectPay } from '../../../core/directpay/DirectPayProvider'
29
+ import { fallbackPrompt, payIdentity } from '../../../core/directpay/payFlow'
30
+ import type { PayOutcome } from '../../../core/directpay/types'
28
31
  import { userFacingPayError } from '../../../core/pay/userError'
29
32
  import PressableScale from '../ui/PressableScale'
30
33
  import { showToast } from '../ui/Toast'
@@ -847,23 +850,64 @@ function UniversalSendInner(
847
850
  [t]
848
851
  )
849
852
 
853
+ const directPay = useDirectPay()
854
+
850
855
  const sendHandle = useCallback(
851
856
  async (to: Extract<RecipientTarget, { kind: 'handle' }>, sats: number) => {
852
857
  const client = peerPayClient
853
858
  if (!client) throw new Error(t('message_box_off_hint'))
854
859
  if (!storage || !wallet) throw new Error(t('wallet_not_ready'))
855
- const { satoshis: paidSats } = await sendViaHandle({
856
- wallet: wallet as any,
857
- adminOriginator,
858
- client,
859
- storage,
860
- recipient: to.identityKey,
861
- recipientHost: to.messageBoxUrl,
862
- satoshis: sats,
863
- messageBoxUrl,
864
- note,
865
- recipientName: recipient.selectedIdentity?.name
866
- })
860
+ const recipientName = recipient.selectedIdentity?.name
861
+ const name = recipientName || abbreviateKey(to.identityKey)
862
+ let paidSats = sats
863
+ const viaMessageBox = async () => {
864
+ const result = await sendViaHandle({
865
+ wallet: wallet as any,
866
+ adminOriginator,
867
+ client,
868
+ storage,
869
+ recipient: to.identityKey,
870
+ recipientHost: to.messageBoxUrl,
871
+ satoshis: sats,
872
+ messageBoxUrl,
873
+ note,
874
+ recipientName
875
+ })
876
+ paidSats = result.satoshis
877
+ }
878
+ // Live first when this build and wallet can pay directly; the message box is the fallback,
879
+ // offered only when the live attempt proved nothing was spent (see payIdentity).
880
+ const viaDirect = directPay.canSendDirect
881
+ ? async () => {
882
+ const result = await directPay.sendDirect({
883
+ recipient: to.identityKey,
884
+ satoshis: sats,
885
+ note,
886
+ recipientName,
887
+ recipientHost: to.messageBoxUrl
888
+ })
889
+ paidSats = result.satoshis
890
+ return result
891
+ }
892
+ : undefined
893
+ let outcome: PayOutcome = await payIdentity({ direct: viaDirect, messageBox: viaMessageBox, name })
894
+ if (outcome.kind === 'ask_fallback') {
895
+ const prompt = fallbackPrompt(outcome.reason, name)
896
+ const choice = await showAlert({
897
+ title: t('direct_pay_fallback_title'),
898
+ message: t(prompt.key, prompt.params),
899
+ buttons: [
900
+ { text: t('cancel'), key: 'cancel', style: 'cancel' },
901
+ { text: t('direct_pay_fallback_send'), key: 'send' }
902
+ ]
903
+ })
904
+ if (choice !== 'send') throw new Error(t('direct_pay_failed_cancelled'))
905
+ outcome = await payIdentity({ messageBox: viaMessageBox, name })
906
+ }
907
+ if (outcome.kind === 'failed') {
908
+ if (outcome.detail) console.warn('[pay] direct pay failed:', outcome.key, outcome.detail)
909
+ throw new Error(t(outcome.key, outcome.params))
910
+ }
867
911
  await loadOutbox()
868
912
  // The overlay stages its own haptic (inside Celebration) and tone; firing
869
913
  // haptics.success() here would double the beat. Only a human-readable
@@ -875,11 +919,12 @@ function UniversalSendInner(
875
919
  // The handle rail always drops the payment in the recipient's message
876
920
  // box rather than handing it over in person — worth saying explicitly
877
921
  // here, since it is the one thing an in-person (Nearby) payer never
878
- // has to wonder about (ux §4.2/§8 "Success / arrival").
879
- statusNote: t('pay_sent_handed_to_wallet')
922
+ // has to wonder about (ux §4.2/§8 "Success / arrival"). A live payment is already in
923
+ // the recipient's wallet, so it says that instead.
924
+ statusNote: outcome.kind === 'paid_live' ? t('direct_pay_sent_live') : t('pay_sent_handed_to_wallet')
880
925
  })
881
926
  },
882
- [peerPayClient, storage, wallet, adminOriginator, messageBoxUrl, note, recipient.selectedIdentity, loadOutbox, t]
927
+ [peerPayClient, storage, wallet, adminOriginator, messageBoxUrl, note, recipient.selectedIdentity, loadOutbox, t, directPay]
883
928
  )
884
929
 
885
930
  const sendAddress = useCallback(
@@ -18,6 +18,7 @@ import { PeerPayClient } from '@bsv/message-box-client'
18
18
  import { showAlert } from '../components/ui/AlertCard'
19
19
  import { makeCreditClassifier } from '../../core/pay/creditErrors'
20
20
  import { creditInboxOnce } from '../../core/pay/creditInbox'
21
+ import { inboxSeenStore } from '../../core/directpay/receive'
21
22
  import { makeBeefRepair } from '../../core/pay/beefRepair'
22
23
  import {
23
24
  acceptWithRetry,
@@ -199,6 +200,12 @@ function useWalletCheckPorts(): WalletCheckPorts {
199
200
  })
200
201
  const repairBeef = makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline })
201
202
  const classify = await makeCreditClassifier({ getOnline, peekLastMissHeight })
203
+ // With direct payments on, one that arrived live as well is credited once.
204
+ const identity = await wallet
205
+ .getPublicKey({ identityKey: true }, adminOriginator)
206
+ .then(r => r.publicKey)
207
+ .catch(() => undefined)
208
+ const seen = inboxSeenStore(identity, selectedNetwork)
202
209
  const outcome = await creditInboxOnce({
203
210
  client,
204
211
  messageBoxUrl,
@@ -206,7 +213,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
206
213
  classify,
207
214
  accept: payment =>
208
215
  acceptWithRetry(client, messageBoxUrl, payment, p =>
209
- internalizeIncoming(wallet as never, client, adminOriginator, p, repairBeef)
216
+ internalizeIncoming(wallet as never, client, adminOriginator, p, repairBeef, seen)
210
217
  )
211
218
  })
212
219
  return { accepted: outcome.accepted }