@le-space/eigenbeleg 0.6.1 → 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 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.6.1",
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,16 +36,16 @@
36
36
  "dependencies": {
37
37
  "pdf-lib": "1.17.1",
38
38
  "uqr": "0.1.3",
39
+ "@le-space/pdf": "^0.3.0",
39
40
  "@le-space/charts": "^0.2.0",
40
- "@le-space/pdf": "^0.2.0",
41
- "@le-space/ledger": "^0.3.0"
41
+ "@le-space/ledger": "^0.3.1"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@noble/hashes": "2.4.0",
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.7.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/document.js CHANGED
@@ -181,7 +181,9 @@ export const CHAIN_NAMES = {
181
181
  aleph: 'Aleph Cloud (Credits)',
182
182
  'filecoin-pay': 'Filecoin Pay',
183
183
  ethereum: 'Ethereum',
184
- base: 'Base'
184
+ base: 'Base',
185
+ bitcoin: 'Bitcoin',
186
+ doichain: 'Doichain'
185
187
  };
186
188
 
187
189
  /**
@@ -196,9 +198,22 @@ export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
196
198
  aleph: 'Aleph-API (api2.aleph.im)',
197
199
  'filecoin-pay': 'Index von Filecoin Pay (Goldsky), Blockscout, Filfox',
198
200
  ethereum: 'Alchemy APIs (Ethereum Mainnet)',
199
- base: 'Alchemy APIs (Base Mainnet)'
201
+ base: 'Alchemy APIs (Base Mainnet)',
202
+ bitcoin: 'Esplora-API von mempool.space',
203
+ doichain: 'ElectrumX-Server des Doichain-Netzes'
200
204
  });
201
205
 
206
+ /**
207
+ * The data source a document names: the one the caller read from when it
208
+ * says so (an own Esplora, say), else the chain's usual one.
209
+ *
210
+ * @param {string} chain
211
+ * @param {string} chainName
212
+ * @param {string} [given]
213
+ */
214
+ export const dataSourceOf = (chain, chainName, given) =>
215
+ given?.trim() || DATA_SOURCES[chain] || chainName;
216
+
202
217
  /**
203
218
  * @typedef {object} Payer who pays and issues the Eigenbeleg
204
219
  * @property {string} name
@@ -246,6 +261,7 @@ export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
246
261
  * @param {string[]} [p.includeKinds]
247
262
  * @param {string} [p.issuedAt] ISO; now when not given
248
263
  * @param {'collective' | 'single'} [p.layout]
264
+ * @param {string} [p.dataSource] where the entries were read from, when not the chain's usual source
249
265
  * @param {string} [p.currency] the document's currency (DOCUMENT_CURRENCIES), EUR when not
250
266
  * given; the entries are valued in it. The fields named `eur…` hold the values in this
251
267
  * currency: they keep the name they had when every document was in euro.
@@ -260,6 +276,7 @@ export function buildDocument({
260
276
  includeKinds = DEFAULT_KINDS,
261
277
  issuedAt,
262
278
  layout = 'collective',
279
+ dataSource,
263
280
  currency: asked
264
281
  }) {
265
282
  if (layout !== 'collective' && layout !== 'single')
@@ -365,6 +382,7 @@ export function buildDocument({
365
382
  },
366
383
  chain,
367
384
  chainName,
385
+ dataSource: dataSourceOf(chain, chainName, dataSource),
368
386
  network,
369
387
  testnet: network !== 'mainnet',
370
388
  period,
package/src/index.js CHANGED
@@ -13,6 +13,7 @@ export {
13
13
  ALEPH_NOTE,
14
14
  noInvoice,
15
15
  CHAIN_NAMES,
16
+ dataSourceOf,
16
17
  DATA_SOURCES,
17
18
  deNumber,
18
19
  deRate,
package/src/layout.js CHANGED
@@ -273,8 +273,9 @@ export function pageLayout(pdf, fonts, { margin = 48, bottom = 14, leavePage, en
273
273
  * @param {string} caption
274
274
  */
275
275
  signature(caption) {
276
- l.ensure(70);
277
- l.gap(40);
276
+ // What it takes and no more: a line to sign alone on a new page helps nobody.
277
+ l.ensure(54);
278
+ l.gap(36);
278
279
  l.page.drawLine({
279
280
  start: { x: margin, y: l.y },
280
281
  end: { x: margin + 230, y: l.y },
package/src/pdf.js CHANGED
@@ -61,7 +61,7 @@ export async function eigenbelegPdf(
61
61
  : `unter ${money(places ? `0.${'1'.padStart(places, '0')}` : '1')}`;
62
62
  let pageNo = 1;
63
63
  let current = doc.number;
64
- const footerRight = `Daten: ${DATA_SOURCES[doc.chain] ?? doc.chainName} · Kurse: siehe Kursquelle`;
64
+ const footerRight = `Daten: ${doc.dataSource ?? DATA_SOURCES[doc.chain] ?? doc.chainName} · Kurse: siehe Kursquelle`;
65
65
 
66
66
  const footer = (/** @type {import('./layout.js').Layout} */ l) =>
67
67
  l.foot(l.page, `${current} · Seite ${pageNo}`, footerRight);
@@ -112,11 +112,13 @@ export async function eigenbelegPdf(
112
112
  }
113
113
 
114
114
  const columns = [
115
- { title: 'Bewegung', width: 150 },
116
- { title: 'Menge', width: 112, right: true },
117
- // Six significant digits (deRate): the smallest rate, Aleph's credits, still fits on one line.
118
- { title: `Kurs ${cur}`, width: 58, right: true },
119
- { title: `Wert ${cur}`, width: 66, right: true },
115
+ // Measured in the document's face, whose figures are wider than its letters: a rate of six
116
+ // significant digits below a millionth (deRate; Aleph's credits) and a value of four digits
117
+ // before the comma with a currency's code each stand on one line.
118
+ { title: 'Bewegung', width: 143 },
119
+ { title: 'Menge', width: 106, right: true },
120
+ { title: `Kurs ${cur}`, width: 67, right: true },
121
+ { title: `Wert ${cur}`, width: 70, right: true },
120
122
  { title: 'Auf dem Beleg', width: width - 386 }
121
123
  ];
122
124
 
@@ -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
- l.ensure(90);
149
- // A section: its head on a hairline. No band, no fill.
150
- text(`${s.asset} · ${st.account}`, { face: bold, size: TYPE.lead });
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 detail = [
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` : ''} – ${valued(...marketOrReference(s))}.`,
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;
@@ -317,7 +363,7 @@ export async function statementPdf(
317
363
  );
318
364
 
319
365
  // page numbers and footer on every page
320
- const data = `Daten: ${DATA_SOURCES[st.chain] ?? st.chainName} · kein Dokument eines Kreditinstituts`;
366
+ const data = `Daten: ${st.dataSource ?? DATA_SOURCES[st.chain] ?? st.chainName} · kein Dokument eines Kreditinstituts`;
321
367
  l.pages.forEach((p, i) => l.foot(p, `${st.number} · Seite ${i + 1} von ${l.pages.length}`, data));
322
368
 
323
369
  return savePdfA(pdf, {
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.
@@ -22,6 +24,7 @@
22
24
  import { normalize, sum } from '@le-space/ledger';
23
25
  import {
24
26
  CHAIN_NAMES,
27
+ dataSourceOf,
25
28
  checkValued,
26
29
  conversionText,
27
30
  documentCurrency,
@@ -95,6 +98,17 @@ export function valuedBy(rows) {
95
98
  };
96
99
  }
97
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
+
98
112
  export const STATEMENT_NOTE =
99
113
  'Kontoauszug eines Blockchain-Kontos, erstellt vom Kontoinhaber aus öffentlichen Chain-Daten. ' +
100
114
  'Kein Dokument eines Kreditinstituts. Jede Buchung ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
@@ -186,8 +200,12 @@ export function monthly(rows) {
186
200
  * @param {Map<string, string>} [p.belege] hash → Eigenbeleg number
187
201
  * @param {string} [p.number]
188
202
  * @param {string} [p.issuedAt]
203
+ * @param {string} [p.dataSource] where the entries were read from, when not the chain's usual source
189
204
  * @param {string} [p.currency] the statement's currency (DOCUMENT_CURRENCIES), EUR when not
190
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
191
209
  */
192
210
  export function buildStatement({
193
211
  payer,
@@ -203,7 +221,9 @@ export function buildStatement({
203
221
  belege = new Map(),
204
222
  number,
205
223
  issuedAt,
206
- currency: asked
224
+ dataSource,
225
+ currency: asked,
226
+ contracts = {}
207
227
  }) {
208
228
  const currency = documentCurrency(asked);
209
229
  checkValued(entries, currency);
@@ -213,10 +233,17 @@ export function buildStatement({
213
233
  (e) => e.account === account && !(e.chain === 'aleph' && e.kind === 'swap')
214
234
  );
215
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.
216
237
  const assets = [
217
- ...new Set([...Object.keys(opening), ...own.filter((e) => e.priceAs).map((e) => e.asset)])
238
+ ...new Set([
239
+ ...Object.keys(opening),
240
+ ...own.filter((e) => e.priceAs || unlistedContract(e)).map((e) => e.asset)
241
+ ])
218
242
  ];
219
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] });
220
247
  let balance = normalize(opening[asset] ?? '0');
221
248
  /** @type {StatementRow[]} */
222
249
  const rows = [];
@@ -252,6 +279,8 @@ export function buildStatement({
252
279
  const reported = closing[asset];
253
280
  return {
254
281
  asset,
282
+ // A token not in the list: its contract, which names it; the symbol is the token's own claim.
283
+ contract,
255
284
  opening: normalize(opening[asset] ?? '0'),
256
285
  closing: balance,
257
286
  reported: reported === undefined ? null : normalize(reported),
@@ -268,7 +297,16 @@ export function buildStatement({
268
297
  eurFees: sum(rows.filter((r) => r.fee && r.eur).map((r) => r.eur.replace(/^-/, ''))),
269
298
  eurUsage: sum(rows.filter((r) => r.usage && r.eur).map((r) => r.eur.replace(/^-/, ''))),
270
299
  unvalued: rows.filter((r) => !r.eur).length,
271
- ...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
+ : {})
272
310
  };
273
311
  });
274
312
  // Aleph credits, Filecoin Pay: a monthly usage statement, laid out as the Kontoauszug.
@@ -282,6 +320,11 @@ export function buildStatement({
282
320
  account,
283
321
  chain,
284
322
  chainName: CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
323
+ dataSource: dataSourceOf(
324
+ chain,
325
+ CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
326
+ dataSource
327
+ ),
285
328
  network,
286
329
  testnet: network !== 'mainnet',
287
330
  period,
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
- /** @typedef {{ rateFor: (asset: string, date: string) => Promise<Rate | null> }} Rates */
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
- const rateFor = async (asset, date) => {
49
- const r = await rates.rateFor(asset, date);
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.priceAs && e.success ? await rateFor(e.priceAs, e.date) : null;
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
  }