@le-space/eigenbeleg 0.7.0 → 0.8.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/README.md +2 -2
- package/package.json +3 -3
- package/src/statement-pdf.js +64 -18
- package/src/statement.js +39 -4
- package/src/value.js +58 -5
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@ The Eigenbeleg and the Kontoauszug of Le Space's tools – [Belege](https://gith
|
|
|
4
4
|
|
|
5
5
|
An Eigenbeleg is a receipt the payer writes for a payment that has no receipt from the other side. It is never an invoice, and never one written for somebody else.
|
|
6
6
|
|
|
7
|
-
- **A period's Eigenbeleg** (Eigenbeleg's): `valueEntries(entries, rates)` values [`@le-space/ledger`](../ledger) entries at the day's rate (`rates.rateFor(asset, day)`, e.g. from [`@le-space/rates`](../rates); `fixedRates` for tests; Aleph credits at their USD price per credit). `buildDocument({ payer, chain, network, period, entries, number, includeKinds, layout })` puts the payments to the network on it (fees, storage deposits; transfers only when included) and says of every other movement why not; `layout: 'collective'` (one Sammel-Eigenbeleg) or `'single'` (one per transaction, numbered up from the first, `nthNumber`). `eigenbelegPdf(doc, { logo })`, `eigenbelegCsv(doc)` (semicolons, decimal commas, BOM; formulas defused).
|
|
8
|
-
- **The Kontoauszug** (Eigenbeleg's): `buildStatement({ payer, account, chain, period, entries, opening, closing, method, belege })` – opening balance, each booking with debit, credit and running balance, closing balance checked against the chain (`reconciled(difference)`: exactly, or but for dust below the twelve decimals the documents print, `isDust`, such as NEAR's 1 yocto deposit of a token transfer); Aleph credits and a payer's balance in Filecoin Pay (chain `filecoin-pay`, the entries of `@le-space/chains/filecoin-pay`'s `filecoinPayEntries`) as a monthly **Verbrauchsauszug**, each with its own note (`USAGE_NOTES`). `statementPdf(st, { logo, chart })`. Above each list of bookings stands a small diagram ([#889](https://github.com/Le-Space/belege/issues/889)), drawn as vectors from [`@le-space/charts`](../charts): the balance over the period on a Kontoauszug, the consumption per resource on a Verbrauchsauszug, per day (per month where the period is longer than a quarter), in the asset's own unit; `chart: false` leaves it out. `statementChart(st, section)` gives its series and its scene, for an API's answer or `svg(scene)`; `drawScene(page, scene, { x, top, fonts })` draws any scene on a PDF page. `logo: true` draws the chain's mark, small, beside the title (NEAR, Akash, Filecoin, Aleph; from `@le-space/pdf`'s `LOGOS`, sources and terms in its `assets/README.md`); off unless asked for.
|
|
7
|
+
- **A period's Eigenbeleg** (Eigenbeleg's): `valueEntries(entries, rates)` values [`@le-space/ledger`](../ledger) entries at the day's rate (`rates.rateFor(asset, day)`, e.g. from [`@le-space/rates`](../rates); `fixedRates` for tests; Aleph credits at their USD price per credit; an EVM token not in the chain's list – `listed: false`, by its contract – only through `rates.tokenRateFor({ asset, contract, chain, block, decimals }, day)`, e.g. `@le-space/rates` `rate(asset, day, { contract, chain, block, decimals })`: CoinGecko by contract, else a DEX pool at the block; without it such a token stays unvalued, and its symbol, the token's own claim, is never asked for as a market asset, #93). `buildDocument({ payer, chain, network, period, entries, number, includeKinds, layout })` puts the payments to the network on it (fees, storage deposits; transfers only when included) and says of every other movement why not; `layout: 'collective'` (one Sammel-Eigenbeleg) or `'single'` (one per transaction, numbered up from the first, `nthNumber`). `eigenbelegPdf(doc, { logo })`, `eigenbelegCsv(doc)` (semicolons, decimal commas, BOM; formulas defused).
|
|
8
|
+
- **The Kontoauszug** (Eigenbeleg's): `buildStatement({ payer, account, chain, period, entries, opening, closing, method, belege })` – opening balance, each booking with debit, credit and running balance, closing balance checked against the chain (`reconciled(difference)`: exactly, or but for dust below the twelve decimals the documents print, `isDust`, such as NEAR's 1 yocto deposit of a token transfer); Aleph credits and a payer's balance in Filecoin Pay (chain `filecoin-pay`, the entries of `@le-space/chains/filecoin-pay`'s `filecoinPayEntries`) as a monthly **Verbrauchsauszug**, each with its own note (`USAGE_NOTES`). An EVM token not in the chain's list (`listed: false`, #93) gets a section of its own, named by its contract (`section.contract`; for one with a balance and no booking in the period from `contracts: { asset: '0x…' }`): _XYZ (laut Token-Vertrag)_ with the address below, the symbol and decimals marked as the contract's own claim, and its values said to be at a rate by contract address (`section.sources`), or that no source has one. A section that does not fit on the rest of the page starts on a new one. `statementPdf(st, { logo, chart })`. Above each list of bookings stands a small diagram ([#889](https://github.com/Le-Space/belege/issues/889)), drawn as vectors from [`@le-space/charts`](../charts): the balance over the period on a Kontoauszug, the consumption per resource on a Verbrauchsauszug, per day (per month where the period is longer than a quarter), in the asset's own unit; `chart: false` leaves it out. `statementChart(st, section)` gives its series and its scene, for an API's answer or `svg(scene)`; `drawScene(page, scene, { x, top, fonts })` draws any scene on a PDF page. `logo: true` draws the chain's mark, small, beside the title (NEAR, Akash, Filecoin, Aleph; from `@le-space/pdf`'s `LOGOS`, sources and terms in its `assets/README.md`); off unless asked for.
|
|
9
9
|
- **Another currency than the euro** ([eigenbeleg-agent#72](https://github.com/Le-Space/eigenbeleg-agent/issues/72)): `valueEntries(entries, rates, { currency })`, `buildDocument({ …, currency })` and `buildStatement({ …, currency })` take the document's currency, EUR when none is given – `DOCUMENT_CURRENCIES`: EUR, USD, CHF, GBP, SEK, NOK, DKK, PLN, CZK, HUF, RON, ISK, TRY (through the ECB's reference rate) and RUB (the Bank of Russia's official rate). The rates handed in are in that currency and say so (`{ rate, source, date, currency }`; `@le-space/rates` `rate(asset, date, { currency })`), `source` naming both legs; a value in one currency under a head in another is refused. The documents then say _Kurs CHF_, _Wert CHF_, amounts as `1.234,56 CHF`, sums rounded to the currency's own decimals (ISK: none), and how the value came about (`conversionText`, `usageNote`); Aleph credits in USD are Aleph's own USD price, without a rate. The fields named `eur…` (`entry.eur`, `totals.eur`, `eurOut` …) keep their names and hold the value in the document's currency, with `currency` beside them. An EUR document is the same file as before. `bookingPdf` is Belege's own booking and stays in euro.
|
|
10
10
|
- **The Eigenbeleg of one booking** (Belege's, `@le-space/eigenbeleg/booking`, `/booking-pdf`): `bookingPdf(doc)` for a `BookingEigenbeleg` – a bank booking or a crypto payment, with an own wallet's transaction in full (whole hash, both addresses, every movement with the gas, the explorer link as a QR code). The booking's context is the caller's to gather. `nextSelfNumber(receipts, year)` – the range EB-YYYY-NNN.
|
|
11
11
|
- **A statement Eigenbeleg** (Belege's Aleph, Akash and travel statements, `@le-space/eigenbeleg/statement-layout`): `statementLayout({ title, created, continuation })` → `head`, `field`, `rule`, `heading`, `table` (the header repeats on a new page), `signature`, `save`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@le-space/eigenbeleg",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "The Eigenbeleg and the Kontoauszug of Le Space's tools: a payer's own receipt for payments without one from the other side (a period's network fees, one booking in any script), a blockchain account's statement (Aleph credits as a Verbrauchsauszug), as PDF/A-2b and CSV. Browser and Node; the rates handed in.",
|
|
5
5
|
"license": "AGPL-3.0-or-later",
|
|
6
6
|
"type": "module",
|
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"pdf-lib": "1.17.1",
|
|
38
38
|
"uqr": "0.1.3",
|
|
39
|
-
"@le-space/charts": "^0.2.0",
|
|
40
39
|
"@le-space/pdf": "^0.3.0",
|
|
40
|
+
"@le-space/charts": "^0.2.0",
|
|
41
41
|
"@le-space/ledger": "^0.3.1"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"prettier": "3.6.2",
|
|
46
46
|
"unpdf": "1.8.1",
|
|
47
47
|
"@le-space/browser-test": "0.1.0",
|
|
48
|
-
"@le-space/chains": "^0.
|
|
48
|
+
"@le-space/chains": "^0.9.0"
|
|
49
49
|
},
|
|
50
50
|
"scripts": {
|
|
51
51
|
"test": "node --test --test-reporter=spec \"test/*.test.js\"",
|
package/src/statement-pdf.js
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
// bookkeeper needs. German, for German bookkeeping. Aleph Cloud credits get
|
|
8
8
|
// the same layout titled »Verbrauchsauszug« (`st.title`). Above each list of
|
|
9
9
|
// bookings a small diagram (#889, statement-chart.js): the balance over the
|
|
10
|
-
// period, or what was consumed per day.
|
|
10
|
+
// period, or what was consumed per day. A token not in the chain's list (#93)
|
|
11
|
+
// is named by its contract, its symbol the contract's own claim; a section
|
|
12
|
+
// that does not fit on the rest of the page starts on a new one.
|
|
11
13
|
|
|
12
14
|
import { asset, createPdfA, LOGOS, savePdfA, wrapText } from '@le-space/pdf';
|
|
13
15
|
import { round } from '@le-space/ledger';
|
|
@@ -143,14 +145,60 @@ export async function statementPdf(
|
|
|
143
145
|
l.note(st.note, TYPE.table);
|
|
144
146
|
l.y -= 18;
|
|
145
147
|
|
|
148
|
+
/** A booking's two lines of text, and the height of its row. @param {import('./statement.js').StatementRow} r */
|
|
149
|
+
const rowText = (r) => {
|
|
150
|
+
const detail = [
|
|
151
|
+
r.counterparty && `${r.debit ? 'an' : 'von'} ${r.counterparty}`,
|
|
152
|
+
r.hash && `${r.hashLabel} ${r.hash.slice(0, 10)}…${r.hash.slice(-6)}`,
|
|
153
|
+
r.beleg && `Eigenbeleg ${r.beleg}`
|
|
154
|
+
]
|
|
155
|
+
.filter(Boolean)
|
|
156
|
+
.join(' · ');
|
|
157
|
+
const lines = wrapText(r.text, regular, 8, COLS[1].width - 6);
|
|
158
|
+
const sub = wrapText(detail, regular, 6.5, COLS[1].width - 6);
|
|
159
|
+
return { lines, sub, h: lines.length * 10 + sub.length * 8.5 + 6 };
|
|
160
|
+
};
|
|
161
|
+
/** What a page holds below its running head, above the footer. */
|
|
162
|
+
const pageRoom = l.page.getHeight() - 2 * M - 18 - 16;
|
|
163
|
+
|
|
146
164
|
// ---- one section per asset
|
|
147
|
-
for (const s of st.sections) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
165
|
+
for (const [i, s] of st.sections.entries()) {
|
|
166
|
+
// The diagram, above the list of bookings (#889); every figure in it is in the tables.
|
|
167
|
+
const drawn = chart ? statementChart(st, s, { width, measure: sceneMeasure(fonts) }) : null;
|
|
168
|
+
const monthLines =
|
|
169
|
+
aleph || pay
|
|
170
|
+
? [s.monthly.usage, s.monthly.usageTotal, s.monthly.purchases, s.monthly.transfersIn]
|
|
171
|
+
.concat([s.monthly.transfersOut])
|
|
172
|
+
.flat()
|
|
173
|
+
.filter((x) => x !== null).length
|
|
174
|
+
: 0;
|
|
175
|
+
// A section that does not fit on the rest of the page starts on a new one (#93: a wallet with
|
|
176
|
+
// many tokens): its head never stands apart from its bookings. The first follows the head.
|
|
177
|
+
const tall =
|
|
178
|
+
(s.contract ? 70 : 40) +
|
|
179
|
+
(monthLines ? 14 + monthLines * 12 + 15 : 0) +
|
|
180
|
+
(drawn ? drawn.scene.height + 14 : 0) +
|
|
181
|
+
30 +
|
|
182
|
+
(s.rows.length ? s.rows.reduce((h, r) => h + rowText(r).h, 0) : 13) +
|
|
183
|
+
110;
|
|
184
|
+
if (i > 0 && l.y - (M + 16) < Math.min(tall, pageRoom)) l.newPage();
|
|
185
|
+
else l.ensure(90);
|
|
186
|
+
// A section: its head on a hairline. No band, no fill. A token not in the list is named by its
|
|
187
|
+
// contract; what it calls itself is the contract's own claim.
|
|
188
|
+
if (s.contract) {
|
|
189
|
+
text(`${s.asset} (laut Token-Vertrag)`, { face: bold, size: TYPE.lead });
|
|
190
|
+
text(s.contract, { face: mono, size: TYPE.body });
|
|
191
|
+
} else text(`${s.asset} · ${st.account}`, { face: bold, size: TYPE.lead });
|
|
151
192
|
l.y -= 3;
|
|
152
193
|
l.rule();
|
|
153
194
|
l.y -= 10;
|
|
195
|
+
if (s.contract) {
|
|
196
|
+
text(
|
|
197
|
+
`Token außerhalb der Liste geprüfter Token dieser Chain: Name »${s.asset}« und Nachkommastellen nennt der Vertrag selbst; maßgeblich ist seine Adresse oben.`,
|
|
198
|
+
{ size: TYPE.small, color: GREY }
|
|
199
|
+
);
|
|
200
|
+
l.y -= 6;
|
|
201
|
+
}
|
|
154
202
|
// The month in sums, first (#24): what the books take as one booking each; the rows below are the proof.
|
|
155
203
|
if (aleph || pay) {
|
|
156
204
|
const m = s.monthly;
|
|
@@ -184,8 +232,6 @@ export async function statementPdf(
|
|
|
184
232
|
l.y -= 14;
|
|
185
233
|
}
|
|
186
234
|
}
|
|
187
|
-
// The diagram, above the list of bookings (#889); every figure in it is in the tables.
|
|
188
|
-
const drawn = chart ? statementChart(st, s, { width, measure: sceneMeasure(fonts) }) : null;
|
|
189
235
|
if (drawn) {
|
|
190
236
|
l.ensure(drawn.scene.height + 40);
|
|
191
237
|
drawScene(l.page, drawn.scene, { x: M, top: l.y, fonts });
|
|
@@ -210,16 +256,7 @@ export async function statementPdf(
|
|
|
210
256
|
l.rule();
|
|
211
257
|
l.y -= 2;
|
|
212
258
|
for (const r of s.rows) {
|
|
213
|
-
const
|
|
214
|
-
r.counterparty && `${r.debit ? 'an' : 'von'} ${r.counterparty}`,
|
|
215
|
-
r.hash && `${r.hashLabel} ${r.hash.slice(0, 10)}…${r.hash.slice(-6)}`,
|
|
216
|
-
r.beleg && `Eigenbeleg ${r.beleg}`
|
|
217
|
-
]
|
|
218
|
-
.filter(Boolean)
|
|
219
|
-
.join(' · ');
|
|
220
|
-
const lines = wrapText(r.text, regular, 8, COLS[1].width - 6);
|
|
221
|
-
const sub = wrapText(detail, regular, 6.5, COLS[1].width - 6);
|
|
222
|
-
const h = lines.length * 10 + sub.length * 8.5 + 6;
|
|
259
|
+
const { lines, sub, h } = rowText(r);
|
|
223
260
|
if (l.ensure(h)) head();
|
|
224
261
|
const y = l.y;
|
|
225
262
|
regular.draw(l.page, deDate(r.date), { x: M, y: y - 8, size: 8, color: INK });
|
|
@@ -305,7 +342,16 @@ export async function statementPdf(
|
|
|
305
342
|
? 'Euro-Werte: USD-Preis je Credit (letzter Kauf am oder vor dem Tag, sonst Listenpreis) × EZB-Referenzkurs USD/EUR des Tages'
|
|
306
343
|
: `Werte in ${cur}: USD-Preis je Credit (letzter Kauf am oder vor dem Tag, sonst Listenpreis)${cur === 'USD' ? '' : `, ${conversionText(cur)}`}`
|
|
307
344
|
}.`
|
|
308
|
-
: `Ausgänge ${money(s.eurOut)} · Eingänge ${money(s.eurIn)} · davon Netzwerkgebühren (Aufwand) ${money(s.eurFees)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – ${
|
|
345
|
+
: `Ausgänge ${money(s.eurOut)} · Eingänge ${money(s.eurIn)} · davon Netzwerkgebühren (Aufwand) ${money(s.eurFees)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – ${
|
|
346
|
+
!s.contract
|
|
347
|
+
? valued(...marketOrReference(s))
|
|
348
|
+
: s.sources?.length
|
|
349
|
+
? valued(
|
|
350
|
+
`zum Kurs nach der Vertragsadresse: ${s.sources.join(' und ')}`,
|
|
351
|
+
`Kurs nach der Vertragsadresse: ${s.sources.join(' und ')}`
|
|
352
|
+
)
|
|
353
|
+
: 'für diesen Token nennt keine Kursquelle einen Kurs'
|
|
354
|
+
}.`,
|
|
309
355
|
{ size: TYPE.small, color: GREY }
|
|
310
356
|
);
|
|
311
357
|
l.y -= 20;
|
package/src/statement.js
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
// The Kontoauszug: every booking of one own blockchain account in a period,
|
|
4
4
|
// laid out the way a bank lays out an account statement – opening balance,
|
|
5
5
|
// each booking with debit (Soll) or credit (Haben) and the running balance,
|
|
6
|
-
// closing balance, sums. One section per asset the account holds.
|
|
6
|
+
// closing balance, sums. One section per asset the account holds. A token
|
|
7
|
+
// not in the chain's list (EVM, #93) has one too, named by its contract: the
|
|
8
|
+
// symbol and decimals are what the contract says of itself.
|
|
7
9
|
//
|
|
8
10
|
// It is built from public chain data by the account holder. It is no
|
|
9
11
|
// document of a bank or of anyone else, and says so.
|
|
@@ -96,6 +98,17 @@ export function valuedBy(rows) {
|
|
|
96
98
|
};
|
|
97
99
|
}
|
|
98
100
|
|
|
101
|
+
/**
|
|
102
|
+
* The contract of a token not in the chain's list (EVM, #93): lower case, '' for
|
|
103
|
+
* the native coin, a listed token and anything else.
|
|
104
|
+
*
|
|
105
|
+
* @param {{ listed?: boolean, contract?: string }} e
|
|
106
|
+
*/
|
|
107
|
+
const unlistedContract = (e) =>
|
|
108
|
+
e.listed === false && /^0x[0-9a-fA-F]{40}$/.test(e.contract ?? '')
|
|
109
|
+
? /** @type {string} */ (e.contract).toLowerCase()
|
|
110
|
+
: '';
|
|
111
|
+
|
|
99
112
|
export const STATEMENT_NOTE =
|
|
100
113
|
'Kontoauszug eines Blockchain-Kontos, erstellt vom Kontoinhaber aus öffentlichen Chain-Daten. ' +
|
|
101
114
|
'Kein Dokument eines Kreditinstituts. Jede Buchung ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
|
|
@@ -190,6 +203,9 @@ export function monthly(rows) {
|
|
|
190
203
|
* @param {string} [p.dataSource] where the entries were read from, when not the chain's usual source
|
|
191
204
|
* @param {string} [p.currency] the statement's currency (DOCUMENT_CURRENCIES), EUR when not
|
|
192
205
|
* given; the entries are valued in it, and the fields named `eur…` hold values in it
|
|
206
|
+
* @param {Record<string, string>} [p.contracts] asset → contract of a token not in the
|
|
207
|
+
* chain's list whose balance is in `opening`/`closing` (the reader's balances, #93);
|
|
208
|
+
* for one that moved in the period its entries name it already
|
|
193
209
|
*/
|
|
194
210
|
export function buildStatement({
|
|
195
211
|
payer,
|
|
@@ -206,7 +222,8 @@ export function buildStatement({
|
|
|
206
222
|
number,
|
|
207
223
|
issuedAt,
|
|
208
224
|
dataSource,
|
|
209
|
-
currency: asked
|
|
225
|
+
currency: asked,
|
|
226
|
+
contracts = {}
|
|
210
227
|
}) {
|
|
211
228
|
const currency = documentCurrency(asked);
|
|
212
229
|
checkValued(entries, currency);
|
|
@@ -216,10 +233,17 @@ export function buildStatement({
|
|
|
216
233
|
(e) => e.account === account && !(e.chain === 'aleph' && e.kind === 'swap')
|
|
217
234
|
);
|
|
218
235
|
const own = mine.filter((e) => e.success !== false);
|
|
236
|
+
// A token not in the list (#93) has no priceAs, but its contract: it gets a section too.
|
|
219
237
|
const assets = [
|
|
220
|
-
...new Set([
|
|
238
|
+
...new Set([
|
|
239
|
+
...Object.keys(opening),
|
|
240
|
+
...own.filter((e) => e.priceAs || unlistedContract(e)).map((e) => e.asset)
|
|
241
|
+
])
|
|
221
242
|
];
|
|
222
243
|
const sections = assets.map((asset) => {
|
|
244
|
+
const contract =
|
|
245
|
+
unlistedContract(own.find((e) => e.asset === asset && unlistedContract(e)) ?? {}) ||
|
|
246
|
+
unlistedContract({ listed: false, contract: contracts[asset] });
|
|
223
247
|
let balance = normalize(opening[asset] ?? '0');
|
|
224
248
|
/** @type {StatementRow[]} */
|
|
225
249
|
const rows = [];
|
|
@@ -255,6 +279,8 @@ export function buildStatement({
|
|
|
255
279
|
const reported = closing[asset];
|
|
256
280
|
return {
|
|
257
281
|
asset,
|
|
282
|
+
// A token not in the list: its contract, which names it; the symbol is the token's own claim.
|
|
283
|
+
contract,
|
|
258
284
|
opening: normalize(opening[asset] ?? '0'),
|
|
259
285
|
closing: balance,
|
|
260
286
|
reported: reported === undefined ? null : normalize(reported),
|
|
@@ -271,7 +297,16 @@ export function buildStatement({
|
|
|
271
297
|
eurFees: sum(rows.filter((r) => r.fee && r.eur).map((r) => r.eur.replace(/^-/, ''))),
|
|
272
298
|
eurUsage: sum(rows.filter((r) => r.usage && r.eur).map((r) => r.eur.replace(/^-/, ''))),
|
|
273
299
|
unvalued: rows.filter((r) => !r.eur).length,
|
|
274
|
-
...valuedBy(rows)
|
|
300
|
+
...valuedBy(rows),
|
|
301
|
+
// A token not in the list: each source of its values by name, without its day – no
|
|
302
|
+
// market rate of the usual feeds (CoinGecko by contract, a DEX pool, a reference value).
|
|
303
|
+
...(contract
|
|
304
|
+
? {
|
|
305
|
+
sources: [
|
|
306
|
+
...new Set(rows.filter((r) => r.eur).map((r) => sourceName(r.rateSource ?? '')))
|
|
307
|
+
]
|
|
308
|
+
}
|
|
309
|
+
: {})
|
|
275
310
|
};
|
|
276
311
|
});
|
|
277
312
|
// Aleph credits, Filecoin Pay: a monthly usage statement, laid out as the Kontoauszug.
|
package/src/value.js
CHANGED
|
@@ -9,6 +9,11 @@
|
|
|
9
9
|
// price per credit the reader hands with each entry (`unitPrice`: the last
|
|
10
10
|
// purchase on or before the day, else Aleph's list price) at that day's ECB
|
|
11
11
|
// rate for USD (@le-space/rates/aleph-credits).
|
|
12
|
+
//
|
|
13
|
+
// A token not in the chain's list (EVM, `listed: false`, #93) has no market
|
|
14
|
+
// asset either: it is valued only when the caller hands in `tokenRateFor`,
|
|
15
|
+
// asked by its contract, chain, block and decimals. Its symbol is the token's
|
|
16
|
+
// own claim and is never asked for as a market asset.
|
|
12
17
|
|
|
13
18
|
import { multiply } from '@le-space/ledger';
|
|
14
19
|
|
|
@@ -22,7 +27,22 @@ import { documentCurrency } from './document.js';
|
|
|
22
27
|
* @property {string} [currency] what the rate is in; EUR when not given
|
|
23
28
|
*/
|
|
24
29
|
|
|
25
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {object} TokenRef a token not in the chain's list, by its contract (#93)
|
|
32
|
+
* @property {string} asset the symbol it calls itself, its own claim
|
|
33
|
+
* @property {string} contract 0x + 40 hex, lower case
|
|
34
|
+
* @property {string} chain e.g. `ethereum`, `base`
|
|
35
|
+
* @property {number} block the booking's block, for a DEX pool's price at it
|
|
36
|
+
* @property {number} decimals
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @typedef {object} Rates
|
|
41
|
+
* @property {(asset: string, date: string) => Promise<Rate | null>} rateFor a listed asset
|
|
42
|
+
* @property {(token: TokenRef, date: string) => Promise<Rate | null>} [tokenRateFor] a token
|
|
43
|
+
* not in the list, by its contract (@le-space/rates: CoinGecko by contract, else a DEX
|
|
44
|
+
* pool at the block); without it such a token stays unvalued
|
|
45
|
+
*/
|
|
26
46
|
|
|
27
47
|
/**
|
|
28
48
|
* @typedef {import('@le-space/ledger').LedgerEntry & { eur: { value: string, rate: string, source: string, currency?: string } | null }} ValuedEntry
|
|
@@ -30,6 +50,13 @@ import { documentCurrency } from './document.js';
|
|
|
30
50
|
* currency it carries that `currency`
|
|
31
51
|
*/
|
|
32
52
|
|
|
53
|
+
/**
|
|
54
|
+
* A token not in the chain's list (#115, #93): booked by its contract, no market asset.
|
|
55
|
+
* @param {import('@le-space/ledger').LedgerEntry} e
|
|
56
|
+
*/
|
|
57
|
+
const isToken = (e) =>
|
|
58
|
+
e.listed === false && /^0x[0-9a-fA-F]{40}$/.test(e.contract) && Number.isSafeInteger(e.height);
|
|
59
|
+
|
|
33
60
|
/**
|
|
34
61
|
* Every entry with its euro value (8 decimals; printed with 4, the total rounded to cents
|
|
35
62
|
* where it is printed). An entry without a price gets `eur: null`. One with a
|
|
@@ -45,12 +72,14 @@ export async function valueEntries(entries, rates, { currency: asked } = {}) {
|
|
|
45
72
|
// An EUR value stays as it always was; another currency is named on it.
|
|
46
73
|
const mark = currency === 'EUR' ? {} : { currency };
|
|
47
74
|
/** A rate in another currency than the document's is the caller's mistake, not a value. @param {string} asset @param {string} date */
|
|
48
|
-
|
|
49
|
-
|
|
75
|
+
/** @param {Rate | null} r */
|
|
76
|
+
const checked = (r) => {
|
|
50
77
|
if (r && (r.currency ?? 'EUR') !== currency)
|
|
51
78
|
throw new Error(`a rate in ${r.currency ?? 'EUR'} for a document in ${currency}`);
|
|
52
79
|
return r;
|
|
53
80
|
};
|
|
81
|
+
const rateFor = async (/** @type {string} */ asset, /** @type {string} */ date) =>
|
|
82
|
+
checked(await rates.rateFor(asset, date));
|
|
54
83
|
const out = [];
|
|
55
84
|
for (const e of entries) {
|
|
56
85
|
const unit =
|
|
@@ -86,7 +115,24 @@ export async function valueEntries(entries, rates, { currency: asked } = {}) {
|
|
|
86
115
|
});
|
|
87
116
|
continue;
|
|
88
117
|
}
|
|
89
|
-
const r = e.
|
|
118
|
+
const r = !e.success
|
|
119
|
+
? null
|
|
120
|
+
: e.priceAs
|
|
121
|
+
? await rateFor(e.priceAs, e.date)
|
|
122
|
+
: isToken(e) && rates.tokenRateFor
|
|
123
|
+
? await checked(
|
|
124
|
+
await rates.tokenRateFor(
|
|
125
|
+
{
|
|
126
|
+
asset: e.asset,
|
|
127
|
+
contract: e.contract.toLowerCase(),
|
|
128
|
+
chain: e.chain,
|
|
129
|
+
block: e.height,
|
|
130
|
+
decimals: e.decimals
|
|
131
|
+
},
|
|
132
|
+
e.date
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
: null;
|
|
90
136
|
out.push({
|
|
91
137
|
...e,
|
|
92
138
|
eur: r
|
|
@@ -100,7 +146,8 @@ export async function valueEntries(entries, rates, { currency: asked } = {}) {
|
|
|
100
146
|
/**
|
|
101
147
|
* Fixed rates, for tests and offline demos.
|
|
102
148
|
*
|
|
103
|
-
* @param {Record<string, string>} table `NEAR:2026-10-05` → `3.8796
|
|
149
|
+
* @param {Record<string, string>} table `NEAR:2026-10-05` → `3.8796`; a token not in the list by
|
|
150
|
+
* its contract (lower case): `0x…:2026-10-05` or `0x…`
|
|
104
151
|
* @param {string} [currency] what the table's rates are in; EUR when not given
|
|
105
152
|
* @returns {Rates}
|
|
106
153
|
*/
|
|
@@ -110,6 +157,12 @@ export function fixedRates(table, currency) {
|
|
|
110
157
|
async rateFor(asset, date) {
|
|
111
158
|
const rate = table[`${asset}:${date}`] ?? table[asset];
|
|
112
159
|
return rate ? { rate, source: `fester Testkurs (${asset})`, date, ...mark } : null;
|
|
160
|
+
},
|
|
161
|
+
async tokenRateFor({ contract }, date) {
|
|
162
|
+
const rate = table[`${contract}:${date}`] ?? table[contract];
|
|
163
|
+
return rate
|
|
164
|
+
? { rate, source: `fester Testkurs (Token-Vertrag ${contract})`, date, ...mark }
|
|
165
|
+
: null;
|
|
113
166
|
}
|
|
114
167
|
};
|
|
115
168
|
}
|