Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion redis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { TransactionsWithPaybuttonsAndPrices } from 'services/transactionService
import { fetchUsersForAddress } from 'services/userService'
import { cacheBalanceForAddress, clearBalanceCache, getBalanceForAddress, updateBalanceCacheFromTx } from './balanceCache'
import { clearDashboardCache, getUserDashboardData } from './dashboardCache'
import { appendPaybuttonToAddressesCache, cacheGroupedPayments, cacheManyTxs, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache'
import { appendPaybuttonToAddressesCache, cacheGroupedPayments, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache'
import { DashboardData, Payment } from './types'
import { Address } from '@prisma/client'

Expand Down Expand Up @@ -48,6 +48,23 @@ export const CacheSet = {
await clearBalanceCache(addr)
}
},
// After a bulk (on-demand) sync committed txs for these addresses without
// touching the cache: drop their payment, balance and users' dashboard caches
// so they are rebuilt from the DB, now including the synced txs.
addressesSynced: async (addressStringList: string[]): Promise<void> => {
const userIds = new Set<string>()
for (const addressString of addressStringList) {
await clearPaymentCacheForAddress(addressString)
await clearBalanceCache(addressString)
const users = await fetchUsersForAddress(addressString)
users.forEach(u => userIds.add(u.id))
}
await Promise.all(
[...userIds].map(async id => {
await clearDashboardCache(id)
})
)
},
paybuttonCreation: async ({ paybutton, addressStringList, userId }: PaybuttonCreationParams): Promise<void> => {
await appendPaybuttonToAddressesCache(
addressStringList,
Expand Down
27 changes: 25 additions & 2 deletions services/chronikService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ import {
markTransactionsOrphaned,
upsertTransaction,
getSimplifiedTransactions,
getSimplifiedTrasaction
getSimplifiedTrasaction,
connectTransactionsToPricesForAddresses
} from './transactionService'
import { CacheSet } from 'redis/index'
import {
updateClientPaymentStatus,
getClientPayment
Expand Down Expand Up @@ -1511,7 +1513,28 @@ class MultiBlockchainClient {

public async syncAndSubscribeAddresses (addresses: Address[]): Promise<SyncAndSubscriptionReturn> {
await this.subscribeAddresses(addresses)
return await this.syncAddresses(addresses)
const result = await this.syncAddresses(addresses)
await this.finalizeOnDemandSync(addresses)
return result
}

// syncAddresses commits through the bulk path, which defers price linking and
// cache updates to the sync job. On-demand syncs (new paybutton/address, client
// payment) run outside that job, so link prices and drop stale caches here —
// otherwise the synced txs stay unpriced and missing from payments until the
// next restart, and a cache rebuilt mid-sync stays partial.
private async finalizeOnDemandSync (addresses: Address[]): Promise<void> {
if (addresses.length === 0) return
try {
await connectTransactionsToPricesForAddresses(addresses.map(a => a.id))
} catch (err: any) {
console.error(`[CHRONIK]: Failed to link prices after syncing ${addresses.length} addresses: ${err.message as string}`)
}
try {
await CacheSet.addressesSynced(addresses.map(a => a.address))
} catch (err: any) {
console.error(`[CHRONIK]: Failed to invalidate caches after syncing ${addresses.length} addresses: ${err.message as string}`)
}
}

public async destroy (): Promise<void> {
Expand Down
30 changes: 30 additions & 0 deletions services/transactionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,36 @@ export async function connectAllTransactionsToPrices (): Promise<void> {
console.log('[PRICES] Finished connecting txs to prices.')
}

/**
* Link prices for the given addresses' txs that have none (or an incomplete set).
* The bulk sync path (createManyTransactionsForSync) leaves txs unpriced; the
* sync job fixes that globally with connectAllTransactionsToPrices, but on-demand
* syncs (syncAndSubscribeAddresses) must do it for their own addresses.
*/
export async function connectTransactionsToPricesForAddresses (addressIds: string[]): Promise<void> {
if (addressIds.length === 0) return
const noPricesTxs = await prisma.transaction.findMany({
where: {
addressId: { in: addressIds },
prices: { none: {} }
},
include: includeNetwork
})
const irregular = await prisma.pricesOnTransactions.groupBy({
by: ['transactionId'],
where: { transaction: { addressId: { in: addressIds } } },
_count: { transactionId: true },
having: { transactionId: { _count: { lt: N_OF_QUOTES } } }
})
const irregularTxs = irregular.length === 0
? []
: await prisma.transaction.findMany({
where: { id: { in: irregular.map(g => g.transactionId) } },
include: includeNetwork
})
await connectTransactionsListToPrices([...noPricesTxs, ...irregularTxs])
}

interface ExistingTxSnapshot {
confirmed: boolean
timestamp: number
Expand Down
59 changes: 57 additions & 2 deletions tests/unittests/chronikService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import {
} from '../../services/chronikService'
import { Address, Prisma } from '@prisma/client'
import { fetchAddressesArray } from '../../services/addressService'
import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction } from '../../services/transactionService'
import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses } from '../../services/transactionService'
import { executeAddressTriggers } from '../../services/triggerService'
import { CacheSet } from '../../redis/index'

process.env.WS_AUTH_KEY = 'test-auth-key'

Expand Down Expand Up @@ -71,7 +72,14 @@ jest.mock('../../services/transactionService', () => ({
upsertTransaction: jest.fn(),
getSimplifiedTransactions: jest.fn(),
getSimplifiedTrasaction: jest.fn(),
connectAllTransactionsToPrices: jest.fn()
connectAllTransactionsToPrices: jest.fn(),
connectTransactionsToPricesForAddresses: jest.fn()
}))

jest.mock('../../redis/index', () => ({
CacheSet: {
addressesSynced: jest.fn()
}
}))

jest.mock('../../services/priceService', () => ({
Expand Down Expand Up @@ -1145,6 +1153,53 @@ describe('MultiBlockchainClient method coverage', () => {
expect(result).toHaveProperty('successfulAddressesWithCount')
})

it('Should link prices and invalidate caches after an on-demand sync', async () => {
const validAddress = fromHash160('ecash', 'p2pkh', 'c5d2460186f7233c927e7db2dcc703c0e500b653')
const mockAddresses = [
{ id: 'addr-1', address: validAddress, networkId: 1, syncing: false, createdAt: new Date(), updatedAt: new Date(), lastSynced: null }
]
const linkPrices = connectTransactionsToPricesForAddresses as jest.Mock
const invalidate = CacheSet.addressesSynced as jest.Mock
const order: string[] = []
linkPrices.mockReset().mockImplementation(async () => { order.push('prices') })
invalidate.mockReset().mockImplementation(async () => { order.push('cache') })
jest.spyOn(multiBlockchainClient, 'subscribeAddresses').mockResolvedValue()
jest.spyOn(multiBlockchainClient, 'syncAddresses').mockImplementation(async () => {
order.push('sync')
return { failedAddressesWithErrors: {}, successfulAddressesWithCount: { [validAddress]: 3 } }
})

await multiBlockchainClient.syncAndSubscribeAddresses(mockAddresses)

expect(linkPrices).toHaveBeenCalledWith(['addr-1'])
expect(invalidate).toHaveBeenCalledWith([validAddress])
expect(order).toEqual(['sync', 'prices', 'cache'])
})

it('Should still invalidate caches and return the sync result if price linking fails', async () => {
const validAddress = fromHash160('ecash', 'p2pkh', 'c5d2460186f7233c927e7db2dcc703c0e500b653')
const mockAddresses = [
{ id: 'addr-1', address: validAddress, networkId: 1, syncing: false, createdAt: new Date(), updatedAt: new Date(), lastSynced: null }
]
const linkPrices = connectTransactionsToPricesForAddresses as jest.Mock
const invalidate = CacheSet.addressesSynced as jest.Mock
linkPrices.mockReset().mockRejectedValue(new Error('price API down'))
invalidate.mockReset().mockResolvedValue(undefined)
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
jest.spyOn(multiBlockchainClient, 'subscribeAddresses').mockResolvedValue()
jest.spyOn(multiBlockchainClient, 'syncAddresses').mockResolvedValue({
failedAddressesWithErrors: {},
successfulAddressesWithCount: { [validAddress]: 3 }
})

const result = await multiBlockchainClient.syncAndSubscribeAddresses(mockAddresses)

expect(result.successfulAddressesWithCount[validAddress]).toBe(3)
expect(invalidate).toHaveBeenCalledWith([validAddress])
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('price API down'))
errorSpy.mockRestore()
})

it('Should get transaction details for specific network', async () => {
// Mock the method
const mockDetails = {
Expand Down
Loading