Repository navigation
Expand file tree
/
Copy pathapi.ts
More file actions
323 lines (297 loc) · 9.94 KB
/
Copy pathapi.ts
File metadata and controls
323 lines (297 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Heliobond — project data API client with lazy-loading and pagination support.
//
// Requests go to the versioned `/v1` backend. The browser reaches it through the
// same-origin `/api/backend` proxy, which attaches the API key server-side, so no
// secret ships in the bundle (#588). With no backend configured the app falls
// back to bundled demo data and shows a "Demo data" badge.
import { type Project } from '../data'
import { type ProjectDetail } from '../data/projectDetails'
import { selectProjectById, selectProjectDetail, selectProjects } from '../state/selectors'
import {
isRegistryConfigured,
fetchProjectsPage,
fetchProjectWithDetails,
type MetadataVerificationStatus,
} from '../wallet/registry'
import { ApiError } from './error'
import { loginBiometric } from './webauthn'
export { ApiError } from './error'
export type { MetadataVerificationStatus } from '../wallet/registry'
import {
API_TIMEOUT_MS,
apiGet,
fetchBackendHistory,
fetchBackendPortfolio,
fetchBackendProject,
fetchBackendProjects,
historyToScorePoints,
isBackendConfigured,
type BackendProject,
type ScoreObservation,
} from './apiClient'
export { API_TIMEOUT_MS }
export type { ScoreObservation }
export interface Investment {
id: number
projectId: number
amount: number
projectUrl: string
}
const DEMO_MODE = !isBackendConfigured()
function isDemoMode(): boolean {
return DEMO_MODE
}
export type ProjectSource = 'registry' | 'backend' | 'demo'
/** Returns true if the UI should show a "Demo data" badge. */
export function shouldShowDemoBadge(source?: ProjectSource): boolean {
if (source !== undefined) return source === 'demo'
return isDemoMode()
}
/**
* GET a `/v1/...` path and parse the JSON body. Rejects with an `ApiError` on a
* non-2xx status, a timeout, a network error or a malformed body. Demo
* fallbacks are selected before calling this helper; production errors bubble up.
*/
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
return apiGet<T>(path, init)
}
/** Alias for request helper (#587) */
export const apiFetch = request
/**
* Maps a backend project row onto the app's `Project` shape.
*
* The backend reports scores and telemetry; presentation fields that only exist
* on-chain or in the bundled fixtures come from the local project, so a live
* backend fills in the scores without losing names and funding copy.
*/
export function mapBackendProject(raw: BackendProject, fallback?: Project): Project {
const credit = Number(raw.credit_quality)
const green = Number(raw.green_impact)
if (!fallback) {
return {
id: raw.id,
name: `Bond Project #${raw.id}`,
location: 'Stellar Network',
type: 'Solar',
credit: Number.isFinite(credit) ? credit : undefined,
green: Number.isFinite(green) ? green : undefined,
funded: '$0',
fundedAmount: 0,
fundingGoal: 0,
status: 'open',
priceHistory: [],
}
}
return {
...fallback,
id: raw.id,
credit: Number.isFinite(credit) ? credit : fallback.credit,
green: Number.isFinite(green) ? green : fallback.green,
}
}
/**
* Builds a detail record for a project that exists in the backend but has no
* bundled fixture. Every required field is present so consumers never crash on
* a missing nested object, and the absent sections are named explicitly so the
* UI can show an honest "information unavailable" state rather than inventing
* a creator, story, or history. The backend scores live on `project` and are
* rendered independently of this record.
*/
export function createBackendProjectDetail(project: Project): ProjectDetail {
return {
name: project.name,
location: project.location,
story: '',
creator: { name: '', verified: false, since: '' },
scoreHistory: { credit: [], green: [] },
fundingTimeline: [],
fundedAmount: project.fundedAmount,
fundingGoal: project.fundingGoal,
priceHistory: [],
heroGradient: 'linear-gradient(135deg, var(--ink-12), var(--ink-06))',
missingSections: ['story', 'creator', 'scoreHistory', 'fundingTimeline', 'priceHistory'],
}
}
export interface ProjectWithDetail {
project: Project
detail: ProjectDetail
verifiedMetadata?: MetadataVerificationStatus
source?: ProjectSource
}
export interface PaginatedProjectsResponse {
projects: Project[]
total: number
page: number
pageSize: number
hasMore: boolean
}
/**
* Fetches a paginated/lazy chunk of bonds to optimize initial load time from 3-5s down to sub-second.
*/
export async function getProjectsPaginated(
page = 1,
pageSize = 12,
): Promise<PaginatedProjectsResponse> {
if (isRegistryConfigured()) {
const offset = (page - 1) * pageSize
const pageResult = await fetchProjectsPage(offset, pageSize)
return {
projects: pageResult.projects,
total: pageResult.total,
page,
pageSize,
hasMore: pageResult.hasMore,
}
}
if (isDemoMode()) {
const all = selectProjects()
const start = (page - 1) * pageSize
const projects = all.slice(start, start + pageSize)
return {
projects,
total: all.length,
page,
pageSize,
hasMore: start + pageSize < all.length,
}
}
try {
// The backend paginates with a cursor; the page number maps to an offset.
const offset = (page - 1) * pageSize
const data = await fetchBackendProjects(offset, pageSize)
const projects = data.projects.map((row) => mapBackendProject(row, selectProjectById(row.id)))
return {
projects,
total: data.filtered_total ?? data.projects.length,
page,
pageSize,
hasMore: data.cursor !== undefined,
}
} catch (error) {
if (error instanceof ApiError) throw error
throw new ApiError({ cause: error, message: 'Failed to fetch projects' })
}
}
export async function getProjects(): Promise<Project[]> {
if (isRegistryConfigured()) {
const pageResult = await fetchProjectsPage(0, 100)
return pageResult.projects
}
if (isDemoMode()) return selectProjects()
try {
const data = await fetchBackendProjects(0, 100)
return data.projects.map((row) => mapBackendProject(row, selectProjectById(row.id)))
} catch (error) {
if (error instanceof ApiError) throw error
throw new ApiError({ cause: error, message: 'Failed to fetch projects' })
}
}
export async function getProject(id: number): Promise<ProjectWithDetail | null> {
if (isRegistryConfigured()) {
const res = await fetchProjectWithDetails(id)
if (res) {
return {
project: res.project,
detail: res.detail,
verifiedMetadata: res.verifiedMetadata,
source: 'registry',
}
}
}
const mockProject = selectProjectById(id)
const mockDetail = selectProjectDetail(id)
if (isDemoMode()) {
if (!mockProject || !mockDetail) return null
return {
project: mockProject,
detail: mockDetail,
verifiedMetadata: 'unverified',
source: 'demo',
}
}
try {
const raw = await fetchBackendProject(id)
if (!raw) return null
const project = mapBackendProject(raw, mockProject)
return {
project,
detail: mockDetail
? {
...mockDetail,
priceHistory: [],
missingSections: [...(mockDetail.missingSections ?? []), 'priceHistory'],
}
: createBackendProjectDetail(project),
verifiedMetadata: 'unverified',
source: 'backend',
}
} catch (error) {
if (error instanceof ApiError) throw error
throw new ApiError({ cause: error, message: `Failed to fetch project ${id}` })
}
}
/**
* Performs biometric login (Face ID / Touch ID) using the WebAuthn API.
* Delegates to the canonical WebAuthn challenge-response implementation in webauthn.ts.
* Returns true if the user successfully authenticates via server verification, false otherwise.
*/
export async function biometricLogin(username: string = ''): Promise<boolean> {
if (typeof window === 'undefined' || !window.PublicKeyCredential) {
console.warn('[api] Biometric login not supported on this device/browser')
return false
}
try {
await loginBiometric(username)
return true
} catch (error) {
console.warn('[api] biometric login failed:', error)
return false
}
}
/**
* Dated impact-score observations for a project, oldest first.
*
* Sourced from `GET /v1/projects/:id/history`, which reports impact-score
* snapshots (credit quality and green impact). It carries no trade prices or
* yield observations, so those fields are deliberately absent from the result.
* Demo mode synthesises score points so a chart has something to draw without
* a backend.
*/
export async function getScoreHistory(projectId: number): Promise<ScoreObservation[]> {
const makeMock = (): ScoreObservation[] => {
const today = new Date()
const points = Array.from({ length: 30 }, (_, i) => {
const d = new Date(today)
d.setDate(d.getDate() - i)
return {
date: d.toISOString().split('T')[0],
credit: Math.round(50 + ((i * 7 + projectId * 11) % 40)),
green: Math.round(55 + ((i * 5 + projectId * 13) % 40)),
}
})
return points.reverse() // ascending chronological order
}
if (isDemoMode()) return makeMock()
try {
const history = await fetchBackendHistory(projectId)
return historyToScorePoints(history.entries)
} catch (error) {
if (error instanceof ApiError) throw error
throw new ApiError({
cause: error,
message: `Failed to fetch score history for project ${projectId}`,
})
}
}
/**
* @deprecated The history endpoint returns scores, not prices. This alias only
* exists for older callers and now yields score observations with no price or
* yield. Use `getScoreHistory` instead.
*/
export const getPriceHistory = getScoreHistory
/**
* On-chain vault position for an address, from `GET /v1/portfolio/:address`.
* Exposed so screens can reach the backend portfolio when one is configured;
* the Soroban vault remains the source of truth for balances (#588).
*/
export { fetchBackendPortfolio }