@le-space/eigenbeleg 0.7.0 → 0.9.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/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.
@@ -29,6 +31,7 @@ import {
29
31
  kindText,
30
32
  sourceName
31
33
  } from './document.js';
34
+ import { documentLanguage, localizeLabel, say } from './language.js';
32
35
 
33
36
  /** Smaller than the twelve decimals the documents print (and not zero). @param {string} difference */
34
37
  export const isDust = (difference) => /^-?0\.0{12}\d*$/.test(difference);
@@ -62,14 +65,39 @@ export const USAGE_NOTES = /** @type {Record<string, string>} */ ({
62
65
  'filecoin-pay': FILECOIN_PAY_USAGE_NOTE
63
66
  });
64
67
 
68
+ /** The same notes in English (language.js). */
69
+ export const USAGE_NOTES_EN = /** @type {Record<string, string>} */ ({
70
+ aleph:
71
+ 'Verbrauchsauszug (usage statement) of an Aleph Cloud account (credits), made by the account holder from the public Aleph API. ' +
72
+ 'No document of a bank and no invoice of Aleph. Usage per day and resource; value: the USD price per credit ' +
73
+ "(the last purchase on or before the day, else Aleph's list price of 1 USD per 1,000,000 credits) at the ECB reference rate of the day.",
74
+ 'filecoin-pay':
75
+ 'Verbrauchsauszug (usage statement) of a balance in the Filecoin Pay payment contract (Filecoin Onchain Cloud), made by the payer from public chain data. ' +
76
+ 'No document of a bank and no invoice of a storage provider. Usage is every settlement of a rail to its provider; ' +
77
+ 'it pays up to the time it names, so it does not cover the month exactly. Only USDFC is read; what the payer takes in through rails is missing. ' +
78
+ 'Value: USDFC is pegged to the US dollar and valued at the rate of USDC of the day.'
79
+ });
80
+
65
81
  /**
66
82
  * The note of a Verbrauchsauszug in the document's currency: what its values
67
83
  * are, said for that currency. EUR: the notes above, as they were.
68
84
  *
69
85
  * @param {string} chain from USAGE_NOTES
70
86
  * @param {string} currency
87
+ * @param {import('./language.js').DocumentLanguage} [language]
71
88
  */
72
- export function usageNote(chain, currency) {
89
+ export function usageNote(chain, currency, language = 'de') {
90
+ if (language === 'en') {
91
+ const note = USAGE_NOTES_EN[chain];
92
+ if (currency === 'EUR') return note;
93
+ const head = note.slice(0, note.indexOf('Value:'));
94
+ if (chain === 'aleph') {
95
+ const price =
96
+ "the USD price per credit (the last purchase on or before the day, else Aleph's list price of 1 USD per 1,000,000 credits)";
97
+ return `${head}Value in ${currency}: ${price}${currency === 'USD' ? '' : `, ${conversionText(currency, 'en')}`}.`;
98
+ }
99
+ return `${head}Value in ${currency}: USDFC is pegged to the US dollar and valued at the rate of USDC of the day, ${conversionText(currency, 'en')}.`;
100
+ }
73
101
  const note = USAGE_NOTES[chain];
74
102
  if (currency === 'EUR') return note;
75
103
  const head = note.slice(0, note.indexOf('Euro-Wert:'));
@@ -96,10 +124,25 @@ export function valuedBy(rows) {
96
124
  };
97
125
  }
98
126
 
127
+ /**
128
+ * The contract of a token not in the chain's list (EVM, #93): lower case, '' for
129
+ * the native coin, a listed token and anything else.
130
+ *
131
+ * @param {{ listed?: boolean, contract?: string }} e
132
+ */
133
+ const unlistedContract = (e) =>
134
+ e.listed === false && /^0x[0-9a-fA-F]{40}$/.test(e.contract ?? '')
135
+ ? /** @type {string} */ (e.contract).toLowerCase()
136
+ : '';
137
+
99
138
  export const STATEMENT_NOTE =
100
139
  'Kontoauszug eines Blockchain-Kontos, erstellt vom Kontoinhaber aus öffentlichen Chain-Daten. ' +
101
140
  'Kein Dokument eines Kreditinstituts. Jede Buchung ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
102
141
 
142
+ export const STATEMENT_NOTE_EN =
143
+ 'Kontoauszug (account statement) of a blockchain account, made by the account holder from public chain data. ' +
144
+ 'No document of a bank. Every booking can be checked by its transaction hash in a public block explorer.';
145
+
103
146
  /**
104
147
  * @typedef {object} StatementRow
105
148
  * @property {string} date YYYY-MM-DD
@@ -134,8 +177,11 @@ export const STATEMENT_NOTE =
134
177
  * credits bought, transfers in and out, fees. One booking each instead of the day's rows below.
135
178
  *
136
179
  * @param {StatementRow[]} rows
180
+ * @param {import('./language.js').DocumentLanguage} [language]
137
181
  */
138
- export function monthly(rows) {
182
+ export function monthly(rows, language = 'de') {
183
+ /** @param {string} de @param {string} en */
184
+ const t = (de, en) => say(language, de, en);
139
185
  /** @param {StatementRow[]} rs @param {string} label @param {'debit' | 'credit'} side @returns {MonthlyLine} */
140
186
  const line = (rs, label, side) => ({
141
187
  label,
@@ -147,7 +193,7 @@ export function monthly(rows) {
147
193
  const byResource = [...new Set(rows.filter((r) => r.usage).map((r) => r.label))].map((label) =>
148
194
  line(
149
195
  rows.filter((r) => r.usage && r.label === label),
150
- `Verbrauch ${label.replace(/^Aleph Cloud \((.*)\)$/, '$1').replace(/^storage$/, 'Speicher (storage)')}`,
196
+ `${t('Verbrauch', 'Usage')} ${label.replace(/^Aleph Cloud \((.*)\)$/, '$1').replace(/^storage$/, t('Speicher (storage)', 'storage'))}`,
151
197
  'debit'
152
198
  )
153
199
  );
@@ -158,17 +204,32 @@ export function monthly(rows) {
158
204
  const fees = rows.filter((r) => r.fee);
159
205
  return {
160
206
  usage: byResource,
161
- usageTotal: usage.length ? line(usage, 'Verbrauch gesamt (Aufwand)', 'debit') : null,
207
+ usageTotal: usage.length
208
+ ? line(usage, t('Verbrauch gesamt (Aufwand)', 'Usage in all (expense)'), 'debit')
209
+ : null,
162
210
  purchases: purchases.length
163
- ? line(purchases, 'Käufe von Guthaben (Vorauszahlung; Eigenbeleg je Kauf)', 'credit')
211
+ ? line(
212
+ purchases,
213
+ t(
214
+ 'Käufe von Guthaben (Vorauszahlung; Eigenbeleg je Kauf)',
215
+ 'Purchases of credits (prepayment; an Eigenbeleg per purchase)'
216
+ ),
217
+ 'credit'
218
+ )
164
219
  : null,
165
220
  transfersIn: transfersIn.length
166
- ? line(transfersIn, 'Eingänge von anderen Konten', 'credit')
221
+ ? line(
222
+ transfersIn,
223
+ t('Eingänge von anderen Konten', 'Incoming from other accounts'),
224
+ 'credit'
225
+ )
167
226
  : null,
168
227
  transfersOut: transfersOut.length
169
- ? line(transfersOut, 'Ausgänge an andere Konten', 'debit')
228
+ ? line(transfersOut, t('Ausgänge an andere Konten', 'Outgoing to other accounts'), 'debit')
170
229
  : null,
171
- fees: fees.length ? line(fees, 'Netzwerkgebühren (Aufwand)', 'debit') : null
230
+ fees: fees.length
231
+ ? line(fees, t('Netzwerkgebühren (Aufwand)', 'Network fees (expense)'), 'debit')
232
+ : null
172
233
  };
173
234
  }
174
235
 
@@ -190,6 +251,10 @@ export function monthly(rows) {
190
251
  * @param {string} [p.dataSource] where the entries were read from, when not the chain's usual source
191
252
  * @param {string} [p.currency] the statement's currency (DOCUMENT_CURRENCIES), EUR when not
192
253
  * given; the entries are valued in it, and the fields named `eur…` hold values in it
254
+ * @param {Record<string, string>} [p.contracts] asset → contract of a token not in the
255
+ * chain's list whose balance is in `opening`/`closing` (the reader's balances, #93);
256
+ * for one that moved in the period its entries name it already
257
+ * @param {import('./language.js').DocumentLanguage} [p.language] `de` (the default) or `en` (language.js)
193
258
  */
194
259
  export function buildStatement({
195
260
  payer,
@@ -206,9 +271,12 @@ export function buildStatement({
206
271
  number,
207
272
  issuedAt,
208
273
  dataSource,
209
- currency: asked
274
+ currency: asked,
275
+ contracts = {},
276
+ language: askedLanguage
210
277
  }) {
211
278
  const currency = documentCurrency(asked);
279
+ const L = documentLanguage(askedLanguage);
212
280
  checkValued(entries, currency);
213
281
  // An Aleph credit purchase (kind `swap`) is the payment on another chain; the
214
282
  // credits it bought are the incoming row. Only that row belongs on the statement.
@@ -216,10 +284,17 @@ export function buildStatement({
216
284
  (e) => e.account === account && !(e.chain === 'aleph' && e.kind === 'swap')
217
285
  );
218
286
  const own = mine.filter((e) => e.success !== false);
287
+ // A token not in the list (#93) has no priceAs, but its contract: it gets a section too.
219
288
  const assets = [
220
- ...new Set([...Object.keys(opening), ...own.filter((e) => e.priceAs).map((e) => e.asset)])
289
+ ...new Set([
290
+ ...Object.keys(opening),
291
+ ...own.filter((e) => e.priceAs || unlistedContract(e)).map((e) => e.asset)
292
+ ])
221
293
  ];
222
294
  const sections = assets.map((asset) => {
295
+ const contract =
296
+ unlistedContract(own.find((e) => e.asset === asset && unlistedContract(e)) ?? {}) ||
297
+ unlistedContract({ listed: false, contract: contracts[asset] });
223
298
  let balance = normalize(opening[asset] ?? '0');
224
299
  /** @type {StatementRow[]} */
225
300
  const rows = [];
@@ -230,9 +305,9 @@ export function buildStatement({
230
305
  date: e.date,
231
306
  time: e.time.slice(11, 19),
232
307
  // Filecoin Pay: up to when a settlement paid its rail (the entry's memo).
233
- text: `${kindText(e)}${e.type === 'received' ? ' (Eingang)' : ''}${e.chain === 'filecoin-pay' && e.kind === 'usage' && e.memo ? `, ${e.memo}` : ''}`,
308
+ text: `${kindText(e, L)}${e.type === 'received' ? say(L, ' (Eingang)', ' (incoming)') : ''}${e.chain === 'filecoin-pay' && e.kind === 'usage' && e.memo ? `, ${localizeLabel(e.memo, L)}` : ''}`,
234
309
  counterparty: e.counterpartyLabel
235
- ? `${e.counterpartyLabel} · ${e.counterparty}`
310
+ ? `${localizeLabel(e.counterpartyLabel, L)} · ${e.counterparty}`
236
311
  : e.counterparty,
237
312
  hash: e.hash,
238
313
  explorerUrl: e.explorerUrl,
@@ -247,7 +322,8 @@ export function buildStatement({
247
322
  purchase: e.type === 'received' && e.counterparty === 'aleph',
248
323
  label: e.counterpartyLabel,
249
324
  // Aleph's usage names a resource; a Filecoin Pay settlement is a transaction.
250
- hashLabel: e.kind === 'usage' && e.chain === 'aleph' ? 'Ressource' : 'Tx'
325
+ hashLabel:
326
+ e.kind === 'usage' && e.chain === 'aleph' ? say(L, 'Ressource', 'Resource') : 'Tx'
251
327
  });
252
328
  }
253
329
  const debit = sum(rows.map((r) => r.debit || '0'));
@@ -255,6 +331,8 @@ export function buildStatement({
255
331
  const reported = closing[asset];
256
332
  return {
257
333
  asset,
334
+ // A token not in the list: its contract, which names it; the symbol is the token's own claim.
335
+ contract,
258
336
  opening: normalize(opening[asset] ?? '0'),
259
337
  closing: balance,
260
338
  reported: reported === undefined ? null : normalize(reported),
@@ -265,20 +343,34 @@ export function buildStatement({
265
343
  debit,
266
344
  credit,
267
345
  rows,
268
- monthly: monthly(rows),
346
+ monthly: monthly(rows, L),
269
347
  eurOut: sum(rows.filter((r) => r.debit && r.eur).map((r) => r.eur.replace(/^-/, ''))),
270
348
  eurIn: sum(rows.filter((r) => r.credit && r.eur).map((r) => r.eur)),
271
349
  eurFees: sum(rows.filter((r) => r.fee && r.eur).map((r) => r.eur.replace(/^-/, ''))),
272
350
  eurUsage: sum(rows.filter((r) => r.usage && r.eur).map((r) => r.eur.replace(/^-/, ''))),
273
351
  unvalued: rows.filter((r) => !r.eur).length,
274
- ...valuedBy(rows)
352
+ ...valuedBy(rows),
353
+ // A token not in the list: each source of its values by name, without its day – no
354
+ // market rate of the usual feeds (CoinGecko by contract, a DEX pool, a reference value).
355
+ ...(contract
356
+ ? {
357
+ sources: [
358
+ ...new Set(rows.filter((r) => r.eur).map((r) => sourceName(r.rateSource ?? '')))
359
+ ]
360
+ }
361
+ : {})
275
362
  };
276
363
  });
277
364
  // Aleph credits, Filecoin Pay: a monthly usage statement, laid out as the Kontoauszug.
278
365
  const usage = Object.hasOwn(USAGE_NOTES, chain);
279
366
  return {
280
367
  kind: 'kontoauszug',
281
- title: usage ? 'Verbrauchsauszug' : 'Kontoauszug',
368
+ // The German name stays the document's name; an English one adds what it is.
369
+ title: usage
370
+ ? say(L, 'Verbrauchsauszug', 'Usage statement (Verbrauchsauszug)')
371
+ : say(L, 'Kontoauszug', 'Account statement (Kontoauszug)'),
372
+ usage,
373
+ language: L,
282
374
  number: number || `KA-${period.from}`,
283
375
  issuedAt: issuedAt ?? new Date().toISOString(),
284
376
  holder: { name: payer.name.trim(), address: payer.address.trim() },
@@ -288,7 +380,8 @@ export function buildStatement({
288
380
  dataSource: dataSourceOf(
289
381
  chain,
290
382
  CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
291
- dataSource
383
+ dataSource,
384
+ L
292
385
  ),
293
386
  network,
294
387
  testnet: network !== 'mainnet',
@@ -298,7 +391,7 @@ export function buildStatement({
298
391
  at,
299
392
  sections,
300
393
  unlisted: mine.filter((e) => !e.priceAs && !assets.includes(e.asset)).length,
301
- note: usage ? usageNote(chain, currency) : STATEMENT_NOTE
394
+ note: usage ? usageNote(chain, currency, L) : L === 'en' ? STATEMENT_NOTE_EN : STATEMENT_NOTE
302
395
  };
303
396
  }
304
397
 
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
  }