Skip to content

Open source personal finance application

feat: improve exchange rates fetching and auth token flow

Ilya Komichevfe0b9a3d65df
diff --git a/app/components/offline/replay.ts b/app/components/offline/replay.ts
index da325ead..beb94aa5 100644
--- a/app/components/offline/replay.ts
+++ b/app/components/offline/replay.ts
@@ -1,11 +1,11 @@
+import type { LocaleSlug } from '~/components/locale/types'
+
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { clearOfflineQueue, getAllOfflineOps, getQueueUserId, removeOfflineOp, setOfflineQueueUserId, setQueueUserId } from '~/components/offline/helpers'
import { groupOpsByEntity, replayCategoryOps, replaySettingsOps, replayTrnOps, replayWalletOps } from '~/components/offline/replayHelpers'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useUserStore } from '~/components/user/useUserStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-import type { LocaleSlug } from '~/components/locale/types'
-
import { isLocalId } from '~/utils/convexId'
import { createLogger } from '~/utils/logger'
diff --git a/app/plugins/convex.ts b/app/plugins/convex.ts
index e1f56837..7bf42d36 100644
--- a/app/plugins/convex.ts
+++ b/app/plugins/convex.ts
@@ -48,6 +48,9 @@ export default defineNuxtPlugin(() => {
authReadyResolve = resolve
})
client.setAuth(fetchToken)
+ // Eagerly fetch token so authReadyPromise resolves immediately,
+ // rather than waiting for the Convex client to schedule fetchToken.
+ fetchToken({ forceRefreshToken: false })
}
let authSet = false
diff --git a/convex/rates.ts b/convex/rates.ts
index fdaf2e56..cd2cd585 100644
--- a/convex/rates.ts
+++ b/convex/rates.ts
@@ -3,17 +3,95 @@ import { v } from 'convex/values'
import { internal } from './_generated/api'
import { internalAction, internalMutation, query } from './_generated/server'
-const RATES_API_URL = 'https://openexchangerates.org/api/latest.json'
-const appId = process.env.OPEN_EXCHANGE_RATES_KEY
+const OER_API_URL = 'https://openexchangerates.org/api/latest.json'
+const COINBASE_API_URL = 'https://api.coinbase.com/v2/exchange-rates'
+
+async function fetchFromCoinbase(): Promise<Record<string, number> | null> {
+ try {
+ const res = await fetch(`${COINBASE_API_URL}?currency=USD`)
+
+ if (!res.ok) {
+ console.error(`Coinbase fetch failed: ${res.status} ${res.statusText}`)
+ return null
+ }
+
+ const json = await res.json()
+ const rawRates: Record<string, string> = json.data?.rates
+
+ if (!rawRates) {
+ console.error('Coinbase: unexpected response shape')
+ return null
+ }
+
+ const parsed: Record<string, number> = {}
+ for (const [code, value] of Object.entries(rawRates)) {
+ const num = Number.parseFloat(value)
+ if (Number.isFinite(num) && num > 0) {
+ parsed[code] = num
+ }
+ }
+
+ return parsed
+ }
+ catch (e) {
+ console.error('Coinbase fetch error:', e)
+ return null
+ }
+}
+
+async function fetchFromOER(): Promise<Record<string, number> | null> {
+ const appId = process.env.OPEN_EXCHANGE_RATES_KEY
+
+ if (!appId) {
+ console.error('OPEN_EXCHANGE_RATES_KEY not set')
+ return null
+ }
+
+ try {
+ const res = await fetch(`${OER_API_URL}?app_id=${appId}`)
+
+ if (!res.ok) {
+ console.error(`OER fetch failed: ${res.status} ${res.statusText}`)
+ return null
+ }
+
+ const data = await res.json()
+ return data.rates ?? null
+ }
+ catch (e) {
+ console.error('OER fetch error:', e)
+ return null
+ }
+}
export const getLatest = query({
args: {},
handler: async (ctx) => {
- return await ctx.db
+ const records = await ctx.db
.query('rates')
.withIndex('by_date')
.order('desc')
- .first()
+ .take(4)
+
+ if (records.length === 0)
+ return null
+
+ // Merge: newest first, first-seen currency wins
+ const merged: Record<string, number> = {}
+
+ for (const record of records) {
+ for (const [currency, rate] of Object.entries(record.rates)) {
+ if (!(currency in merged)) {
+ merged[currency] = rate
+ }
+ }
+ }
+
+ return {
+ date: records[0]!.date,
+ rates: merged,
+ updatedAt: records[0]!.updatedAt,
+ }
},
})
@@ -21,18 +99,19 @@ export const saveRates = internalMutation({
args: {
date: v.string(),
rates: v.record(v.string(), v.number()),
+ source: v.string(),
},
- handler: async (ctx, { date, rates }) => {
+ handler: async (ctx, { date, rates, source }) => {
const existing = await ctx.db
.query('rates')
- .withIndex('by_date', q => q.eq('date', date))
+ .withIndex('by_date_source', q => q.eq('date', date).eq('source', source))
.first()
if (existing) {
await ctx.db.patch(existing._id, { rates, updatedAt: Date.now() })
}
else {
- await ctx.db.insert('rates', { date, rates, updatedAt: Date.now() })
+ await ctx.db.insert('rates', { date, rates, source, updatedAt: Date.now() })
}
},
})
@@ -40,26 +119,32 @@ export const saveRates = internalMutation({
export const fetchAndSaveRates = internalAction({
args: {},
handler: async (ctx) => {
- if (!appId) {
- console.error('OPEN_EXCHANGE_RATES_KEY not set')
- return
- }
-
- const res = await fetch(
- `${RATES_API_URL}?app_id=${appId}`,
- )
+ const today = new Date().toISOString().slice(0, 10)
- if (!res.ok) {
- console.error(`Rates fetch failed: ${res.status} ${res.statusText}`)
- return
+ // Coinbase (primary — no API key, ~960 currencies incl. crypto)
+ const coinbaseRates = await fetchFromCoinbase()
+ if (coinbaseRates) {
+ await ctx.runMutation(internal.rates.saveRates, {
+ date: today,
+ rates: coinbaseRates,
+ source: 'coinbase',
+ })
+ console.log(`Coinbase: saved ${Object.keys(coinbaseRates).length} rates`)
}
- const data = await res.json()
- const today = new Date().toISOString().slice(0, 10)
+ // OER (secondary — better fiat precision, ~173 currencies)
+ const oerRates = await fetchFromOER()
+ if (oerRates) {
+ await ctx.runMutation(internal.rates.saveRates, {
+ date: today,
+ rates: oerRates,
+ source: 'oer',
+ })
+ console.log(`OER: saved ${Object.keys(oerRates).length} rates`)
+ }
- await ctx.runMutation(internal.rates.saveRates, {
- date: today,
- rates: data.rates,
- })
+ if (!coinbaseRates && !oerRates) {
+ console.error('All exchange rate sources failed')
+ }
},
})