@le-space/chains 0.0.0-stage → 0.2.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/aleph.js ADDED
@@ -0,0 +1,448 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Aleph Cloud, read only: what an account's credits did in one month – the
3
+ // source of the monthly consumption statement (issue #113). No key, no
4
+ // signing, no transfer or forget: only the public API that the official
5
+ // client (aleph-im/aleph-rs, `aleph credit history|summary`) reads too.
6
+ //
7
+ // GET /api/v0/addresses/<a>/balance `credit_balance` now
8
+ // GET /api/v0/addresses/<a>/credit_history one row per entry, newest
9
+ // ?page=&pagination=&startDate=&endDate= first; filters in Unix
10
+ // seconds, inclusive
11
+ // GET /api/v0/addresses/<a>/credit_history/summary net, in and out of a window
12
+ //
13
+ // A row with a positive amount brings credits in: a purchase (with its
14
+ // per-credit `price` in USD, token, chain and transaction hash) or a transfer
15
+ // from another account. A negative one takes them out: `credit_expense` is
16
+ // consumption, billed about hourly per kind of resource (`origin_ref`:
17
+ // `storage`, `execution`, …) with the number of resources and their size;
18
+ // anything else is a transfer out. Storage is billed as one line for all
19
+ // stores (`origin_ref: storage`, with their number and size); compute per
20
+ // resource: `origin` is the instance's or program's item hash, `origin_ref`
21
+ // the billing message. The statement lists consumption per day, storage in
22
+ // one line and each instance in its own, named from its message
23
+ // (`/api/v0/messages/<hash>`, `content.metadata.name`).
24
+ //
25
+ // Opening and closing balance: the balance now, less what came and went
26
+ // since the month began or ended (the summary endpoint), so they are exact
27
+ // and need no history before the month.
28
+ //
29
+ // Euro value (a choice for the tax adviser, documented on the statement):
30
+ // credits are priced in USD; a day's consumption is valued at the per-credit
31
+ // price of the last purchase on or before that day, or Aleph's list price of
32
+ // 1 USD per 1,000,000 credits when the account never bought any (credits
33
+ // moved in from another account), then converted at that day's ECB
34
+ // reference rate – the rule is @le-space/rates' (aleph-credits.js).
35
+ //
36
+ // Aleph is no blockchain: the credits live in Aleph's own network, keyed by
37
+ // the account's Ethereum address. `alephEntries` gives a statement's lines as
38
+ // @le-space/ledger entries (`chain: 'aleph'`): purchases and transfers in,
39
+ // transfers out, and a day's consumption per resource as `usage`. The ALEPH
40
+ // token itself is an ERC-20 on Ethereum and Base, read by the EVM reader.
41
+ //
42
+ // In a browser: Aleph's API answers with CORS headers for the origins that
43
+ // read it (checked 2026-11-06 for eigenbelege.le-space.de), so no proxy.
44
+ //
45
+ // Aleph keys accounts by their EIP-55 checksummed address: asked in lower
46
+ // case, it answers a balance of 0 and no history. Every address is
47
+ // checksummed before it is asked about.
48
+ //
49
+ // Times are UTC; the month is the UTC month. The log gets counts, never an
50
+ // address.
51
+
52
+ import { entry, sortEntries } from '@le-space/ledger';
53
+ import {
54
+ ALEPH_LIST_PRICE_USD,
55
+ alephCreditPrice,
56
+ alephCreditsInEur,
57
+ plain
58
+ } from '@le-space/rates/aleph-credits';
59
+ import { createJsonFetcher, WalletError } from './http.js';
60
+ import { toChecksumAddress } from './evm.js';
61
+
62
+ export const ALEPH_API = 'https://api2.aleph.im';
63
+ /** Aleph's list price, USD per credit (@le-space/rates). */
64
+ export const LIST_PRICE_USD = ALEPH_LIST_PRICE_USD;
65
+ /** Where an Aleph message (an instance, a program, a purchase) can be looked at. */
66
+ export const ALEPH_EXPLORER = 'https://explorer.aleph.cloud/address/ETH/';
67
+ const PER_PAGE = 100;
68
+
69
+ /** @param {unknown} v */
70
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : Number(v ?? NaN));
71
+
72
+ /**
73
+ * `YYYY-MM` → its first and last second, Unix, UTC.
74
+ *
75
+ * @param {string} month
76
+ */
77
+ export function monthWindow(month) {
78
+ const m = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(month);
79
+ if (!m) throw new WalletError('month must be YYYY-MM', 'ALEPH_MONTH', 400);
80
+ const start = Date.UTC(Number(m[1]), Number(m[2]) - 1, 1) / 1000;
81
+ const next = Date.UTC(Number(m[1]), Number(m[2]), 1) / 1000;
82
+ return { start, end: next - 1, next };
83
+ }
84
+
85
+ /**
86
+ * @typedef {object} TopUp
87
+ * @property {string} time ISO
88
+ * @property {number} credits
89
+ * @property {number} bonus credits given on top
90
+ * @property {'purchase' | 'transfer'} how
91
+ * @property {string | null} price USD per credit, a purchase's
92
+ * @property {string | null} token
93
+ * @property {string | null} chain
94
+ * @property {string | null} txHash the paying transaction
95
+ * @property {string} from for a transfer, the account it came from ('' when not said)
96
+ */
97
+
98
+ /**
99
+ * @typedef {object} UsageLine one day's consumption of one kind of resource
100
+ * @property {string} date YYYY-MM-DD (UTC)
101
+ * @property {string} kind `storage`, or `execution` for a billed instance or program
102
+ * @property {string | null} resource the instance's item hash, for `execution`
103
+ * @property {number} credits
104
+ * @property {number} entries how many billing entries (about one an hour)
105
+ * @property {number} resources the most resources billed at once that day
106
+ * @property {number | null} sizeMib the largest size billed that day
107
+ * @property {string} usdPerCredit
108
+ * @property {'purchase' | 'list'} priceSource
109
+ * @property {string | null} eurPerUsd the ECB rate of the day
110
+ * @property {number | null} eurCents
111
+ */
112
+
113
+ /**
114
+ * The rows of one month → the statement's lines. Pure.
115
+ *
116
+ * @param {object} p
117
+ * @param {any[]} p.rows credit_history rows of the month
118
+ * @param {any[]} p.purchases every incoming row with a price, any time
119
+ */
120
+ export function summarise({ rows, purchases }) {
121
+ /** @type {TopUp[]} */
122
+ const topUps = [];
123
+ /** @type {{ time: string, credits: number, to: string }[]} */
124
+ const transfersOut = [];
125
+ /** @type {Map<string, UsageLine>} */
126
+ const days = new Map();
127
+ const priceOn = alephCreditPrice(
128
+ purchases.map((p) => ({ time: String(p?.message_timestamp), price: p?.price }))
129
+ );
130
+
131
+ for (const r of rows) {
132
+ const amount = num(r?.amount);
133
+ const time = new Date(String(r?.message_timestamp)).toISOString();
134
+ if (!Number.isFinite(amount) || amount === 0) continue;
135
+ if (amount > 0) {
136
+ const purchase = Boolean(r.price || r.tx_hash);
137
+ topUps.push({
138
+ time,
139
+ credits: amount,
140
+ bonus: num(r.bonus_amount) || 0,
141
+ how: purchase ? 'purchase' : 'transfer',
142
+ price: r.price ? String(r.price) : null,
143
+ token: r.token ? String(r.token) : null,
144
+ chain: r.chain ? String(r.chain) : null,
145
+ txHash: r.tx_hash ? String(r.tx_hash) : null,
146
+ from: purchase ? '' : String(r.origin ?? '')
147
+ });
148
+ continue;
149
+ }
150
+ if (r.payment_method !== 'credit_expense') {
151
+ transfersOut.push({ time, credits: -amount, to: String(r.origin ?? '') });
152
+ continue;
153
+ }
154
+ const date = time.slice(0, 10);
155
+ const resource = /^[0-9a-f]{64}$/.test(String(r.origin ?? '')) ? String(r.origin) : null;
156
+ const kind = resource ? 'execution' : String(r.origin_ref || 'other');
157
+ const key = `${date} ${kind} ${resource ?? ''}`;
158
+ const size = num(r.expense_size_mib);
159
+ const line = days.get(key) ?? {
160
+ date,
161
+ kind,
162
+ resource,
163
+ credits: 0,
164
+ entries: 0,
165
+ resources: 0,
166
+ sizeMib: null,
167
+ usdPerCredit: priceOn(date).usdPerCredit,
168
+ priceSource: priceOn(date).source,
169
+ eurPerUsd: null,
170
+ eurCents: null
171
+ };
172
+ line.credits += -amount;
173
+ line.entries += 1;
174
+ line.resources = Math.max(line.resources, num(r.expense_count) || 0);
175
+ if (Number.isFinite(size)) line.sizeMib = Math.max(line.sizeMib ?? 0, size);
176
+ days.set(key, line);
177
+ }
178
+ const usage = [...days.values()].sort(
179
+ (a, b) =>
180
+ a.date.localeCompare(b.date) ||
181
+ a.kind.localeCompare(b.kind) ||
182
+ String(a.resource).localeCompare(String(b.resource))
183
+ );
184
+ topUps.sort((a, b) => a.time.localeCompare(b.time));
185
+ transfersOut.sort((a, b) => a.time.localeCompare(b.time));
186
+ return { topUps, transfersOut, usage };
187
+ }
188
+
189
+ /**
190
+ * @param {object} [options]
191
+ * @param {typeof fetch} [options.fetch]
192
+ * @param {number} [options.timeoutMs]
193
+ * @param {(ms: number) => Promise<void>} [options.sleep]
194
+ * @param {number} [options.maxPages]
195
+ * @param {{ rate: (asset: string, date: string) => Promise<{ rate: string, source: string }> } | null} [options.rates]
196
+ * @param {() => Date} [options.now]
197
+ */
198
+ export function createAlephClient({
199
+ fetch: f = fetch,
200
+ timeoutMs = 30_000,
201
+ sleep,
202
+ maxPages = 200,
203
+ rates = null,
204
+ now = () => new Date()
205
+ } = {}) {
206
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep });
207
+
208
+ return {
209
+ /**
210
+ * Which of these addresses are Aleph accounts: each one's credits now and
211
+ * how many credit entries it ever had. Read only; one balance and one
212
+ * summary request per address.
213
+ *
214
+ * @param {object} p
215
+ * @param {string[]} p.addresses 0x…, at most 50
216
+ * @param {string} [p.api] checked by the caller
217
+ */
218
+ async accounts({ addresses, api = ALEPH_API }) {
219
+ const unique = [...new Set(addresses.map((a) => String(a).toLowerCase()))];
220
+ if (unique.length > 50) throw new WalletError('at most 50 addresses', 'ALEPH_TOO_MANY', 400);
221
+ /** @type {{ address: string, credits: number, entries: number }[]} */
222
+ const out = [];
223
+ for (const lower of unique) {
224
+ if (!/^0x[0-9a-f]{40}$/.test(lower)) {
225
+ throw new WalletError('not an Aleph account address (0x + 40 hex)', 'ALEPH_ADDRESS', 400);
226
+ }
227
+ const address = toChecksumAddress(lower);
228
+ const base = `${api}/api/v0/addresses/${address}`;
229
+ const balance = await getJson(`${base}/balance`).catch((/** @type {any} */ e) => {
230
+ // An address Aleph has never seen: 404, nothing there.
231
+ if (e?.httpStatus === 404) return { credit_balance: 0 };
232
+ throw e;
233
+ });
234
+ const summary = await getJson(`${base}/credit_history/summary`);
235
+ out.push({
236
+ address,
237
+ credits: num(balance?.credit_balance) || 0,
238
+ entries: num(summary?.entry_count) || 0
239
+ });
240
+ }
241
+ return out;
242
+ },
243
+
244
+ /**
245
+ * @param {object} p
246
+ * @param {string} p.address 0x…
247
+ * @param {string} p.month YYYY-MM
248
+ * @param {string} [p.api] checked by the caller
249
+ */
250
+ async statement({ address: given, month, api = ALEPH_API }) {
251
+ if (!/^0x[0-9a-fA-F]{40}$/.test(given)) {
252
+ throw new WalletError('not an Aleph account address (0x + 40 hex)', 'ALEPH_ADDRESS', 400);
253
+ }
254
+ const address = toChecksumAddress(given);
255
+ const { start, end, next } = monthWindow(month);
256
+ const nowSeconds = Math.floor(now().getTime() / 1000);
257
+ if (start > nowSeconds) throw new WalletError('that month has not begun', 'ALEPH_MONTH', 400);
258
+ const base = `${api}/api/v0/addresses/${address}`;
259
+
260
+ const balance = await getJson(`${base}/balance`);
261
+ const current = num(balance?.credit_balance);
262
+ if (!Number.isFinite(current)) {
263
+ throw new WalletError('Aleph answered the balance without credits', 'ALEPH_DATA');
264
+ }
265
+ /** What came and went from a moment on. @param {number} from */
266
+ const netSince = async (from) => {
267
+ if (from > nowSeconds) return 0;
268
+ const s = await getJson(`${base}/credit_history/summary?startDate=${from}`);
269
+ const net = num(s?.total_amount);
270
+ if (!Number.isFinite(net)) {
271
+ throw new WalletError('Aleph answered the summary without a total', 'ALEPH_DATA');
272
+ }
273
+ return net;
274
+ };
275
+ const opening = current - (await netSince(start));
276
+ const closing = current - (await netSince(next));
277
+
278
+ /** @param {string} query */
279
+ const pages = async (query) => {
280
+ /** @type {any[]} */
281
+ const rows = [];
282
+ for (let page = 1; ; page++) {
283
+ if (page > maxPages) {
284
+ throw new WalletError(
285
+ `more than ${maxPages * PER_PAGE} credit entries; not read`,
286
+ 'ALEPH_TOO_MANY'
287
+ );
288
+ }
289
+ const body = await getJson(
290
+ `${base}/credit_history?page=${page}&pagination=${PER_PAGE}${query}`
291
+ );
292
+ const batch = Array.isArray(body?.credit_history) ? body.credit_history : null;
293
+ if (!batch) throw new WalletError('Aleph answered without a history', 'ALEPH_DATA');
294
+ rows.push(...batch);
295
+ if (!batch.length || page * PER_PAGE >= num(body.pagination_total)) break;
296
+ }
297
+ return rows;
298
+ };
299
+ const rows = await pages(`&startDate=${start}&endDate=${end}`);
300
+ // Prices of every purchase up to the month's end, to value its consumption.
301
+ const purchases = (await pages(`&endDate=${end}&direction=incoming`)).filter((r) => r?.price);
302
+ const { topUps, transfersOut, usage } = summarise({ rows, purchases });
303
+
304
+ // What each billed resource is: its type and the name it was given.
305
+ /** @type {Record<string, { type: string, name: string }>} */
306
+ const resources = {};
307
+ for (const hash of new Set(usage.map((u) => u.resource).filter((h) => h !== null))) {
308
+ if (Object.keys(resources).length >= 50) break;
309
+ const body = await getJson(`${api}/api/v0/messages/${hash}`).catch(() => null);
310
+ const message = body?.message ?? body;
311
+ resources[/** @type {string} */ (hash)] = {
312
+ type: String(message?.type ?? ''),
313
+ name: String(message?.content?.metadata?.name ?? '').slice(0, 80)
314
+ };
315
+ }
316
+
317
+ /** @type {Map<string, string | null>} */
318
+ const eurPerUsd = new Map();
319
+ let rateSource = null;
320
+ if (rates) {
321
+ for (const line of usage) {
322
+ if (!eurPerUsd.has(line.date)) {
323
+ const r = await rates.rate('USD', line.date).catch(() => null);
324
+ eurPerUsd.set(line.date, r?.rate ?? null);
325
+ rateSource ??= r?.source ?? null;
326
+ }
327
+ const rate = eurPerUsd.get(line.date) ?? null;
328
+ line.eurPerUsd = rate;
329
+ line.eurCents =
330
+ rate === null
331
+ ? null
332
+ : Math.round(Number(alephCreditsInEur(line.credits, line.usdPerCredit, rate)) * 100);
333
+ }
334
+ }
335
+
336
+ const sum = (/** @type {number[]} */ xs) => xs.reduce((a, b) => a + b, 0);
337
+ const totals = {
338
+ topUps: sum(topUps.map((t) => t.credits)),
339
+ transfersOut: sum(transfersOut.map((t) => t.credits)),
340
+ usage: sum(usage.map((u) => u.credits)),
341
+ eurCents: usage.every((u) => u.eurCents !== null)
342
+ ? sum(usage.map((u) => /** @type {number} */ (u.eurCents)))
343
+ : null
344
+ };
345
+ return {
346
+ address,
347
+ month,
348
+ from: new Date(start * 1000).toISOString(),
349
+ until: new Date(end * 1000).toISOString(),
350
+ opening,
351
+ closing,
352
+ topUps,
353
+ transfersOut,
354
+ usage,
355
+ resources,
356
+ totals,
357
+ // opening + in − out = closing; a difference means entries the history did not list
358
+ difference: opening + totals.topUps - totals.usage - totals.transfersOut - closing,
359
+ rateSource,
360
+ entries: rows.length
361
+ };
362
+ }
363
+ };
364
+ }
365
+
366
+ /** A credit amount as a decimal string. @param {number} credits */
367
+ const credits = (credits) => plain(credits);
368
+
369
+ /**
370
+ * A statement's lines as ledger entries, seen from the account: purchases and
371
+ * transfers in (`received`), transfers out (`sent`), and each day's
372
+ * consumption per resource (`sent`, kind `usage`, with the USD price per
373
+ * credit it is valued at). Asset `ALEPH-CREDIT`, no market price.
374
+ *
375
+ * @param {Awaited<ReturnType<ReturnType<typeof createAlephClient>['statement']>>} statement
376
+ * @returns {import('@le-space/ledger').LedgerEntry[]}
377
+ */
378
+ export function alephEntries(statement) {
379
+ const { address, topUps, transfersOut, usage, resources } = statement;
380
+ const common = {
381
+ chain: 'aleph',
382
+ network: 'mainnet',
383
+ account: address,
384
+ height: 0,
385
+ asset: 'ALEPH-CREDIT',
386
+ contract: 'native',
387
+ decimals: 0,
388
+ method: '',
389
+ memo: '',
390
+ success: true,
391
+ priceAs: ''
392
+ };
393
+ const explorerUrl = `${ALEPH_EXPLORER}${address}`;
394
+ const out = [
395
+ ...topUps.map((t, i) =>
396
+ entry({
397
+ ...common,
398
+ id: `aleph:${address}:in:${t.time}:${i}`,
399
+ hash: t.txHash ?? '',
400
+ time: t.time,
401
+ type: 'received',
402
+ kind: 'transfer',
403
+ amount: credits(t.credits),
404
+ counterparty: t.how === 'purchase' ? 'aleph' : t.from,
405
+ counterpartyLabel:
406
+ t.how === 'purchase'
407
+ ? `Aleph Cloud (Kauf${t.token ? ` mit ${t.token}` : ''}${t.chain ? ` auf ${t.chain}` : ''})`
408
+ : '',
409
+ explorerUrl,
410
+ ...(t.price
411
+ ? { unitPrice: { currency: 'USD', amount: plain(t.price), source: 'purchase' } }
412
+ : {})
413
+ })
414
+ ),
415
+ ...transfersOut.map((t, i) =>
416
+ entry({
417
+ ...common,
418
+ id: `aleph:${address}:out:${t.time}:${i}`,
419
+ hash: '',
420
+ time: t.time,
421
+ type: 'sent',
422
+ kind: 'transfer',
423
+ amount: `-${credits(t.credits)}`,
424
+ counterparty: t.to,
425
+ counterpartyLabel: '',
426
+ explorerUrl
427
+ })
428
+ ),
429
+ ...usage.map((u) => {
430
+ const what = u.resource ? resources?.[u.resource] : null;
431
+ return entry({
432
+ ...common,
433
+ id: `aleph:${address}:usage:${u.date}:${u.kind}:${u.resource ?? ''}`,
434
+ hash: u.resource ?? '',
435
+ time: `${u.date}T00:00:00Z`,
436
+ type: 'sent',
437
+ kind: 'usage',
438
+ amount: `-${credits(u.credits)}`,
439
+ counterparty: 'aleph',
440
+ counterpartyLabel: `Aleph Cloud (${what?.name || u.kind})`,
441
+ memo: `${u.entries} Abrechnungen`,
442
+ explorerUrl,
443
+ unitPrice: { currency: 'USD', amount: u.usdPerCredit, source: u.priceSource }
444
+ });
445
+ })
446
+ ];
447
+ return sortEntries(out);
448
+ }
package/src/bech32.js ADDED
@@ -0,0 +1,126 @@
1
+ // Bech32 (BIP-173), the address format of Cosmos chains: `n1…` on Nyx,
2
+ // `cosmos1…` on the Hub. Only what a read-only wallet needs: check an
3
+ // address against the chain's prefix, and derive a module account's address
4
+ // (the fee collector, the staking pools) to name it in a booking.
5
+ //
6
+ // Cosmos addresses are bech32, not bech32m, and their data part is 20 bytes
7
+ // (an account) or 32 bytes (a contract or a derived account).
8
+
9
+ import { sha256 } from '@noble/hashes/sha2.js';
10
+ import { utf8 } from '@le-space/ledger/bytes';
11
+
12
+ const CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
13
+ const GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
14
+
15
+ /** @param {number[]} values */
16
+ function polymod(values) {
17
+ let chk = 1;
18
+ for (const v of values) {
19
+ const top = chk >>> 25;
20
+ chk = ((chk & 0x1ffffff) << 5) ^ v;
21
+ for (let i = 0; i < 5; i++) if ((top >>> i) & 1) chk ^= GENERATOR[i];
22
+ }
23
+ return chk >>> 0;
24
+ }
25
+
26
+ /** @param {string} hrp */
27
+ function expand(hrp) {
28
+ const codes = [...hrp].map((c) => c.charCodeAt(0));
29
+ return [...codes.map((c) => c >> 5), 0, ...codes.map((c) => c & 31)];
30
+ }
31
+
32
+ /**
33
+ * @param {number[]} data
34
+ * @param {number} from
35
+ * @param {number} to
36
+ * @param {boolean} pad
37
+ * @returns {number[] | null}
38
+ */
39
+ function convertBits(data, from, to, pad) {
40
+ let acc = 0;
41
+ let bits = 0;
42
+ /** @type {number[]} */
43
+ const out = [];
44
+ const max = (1 << to) - 1;
45
+ for (const value of data) {
46
+ if (value < 0 || value >> from) return null;
47
+ acc = (acc << from) | value;
48
+ bits += from;
49
+ while (bits >= to) {
50
+ bits -= to;
51
+ out.push((acc >> bits) & max);
52
+ }
53
+ }
54
+ if (pad) {
55
+ if (bits > 0) out.push((acc << (to - bits)) & max);
56
+ } else if (bits >= from || (acc << (to - bits)) & max) {
57
+ return null;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * @param {string} hrp
64
+ * @param {Uint8Array | number[]} bytes
65
+ */
66
+ export function bech32Encode(hrp, bytes) {
67
+ const data = /** @type {number[]} */ (convertBits([...bytes], 8, 5, true));
68
+ const mod = polymod([...expand(hrp), ...data, 0, 0, 0, 0, 0, 0]) ^ 1;
69
+ const checksum = [0, 1, 2, 3, 4, 5].map((i) => (mod >>> (5 * (5 - i))) & 31);
70
+ return `${hrp}1${[...data, ...checksum].map((d) => CHARSET[d]).join('')}`;
71
+ }
72
+
73
+ /**
74
+ * `n1…` → its prefix and bytes; null when it is no valid bech32 string
75
+ * (mixed case, a wrong checksum, a character outside the charset).
76
+ *
77
+ * @param {string} text
78
+ * @returns {{ hrp: string, bytes: Uint8Array } | null}
79
+ */
80
+ export function bech32Decode(text) {
81
+ if (typeof text !== 'string' || text.length < 8 || text.length > 90) return null;
82
+ if (text !== text.toLowerCase() && text !== text.toUpperCase()) return null;
83
+ const s = text.toLowerCase();
84
+ const sep = s.lastIndexOf('1');
85
+ if (sep < 1 || sep + 7 > s.length) return null;
86
+ const hrp = s.slice(0, sep);
87
+ if (![...hrp].every((c) => c.charCodeAt(0) >= 33 && c.charCodeAt(0) <= 126)) return null;
88
+ /** @type {number[]} */
89
+ const data = [];
90
+ for (const c of s.slice(sep + 1)) {
91
+ const d = CHARSET.indexOf(c);
92
+ if (d === -1) return null;
93
+ data.push(d);
94
+ }
95
+ if (polymod([...expand(hrp), ...data]) !== 1) return null;
96
+ const bytes = convertBits(data.slice(0, -6), 5, 8, false);
97
+ return bytes ? { hrp, bytes: Uint8Array.from(bytes) } : null;
98
+ }
99
+
100
+ /**
101
+ * Whether `address` is an account or contract address on a chain with
102
+ * `prefix`: valid bech32, that prefix, 20 or 32 bytes.
103
+ *
104
+ * @param {string} address
105
+ * @param {string} prefix
106
+ */
107
+ export function isCosmosAddress(address, prefix) {
108
+ const decoded = bech32Decode(address);
109
+ return Boolean(
110
+ decoded &&
111
+ decoded.hrp === prefix &&
112
+ (decoded.bytes.length === 20 || decoded.bytes.length === 32) &&
113
+ address === address.toLowerCase()
114
+ );
115
+ }
116
+
117
+ /**
118
+ * A module account's address: the first 20 bytes of SHA-256 of its name
119
+ * (cosmos-sdk `authtypes.NewModuleAddress`).
120
+ *
121
+ * @param {string} prefix
122
+ * @param {string} name `fee_collector`, `distribution`, `bonded_tokens_pool`, …
123
+ */
124
+ export function moduleAddress(prefix, name) {
125
+ return bech32Encode(prefix, sha256(utf8(name)).subarray(0, 20));
126
+ }