@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.
@@ -0,0 +1,145 @@
1
+ // An Akash wallet's deployments and what they cost (issue #305, step 2): for
2
+ // the monthly usage statement in the app.
3
+ //
4
+ // Deployments are paid in ACT (Akash's compute credit, minted from AKT by
5
+ // burn-mint, ~1 USD) through an escrow account per deployment. The node
6
+ // keeps every deployment of an owner, closed ones too, with its escrow state:
7
+ // GET <rest>/akash/deployment/v1beta4/deployments/list?filters.owner=<a>
8
+ // deployment.created_at the block it was created in
9
+ // escrow_account.state transferred (paid to the providers so far),
10
+ // funds (left), settled_at (the last settlement;
11
+ // for a closed one, its end)
12
+ // Amounts are decimal coins in uact. The blocks' times come from the Akash
13
+ // Console indexer (`/v1/blocks/<height>`), as the node is pruned. With them,
14
+ // the wallet's ACT held now (`/cosmos/bank/v1beta1/balances/<a>`, uact), for
15
+ // the ACT account (step 3): what was minted is what is held, in escrow and
16
+ // used up.
17
+ //
18
+ // What a deployment cost in a month is not kept per month on chain: the app
19
+ // spreads its transferred amount evenly over its time from creation to the
20
+ // last settlement, and says so on the statement.
21
+ //
22
+ // The log gets counts, never an address.
23
+
24
+ import { createJsonFetcher, WalletError } from './core.js';
25
+ import { unitsToDecimal } from './cosmos.js';
26
+
27
+ const LIMIT = 1000;
28
+
29
+ /**
30
+ * `49.000000000000000000` (uact, a decimal coin) → 49n, rounded half up.
31
+ *
32
+ * @param {unknown} amount
33
+ */
34
+ export function decUnits(amount) {
35
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(String(amount ?? '').trim());
36
+ if (!m) return 0n;
37
+ return BigInt(m[1]) + ((m[2] ?? '0')[0] >= '5' ? 1n : 0n);
38
+ }
39
+
40
+ /** @param {any} coins @param {string} denom */
41
+ const sumOf = (coins, denom) =>
42
+ (Array.isArray(coins) ? coins : [])
43
+ .filter((c) => c?.denom === denom)
44
+ .reduce((n, c) => n + decUnits(c?.amount), 0n);
45
+
46
+ /**
47
+ * @typedef {object} AkashDeployment
48
+ * @property {string} dseq
49
+ * @property {string} state active | closed
50
+ * @property {number} createdHeight
51
+ * @property {string | null} createdAt ISO, from the indexer
52
+ * @property {number} settledHeight
53
+ * @property {string | null} settledAt ISO, from the indexer
54
+ * @property {string} transferred ACT paid to the providers, decimal
55
+ * @property {string} funds ACT left in the escrow, decimal
56
+ */
57
+
58
+ /**
59
+ * @param {object} [options]
60
+ * @param {typeof fetch} [options.fetch]
61
+ * @param {number} [options.timeoutMs]
62
+ * @param {(ms: number) => Promise<void>} [options.sleep]
63
+ */
64
+ export function createAkashDeploymentsClient({ fetch: f = fetch, timeoutMs, sleep } = {}) {
65
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep });
66
+ /** @type {Map<string, string | null>} `<indexer>@<height>` → ISO time */
67
+ const times = new Map();
68
+
69
+ /** @param {string} indexer @param {number} height */
70
+ async function timeOf(indexer, height) {
71
+ const key = `${indexer}@${height}`;
72
+ if (times.has(key)) return times.get(key) ?? null;
73
+ const block = await getJson(`${indexer}/v1/blocks/${height}`).catch(() => null);
74
+ const ms = Date.parse(String(block?.datetime ?? ''));
75
+ const iso = Number.isNaN(ms) ? null : new Date(ms).toISOString();
76
+ // Only an answer is kept: an indexer that did not answer this time is
77
+ // asked again next time, not remembered as silent for the bridge's life.
78
+ if (iso) times.set(key, iso);
79
+ return iso;
80
+ }
81
+
82
+ return {
83
+ /**
84
+ * The wallet's ACT held now, decimal.
85
+ *
86
+ * @param {{ address: string, rest: string }} p checked by the caller
87
+ */
88
+ async actBalance({ address, rest }) {
89
+ const body = await getJson(
90
+ `${rest}/cosmos/bank/v1beta1/balances/${encodeURIComponent(address)}?pagination.limit=200`
91
+ );
92
+ if (!Array.isArray(body?.balances)) {
93
+ throw new WalletError('the node answered without balances', 'WALLET_DATA');
94
+ }
95
+ const uact = body.balances.find((/** @type {any} */ b) => b?.denom === 'uact');
96
+ return unitsToDecimal(decUnits(uact?.amount ?? '0'), 6);
97
+ },
98
+
99
+ /**
100
+ * @param {{ address: string, rest: string, indexer: string }} p checked by the caller
101
+ * @returns {Promise<AkashDeployment[]>}
102
+ */
103
+ async deployments({ address, rest, indexer }) {
104
+ /** @type {any[]} */
105
+ const raw = [];
106
+ let key = '';
107
+ for (let page = 0; page < 50; page++) {
108
+ const q = new URLSearchParams({
109
+ 'filters.owner': address,
110
+ 'pagination.limit': String(LIMIT),
111
+ ...(key ? { 'pagination.key': key } : {})
112
+ });
113
+ const body = await getJson(`${rest}/akash/deployment/v1beta4/deployments/list?${q}`);
114
+ if (!Array.isArray(body?.deployments)) {
115
+ throw new WalletError('the node answered without deployments', 'WALLET_DATA');
116
+ }
117
+ raw.push(...body.deployments);
118
+ key = String(body?.pagination?.next_key ?? '');
119
+ if (!key) break;
120
+ }
121
+ /** @type {AkashDeployment[]} */
122
+ const out = [];
123
+ for (const d of raw) {
124
+ const dseq = String(d?.deployment?.id?.dseq ?? '');
125
+ const createdHeight = Number(d?.deployment?.created_at);
126
+ const state = d?.escrow_account?.state ?? {};
127
+ const settledHeight = Number(state.settled_at);
128
+ if (!/^\d+$/.test(dseq) || !Number.isSafeInteger(createdHeight)) continue;
129
+ out.push({
130
+ dseq,
131
+ state: String(d?.deployment?.state ?? ''),
132
+ createdHeight,
133
+ createdAt: await timeOf(indexer, createdHeight),
134
+ settledHeight: Number.isSafeInteger(settledHeight) ? settledHeight : createdHeight,
135
+ settledAt: Number.isSafeInteger(settledHeight)
136
+ ? await timeOf(indexer, settledHeight)
137
+ : null,
138
+ transferred: unitsToDecimal(sumOf(state.transferred, 'uact'), 6),
139
+ funds: unitsToDecimal(sumOf(state.funds, 'uact'), 6)
140
+ });
141
+ }
142
+ return out.sort((a, b) => a.createdHeight - b.createdHeight);
143
+ }
144
+ };
145
+ }