-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesRegister.tsx
More file actions
437 lines (419 loc) · 19.2 KB
/
Copy pathNotesRegister.tsx
File metadata and controls
437 lines (419 loc) · 19.2 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"use client";
import { useRef, useState } from "react";
import useSWR from "swr";
import type { Abi } from "viem";
import { useMode } from "@/lib/mode";
import { useCovenant } from "@/lib/useCovenant";
import { useDemo } from "@/lib/demoStore";
import { abis, assetAbiFor, explorerTxUrl, identityAbiFor } from "@/lib/contracts";
import { waitForTxSuccess } from "@/lib/wallet";
import { truncateAddress, formatUnits6, bpsToPercent, formatTimestamp } from "@/lib/format";
import { formatDate, formatAmount, advanceRateBpsFor } from "@/lib/demoData";
import type { Instrument } from "@/lib/demoData";
import { RefreshIcon, SpinnerIcon, CheckCircleIcon, XCircleIcon, FolderIcon, InboxIcon } from "./icons";
interface Note {
tokenId: bigint;
invoiceHash: `0x${string}`;
obligor: `0x${string}`;
supplier: `0x${string}`;
faceValue: bigint;
maturity: bigint;
minFinancierSubTier: number;
requiredJurisdiction: number;
advanceRateBps: bigint;
advanceAmount: bigint;
financier: `0x${string}`;
funded: boolean;
settled: boolean;
}
interface Row {
id: string;
description: string;
obligorLabel: string;
obligorAddress: string;
supplierLabel: string;
supplierAddress: string;
dueLabel: string;
rateLabel: string;
statusLabel: string;
statusTone: "accent" | "accent-2" | "neutral" | "outline";
showFinance: boolean;
financeDisabled: boolean;
financeDisabledReason: string;
showRepay: boolean;
repayDisabled: boolean;
busy: boolean;
stageLabel: string;
hasError: boolean;
errorText: string;
receipt: { amount: string; link: string | null; blockLabel: string | null } | null;
onFinance: () => void;
onRepay: () => void;
onRetry: () => void;
}
interface RawIdentity {
verified: boolean;
tier: number;
subTier: number;
}
function statusMeta(status: string): { label: string; tone: Row["statusTone"] } {
return (
{
awaiting: { label: "Awaiting financier", tone: "neutral" as const },
financed: { label: "Financed", tone: "accent" as const },
financed_overdue: { label: "Financed · overdue", tone: "accent-2" as const },
repaid: { label: "Repaid", tone: "outline" as const },
}[status] ?? { label: status, tone: "neutral" as const }
);
}
function tagClass(tone: Row["statusTone"]): string {
return { accent: "desk-tag", "accent-2": "desk-tag desk-tag-warn", neutral: "desk-tag desk-tag-neutral", outline: "desk-tag" }[tone];
}
export function NotesRegister() {
const { mode } = useMode();
const isDemo = mode === "demo";
const { address, addresses, publicClient, walletClient, readClient, readAddresses } = useCovenant();
const demo = useDemo();
const [busyTokenId, setBusyTokenId] = useState<bigint | null>(null);
const [rowMessage, setRowMessage] = useState<Record<string, string>>({});
const [rowReceipt, setRowReceipt] = useState<Record<string, { amount: string; txHash: string }>>({});
const busyTokenIdRef = useRef<bigint | null>(null);
const { data: notes, isLoading: liveLoading, mutate } = useSWR<Note[]>(
!isDemo && readClient && readAddresses ? ["notes", readAddresses.receivableNote] : null,
async () => {
// Token ids are sequential from 1, so the registry is a scan — but a scan does
// not have to be a round trip per note. Each pass folds BATCH reads into one
// eth_call through Multicall3, so the cost is ceil(n / BATCH) requests instead of
// n, and there is no arbitrary ceiling: it keeps going while a batch comes back
// full. This used to loop `id = 1..200` one call at a time, which was fine at
// twelve notes, quietly slow at two hundred, and silently truncating past that.
const BATCH = 50;
const found: Note[] = [];
for (let start = 1n; ; start += BigInt(BATCH)) {
const ids = Array.from({ length: BATCH }, (_, i) => start + BigInt(i));
const results = await readClient!.multicall({
allowFailure: true,
contracts: ids.map((id) => ({
address: readAddresses!.receivableNote,
abi: abis.receivableNote as Abi,
functionName: "getNote",
args: [id],
})),
});
let exhausted = false;
for (let i = 0; i < results.length; i++) {
const r = results[i];
// A failed read is treated as the end rather than a gap: ids are dense, so the
// first thing that does not come back cleanly is past the last minted note.
if (r.status !== "success") { exhausted = true; break; }
const note = r.result as unknown as Omit<Note, "tokenId">;
if (note.faceValue === 0n) { exhausted = true; break; }
found.push({ tokenId: ids[i], ...note });
}
if (exhausted) break;
}
return found;
},
);
const { data: myIdentity } = useSWR(
!isDemo && address && readAddresses && readClient ? ["identity", readAddresses.identityRegistry, address] : null,
async () => {
const read = (functionName: string) =>
readClient!.readContract({
address: readAddresses!.identityRegistry,
abi: identityAbiFor(readAddresses),
functionName,
args: [address!],
});
const [verified, tier, subTier] = (await Promise.all([read("isVerified"), read("tier"), read("subTier")])) as [
boolean,
number,
number,
];
return { verified, tier, subTier } satisfies RawIdentity;
},
);
async function ensureAllowance(owner: `0x${string}`, amount: bigint) {
if (!publicClient || !walletClient || !addresses) return;
const allowance = (await publicClient.readContract({
address: addresses.settlementAsset,
abi: assetAbiFor(addresses),
functionName: "allowance",
args: [owner, addresses.factoringEscrow],
})) as bigint;
if (allowance >= amount) return;
const hash = await walletClient.writeContract({
account: owner,
chain: walletClient.chain,
address: addresses.settlementAsset,
abi: assetAbiFor(addresses),
functionName: "approve",
args: [addresses.factoringEscrow, amount],
});
await waitForTxSuccess(publicClient, hash);
}
async function onLiveFinance(note: Note) {
if (!address || !addresses || !publicClient || !walletClient || busyTokenIdRef.current !== null) return;
busyTokenIdRef.current = note.tokenId;
setBusyTokenId(note.tokenId);
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: "Approving…" }));
try {
const advanceAmount = (note.faceValue * note.advanceRateBps) / 10_000n;
await ensureAllowance(address, advanceAmount);
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: "Financing…" }));
const hash = await walletClient.writeContract({
account: address,
chain: walletClient.chain,
address: addresses.receivableNote,
abi: abis.receivableNote,
functionName: "fund",
args: [note.tokenId],
});
await waitForTxSuccess(publicClient, hash);
await mutate();
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: "" }));
setRowReceipt((r) => ({ ...r, [note.tokenId.toString()]: { amount: `${formatUnits6(advanceAmount)} cvaUSD`, txHash: hash } }));
} catch (err) {
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: err instanceof Error ? err.message : "The network rejected the transaction." }));
} finally {
busyTokenIdRef.current = null;
setBusyTokenId(null);
}
}
async function onLiveRepay(note: Note) {
if (!address || !addresses || !publicClient || !walletClient || busyTokenIdRef.current !== null) return;
busyTokenIdRef.current = note.tokenId;
setBusyTokenId(note.tokenId);
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: "Approving…" }));
try {
await ensureAllowance(address, note.faceValue);
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: "Repaying…" }));
const hash = await walletClient.writeContract({
account: address,
chain: walletClient.chain,
address: addresses.receivableNote,
abi: abis.receivableNote,
functionName: "settle",
args: [note.tokenId],
});
await waitForTxSuccess(publicClient, hash);
await mutate();
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: "" }));
setRowReceipt((r) => ({ ...r, [note.tokenId.toString()]: { amount: `${formatUnits6(note.faceValue)} cvaUSD`, txHash: hash } }));
} catch (err) {
setRowMessage((m) => ({ ...m, [note.tokenId.toString()]: err instanceof Error ? err.message : "The network rejected the transaction." }));
} finally {
busyTokenIdRef.current = null;
setBusyTokenId(null);
}
}
let rows: Row[] = [];
let loading: boolean;
let onRefresh: () => void;
if (isDemo) {
loading = demo.state.registryLoading;
onRefresh = demo.refreshRegistry;
const source = demo.state.forceEmptyRegistry ? [] : demo.state.instruments;
rows = source.map((it: Instrument) => {
const ra = demo.state.rowActions[it.id] ?? { stage: "idle" as const, kind: null, approved: false, error: "" };
const busy = ra.stage === "approving" || ra.stage === "financing" || ra.stage === "repaying";
const hasError = ra.stage === "error";
const account = demo.state.account;
const isOwnObligor = Boolean(account) && it.obligorAddress.toLowerCase() === account!.address.toLowerCase();
const isFinancier = account?.role === "financier";
const meetsSubTier = Boolean(account) && account!.subTier >= it.minSubTier;
const meetsJurisdiction = Boolean(account) && (it.jurisdictionReq === "Any" || it.jurisdictionReq === account!.region);
const showFinance = demo.state.connected && isFinancier && it.status === "awaiting" && !busy && !hasError;
const showRepay = demo.state.connected && isOwnObligor && (it.status === "financed" || it.status === "financed_overdue") && !busy && !hasError;
const meta = statusMeta(it.status);
const rate = advanceRateBpsFor(it.obligorSubTier);
const advance = (it.amount * rate) / 10_000;
const receiptRaw = demo.state.rowReceipts[it.id];
const receipt = receiptRaw ? { amount: receiptRaw.amount, link: null, blockLabel: `Block ${receiptRaw.block}` } : null;
return {
id: it.id,
description: it.description,
obligorLabel: it.obligor,
obligorAddress: it.obligorAddress,
supplierLabel: it.supplier,
supplierAddress: it.supplierAddress,
dueLabel: formatDate(it.dueDate),
rateLabel: `${(rate / 100).toFixed(2)}% · ${formatAmount(advance)} cvaUSD`,
statusLabel: meta.label,
statusTone: meta.tone,
showFinance,
financeDisabled: demo.actionsBlocked || !meetsSubTier || !meetsJurisdiction,
financeDisabledReason: showFinance && !meetsSubTier ? `Requires an A-Pass subTier of ${it.minSubTier} or higher` : showFinance && !meetsJurisdiction ? `Requires ${it.jurisdictionReq} jurisdiction` : "",
showRepay,
repayDisabled: demo.actionsBlocked,
busy,
stageLabel: ra.stage === "approving" ? "Approving…" : ra.stage === "financing" ? "Financing…" : ra.stage === "repaying" ? "Repaying…" : "",
hasError,
errorText: ra.error,
receipt,
onFinance: () => demo.financeRow(it.id),
onRepay: () => demo.repayRow(it.id),
onRetry: () => demo.retryRow(it.id),
};
});
} else {
loading = liveLoading ?? false;
onRefresh = () => mutate();
const nowSeconds = Math.floor(Date.now() / 1000);
const mySubTier = myIdentity?.subTier ?? 0;
rows = (notes ?? []).map((note) => {
const key = note.tokenId.toString();
const isObligor = Boolean(address) && address!.toLowerCase() === note.obligor.toLowerCase();
const overdue = note.funded && note.maturity <= BigInt(nowSeconds);
const status = note.settled ? "repaid" : note.funded ? (overdue ? "financed_overdue" : "financed") : "awaiting";
const meta = statusMeta(status);
// The note carries the minimum verification depth its originator demanded of a
// financier. Jurisdiction is not checked here: live A-Passes come back with an
// empty group, so every note is originated with requiredJurisdiction = 0 and a
// client-side check would only ever be theatre.
const meetsSubTier = mySubTier >= note.minFinancierSubTier;
const showFinance = !note.funded && busyTokenId !== note.tokenId && !rowMessage[key];
const showRepay = isObligor && note.funded && !note.settled && busyTokenId !== note.tokenId && !rowMessage[key];
const busy = busyTokenId === note.tokenId;
const receiptRaw = rowReceipt[key];
const receipt = receiptRaw ? { amount: receiptRaw.amount, link: explorerTxUrl(addresses, receiptRaw.txHash), blockLabel: null } : null;
return {
id: key,
description: `Note #${key}`,
obligorLabel: truncateAddress(note.obligor),
obligorAddress: note.obligor,
supplierLabel: truncateAddress(note.supplier),
supplierAddress: note.supplier,
dueLabel: formatTimestamp(note.maturity),
rateLabel: `${bpsToPercent(note.advanceRateBps)} · ${formatUnits6((note.faceValue * note.advanceRateBps) / 10_000n)} cvaUSD`,
statusLabel: meta.label,
statusTone: meta.tone,
showFinance,
financeDisabled: !meetsSubTier,
financeDisabledReason: showFinance && !meetsSubTier ? `Requires an A-Pass subTier of ${note.minFinancierSubTier} or higher` : "",
showRepay,
repayDisabled: false,
busy,
stageLabel: busy ? rowMessage[key] || "Working…" : "",
hasError: Boolean(rowMessage[key]) && !busy,
errorText: rowMessage[key] || "",
receipt,
onFinance: () => onLiveFinance(note),
onRepay: () => onLiveRepay(note),
onRetry: () => (note.funded ? onLiveRepay(note) : onLiveFinance(note)),
};
});
}
return (
<div className="card elev-sm">
<div className="desk-card-head">
<span className="desk-card-title">
<FolderIcon /> Instrument Registry
</span>
<button type="button" className="btn btn-ghost btn-icon ml-auto" aria-label="Refresh" onClick={onRefresh}>
<RefreshIcon spinning={loading} />
</button>
</div>
{loading && (
<div className="flex flex-col gap-2">
<div className="animate-pulse-cv h-[38px] rounded-[7px]" style={{ background: "var(--color-neutral-200)" }} />
<div className="animate-pulse-cv h-[38px] rounded-[7px]" style={{ background: "var(--color-neutral-200)" }} />
<div className="animate-pulse-cv h-[38px] rounded-[7px]" style={{ background: "var(--color-neutral-200)" }} />
</div>
)}
{!loading && rows.length === 0 && (
<div className="desk-empty">
<InboxIcon />
<span>No active instruments found.</span>
</div>
)}
{!loading && rows.length > 0 && (
<div className="cv-table-wrap overflow-x-auto">
<table className="table">
<thead>
<tr>
<th>Instrument</th>
<th>Parties</th>
<th>Due</th>
<th>Rate</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
<td>
<span className="block font-mono text-[12.5px]">{row.id}</span>
<span className="block max-w-[180px] text-[11.5px] opacity-65">{row.description}</span>
</td>
<td>
<span className="block text-[12.5px]" title={row.obligorAddress}>
{row.obligorLabel}
</span>
<span className="block text-[11.5px] opacity-65" title={row.supplierAddress}>
→ {row.supplierLabel}
</span>
</td>
<td className="text-muted text-[12.5px] whitespace-nowrap">{row.dueLabel}</td>
<td className="whitespace-nowrap">
<span className="block font-mono text-[12.5px]">{row.rateLabel.split(" \u00b7 ")[0]}</span>
<span className="block text-[11.5px] opacity-65">{row.rateLabel.split(" \u00b7 ")[1]}</span>
</td>
<td>
<span className={tagClass(row.statusTone)}>{row.statusLabel}</span>
</td>
<td>
{row.showFinance && (
<>
<button type="button" className="btn btn-secondary whitespace-nowrap" disabled={row.financeDisabled} title={row.financeDisabledReason} onClick={row.onFinance}>
Finance
</button>
{row.financeDisabledReason && <span className="mt-0.5 block text-[11px] opacity-60">{row.financeDisabledReason}</span>}
</>
)}
{row.showRepay && (
<button type="button" className="btn btn-secondary whitespace-nowrap" disabled={row.repayDisabled} onClick={row.onRepay}>
Repay
</button>
)}
{row.busy && (
<span className="flex items-center gap-1.5 text-xs whitespace-nowrap">
<SpinnerIcon size={13} /> {row.stageLabel}
</span>
)}
{row.hasError && (
<span className="flex flex-col gap-0.5">
<span className="inline-flex items-center gap-1 text-xs" style={{ color: "var(--color-accent-2-700)" }} title={row.errorText || undefined}>
<XCircleIcon size={13} /> Didn’t go through.
</span>
<button type="button" className="btn btn-ghost self-start p-0 text-xs" onClick={row.onRetry}>
Retry
</button>
</span>
)}
{row.receipt && !row.busy && !row.hasError && (
<span className="flex flex-col gap-0.5">
<span className="inline-flex items-center gap-1 text-xs whitespace-nowrap" style={{ color: "var(--color-accent-700)" }}>
<CheckCircleIcon size={13} /> Paid {row.receipt.amount}
</span>
{row.receipt.link ? (
<a href={row.receipt.link} target="_blank" rel="noopener noreferrer" className="text-[11px] underline" style={{ color: "var(--color-accent-700)" }}>
View tx ↗
</a>
) : (
row.receipt.blockLabel && <span className="text-[11px] opacity-60">{row.receipt.blockLabel}</span>
)}
</span>
)}
{!row.showFinance && !row.showRepay && !row.busy && !row.hasError && !row.receipt && <span className="opacity-40">—</span>}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}