@bsv/expo-wallet-toolbox 0.1.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/LICENSE.txt +28 -0
- package/README.md +512 -0
- package/assets/sounds/payment-receive.wav +0 -0
- package/assets/sounds/payment-send.wav +0 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/amountFormatHelpers.ts +330 -0
- package/core/backup/RemoteSyncReader.ts +94 -0
- package/core/backup/client.ts +111 -0
- package/core/backup/codec.ts +218 -0
- package/core/backup/constants.ts +88 -0
- package/core/backup/cursor.ts +138 -0
- package/core/backup/derive.ts +46 -0
- package/core/backup/deviceId.ts +33 -0
- package/core/backup/erase.ts +67 -0
- package/core/backup/preference.ts +33 -0
- package/core/backup/push.ts +295 -0
- package/core/backup/restore.ts +152 -0
- package/core/backup/restoreOnImport.ts +119 -0
- package/core/backup/status.ts +46 -0
- package/core/config.tsx +47 -0
- package/core/constants.ts +35 -0
- package/core/context/ExchangeRateContext.tsx +69 -0
- package/core/context/LocalStorageProvider.tsx +225 -0
- package/core/context/UserContext.tsx +129 -0
- package/core/context/VaultContext.tsx +79 -0
- package/core/context/WalletConnectionContext.tsx +454 -0
- package/core/context/WalletContext.tsx +2938 -0
- package/core/context/buildGeneration.ts +37 -0
- package/core/deviceTier.ts +89 -0
- package/core/diskSpace.ts +62 -0
- package/core/displayCurrencies.ts +56 -0
- package/core/headers/OfflineFirstChaintracks.ts +176 -0
- package/core/headers/checkpoints.ts +39 -0
- package/core/headers/fs.ts +119 -0
- package/core/headers/headerStore.ts +333 -0
- package/core/headers/prewarm.ts +36 -0
- package/core/headers/syncHeaders.ts +73 -0
- package/core/hooks/useConfirmationSound.ts +135 -0
- package/core/hooks/useHaptics.ts +51 -0
- package/core/hooks/usePermissionQueue.ts +69 -0
- package/core/i18n/translations.tsx +6692 -0
- package/core/index.ts +295 -0
- package/core/localpay/blePermissions.ts +32 -0
- package/core/localpay/build.ts +392 -0
- package/core/localpay/codec.ts +338 -0
- package/core/localpay/deviceCaps.ts +175 -0
- package/core/localpay/nearbyAdvisory.ts +32 -0
- package/core/localpay/nearbyPermissions.ts +34 -0
- package/core/localpay/pending.ts +385 -0
- package/core/localpay/pendingAborts.ts +67 -0
- package/core/localpay/qr.ts +16 -0
- package/core/localpay/session.ts +277 -0
- package/core/localpay/sessionPolicy.ts +5 -0
- package/core/localpay/transport/awdl.ts +11 -0
- package/core/localpay/transport/ble.ts +159 -0
- package/core/localpay/transport/nearby.ts +12 -0
- package/core/localpay/transport/race.ts +110 -0
- package/core/localpay/transport/select.ts +128 -0
- package/core/localpay/transport/socket.ts +244 -0
- package/core/localpay/types.ts +82 -0
- package/core/localpay/verify.ts +204 -0
- package/core/logging.config.ts +10 -0
- package/core/logging.ts +77 -0
- package/core/mnemonicWallet.ts +180 -0
- package/core/monitor/TaskBackupPush.ts +168 -0
- package/core/monitor/TaskCreditInbox.ts +116 -0
- package/core/monitor/TaskDrainOutbox.ts +122 -0
- package/core/monitor/TaskSendOffline.ts +123 -0
- package/core/monitor/unfailRetry.ts +116 -0
- package/core/net/chainMatch.ts +34 -0
- package/core/net/online.ts +34 -0
- package/core/offline/cancelParked.ts +56 -0
- package/core/offline/hold.ts +127 -0
- package/core/offline/order.ts +109 -0
- package/core/offline/payerHold.ts +144 -0
- package/core/offline/plan.ts +264 -0
- package/core/offline/queueGrace.ts +52 -0
- package/core/parsePeerPayURI.ts +119 -0
- package/core/pay/beefRepair.ts +106 -0
- package/core/pay/creditErrors.ts +46 -0
- package/core/pay/creditInbox.ts +202 -0
- package/core/pay/damagedInbox.ts +64 -0
- package/core/pay/proofNudge.ts +23 -0
- package/core/pay/provenTxFromBump.ts +31 -0
- package/core/pay/rails/address.ts +329 -0
- package/core/pay/rails/handle.ts +617 -0
- package/core/pay/rails/index.ts +197 -0
- package/core/pay/rails/nearby.ts +79 -0
- package/core/pay/receiveFocus.ts +13 -0
- package/core/pay/recordProof.ts +91 -0
- package/core/pay/refreshProofGuard.ts +34 -0
- package/core/pay/sweeper.ts +75 -0
- package/core/pay/tokenAmount.ts +18 -0
- package/core/pay/userError.ts +18 -0
- package/core/pay/watchlist.ts +126 -0
- package/core/peerpay/control.ts +122 -0
- package/core/peerpay/handleResendRequests.ts +475 -0
- package/core/peerpay/inboxAttempts.ts +33 -0
- package/core/peerpay/metadataDecryptor.ts +42 -0
- package/core/peerpay/offlineNacks.ts +96 -0
- package/core/peerpay/outbox.ts +209 -0
- package/core/peerpay/rebuildToken.ts +76 -0
- package/core/peerpay/resendBeef.ts +115 -0
- package/core/services/arcadeBroadcastProvider.ts +214 -0
- package/core/services/capWalletArgs.ts +99 -0
- package/core/services/exchangeRate.ts +63 -0
- package/core/services/secrets/envelope.ts +102 -0
- package/core/services/secrets/hkdf.ts +37 -0
- package/core/services/secrets/index.ts +63 -0
- package/core/services/secrets/kek.ts +274 -0
- package/core/services/secrets/migration.ts +188 -0
- package/core/services/secrets/policy.ts +120 -0
- package/core/services/secrets/storage.ts +54 -0
- package/core/services/secrets/store.ts +125 -0
- package/core/services/secrets/types.ts +85 -0
- package/core/services/usdFxRates.ts +101 -0
- package/core/services/vault/VaultKeyService.ts +312 -0
- package/core/services/vault/backupAttestation.ts +136 -0
- package/core/services/vault/ceremony.ts +972 -0
- package/core/services/vault/ceremonyHost.ts +46 -0
- package/core/services/vault/devMock.ts +22 -0
- package/core/services/vault/driver.ts +197 -0
- package/core/services/vault/guard.ts +90 -0
- package/core/services/vault/k1.ts +75 -0
- package/core/services/vault/mockYubiKey.ts +217 -0
- package/core/services/vault/random.ts +20 -0
- package/core/services/vault/sealing.ts +84 -0
- package/core/services/vault/session.ts +59 -0
- package/core/services/vault/transfers.ts +1151 -0
- package/core/services/vault/types.ts +109 -0
- package/core/services/vault/vaultDerivation.ts +152 -0
- package/core/services/vault/vaultPassphrase.ts +287 -0
- package/core/services/vault/vaultStore.ts +104 -0
- package/core/services/walletArgLimits.ts +234 -0
- package/core/services/walletServiceConfig.ts +170 -0
- package/core/storage/LocalStorageAdapter.ts +58 -0
- package/core/storage/README.md +391 -0
- package/core/storage/StorageExpoSQLite.ts +2008 -0
- package/core/storage/errors.ts +73 -0
- package/core/storage/index.ts +3 -0
- package/core/storage/methods/findSql.ts +286 -0
- package/core/storage/methods/historyNotes.ts +61 -0
- package/core/storage/methods/listActionsSql.ts +212 -0
- package/core/storage/methods/listOutputsSql.ts +211 -0
- package/core/storage/methods/offlineActions.ts +156 -0
- package/core/storage/methods/processOfflineActions.ts +503 -0
- package/core/storage/methods/reclaim.ts +135 -0
- package/core/storage/methods/reviewStatusSql.ts +167 -0
- package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
- package/core/storage/methods/walletBalanceSql.ts +55 -0
- package/core/storage/schema/createTables.ts +385 -0
- package/core/storage/skipQueuedAncestors.ts +29 -0
- package/core/storage/sqlUpdateValue.ts +12 -0
- package/core/stores/ConnectionStore.ts +71 -0
- package/core/theme/ThemeContext.tsx +182 -0
- package/core/theme/assertThemeContrast.ts +109 -0
- package/core/theme/motion.ts +50 -0
- package/core/theme/tokens.ts +232 -0
- package/core/theme/useThemeStyles.tsx +156 -0
- package/core/walletDbRegistry.ts +110 -0
- package/core/walletMonitor.ts +149 -0
- package/core/walletRepair/runWalletCheck.ts +195 -0
- package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
- package/package.json +86 -0
- package/ui/backupShares.ts +367 -0
- package/ui/components/QRScanner.tsx +353 -0
- package/ui/components/pay/AddressReceive.tsx +507 -0
- package/ui/components/pay/AvailableBalance.tsx +61 -0
- package/ui/components/pay/HandleReceive.tsx +896 -0
- package/ui/components/pay/MessageBoxConfig.tsx +256 -0
- package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
- package/ui/components/pay/NearbyFlow.tsx +2542 -0
- package/ui/components/pay/OfflineNotice.tsx +337 -0
- package/ui/components/pay/PayCellRow.tsx +101 -0
- package/ui/components/pay/PayForm.tsx +223 -0
- package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
- package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
- package/ui/components/pay/RecipientField.tsx +308 -0
- package/ui/components/pay/RequestHub.tsx +75 -0
- package/ui/components/pay/ResultBanner.tsx +69 -0
- package/ui/components/pay/UniversalSend.tsx +687 -0
- package/ui/components/pay/useRecipientInput.ts +270 -0
- package/ui/components/security/WalletLockNotice.tsx +138 -0
- package/ui/components/ui/AlertCard.tsx +223 -0
- package/ui/components/ui/AppLogo.tsx +166 -0
- package/ui/components/ui/BlurChrome.tsx +72 -0
- package/ui/components/ui/Celebration.tsx +84 -0
- package/ui/components/ui/ChoiceSheet.ts +69 -0
- package/ui/components/ui/CustomSafeArea.tsx +74 -0
- package/ui/components/ui/ErrorBoundary.tsx +154 -0
- package/ui/components/ui/GroupedList.tsx +125 -0
- package/ui/components/ui/IconButton.tsx +105 -0
- package/ui/components/ui/ListRow.tsx +197 -0
- package/ui/components/ui/PermissionSheet.tsx +920 -0
- package/ui/components/ui/PresenceRow.tsx +215 -0
- package/ui/components/ui/PressableScale.tsx +105 -0
- package/ui/components/ui/ScreenGradient.tsx +47 -0
- package/ui/components/ui/ScrollFade.tsx +76 -0
- package/ui/components/ui/Sheet.tsx +342 -0
- package/ui/components/ui/Toast.tsx +142 -0
- package/ui/components/ui/index.ts +8 -0
- package/ui/components/vault/EnrollWizard.tsx +627 -0
- package/ui/components/vault/PassphraseField.tsx +306 -0
- package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
- package/ui/components/vault/VaultBackdrop.tsx +354 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
- package/ui/components/wallet/ActivityRow.tsx +408 -0
- package/ui/components/wallet/AmountDisplay.tsx +48 -0
- package/ui/components/wallet/AmountInput.tsx +256 -0
- package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
- package/ui/components/wallet/Balance.tsx +144 -0
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
- package/ui/exportDatabases.ts +122 -0
- package/ui/exportTransactions.ts +129 -0
- package/ui/hooks/useOfflineNoticeActions.ts +136 -0
- package/ui/hooks/useOnline.ts +70 -0
- package/ui/hooks/useSpendableBalance.ts +58 -0
- package/ui/hooks/useVaultBalance.ts +50 -0
- package/ui/importDatabases.ts +170 -0
- package/ui/index.ts +136 -0
- package/ui/isImageUrl.ts +10 -0
- package/ui/printRecoveryShares.ts +93 -0
- package/ui/resolveIdentity.ts +125 -0
- package/ui/screens/ConnectionsScreen.tsx +438 -0
- package/ui/screens/LogsScreen.tsx +432 -0
- package/ui/screens/PairScreen.tsx +288 -0
- package/ui/screens/PayScreen.tsx +479 -0
- package/ui/screens/SettingsScreen.tsx +180 -0
- package/ui/screens/TrustScreen.tsx +831 -0
- package/ui/screens/VaultRecoverScreen.tsx +226 -0
- package/ui/screens/VaultScreen.tsx +423 -0
- package/ui/screens/VaultTransferScreen.tsx +293 -0
- package/ui/screens/WalletCheckScreen.tsx +539 -0
- package/ui/screens/WalletConfigScreen.tsx +1095 -0
- package/ui/screens/WalletHomeScreen.tsx +1597 -0
- package/ui/screens/homeBadges.ts +18 -0
- package/ui/txStatus.ts +79 -0
- package/ui/validateTrust.ts +44 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The address rail — payments to and from conventional wallets.
|
|
3
|
+
*
|
|
4
|
+
* This is the only bridge between this wallet and the rest of the ecosystem,
|
|
5
|
+
* so every line here is a straight port from app/legacy-payments.tsx. The
|
|
6
|
+
* derivation in particular is load-bearing in a way that is easy to miss: the
|
|
7
|
+
* key ID is `base64(YYYY-MM-DD) + ' ' + base64('legacy')`, so the date string
|
|
8
|
+
* IS part of the private key path. Any change to how that string is produced
|
|
9
|
+
* makes previously-issued addresses — and the money sitting on them —
|
|
10
|
+
* unreachable. getCurrentDate's local-time/UTC mix is therefore deliberate and
|
|
11
|
+
* must not be "corrected".
|
|
12
|
+
*/
|
|
13
|
+
import {
|
|
14
|
+
Beef,
|
|
15
|
+
P2PKH,
|
|
16
|
+
PrivateKey,
|
|
17
|
+
PublicKey,
|
|
18
|
+
Transaction,
|
|
19
|
+
Utils,
|
|
20
|
+
type InternalizeActionArgs,
|
|
21
|
+
type InternalizeOutput,
|
|
22
|
+
type WalletProtocol
|
|
23
|
+
} from '@bsv/sdk'
|
|
24
|
+
import type { AppChain } from '../../config'
|
|
25
|
+
import { isValidBsvAddress } from './index'
|
|
26
|
+
|
|
27
|
+
export const BRC29_PROTOCOL_ID: WalletProtocol = [2, '3241645161d8']
|
|
28
|
+
|
|
29
|
+
export const LEGACY_DERIVATION_SUFFIX = Utils.toBase64(Utils.toArray('legacy', 'utf8'))
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* How far back the manual recovery stepper may reach. The background sweeper
|
|
33
|
+
* has its own, much tighter bound (see pay/watchlist.ts): this one exists
|
|
34
|
+
* because an address a payer sat on for three weeks still holds real money.
|
|
35
|
+
*/
|
|
36
|
+
export const MAX_RECOVERY_DAYS = 30
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Verbatim from legacy-payments.tsx. `setDate` on a local Date then
|
|
40
|
+
* `toISOString()` — the mix is what previously-issued addresses were derived
|
|
41
|
+
* with, so it stays. `now` is injectable for tests only; production always
|
|
42
|
+
* takes the default.
|
|
43
|
+
*/
|
|
44
|
+
export const getCurrentDate = (daysOffset: number, now: Date = new Date()): string => {
|
|
45
|
+
const today = new Date(now.getTime())
|
|
46
|
+
today.setDate(today.getDate() - daysOffset)
|
|
47
|
+
return today.toISOString().split('T')[0]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function derivationPrefixFor(date: string): string {
|
|
51
|
+
return Utils.toBase64(Utils.toArray(date, 'utf8'))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** One ASCII space. The wallet derives a different key for any other separator. */
|
|
55
|
+
export function legacyKeyId(derivationPrefix: string): string {
|
|
56
|
+
return `${derivationPrefix} ${LEGACY_DERIVATION_SUFFIX}`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface WocConfig {
|
|
60
|
+
apiBase: string
|
|
61
|
+
segment: string
|
|
62
|
+
network: 'mainnet' | 'testnet'
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function wocConfigFor(network: AppChain): WocConfig {
|
|
66
|
+
return {
|
|
67
|
+
main: { apiBase: 'https://api.whatsonchain.com', segment: 'main', network: 'mainnet' as const },
|
|
68
|
+
test: { apiBase: 'https://api.whatsonchain.com', segment: 'test', network: 'testnet' as const },
|
|
69
|
+
teratest: { apiBase: 'https://api.woc-ttn.bsvblockchain.tech', segment: 'test', network: 'testnet' as const }
|
|
70
|
+
}[network]
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface AddressDerivingWallet {
|
|
74
|
+
getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function getPaymentAddress(
|
|
78
|
+
wallet: AddressDerivingWallet,
|
|
79
|
+
adminOriginator: string,
|
|
80
|
+
derivationPrefix: string,
|
|
81
|
+
network: 'mainnet' | 'testnet'
|
|
82
|
+
): Promise<string> {
|
|
83
|
+
const { publicKey } = await wallet.getPublicKey(
|
|
84
|
+
{
|
|
85
|
+
protocolID: BRC29_PROTOCOL_ID,
|
|
86
|
+
keyID: legacyKeyId(derivationPrefix),
|
|
87
|
+
counterparty: 'anyone',
|
|
88
|
+
forSelf: true
|
|
89
|
+
},
|
|
90
|
+
adminOriginator
|
|
91
|
+
)
|
|
92
|
+
return PublicKey.fromString(publicKey).toAddress(network)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface Utxo {
|
|
96
|
+
txid: string
|
|
97
|
+
vout: number
|
|
98
|
+
satoshis: number
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface ProcessedTx {
|
|
102
|
+
txid: string
|
|
103
|
+
satoshis: number
|
|
104
|
+
status: string
|
|
105
|
+
importedAt: Date | null
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface AddressRailWallet extends AddressDerivingWallet {
|
|
109
|
+
listActions(args: unknown, originator?: string): Promise<{ actions: any[] }>
|
|
110
|
+
internalizeAction(args: unknown, originator?: string): Promise<{ accepted?: boolean } | undefined>
|
|
111
|
+
createAction(args: unknown, originator?: string): Promise<unknown>
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function getUtxosForAddress(woc: WocConfig, address: string): Promise<Utxo[]> {
|
|
115
|
+
const response = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/unspent/all`)
|
|
116
|
+
const rp = await response.json()
|
|
117
|
+
return rp.result
|
|
118
|
+
.filter((r: any) => r.isSpentInMempoolTx === false)
|
|
119
|
+
.map((r: any) => ({ txid: r.tx_hash, vout: r.tx_pos, satoshis: r.value }))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Outputs this wallet has already internalized for `address`, keyed
|
|
124
|
+
* `txid.outputIndex`. The address itself is the action label, which is why the
|
|
125
|
+
* label list in sweepAddress below must keep carrying it.
|
|
126
|
+
*
|
|
127
|
+
* A read failure returns an empty set rather than throwing: the caller's next
|
|
128
|
+
* step is internalizeAction, which is idempotent per output, so the cost of a
|
|
129
|
+
* false "nothing imported" is a rejected duplicate — while a throw here would
|
|
130
|
+
* strand real money behind a transient database error.
|
|
131
|
+
*/
|
|
132
|
+
export async function getInternalizedUtxos(
|
|
133
|
+
wallet: AddressRailWallet,
|
|
134
|
+
adminOriginator: string,
|
|
135
|
+
address: string
|
|
136
|
+
): Promise<Set<string>> {
|
|
137
|
+
try {
|
|
138
|
+
const response = await wallet.listActions(
|
|
139
|
+
{ labels: [address], labelQueryMode: 'all', includeOutputs: true, limit: 1000 },
|
|
140
|
+
adminOriginator
|
|
141
|
+
)
|
|
142
|
+
const set = new Set<string>()
|
|
143
|
+
for (const action of response.actions) {
|
|
144
|
+
if (action.outputs) {
|
|
145
|
+
for (const output of action.outputs) {
|
|
146
|
+
if (action.txid) set.add(`${action.txid}.${output.outputIndex}`)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return set
|
|
151
|
+
} catch {
|
|
152
|
+
return new Set()
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function availableUtxos(all: Utxo[], internalized: Set<string>): Utxo[] {
|
|
157
|
+
return all.filter(u => !internalized.has(`${u.txid}.${u.vout}`))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function fetchBalance(
|
|
161
|
+
wallet: AddressRailWallet,
|
|
162
|
+
adminOriginator: string,
|
|
163
|
+
woc: WocConfig,
|
|
164
|
+
address: string
|
|
165
|
+
): Promise<number> {
|
|
166
|
+
const all = await getUtxosForAddress(woc, address)
|
|
167
|
+
const internalized = await getInternalizedUtxos(wallet, adminOriginator, address)
|
|
168
|
+
return availableUtxos(all, internalized).reduce((acc, u) => acc + u.satoshis, 0)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function getProcessedTransactions(
|
|
172
|
+
wallet: AddressRailWallet,
|
|
173
|
+
adminOriginator: string,
|
|
174
|
+
address: string
|
|
175
|
+
): Promise<ProcessedTx[]> {
|
|
176
|
+
try {
|
|
177
|
+
const response = await wallet.listActions(
|
|
178
|
+
{ labels: [address], labelQueryMode: 'all', includeLabels: true, includeOutputs: true, limit: 1000 },
|
|
179
|
+
adminOriginator
|
|
180
|
+
)
|
|
181
|
+
return response.actions
|
|
182
|
+
.map((action: any) => {
|
|
183
|
+
const totalSats = action.outputs
|
|
184
|
+
? action.outputs.reduce((sum: number, o: any) => sum + o.satoshis, 0)
|
|
185
|
+
: action.satoshis
|
|
186
|
+
const tsLabel = action.labels?.find((l: string) => l.startsWith('ts:'))
|
|
187
|
+
const importedAt = tsLabel ? new Date(Number(tsLabel.slice(3)) * 1000) : null
|
|
188
|
+
return { txid: action.txid, satoshis: totalSats, status: action.status, importedAt }
|
|
189
|
+
})
|
|
190
|
+
.sort((a: ProcessedTx, b: ProcessedTx) => {
|
|
191
|
+
if (a.importedAt && b.importedAt) return b.importedAt.getTime() - a.importedAt.getTime()
|
|
192
|
+
if (a.importedAt) return -1
|
|
193
|
+
if (b.importedAt) return 1
|
|
194
|
+
return 0
|
|
195
|
+
})
|
|
196
|
+
} catch {
|
|
197
|
+
return []
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Bytes of a WhatsOnChain `/tx/{txid}/beef` body, or undefined if the
|
|
203
|
+
* response is not a usable even-length hex payload. A 404 body is prose;
|
|
204
|
+
* feeding it to `Utils.toArray(..., 'hex')` throws and would abort the rest
|
|
205
|
+
* of an address's UTXOs.
|
|
206
|
+
*/
|
|
207
|
+
export function parseWocBeefBody(resp: { ok: boolean; text: string }): number[] | undefined {
|
|
208
|
+
if (!resp.ok) return undefined
|
|
209
|
+
const hex = resp.text.trim()
|
|
210
|
+
if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
|
|
211
|
+
try {
|
|
212
|
+
return Utils.toArray(hex, 'hex')
|
|
213
|
+
} catch {
|
|
214
|
+
return undefined
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The sweep. Ported from legacy-payments.tsx's handleImportFunds with one
|
|
220
|
+
* change and one only: the trigger. Nothing about what it writes moves.
|
|
221
|
+
*
|
|
222
|
+
* The sentinel sender key (PrivateKey(1)'s public key) and the label list are
|
|
223
|
+
* both load-bearing: the labels are how getInternalizedUtxos recognises what
|
|
224
|
+
* has already been imported, and the address label in particular is what makes
|
|
225
|
+
* a second sweep a no-op instead of a double credit.
|
|
226
|
+
*
|
|
227
|
+
* Each UTXO is fetched and internalized in its own try/catch so one bad BEEF
|
|
228
|
+
* cannot skip the rest of the address.
|
|
229
|
+
*/
|
|
230
|
+
export async function sweepAddress(args: {
|
|
231
|
+
wallet: AddressRailWallet
|
|
232
|
+
adminOriginator: string
|
|
233
|
+
woc: WocConfig
|
|
234
|
+
address: string
|
|
235
|
+
derivationPrefix: string
|
|
236
|
+
nowSeconds?: number
|
|
237
|
+
}): Promise<{ importedSatoshis: number; failureCount: number; foundOnChain: boolean }> {
|
|
238
|
+
const { wallet, adminOriginator, woc, address, derivationPrefix } = args
|
|
239
|
+
const nowSeconds = args.nowSeconds ?? Math.floor(Date.now() / 1000)
|
|
240
|
+
|
|
241
|
+
const all = await getUtxosForAddress(woc, address)
|
|
242
|
+
const internalized = await getInternalizedUtxos(wallet, adminOriginator, address)
|
|
243
|
+
const utxos = availableUtxos(all, internalized)
|
|
244
|
+
if (utxos.length === 0) return { importedSatoshis: 0, failureCount: 0, foundOnChain: false }
|
|
245
|
+
|
|
246
|
+
const senderIdentityKey = new PrivateKey(1).toPublicKey().toString()
|
|
247
|
+
let importedSatoshis = 0
|
|
248
|
+
let failureCount = 0
|
|
249
|
+
const seen = new Set<string>()
|
|
250
|
+
|
|
251
|
+
for (const utxo of utxos) {
|
|
252
|
+
if (seen.has(utxo.txid)) continue
|
|
253
|
+
seen.add(utxo.txid)
|
|
254
|
+
const relevant = utxos.filter(o => o.txid === utxo.txid)
|
|
255
|
+
try {
|
|
256
|
+
const resp = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${utxo.txid}/beef`)
|
|
257
|
+
const bytes = parseWocBeefBody({ ok: resp.ok, text: await resp.text() })
|
|
258
|
+
if (!bytes) {
|
|
259
|
+
failureCount++
|
|
260
|
+
continue
|
|
261
|
+
}
|
|
262
|
+
const beef = new Beef()
|
|
263
|
+
beef.mergeBeef(bytes)
|
|
264
|
+
const tx = beef.findAtomicTransaction(utxo.txid)
|
|
265
|
+
if (!tx) {
|
|
266
|
+
failureCount++
|
|
267
|
+
continue
|
|
268
|
+
}
|
|
269
|
+
const outputs: InternalizeOutput[] = relevant.map(o => ({
|
|
270
|
+
outputIndex: o.vout,
|
|
271
|
+
protocol: 'wallet payment' as const,
|
|
272
|
+
paymentRemittance: {
|
|
273
|
+
senderIdentityKey,
|
|
274
|
+
derivationPrefix,
|
|
275
|
+
derivationSuffix: LEGACY_DERIVATION_SUFFIX
|
|
276
|
+
}
|
|
277
|
+
}))
|
|
278
|
+
const internalizeArgs: InternalizeActionArgs = {
|
|
279
|
+
tx: tx.toAtomicBEEF(),
|
|
280
|
+
description: 'Payment to your address',
|
|
281
|
+
outputs,
|
|
282
|
+
labels: ['legacy', 'inbound', 'bsvbrowser', address, `ts:${nowSeconds}`]
|
|
283
|
+
}
|
|
284
|
+
const response = await wallet.internalizeAction(internalizeArgs, adminOriginator)
|
|
285
|
+
if (response?.accepted) importedSatoshis += relevant.reduce((sum, o) => sum + o.satoshis, 0)
|
|
286
|
+
else failureCount++
|
|
287
|
+
} catch {
|
|
288
|
+
failureCount++
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return { importedSatoshis, failureCount, foundOnChain: true }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Pay a conventional wallet. The only route out of this wallet to the rest of
|
|
296
|
+
* the ecosystem, so both guards throw before the wallet is touched: an invalid
|
|
297
|
+
* address here is money burned to an unspendable script.
|
|
298
|
+
*/
|
|
299
|
+
export async function sendToAddress(args: {
|
|
300
|
+
wallet: AddressRailWallet
|
|
301
|
+
adminOriginator: string
|
|
302
|
+
address: string
|
|
303
|
+
satoshis: number
|
|
304
|
+
}): Promise<{ paidSatoshis: number }> {
|
|
305
|
+
const { wallet, adminOriginator, address, satoshis } = args
|
|
306
|
+
const sats = Math.round(Number(satoshis))
|
|
307
|
+
if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
|
|
308
|
+
if (!isValidBsvAddress(address)) throw new Error('Invalid BSV address')
|
|
309
|
+
const lockingScript = new P2PKH().lock(address).toHex()
|
|
310
|
+
// A send-max request carries maxPossibleSatoshis and the wallet rewrites the
|
|
311
|
+
// output to whatever the inputs can fund, so the real figure only exists on
|
|
312
|
+
// the returned transaction. randomizeOutputs: false pins it to output 0.
|
|
313
|
+
const isSendMax = sats === 2099999999999999
|
|
314
|
+
const result = (await wallet.createAction(
|
|
315
|
+
{
|
|
316
|
+
description: 'Send BSV to address',
|
|
317
|
+
outputs: [{ lockingScript, satoshis: sats, outputDescription: 'BSV for recipient address' }],
|
|
318
|
+
labels: ['legacy', 'outbound'],
|
|
319
|
+
...(isSendMax ? { options: { randomizeOutputs: false } } : {})
|
|
320
|
+
},
|
|
321
|
+
adminOriginator
|
|
322
|
+
)) as { tx?: number[] }
|
|
323
|
+
if (!isSendMax) return { paidSatoshis: sats }
|
|
324
|
+
if (!result.tx) throw new Error('Could not determine send-max amount')
|
|
325
|
+
const tx = Transaction.fromAtomicBEEF(result.tx)
|
|
326
|
+
const paid = tx.outputs[0]?.satoshis
|
|
327
|
+
if (typeof paid !== 'number' || paid <= 0) throw new Error('Could not determine send-max amount')
|
|
328
|
+
return { paidSatoshis: paid }
|
|
329
|
+
}
|