@odatano/core 2.0.0-rc.49 → 2.0.0-rc.50
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/@cds-models/CardanoAgentService/index.d.ts +6 -12
- package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
- package/@cds-models/CardanoIndexerService/index.js +24 -0
- package/@cds-models/CardanoODataService/index.d.ts +49 -6
- package/@cds-models/CardanoODataService/index.js +4 -0
- package/@cds-models/CardanoSignService/index.d.ts +3 -3
- package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
- package/@cds-models/index.d.ts +9 -1
- package/@cds-models/index.js +2 -1
- package/@cds-models/odatano/cardano/index.d.ts +59 -5
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/README.md +29 -17
- package/db/schema.cds +117 -24
- package/db/types.cds +8 -0
- package/package.json +17 -15
- package/scripts/migrate-schema.mjs +334 -0
- package/src/index.d.ts +7 -5
- package/src/index.js +12 -10
- package/src/plugin.js +6 -7
- package/srv/blockchain/backends/blockfrost-backend.js +9 -1
- package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
- package/srv/blockchain/backends/cardano-backend.js +5 -0
- package/srv/blockchain/backends/koios-backend.js +16 -10
- package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
- package/srv/blockchain/backends/ogmios-backend.js +60 -18
- package/srv/blockchain/cardano-client.d.ts +5 -4
- package/srv/blockchain/cardano-client.js +46 -13
- package/srv/blockchain/cardano-indexer.d.ts +116 -9
- package/srv/blockchain/cardano-indexer.js +436 -189
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
- package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
- package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/certificate-backfill.js +10 -3
- package/srv/blockchain/crawler/crawler.d.ts +15 -0
- package/srv/blockchain/crawler/crawler.js +68 -3
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/transaction-backfill.js +12 -8
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
- package/srv/blockchain/signing/cose-verifier.js +144 -56
- package/srv/blockchain/signing/hsm-signer.js +2 -1
- package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
- package/srv/blockchain/signing/submission-finalizer.js +201 -69
- package/srv/blockchain/stored-chain.js +1 -1
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
- package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.js +1 -1
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
- package/srv/blockchain/wallet-worker/build-request.js +25 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
- package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
- package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
- package/srv/cardano-agent-service.cds +11 -12
- package/srv/cardano-agent-service.js +2 -0
- package/srv/cardano-backend-service.cds +34 -1
- package/srv/cardano-backend-service.js +20 -17
- package/srv/cardano-indexer-service.cds +153 -12
- package/srv/cardano-indexer-service.js +175 -29
- package/srv/cardano-service.cds +67 -3
- package/srv/cardano-service.js +132 -67
- package/srv/cardano-sign-service.cds +30 -20
- package/srv/cardano-sign-service.js +13 -10
- package/srv/cardano-tx-service.cds +15 -1
- package/srv/cardano-tx-service.js +4 -1
- package/srv/cardano-worker-service.cds +16 -7
- package/srv/cardano-worker-service.js +31 -22
- package/srv/cbor/parse.js +11 -34
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +9 -14
- package/srv/server.js +32 -316
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -17
- package/srv/utils/agent-grants-config.js +6 -81
- package/srv/utils/agent-grants.d.ts +6 -19
- package/srv/utils/agent-grants.js +69 -130
- package/srv/utils/const.d.ts +4 -0
- package/srv/utils/const.js +5 -1
- package/srv/utils/db-indexes.js +11 -3
- package/srv/utils/error-codes.d.ts +4 -0
- package/srv/utils/error-codes.js +4 -0
- package/srv/utils/errors.d.ts +6 -0
- package/srv/utils/errors.js +23 -1
- package/srv/utils/liveness.js +2 -5
- package/srv/utils/mappers.d.ts +5 -7
- package/srv/utils/mappers.js +22 -9
- package/srv/utils/pg-order-nulls.js +4 -3
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/tx-request-parsers.d.ts +1 -1
- package/srv/utils/tx-request-parsers.js +3 -3
- package/srv/utils/tx-utils.d.ts +3 -0
- package/srv/utils/tx-utils.js +17 -3
- package/srv/utils/types.d.ts +16 -3
- package/scripts/migrate-txseq.mjs +0 -138
- package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
- package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
- package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
- package/srv/blockchain/transaction-building/caller-datums.js +0 -133
- package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
- package/srv/cbor/redeemer-tag-patch.js +0 -61
- package/srv/utils/legacy-service-paths.d.ts +0 -11
- package/srv/utils/legacy-service-paths.js +0 -58
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Applies the schema changes the additive schema deploy refuses: a changed key, a changed column
|
|
3
|
+
// type, a dropped column, a renamed table. Every step runs only where it is still due.
|
|
4
|
+
// Run with ODATANO stopped, before the schema deploy. --dry-run only reports.
|
|
5
|
+
import cds from '@sap/cds';
|
|
6
|
+
|
|
7
|
+
const T = (name) => `odatano_cardano_${name}`;
|
|
8
|
+
const E = (name) => `odatano.cardano.${name}`;
|
|
9
|
+
const TX_SEQ_SLOT_FACTOR = 65536;
|
|
10
|
+
/** Column type the schema deploy creates for a timestamp, per database. */
|
|
11
|
+
const TIMESTAMP = { postgres: 'TIMESTAMP', sqlite: 'TIMESTAMP_TEXT' };
|
|
12
|
+
|
|
13
|
+
/** Column names of a table with their declared types, both lower-cased. Empty when the table is missing. */
|
|
14
|
+
export async function columnsOf(db, table) {
|
|
15
|
+
const rows = db.kind === 'postgres'
|
|
16
|
+
? await db.run(`SELECT column_name AS name, data_type AS type FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '${table.toLowerCase()}'`)
|
|
17
|
+
: await db.run(`SELECT name, type FROM pragma_table_info('${table}')`);
|
|
18
|
+
return new Map(rows.map(r => [String(r.name).toLowerCase(), String(r.type).toLowerCase()]));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 'table', 'view' or null for a name in the current schema. */
|
|
22
|
+
export async function relationKind(db, name) {
|
|
23
|
+
const rows = db.kind === 'postgres'
|
|
24
|
+
? await db.run(`SELECT CASE c.relkind WHEN 'v' THEN 'view' ELSE 'table' END AS kind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
25
|
+
WHERE n.nspname = current_schema() AND c.relkind IN ('r', 'p', 'v') AND c.relname = '${name.toLowerCase()}'`)
|
|
26
|
+
: await db.run(`SELECT type AS kind FROM sqlite_schema WHERE type IN ('table', 'view') AND lower(name) = '${name.toLowerCase()}'`);
|
|
27
|
+
return rows[0]?.kind ?? null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** True for a declared type that holds a time as plain text. */
|
|
31
|
+
export function isTextType(type) {
|
|
32
|
+
return /char|text|string/.test(type) && !type.includes('timestamp');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Counts the blocks whose time is not a UTC timestamp in ISO 8601 form. */
|
|
36
|
+
export function unparsableSql(kind) {
|
|
37
|
+
const pattern = kind === 'postgres'
|
|
38
|
+
? `time !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?Z$'`
|
|
39
|
+
: `time NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]*Z'`;
|
|
40
|
+
return `SELECT count(*) AS n FROM ${T('Blocks')} WHERE time IS NOT NULL AND ${pattern}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** CREATE TABLE statement of a SQLite table under a new name, with `time` declared as a timestamp. */
|
|
44
|
+
export function rebuiltTableSql(createSql, table, newName) {
|
|
45
|
+
const retyped = createSql.replace(/(\btime\s+)N?VARCHAR\s*\(\s*\d+\s*\)/i, `$1${TIMESTAMP.sqlite}`);
|
|
46
|
+
if (retyped === createSql) throw new Error(`${table}: no text column time in its table definition`);
|
|
47
|
+
return retyped.replace(new RegExp(`^(\\s*CREATE TABLE\\s+)"?${table}"?`, 'i'), `$1${newName}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Tables that moved from the transaction hash to Transactions.txSeq as their key.
|
|
51
|
+
// `to` is the entity that holds the rows in the model of this version.
|
|
52
|
+
const TX_SEQ_TABLES = [
|
|
53
|
+
{ from: 'TransactionInputs', to: 'TransactionInputs', hashKey: 'tx_hash', seqKey: 'txSeq', order: 'inputIndex' },
|
|
54
|
+
{ from: 'TransactionOutputs', to: 'TransactionOutputs', hashKey: 'tx_hash', seqKey: 'txSeq', order: 'outputIndex' },
|
|
55
|
+
{ from: 'TransactionInputAssets', to: 'TransactionInputAssetCopies', hashKey: 'input_tx_hash', seqKey: 'input_txSeq', order: 'input_inputIndex, unit' },
|
|
56
|
+
{ from: 'TransactionOutputAssets', to: 'TransactionOutputAssets', hashKey: 'output_tx_hash', seqKey: 'output_txSeq', order: 'output_outputIndex, unit' },
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/** Copy statement: the given columns of the old table, the new key from Transactions. */
|
|
60
|
+
export function copySql(spec, columns, target) {
|
|
61
|
+
const others = columns.filter(c => c !== spec.hashKey.toLowerCase());
|
|
62
|
+
const into = [spec.seqKey, ...others].join(', ');
|
|
63
|
+
const source = ['t.txSeq', ...others.map(c => `x.${c}`)].join(', ');
|
|
64
|
+
const order = ['t.txSeq', ...spec.order.split(',').map(c => `x.${c.trim()}`)].join(', ');
|
|
65
|
+
return `INSERT INTO ${target} (${into}) SELECT ${source} FROM ${T(spec.from)} x `
|
|
66
|
+
+ `JOIN ${T('Transactions')} t ON t.hash = x.${spec.hashKey} ORDER BY ${order}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function count(tx, table) {
|
|
70
|
+
const [row] = await tx.run(`SELECT count(*) AS n FROM ${table}`);
|
|
71
|
+
return Number(row.n);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The steps, oldest first. `due` says whether the database still needs the step (`pending` names the
|
|
75
|
+
// earlier steps that are due), `apply` changes the database, `model` makes the stored model say the same.
|
|
76
|
+
export const STEPS = [
|
|
77
|
+
{
|
|
78
|
+
name: 'transaction inputs and outputs keyed by txSeq',
|
|
79
|
+
async due(db) {
|
|
80
|
+
if (!(await columnsOf(db, T('TransactionInputs'))).has('tx_hash')) return false;
|
|
81
|
+
const open = Number((await db.run(`SELECT count(*) AS n FROM ${T('Transactions')} WHERE slot IS NULL OR txIndex IS NULL`))[0].n);
|
|
82
|
+
if (open > 0) throw new Error(`${open} transactions have no slot or txIndex; their txSeq cannot be derived`);
|
|
83
|
+
return true;
|
|
84
|
+
},
|
|
85
|
+
async apply(tx, { ddl, log }) {
|
|
86
|
+
if (!(await columnsOf(tx, T('Transactions'))).has('txseq')) await tx.run(`ALTER TABLE ${T('Transactions')} ADD COLUMN txSeq BIGINT`);
|
|
87
|
+
await tx.run(`UPDATE ${T('Transactions')} SET txSeq = slot * ${TX_SEQ_SLOT_FACTOR} + txIndex`);
|
|
88
|
+
await tx.run(`CREATE INDEX IF NOT EXISTS odatano_cardano_transactions_txseq ON ${T('Transactions')} (txSeq)`);
|
|
89
|
+
|
|
90
|
+
for (const spec of TX_SEQ_TABLES) {
|
|
91
|
+
const from = T(spec.from);
|
|
92
|
+
const to = T(spec.to);
|
|
93
|
+
const rebuilt = `${to}_txseq_new`;
|
|
94
|
+
const rows = await count(tx, from);
|
|
95
|
+
await tx.run(ddl(spec.to).replace(new RegExp(`^(\\s*CREATE TABLE )${to}\\b`, 'i'), `$1${rebuilt}`));
|
|
96
|
+
// only columns both layouts have: a column this version dropped stays behind
|
|
97
|
+
const kept = new Set((await columnsOf(tx, rebuilt)).keys());
|
|
98
|
+
const columns = [...(await columnsOf(tx, from)).keys()].filter(c => c === spec.hashKey.toLowerCase() || kept.has(c));
|
|
99
|
+
await tx.run(copySql(spec, columns, rebuilt));
|
|
100
|
+
const copied = await count(tx, rebuilt);
|
|
101
|
+
if (copied !== rows) throw new Error(`${from}: ${rows} rows, ${copied} copied (rows without a Transactions row?)`);
|
|
102
|
+
await tx.run(`DROP TABLE ${from}`);
|
|
103
|
+
await tx.run(`ALTER TABLE ${rebuilt} RENAME TO ${to}`);
|
|
104
|
+
if (tx.kind === 'postgres') {
|
|
105
|
+
await tx.run(`ALTER TABLE ${to} RENAME CONSTRAINT ${rebuilt.toLowerCase()}_pkey TO ${to.toLowerCase()}_pkey`);
|
|
106
|
+
}
|
|
107
|
+
log(`${to}: ${copied} rows`);
|
|
108
|
+
}
|
|
109
|
+
// fresh planner statistics: without them the rebuilt tables are read by sequential scans
|
|
110
|
+
for (const name of ['Transactions', ...TX_SEQ_TABLES.map(t => t.to)]) await tx.run(`ANALYZE ${T(name)}`);
|
|
111
|
+
},
|
|
112
|
+
model(definitions, image) {
|
|
113
|
+
delete definitions[E('TransactionInputAssets')];
|
|
114
|
+
for (const spec of TX_SEQ_TABLES) definitions[E(spec.to)] = image[E(spec.to)];
|
|
115
|
+
const transactions = definitions[E('Transactions')];
|
|
116
|
+
if (transactions?.elements) transactions.elements.txSeq = image[E('Transactions')].elements.txSeq;
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: 'Blocks.time: text -> timestamp',
|
|
121
|
+
async due(db) {
|
|
122
|
+
const type = (await columnsOf(db, T('Blocks'))).get('time');
|
|
123
|
+
if (type === undefined || !isTextType(type)) return false;
|
|
124
|
+
const unparsable = Number((await db.run(unparsableSql(db.kind)))[0].n);
|
|
125
|
+
if (unparsable > 0) throw new Error(`${unparsable} blocks hold a time that is no ISO 8601 UTC timestamp`);
|
|
126
|
+
return `${await count(db, T('Blocks'))} rows`;
|
|
127
|
+
},
|
|
128
|
+
async apply(tx) {
|
|
129
|
+
const table = T('Blocks');
|
|
130
|
+
if (tx.kind === 'postgres') {
|
|
131
|
+
await tx.run(`ALTER TABLE ${table} ALTER COLUMN time TYPE ${TIMESTAMP.postgres} USING (time::timestamptz AT TIME ZONE 'UTC')`);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// SQLite cannot change a column's type: the table is rebuilt with the same rows
|
|
135
|
+
const rebuilt = `${table}_time_new`;
|
|
136
|
+
const rows = await count(tx, table);
|
|
137
|
+
const [stored] = await tx.run(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = '${table}'`);
|
|
138
|
+
await tx.run(rebuiltTableSql(stored.sql, table, rebuilt));
|
|
139
|
+
await tx.run(`INSERT INTO ${rebuilt} SELECT * FROM ${table}`);
|
|
140
|
+
const copied = await count(tx, rebuilt);
|
|
141
|
+
if (copied !== rows) throw new Error(`${table}: ${rows} rows, ${copied} copied`);
|
|
142
|
+
await tx.run(`DROP TABLE ${table}`);
|
|
143
|
+
await tx.run(`ALTER TABLE ${rebuilt} RENAME TO ${table}`);
|
|
144
|
+
},
|
|
145
|
+
model(definitions, image) {
|
|
146
|
+
const stored = definitions[E('Blocks')];
|
|
147
|
+
if (stored?.elements?.time) stored.elements.time = image[E('Blocks')].elements.time;
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
name: 'CardanoAgentGrants: columns walletId and allowedJobKinds removed',
|
|
152
|
+
async due(db) {
|
|
153
|
+
const columns = await columnsOf(db, T('CardanoAgentGrants'));
|
|
154
|
+
return columns.has('walletid') || columns.has('allowedjobkinds');
|
|
155
|
+
},
|
|
156
|
+
async apply(tx) {
|
|
157
|
+
const columns = await columnsOf(tx, T('CardanoAgentGrants'));
|
|
158
|
+
for (const column of ['walletId', 'allowedJobKinds']) {
|
|
159
|
+
if (columns.has(column.toLowerCase())) await tx.run(`ALTER TABLE ${T('CardanoAgentGrants')} DROP COLUMN ${column}`);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
model(definitions) {
|
|
163
|
+
const elements = definitions[E('CardanoAgentGrants')]?.elements ?? {};
|
|
164
|
+
delete elements.walletId;
|
|
165
|
+
delete elements.allowedJobKinds;
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
name: 'TransactionInputAssets: table renamed to TransactionInputAssetCopies',
|
|
170
|
+
async due(db, pending) {
|
|
171
|
+
// the txSeq step builds the table under its new name already
|
|
172
|
+
if (pending.includes(STEPS[0].name)) return false;
|
|
173
|
+
if (await relationKind(db, T('TransactionInputAssets')) !== 'table') return false;
|
|
174
|
+
if (await relationKind(db, T('TransactionInputAssetCopies'))) {
|
|
175
|
+
throw new Error(`${T('TransactionInputAssets')} and ${T('TransactionInputAssetCopies')} both exist as tables`);
|
|
176
|
+
}
|
|
177
|
+
return true;
|
|
178
|
+
},
|
|
179
|
+
async apply(tx) {
|
|
180
|
+
const from = T('TransactionInputAssets');
|
|
181
|
+
const to = T('TransactionInputAssetCopies');
|
|
182
|
+
await tx.run(`ALTER TABLE ${from} RENAME TO ${to}`);
|
|
183
|
+
if (tx.kind !== 'postgres') return;
|
|
184
|
+
const [key] = await tx.run(`SELECT 1 AS x FROM pg_constraint WHERE conname = '${from.toLowerCase()}_pkey' AND connamespace = current_schema()::regnamespace`);
|
|
185
|
+
if (key) await tx.run(`ALTER TABLE ${to} RENAME CONSTRAINT ${from.toLowerCase()}_pkey TO ${to.toLowerCase()}_pkey`);
|
|
186
|
+
},
|
|
187
|
+
model(definitions, image) {
|
|
188
|
+
delete definitions[E('TransactionInputAssets')];
|
|
189
|
+
definitions[E('TransactionInputAssetCopies')] = image[E('TransactionInputAssetCopies')];
|
|
190
|
+
// the deploy adds the association to the view again; it has no column
|
|
191
|
+
delete definitions[E('TransactionInputs')]?.elements?.assets;
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
];
|
|
195
|
+
|
|
196
|
+
/** Names of all views of the schema, the ones created last first. */
|
|
197
|
+
async function viewNames(db) {
|
|
198
|
+
const rows = db.kind === 'postgres'
|
|
199
|
+
? await db.run(`SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
200
|
+
WHERE c.relkind = 'v' AND n.nspname = current_schema() ORDER BY c.oid DESC`)
|
|
201
|
+
: await db.run(`SELECT name FROM sqlite_schema WHERE type = 'view' ORDER BY rowid DESC`);
|
|
202
|
+
return rows.map(r => r.name);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function hasModelTable(db) {
|
|
206
|
+
const [found] = await db.run(db.kind === 'postgres'
|
|
207
|
+
? `SELECT 1 AS x FROM pg_tables WHERE tablename = 'cds_model' AND schemaname = current_schema()`
|
|
208
|
+
: `SELECT 1 AS x FROM sqlite_schema WHERE name = 'cds_model'`);
|
|
209
|
+
return Boolean(found);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The model of this version as the schema deploy stores it, and the CREATE TABLE statement of an entity. */
|
|
213
|
+
async function modelOfThisVersion(db) {
|
|
214
|
+
const model = await cds.load('*').then(cds.minify);
|
|
215
|
+
cds.deploy.exclude_external_entities_in(model);
|
|
216
|
+
const options = { ...db.options };
|
|
217
|
+
const statements = cds.compile.to.sql(model, options);
|
|
218
|
+
const ddl = (name) => {
|
|
219
|
+
const found = statements.find(s => new RegExp(`^CREATE TABLE ${T(name)} \\(`, 'i').test(s.trim()));
|
|
220
|
+
if (!found) throw new Error(`the model has no table ${T(name)}`);
|
|
221
|
+
return found;
|
|
222
|
+
};
|
|
223
|
+
return { image: cds.compile.to.sql.delta(model, options).afterImage, ddl };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const isView = (def) => Boolean(def.query || def.projection);
|
|
227
|
+
|
|
228
|
+
// The model of this version cut down to what the database holds: its tables and their columns,
|
|
229
|
+
// no views. The schema deploy then adds exactly what is missing.
|
|
230
|
+
export async function modelOfDatabase(db, image) {
|
|
231
|
+
const definitions = {};
|
|
232
|
+
for (const [name, def] of Object.entries(image.definitions)) {
|
|
233
|
+
if (def.kind !== 'entity') { definitions[name] = def; continue; }
|
|
234
|
+
if (isView(def)) continue;
|
|
235
|
+
const columns = await columnsOf(db, name.replace(/\./g, '_'));
|
|
236
|
+
if (!columns.size) continue;
|
|
237
|
+
const elements = Object.fromEntries(Object.entries(def.elements ?? {}).filter(([, element]) => {
|
|
238
|
+
const column = element['@cds.persistence.name'];
|
|
239
|
+
return column === undefined || columns.has(String(column).toLowerCase());
|
|
240
|
+
}));
|
|
241
|
+
definitions[name] = { ...def, elements };
|
|
242
|
+
}
|
|
243
|
+
return { ...image, definitions };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Waits for the first connection, which can take longer than the pool waits for one. */
|
|
247
|
+
async function connected(db) {
|
|
248
|
+
for (let attempt = 1; ; attempt++) {
|
|
249
|
+
try {
|
|
250
|
+
return await db.run('SELECT 1 AS x');
|
|
251
|
+
} catch (err) {
|
|
252
|
+
if (attempt === 15) throw err;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The steps the database still needs, with what `due` reported for each. */
|
|
258
|
+
async function dueSteps(db) {
|
|
259
|
+
const due = [];
|
|
260
|
+
for (const step of STEPS) {
|
|
261
|
+
const detail = await step.due(db, due.map(d => d.step.name));
|
|
262
|
+
if (detail) due.push({ step, detail });
|
|
263
|
+
}
|
|
264
|
+
return due;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Brings an existing database to the point where the additive schema deploy can take over, and
|
|
268
|
+
// returns the names of the steps it ran. A database without a stored model gets one here.
|
|
269
|
+
// Whenever it changes something the views are gone afterwards; the deploy creates them.
|
|
270
|
+
export async function migrateSchema(db, { dryRun = false, log = console.log } = {}) {
|
|
271
|
+
if (db.kind !== 'postgres' && db.kind !== 'sqlite') return [];
|
|
272
|
+
await connected(db);
|
|
273
|
+
|
|
274
|
+
const due = await dueSteps(db);
|
|
275
|
+
const stored = await hasModelTable(db);
|
|
276
|
+
// a database that holds none of our tables is new: the deploy creates it
|
|
277
|
+
const adopt = !stored && (await columnsOf(db, T('Blocks'))).size > 0;
|
|
278
|
+
if (!due.length && !adopt) return [];
|
|
279
|
+
|
|
280
|
+
const [lease] = await db.run(`SELECT leaseUntil FROM ${T('CardanoSyncState')}`).catch(() => []);
|
|
281
|
+
const leaseUntil = lease?.leaseUntil ?? lease?.leaseuntil;
|
|
282
|
+
if (leaseUntil && Date.parse(leaseUntil) > Date.now()) {
|
|
283
|
+
throw new Error(`the crawler lease is held until ${leaseUntil}: stop ODATANO first`);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
for (const { step, detail } of due) log(`due: ${step.name}${detail === true ? '' : ` (${detail})`}`);
|
|
287
|
+
if (adopt) log('due: the database has no stored model (cds_model), it is written from its tables');
|
|
288
|
+
const names = due.map(d => d.step.name);
|
|
289
|
+
if (dryRun) { log('dry run: nothing changed'); return names; }
|
|
290
|
+
|
|
291
|
+
const { image, ddl } = await modelOfThisVersion(db);
|
|
292
|
+
const views = await viewNames(db);
|
|
293
|
+
await db.tx(async (tx) => {
|
|
294
|
+
const started = Date.now();
|
|
295
|
+
const done = (msg) => log(`[${Math.round((Date.now() - started) / 1000)}s] ${msg}`);
|
|
296
|
+
|
|
297
|
+
for (const name of views) await tx.run(`DROP VIEW IF EXISTS "${name}"${db.kind === 'postgres' ? ' CASCADE' : ''}`);
|
|
298
|
+
done(`${views.length} views dropped`);
|
|
299
|
+
|
|
300
|
+
const model = stored ? JSON.parse((await tx.run('SELECT csn FROM cds_model'))[0].csn) : null;
|
|
301
|
+
for (const { step } of due) {
|
|
302
|
+
await step.apply(tx, { ddl, log: done });
|
|
303
|
+
if (model) step.model(model.definitions, image.definitions);
|
|
304
|
+
done(step.name);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (model) {
|
|
308
|
+
// the stored model lists no view any more, so the deploy creates every view of this version
|
|
309
|
+
for (const [name, def] of Object.entries(model.definitions)) {
|
|
310
|
+
if (isView(def)) delete model.definitions[name];
|
|
311
|
+
}
|
|
312
|
+
await tx.run(db.kind === 'postgres' ? 'UPDATE cds_model SET csn = $1' : 'UPDATE cds_model SET csn = ?', [JSON.stringify(model)]);
|
|
313
|
+
} else {
|
|
314
|
+
const csn = JSON.stringify(await modelOfDatabase(tx, image));
|
|
315
|
+
await tx.run(`CREATE TABLE cds_model (csn ${db.kind === 'postgres' ? 'TEXT' : 'CLOB'})`);
|
|
316
|
+
await tx.run(db.kind === 'postgres' ? 'INSERT INTO cds_model VALUES ($1)' : 'INSERT INTO cds_model VALUES (?)', [csn]);
|
|
317
|
+
}
|
|
318
|
+
done(`cds_model ${model ? 'updated' : 'written'}`);
|
|
319
|
+
});
|
|
320
|
+
return adopt ? [...names, 'stored model written'] : names;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function main() {
|
|
324
|
+
const db = await cds.connect.to('db');
|
|
325
|
+
if (db.kind !== 'postgres' && db.kind !== 'sqlite') throw new Error(`unsupported database kind ${db.kind}`);
|
|
326
|
+
const dryRun = process.argv.includes('--dry-run');
|
|
327
|
+
const ran = await migrateSchema(db, { dryRun });
|
|
328
|
+
if (!ran.length) console.log('The schema needs no migration.');
|
|
329
|
+
else if (!dryRun) console.log('Migrated. Deploy the schema now; it creates the views again.');
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (process.argv[1] && import.meta.url === (await import('node:url')).pathToFileURL(process.argv[1]).href) {
|
|
333
|
+
main().then(() => process.exit(0), (err) => { console.error(`FAILED: ${err.message}`); process.exit(1); });
|
|
334
|
+
}
|
package/src/index.d.ts
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import type { TransactionConfirmations } from '../srv/utils/types';
|
|
2
2
|
export { CardanoClient } from '../srv/blockchain/cardano-client';
|
|
3
|
-
export type { CardanoClientConfig, Network, BackendName
|
|
3
|
+
export type { CardanoClientConfig, Network, BackendName } from '../srv/blockchain/cardano-client';
|
|
4
4
|
export { CardanoIndexer } from '../srv/blockchain/cardano-indexer';
|
|
5
5
|
export { CardanoTransactionBuilder } from '../srv/blockchain/cardano-tx-builder';
|
|
6
|
-
export { getAppContext, getCardanoIndexer, getCardanoClient, getCardanoTxBuilder,
|
|
6
|
+
export { getAppContext, getCardanoIndexer, getCardanoClient, getCardanoTxBuilder, startCrawlerIfConfigured, startWalletWorkerIfConfigured, shutdownAppContext, } from '../srv/server';
|
|
7
|
+
export { loadConfigFromEnv, loadHsmConfigFromEnv, loadCrawlerConfigFromEnv, loadWalletWorkerConfigFromEnv, loadAgentGrantsConfig, } from '../srv/config';
|
|
8
|
+
export type { AgentGrantsConfig } from '../srv/config';
|
|
7
9
|
export { getHsmSigner } from '../srv/blockchain/signing/hsm-signer';
|
|
8
|
-
export { issueAgentGrant, updateAgentGrant, rotateAgentGrantToken, revokeAgentGrantById, getGrantUsage, resolveUsageWindow, hashAgentToken, AGENT_TOKEN_HEADER, AGENT_TOKEN_PREFIX, AGENT_ROLE,
|
|
10
|
+
export { issueAgentGrant, updateAgentGrant, rotateAgentGrantToken, revokeAgentGrantById, getGrantUsage, resolveUsageWindow, hashAgentToken, AGENT_TOKEN_HEADER, AGENT_TOKEN_PREFIX, AGENT_ROLE, } from '../srv/utils/agent-grants';
|
|
11
|
+
export { agentAccessOf, agentGrantableActions } from '../srv/utils/agent-access';
|
|
12
|
+
export type { AgentAccess } from '../srv/utils/agent-access';
|
|
9
13
|
export type { IssueAgentGrantInput, IssuedAgentGrant, AgentGrantStatus, UpdateAgentGrantInput, UpdateAgentGrantResult, RotatedAgentGrant, AgentGrantUsage, GrantUsageCall, UsageWindow, } from '../srv/utils/agent-grants';
|
|
10
14
|
export { registerTransportLane } from '@odatano/cap-auth';
|
|
11
15
|
export type { TransportLane, LaneOutcome } from '@odatano/cap-auth';
|
|
12
|
-
export { loadAgentGrantsConfig } from '../srv/utils/agent-grants-config';
|
|
13
|
-
export type { AgentGrantsConfig } from '../srv/utils/agent-grants-config';
|
|
14
16
|
export type { HsmConfig, HsmSignResult } from '../srv/utils/types';
|
|
15
17
|
export { parseTransaction } from '../srv/cbor';
|
|
16
18
|
export type { ParsedTransaction, ParsedInput, ParsedOutput, ParsedAsset, ParsedWitnesses, ParsedWithdrawal, ParsedCertificate, } from '../srv/cbor';
|
package/src/index.js
CHANGED
|
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
36
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.plutusScriptHash = exports.applyScriptParameters = exports.slotToPosixMs = exports.posixToSlot = exports.verifyTxWitnesses = exports.parseTransaction = exports.
|
|
39
|
+
exports.plutusScriptHash = exports.applyScriptParameters = exports.slotToPosixMs = exports.posixToSlot = exports.verifyTxWitnesses = exports.parseTransaction = exports.registerTransportLane = exports.agentGrantableActions = exports.agentAccessOf = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = exports.hashAgentToken = exports.resolveUsageWindow = exports.getGrantUsage = exports.revokeAgentGrantById = exports.rotateAgentGrantToken = exports.updateAgentGrant = exports.issueAgentGrant = exports.getHsmSigner = exports.loadAgentGrantsConfig = exports.loadWalletWorkerConfigFromEnv = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.startCrawlerIfConfigured = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
|
|
40
40
|
exports.initialize = initialize;
|
|
41
41
|
exports.shutdown = shutdown;
|
|
42
42
|
exports.getTransactionConfirmations = getTransactionConfirmations;
|
|
@@ -59,13 +59,15 @@ Object.defineProperty(exports, "getAppContext", { enumerable: true, get: functio
|
|
|
59
59
|
Object.defineProperty(exports, "getCardanoIndexer", { enumerable: true, get: function () { return server_1.getCardanoIndexer; } });
|
|
60
60
|
Object.defineProperty(exports, "getCardanoClient", { enumerable: true, get: function () { return server_1.getCardanoClient; } });
|
|
61
61
|
Object.defineProperty(exports, "getCardanoTxBuilder", { enumerable: true, get: function () { return server_1.getCardanoTxBuilder; } });
|
|
62
|
-
Object.defineProperty(exports, "loadConfigFromEnv", { enumerable: true, get: function () { return server_1.loadConfigFromEnv; } });
|
|
63
|
-
Object.defineProperty(exports, "loadHsmConfigFromEnv", { enumerable: true, get: function () { return server_1.loadHsmConfigFromEnv; } });
|
|
64
|
-
Object.defineProperty(exports, "loadCrawlerConfigFromEnv", { enumerable: true, get: function () { return server_1.loadCrawlerConfigFromEnv; } });
|
|
65
62
|
Object.defineProperty(exports, "startCrawlerIfConfigured", { enumerable: true, get: function () { return server_1.startCrawlerIfConfigured; } });
|
|
66
|
-
Object.defineProperty(exports, "loadWalletWorkerConfigFromEnv", { enumerable: true, get: function () { return server_1.loadWalletWorkerConfigFromEnv; } });
|
|
67
63
|
Object.defineProperty(exports, "startWalletWorkerIfConfigured", { enumerable: true, get: function () { return server_1.startWalletWorkerIfConfigured; } });
|
|
68
64
|
Object.defineProperty(exports, "shutdownAppContext", { enumerable: true, get: function () { return server_1.shutdownAppContext; } });
|
|
65
|
+
var config_1 = require("../srv/config");
|
|
66
|
+
Object.defineProperty(exports, "loadConfigFromEnv", { enumerable: true, get: function () { return config_1.loadConfigFromEnv; } });
|
|
67
|
+
Object.defineProperty(exports, "loadHsmConfigFromEnv", { enumerable: true, get: function () { return config_1.loadHsmConfigFromEnv; } });
|
|
68
|
+
Object.defineProperty(exports, "loadCrawlerConfigFromEnv", { enumerable: true, get: function () { return config_1.loadCrawlerConfigFromEnv; } });
|
|
69
|
+
Object.defineProperty(exports, "loadWalletWorkerConfigFromEnv", { enumerable: true, get: function () { return config_1.loadWalletWorkerConfigFromEnv; } });
|
|
70
|
+
Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return config_1.loadAgentGrantsConfig; } });
|
|
69
71
|
// Re-export HSM signer for programmatic access
|
|
70
72
|
var hsm_signer_1 = require("../srv/blockchain/signing/hsm-signer");
|
|
71
73
|
Object.defineProperty(exports, "getHsmSigner", { enumerable: true, get: function () { return hsm_signer_1.getHsmSigner; } });
|
|
@@ -81,12 +83,11 @@ Object.defineProperty(exports, "hashAgentToken", { enumerable: true, get: functi
|
|
|
81
83
|
Object.defineProperty(exports, "AGENT_TOKEN_HEADER", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_HEADER; } });
|
|
82
84
|
Object.defineProperty(exports, "AGENT_TOKEN_PREFIX", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_PREFIX; } });
|
|
83
85
|
Object.defineProperty(exports, "AGENT_ROLE", { enumerable: true, get: function () { return agent_grants_1.AGENT_ROLE; } });
|
|
84
|
-
|
|
85
|
-
Object.defineProperty(exports, "
|
|
86
|
+
var agent_access_1 = require("../srv/utils/agent-access");
|
|
87
|
+
Object.defineProperty(exports, "agentAccessOf", { enumerable: true, get: function () { return agent_access_1.agentAccessOf; } });
|
|
88
|
+
Object.defineProperty(exports, "agentGrantableActions", { enumerable: true, get: function () { return agent_access_1.agentGrantableActions; } });
|
|
86
89
|
var cap_auth_1 = require("@odatano/cap-auth");
|
|
87
90
|
Object.defineProperty(exports, "registerTransportLane", { enumerable: true, get: function () { return cap_auth_1.registerTransportLane; } });
|
|
88
|
-
var agent_grants_config_1 = require("../srv/utils/agent-grants-config");
|
|
89
|
-
Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_1.loadAgentGrantsConfig; } });
|
|
90
91
|
// Re-export pure CBOR utilities (no CAP round-trip needed)
|
|
91
92
|
var cbor_1 = require("../srv/cbor");
|
|
92
93
|
Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return cbor_1.parseTransaction; } });
|
|
@@ -102,7 +103,8 @@ Object.defineProperty(exports, "plutusScriptHash", { enumerable: true, get: func
|
|
|
102
103
|
// Reads config from cds.env.requires["odatano-core"] or env vars.
|
|
103
104
|
// Starts all blockchain components plus the optional crawler and wallet worker.
|
|
104
105
|
async function initialize() {
|
|
105
|
-
const {
|
|
106
|
+
const { initializeFromConfig, getAppContext } = await Promise.resolve().then(() => __importStar(require('../srv/server')));
|
|
107
|
+
const { loadConfigFromEnv, loadHsmConfigFromEnv } = await Promise.resolve().then(() => __importStar(require('../srv/config')));
|
|
106
108
|
let alreadyInitialized = false;
|
|
107
109
|
try {
|
|
108
110
|
getAppContext();
|
package/src/plugin.js
CHANGED
|
@@ -49,7 +49,7 @@ if (!cds_1.default.env.requires) {
|
|
|
49
49
|
if (!cds_1.default.env.requires.kinds) {
|
|
50
50
|
cds_1.default.env.requires.kinds = {};
|
|
51
51
|
}
|
|
52
|
-
/** The schema and the
|
|
52
|
+
/** The schema and the seven CDS services this package ships, package-qualified. */
|
|
53
53
|
const PLUGIN_MODEL = [
|
|
54
54
|
'@odatano/core/db/schema',
|
|
55
55
|
'@odatano/core/srv/cardano-service',
|
|
@@ -57,7 +57,8 @@ const PLUGIN_MODEL = [
|
|
|
57
57
|
'@odatano/core/srv/cardano-sign-service',
|
|
58
58
|
'@odatano/core/srv/cardano-indexer-service',
|
|
59
59
|
'@odatano/core/srv/cardano-worker-service',
|
|
60
|
-
'@odatano/core/srv/cardano-agent-service'
|
|
60
|
+
'@odatano/core/srv/cardano-agent-service',
|
|
61
|
+
'@odatano/core/srv/cardano-backend-service'
|
|
61
62
|
];
|
|
62
63
|
/** Relative `@impl` values used in the CDS files (rewritten in plugin mode, see below). */
|
|
63
64
|
const IMPL_PATHS = [
|
|
@@ -66,7 +67,8 @@ const IMPL_PATHS = [
|
|
|
66
67
|
'srv/cardano-sign-service',
|
|
67
68
|
'srv/cardano-indexer-service',
|
|
68
69
|
'srv/cardano-worker-service',
|
|
69
|
-
'srv/cardano-agent-service'
|
|
70
|
+
'srv/cardano-agent-service',
|
|
71
|
+
'srv/cardano-backend-service'
|
|
70
72
|
];
|
|
71
73
|
cds_1.default.env.requires.kinds['odatano-core'] = {
|
|
72
74
|
impl: '@odatano/core',
|
|
@@ -83,9 +85,6 @@ logger.debug('Plugin registered');
|
|
|
83
85
|
// Idempotent. server.ts repeats it for standalone mode.
|
|
84
86
|
require('../srv/utils/agent-grants-config')
|
|
85
87
|
.activateAgentGrants();
|
|
86
|
-
// The old path of the read service keeps answering until the 2.0.0 release.
|
|
87
|
-
require('../srv/utils/legacy-service-paths')
|
|
88
|
-
.registerLegacyServicePaths();
|
|
89
88
|
// In plugin mode relative @impl paths resolve from the consumer app.
|
|
90
89
|
// Rewrite them to package-qualified paths that Node can resolve.
|
|
91
90
|
cds_1.default.on('loaded', (model) => {
|
|
@@ -104,7 +103,7 @@ cds_1.default.on('served', async () => {
|
|
|
104
103
|
if (initialized)
|
|
105
104
|
return;
|
|
106
105
|
// SKIP_AUTO_INIT lets consumer test suites mount the plugin without backend connections.
|
|
107
|
-
if (
|
|
106
|
+
if (require('../srv/config').autoInitSkipped()) {
|
|
108
107
|
logger.info('Skipping plugin auto-initialization (SKIP_AUTO_INIT=true)');
|
|
109
108
|
return;
|
|
110
109
|
}
|
|
@@ -5,6 +5,7 @@ const blockfrost_js_1 = require("@blockfrost/blockfrost-js");
|
|
|
5
5
|
const backend_request_handler_1 = require("../../utils/backend-request-handler");
|
|
6
6
|
const errors_1 = require("../../utils/errors");
|
|
7
7
|
const mappers_1 = require("../../utils/mappers");
|
|
8
|
+
const pool_metadata_1 = require("../pool-metadata");
|
|
8
9
|
const tx_build_helper_1 = require("../../utils/tx-build-helper");
|
|
9
10
|
/** CardanoBackend + PaginatingBackend implementation on the Blockfrost API SDK. */
|
|
10
11
|
class BlockfrostBackend {
|
|
@@ -203,7 +204,8 @@ class BlockfrostBackend {
|
|
|
203
204
|
/** Stake pool by id. */
|
|
204
205
|
async getPool(poolId) {
|
|
205
206
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
206
|
-
const poolData = await this.api.poolsById(poolId);
|
|
207
|
+
const [poolData, registered] = await Promise.all([this.api.poolsById(poolId), this.api.poolMetadata(poolId)]);
|
|
208
|
+
const metadata = (0, pool_metadata_1.validPoolMetadata)(registered);
|
|
207
209
|
return {
|
|
208
210
|
poolId: poolData.pool_id,
|
|
209
211
|
vrfKeyHash: poolData.vrf_key,
|
|
@@ -220,6 +222,12 @@ class BlockfrostBackend {
|
|
|
220
222
|
margin: poolData.margin_cost,
|
|
221
223
|
fixedCost: poolData.fixed_cost || '0',
|
|
222
224
|
rewardAccount: poolData.reward_account,
|
|
225
|
+
metadataUrl: registered.url ?? null,
|
|
226
|
+
metadataHash: registered.hash ?? null,
|
|
227
|
+
name: metadata?.name ?? null,
|
|
228
|
+
ticker: metadata?.ticker ?? null,
|
|
229
|
+
homepage: metadata?.homepage ?? null,
|
|
230
|
+
description: metadata?.description ?? null,
|
|
223
231
|
};
|
|
224
232
|
}, this.name);
|
|
225
233
|
}
|
|
@@ -133,6 +133,21 @@ export interface EpochStateBackend extends CardanoBackend {
|
|
|
133
133
|
}
|
|
134
134
|
/** Type guard: can this backend read epoch state at a block? */
|
|
135
135
|
export declare function isEpochStateBackend(backend: CardanoBackend): backend is EpochStateBackend;
|
|
136
|
+
/** A reward account as the node's ledger holds it at one block. */
|
|
137
|
+
export interface RewardAccountState {
|
|
138
|
+
stakeAddress: string;
|
|
139
|
+
withdrawableAmount: string | null;
|
|
140
|
+
deposit: string | null;
|
|
141
|
+
poolId: string | null;
|
|
142
|
+
drepId: string | null;
|
|
143
|
+
}
|
|
144
|
+
/** Answers the accounts among `stakeAddresses` that the ledger reports. */
|
|
145
|
+
export type AskRewardAccounts = (stakeAddresses: string[]) => Promise<RewardAccountState[]>;
|
|
146
|
+
export interface RewardAccountStateBackend extends CardanoBackend {
|
|
147
|
+
rewardAccountsAt<T>(point: ChainPoint, read: (ask: AskRewardAccounts) => Promise<T>): Promise<T>;
|
|
148
|
+
}
|
|
149
|
+
/** Type guard: can this backend read reward accounts at a block? */
|
|
150
|
+
export declare function isRewardAccountStateBackend(backend: CardanoBackend): backend is RewardAccountStateBackend;
|
|
136
151
|
export interface TokenRegistryBackend extends CardanoBackend {
|
|
137
152
|
/** Units (policyId + assetNameHex) that have a registry entry. */
|
|
138
153
|
getTokenRegistryUnits(): Promise<string[]>;
|
|
@@ -5,6 +5,7 @@ exports.isChainSyncBackend = isChainSyncBackend;
|
|
|
5
5
|
exports.isLedgerStateBackend = isLedgerStateBackend;
|
|
6
6
|
exports.isPaginatingBackend = isPaginatingBackend;
|
|
7
7
|
exports.isEpochStateBackend = isEpochStateBackend;
|
|
8
|
+
exports.isRewardAccountStateBackend = isRewardAccountStateBackend;
|
|
8
9
|
exports.isTokenRegistryBackend = isTokenRegistryBackend;
|
|
9
10
|
exports.isEnumeratingBackend = isEnumeratingBackend;
|
|
10
11
|
/** Type guard: does this backend support transaction evaluation? */
|
|
@@ -29,6 +30,10 @@ function isPaginatingBackend(backend) {
|
|
|
29
30
|
function isEpochStateBackend(backend) {
|
|
30
31
|
return typeof backend.epochStateAt === 'function';
|
|
31
32
|
}
|
|
33
|
+
/** Type guard: can this backend read reward accounts at a block? */
|
|
34
|
+
function isRewardAccountStateBackend(backend) {
|
|
35
|
+
return typeof backend.rewardAccountsAt === 'function';
|
|
36
|
+
}
|
|
32
37
|
/** Type guard: can this backend list the token registry? */
|
|
33
38
|
function isTokenRegistryBackend(backend) {
|
|
34
39
|
return typeof backend.getTokenRegistryUnits === 'function';
|
|
@@ -10,6 +10,7 @@ const axios_1 = __importDefault(require("axios"));
|
|
|
10
10
|
const backend_request_handler_1 = require("../../utils/backend-request-handler");
|
|
11
11
|
const errors_1 = require("../../utils/errors");
|
|
12
12
|
const mappers_1 = require("../../utils/mappers");
|
|
13
|
+
const pool_metadata_1 = require("../pool-metadata");
|
|
13
14
|
const const_1 = require("../../utils/const");
|
|
14
15
|
const tx_build_helper_1 = require("../../utils/tx-build-helper");
|
|
15
16
|
const logger = cds_1.default.log('KoiosBackend');
|
|
@@ -168,8 +169,9 @@ class KoiosBackend {
|
|
|
168
169
|
_assets: true,
|
|
169
170
|
_withdrawals: false,
|
|
170
171
|
_certs: false,
|
|
171
|
-
|
|
172
|
-
|
|
172
|
+
// Koios sends inline datum bytes and reference scripts only with both flags.
|
|
173
|
+
_scripts: true,
|
|
174
|
+
_bytecode: true,
|
|
173
175
|
};
|
|
174
176
|
const { data } = await this.api.post('/tx_info', body);
|
|
175
177
|
if (!data || !Array.isArray(data) || data.length === 0) {
|
|
@@ -399,6 +401,7 @@ class KoiosBackend {
|
|
|
399
401
|
}
|
|
400
402
|
/** Map one Koios /pool_info row to the canonical PoolData. */
|
|
401
403
|
_mapKoiosPool(poolData, fallbackId) {
|
|
404
|
+
const metadata = (0, pool_metadata_1.validPoolMetadata)(poolData.meta_json);
|
|
402
405
|
return {
|
|
403
406
|
poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
|
|
404
407
|
vrfKeyHash: poolData.vrf_key_hash || '',
|
|
@@ -419,6 +422,12 @@ class KoiosBackend {
|
|
|
419
422
|
margin: poolData.margin || 0,
|
|
420
423
|
fixedCost: poolData.fixed_cost || '0',
|
|
421
424
|
rewardAccount: poolData.reward_addr || '',
|
|
425
|
+
metadataUrl: poolData.meta_url ?? null,
|
|
426
|
+
metadataHash: poolData.meta_hash ?? null,
|
|
427
|
+
name: metadata?.name ?? null,
|
|
428
|
+
ticker: metadata?.ticker ?? null,
|
|
429
|
+
homepage: metadata?.homepage ?? null,
|
|
430
|
+
description: metadata?.description ?? null,
|
|
422
431
|
};
|
|
423
432
|
}
|
|
424
433
|
/** Asset info from Koios `asset_info`. */
|
|
@@ -439,14 +448,11 @@ class KoiosBackend {
|
|
|
439
448
|
// Koios token_registry_metadata fields are typically strings, but the
|
|
440
449
|
// CIP-26 registry entries may be wrapped in {value, signatures}. Accept either form.
|
|
441
450
|
const regRaw = (a.token_registry_metadata ?? null);
|
|
451
|
+
// Koios sends an empty string for a registry field the entry does not carry.
|
|
442
452
|
const regStr = (key) => {
|
|
443
453
|
const v = regRaw?.[key];
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
if (v && typeof v === 'object' && typeof v.value === 'string') {
|
|
447
|
-
return v.value;
|
|
448
|
-
}
|
|
449
|
-
return null;
|
|
454
|
+
const text = v && typeof v === 'object' ? v.value : v;
|
|
455
|
+
return typeof text === 'string' && text !== '' ? text : null;
|
|
450
456
|
};
|
|
451
457
|
const regNum = (key) => {
|
|
452
458
|
const v = regRaw?.[key];
|
|
@@ -754,8 +760,8 @@ class KoiosBackend {
|
|
|
754
760
|
// certificates + withdrawals only when the crawl will write them (larger payload)
|
|
755
761
|
_withdrawals: this.crawlCertificates,
|
|
756
762
|
_certs: this.crawlCertificates,
|
|
757
|
-
_scripts:
|
|
758
|
-
_bytecode:
|
|
763
|
+
_scripts: true,
|
|
764
|
+
_bytecode: true,
|
|
759
765
|
});
|
|
760
766
|
if (data && Array.isArray(data)) {
|
|
761
767
|
for (const tx of data) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
|
|
2
|
-
import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint, LedgerStateBackend, EpochStateBackend, EpochLedgerState } from './cardano-backend';
|
|
2
|
+
import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint, LedgerStateBackend, EpochStateBackend, EpochLedgerState, RewardAccountStateBackend, AskRewardAccounts } from './cardano-backend';
|
|
3
3
|
import { Network } from '../cardano-client';
|
|
4
4
|
/** Ogmios response shapes not fully typed in @cardano-ogmios/client. */
|
|
5
5
|
interface OgmiosStakePool {
|
|
@@ -21,6 +21,10 @@ interface OgmiosStakePool {
|
|
|
21
21
|
};
|
|
22
22
|
} | number | bigint;
|
|
23
23
|
rewardAccount?: string;
|
|
24
|
+
metadata?: {
|
|
25
|
+
url?: string;
|
|
26
|
+
hash?: string;
|
|
27
|
+
};
|
|
24
28
|
}
|
|
25
29
|
/** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
|
|
26
30
|
export declare function ogmiosScriptHash(script: unknown): string | null;
|
|
@@ -86,8 +90,7 @@ export declare function resolveOgmiosTip(tip: 'origin' | {
|
|
|
86
90
|
};
|
|
87
91
|
/** Resolve Ogmios block height which may be 'origin' (genesis block) or a number */
|
|
88
92
|
export declare function resolveOgmiosHeight(height: 'origin' | number): number;
|
|
89
|
-
|
|
90
|
-
export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend, LedgerStateBackend, EpochStateBackend {
|
|
93
|
+
export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend, LedgerStateBackend, EpochStateBackend, RewardAccountStateBackend {
|
|
91
94
|
readonly name = "ogmios";
|
|
92
95
|
/** Ogmios cannot answer historic queries. The orchestrator skips it for these. */
|
|
93
96
|
readonly unsupportedMethods: ReadonlySet<string>;
|
|
@@ -132,6 +135,9 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
|
|
|
132
135
|
/** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
|
|
133
136
|
private mapOgmiosUtxo;
|
|
134
137
|
private withLedgerStateAt;
|
|
138
|
+
/** A connection of its own with the ledger state at `point` acquired. The caller closes it. */
|
|
139
|
+
private openLedgerStateAt;
|
|
140
|
+
rewardAccountsAt<T>(point: ChainPoint, read: (ask: AskRewardAccounts) => Promise<T>): Promise<T>;
|
|
135
141
|
/** Whole UTxO set as of `point` (crawler snapshot import). */
|
|
136
142
|
queryUtxoSetAt(point: ChainPoint): Promise<UTxO[]>;
|
|
137
143
|
/** Pools, DReps and pots at `point` from one ledger state. Without nOpt saturation stays 0. */
|