-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathindex.mjs
More file actions
487 lines (459 loc) · 14.4 KB
/
index.mjs
File metadata and controls
487 lines (459 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import { ApiPromise, WsProvider, Keyring } from "@polkadot/api";
import { readFile } from "node:fs/promises";
import path from "node:path";
const MAINNET_SOURCE_URL = "wss://1.rpc.frequency.xyz";
const PASEO_SOURCE_URL = "wss://0.rpc.testnet.amplica.io";
const LOCAL_SOURCE_URL = "ws://127.0.0.1:9944";
const MAINNET = "MAINNET";
const PASEO = "PASEO";
const LOCAL = "LOCAL";
const INTENT = "INTENT";
const SCHEMA = "SCHEMA";
const RPC_AUGMENTS = {
rpc: {
schemas: {
getBySchemaId: {
description: "Get a Schema by Id",
params: [
{
name: "schema_id",
type: "SchemaId",
},
],
type: "Option<SchemaResponse>",
},
},
},
types: {
SchemaId: "u16",
SchemaModel: "Vec<u8>",
SchemaVersion: "u8",
SchemaResponse: {
schema_id: "SchemaId",
model: "SchemaModel",
model_type: "ModelType",
payload_location: "PayloadLocation",
settings: "Vec<SchemaSetting>",
},
IntentGroupId: "u16",
IntentGroupResponse: {
intent_group_id: "IntentGroupId",
intent_ids: "Vec<IntentId>",
},
IntentId: "u16",
IntentResponse: {
intent_id: "IntentId",
payload_location: "PayloadLocation",
settings: "Vec<IntentSetting>",
schema_ids: "Option<Vec<SchemaId>>",
},
IntentSetting: {
_enum: ["AppendOnly", "SignatureRequired"],
},
MappedEntityIdentifier: {
_enum: {
Intent: "IntentId",
IntentGroup: "IntentGroupId",
},
},
ModelType: {
_enum: ["AvroBinary", "Parquet"],
},
NameLookupResponse: {
name: "String",
entity_id: "MappedEntityIdentifier",
},
PayloadLocation: {
_enum: ["OnChain", "IPFS", "Itemized", "Paginated"],
},
SchemaInfoResponse: {
schema_id: "SchemaId",
intent_id: "IntentId",
model_type: "ModelType",
status: "SchemaStatus",
payload_location: "PayloadLocation",
settings: "Vec<IntentSetting>",
},
SchemaResponseV2: {
schema_id: "SchemaId",
intent_id: "IntentId",
model: "SchemaModel",
model_type: "ModelType",
payload_location: "PayloadLocation",
settings: "Vec<IntentSetting>",
status: "SchemaStatus",
},
SchemaSetting: {
_enum: ["AppendOnly", "SignatureRequired"],
},
SchemaStatus: {
_enum: ["Active", "Deprecated", "Unsupported"],
},
SchemaVersionResponse: {
schema_name: "String",
schema_version: "SchemaVersion",
schema_id: "SchemaId",
},
},
};
// DEPLOY_SCHEMA_ACCOUNT_URI (environment variable)
// The value is a URI for the account. e.g. //Alice or a mnemonic (seed words)
const getSignerAccountKeys = () => {
const keyring = new Keyring();
let DEPLOY_SCHEMA_ACCOUNT_URI = process.env.DEPLOY_SCHEMA_ACCOUNT_URI;
if (DEPLOY_SCHEMA_ACCOUNT_URI === undefined) {
DEPLOY_SCHEMA_ACCOUNT_URI = "//Alice";
}
return keyring.addFromUri(DEPLOY_SCHEMA_ACCOUNT_URI, {}, "sr25519");
};
function getIntentId(api, intent) {
// Propose to create
const promise = new Promise((resolve, reject) => {
api.call.schemasRuntimeApi.getRegisteredEntitiesByName(intent.name)
.then(response => {
if (response.isSome && response.unwrap().length > 0) {
const registeredEntities = response.unwrap().toArray();
const last = registeredEntities[registeredEntities.length - 1];
const id = last.entityId;
resolve(id.value);
} else {
console.log(`No intent exists for "${intent.name}"`);
resolve(undefined);
}
})
.catch(error => {
console.error(`ERROR: ${error}`);
reject(error);
});
});
return promise;
}
async function hasDuplicateLatestSchema(api, schemaDeploy, intentId) {
const intentResponse = await api.call.schemasRuntimeApi.getIntentById(intentId, true);
if (!intentResponse.isSome) {
throw new Error(`Intent ${intentId} not found`);
}
const schemaIds = intentResponse.unwrap().schemaIds;
if (!schemaIds.isSome || schemaIds.unwrap().length === 0) {
return false;
}
const ids = schemaIds.unwrap();
const latestSchemaId = ids[ids.length - 1];
const latestSchemaResponse = await api.call.schemasRuntimeApi.getSchemaById(latestSchemaId);
if (!latestSchemaResponse.isSome) {
return false;
}
const latestSchema = latestSchemaResponse.unwrap();
const latestModelType = latestSchema.modelType.toString();
const latestModel = latestSchema.model.toUtf8();
const normalizeJsonString = (jsonString) => {
const sortKeysDeep = (value) => {
if (Array.isArray(value)) {
return value.map(sortKeysDeep);
}
if (value && typeof value === "object") {
return Object.keys(value)
.sort()
.reduce((acc, key) => {
acc[key] = sortKeysDeep(value[key]);
return acc;
}, {});
}
return value;
};
return JSON.stringify(sortKeysDeep(JSON.parse(jsonString)));
};
const normalizedLatestModel = normalizeJsonString(latestModel);
const normalizedSchemaModel = normalizeJsonString(schemaDeploy.model);
return latestModelType === schemaDeploy.model_type && normalizedLatestModel === normalizedSchemaModel ? latestSchemaId : false;
}
async function deploy(chainType, operationType, intents, schemas) {
const selectedUrl =
chainType === MAINNET
? MAINNET_SOURCE_URL
: chainType === PASEO
? PASEO_SOURCE_URL
: LOCAL_SOURCE_URL;
console.log(`Selected CHAIN: ${chainType}, URL: ${selectedUrl}`);
// get existing schemas on chain
const provider = new WsProvider(selectedUrl);
const api = await ApiPromise.create({
provider,
throwOnConnect: true,
...RPC_AUGMENTS,
});
const signerAccountKeys = getSignerAccountKeys();
// Retrieve the current account nonce so we can increment it when submitting transactions
let baseNonce = (await api.rpc.system.accountNextIndex(signerAccountKeys.address)).toNumber();
const intentPromises = [];
let intentNonceOffset = 0;
for (const idx in intents) {
const intent = intents[idx];
const nonce = baseNonce + intentNonceOffset;
// check if intent already exists
const intentId = await getIntentId(api, intent);
if (intentId) {
console.log(`Intent "${intent.name}" already exists with ID ${intentId}`);
intentPromises[idx] = Promise.resolve(intentId);
continue;
}
if (chainType === MAINNET) {
// create proposal
if (operationType === INTENT) {
intentPromises[idx] = getIntentProposalTransaction(api, signerAccountKeys, nonce, intent);
intentNonceOffset += 1;
} else {
intentPromises[idx] = getIntentId(api, intent);
}
} else {
// create directly via sudo
intentPromises[idx] = getIntentSudoTransaction(api, signerAccountKeys, nonce, intent);
intentNonceOffset += 1;
}
}
const intentResults = await Promise.all(intentPromises);
const idMap = new Map(intentResults.map((result, index) => {
const id = Array.isArray(result) ? `${result[0]}` : `${result}`;
return [intents[index].name, parseInt(id, 10)];
}));
console.log('Resolved intents: ', idMap);
baseNonce = (await api.rpc.system.accountNextIndex(signerAccountKeys.address)).toNumber();
const schemaPromises = [];
let schemaNonceOffset = 0;
for (const idx in schemas) {
const schema = schemas[idx];
const intentId = await getIntentId(api, { name: schema.intent_name });
if (!intentId) {
throw new Error(`Intent ID not found for schema with intent_name: ${schema.intent_name}`);
}
console.log(`Found intentId ${intentId} for "${schema.intent_name}"`);
const duplicateSchemaId = await hasDuplicateLatestSchema(api, schema, intentId);
if (duplicateSchemaId) {
console.log(
`Skipping schema publish for intent ${schema.intent_name}: latest published schema (${duplicateSchemaId}) has the same model and modelType`,
);
schemaPromises[idx] = Promise.resolve(duplicateSchemaId);
continue;
}
const nonce = baseNonce + schemaNonceOffset;
if (chainType === MAINNET) {
// create proposal
if (operationType === SCHEMA) {
schemaPromises[idx] = getSchemaProposalTransaction(
api,
signerAccountKeys,
nonce,
schema,
intentId,
);
schemaNonceOffset += 1;
}
} else {
// create directly via sudo
schemaPromises[idx] = getSchemaSudoTransaction(
api,
signerAccountKeys,
nonce,
schema,
intentId,
);
schemaNonceOffset += 1;
}
}
const schemaResults = await Promise.all(schemaPromises);
console.log('Resolved/created schemas: ', new Map(schemaResults.map((result, index) => {
const id = Array.isArray(result) ? `${result[0]}` : `${result}`;
return [schemas[index].intent_name, parseInt(id, 10)];
})));
}
async function loadIntentsAndSchemas(fileName) {
const filePath = path.isAbsolute(fileName) ? fileName : path.resolve(process.cwd(), fileName);
const fileContents = await readFile(filePath, "utf-8");
const parsed = JSON.parse(fileContents);
if (!Array.isArray(parsed.intents) || !Array.isArray(parsed.schemas)) {
throw new Error(`Invalid format in ${filePath}: expected "intents" and "schemas" arrays`);
}
return parsed;
}
// Given a list of events, a section and a method,
// returns the first event with matching section and method.
const eventWithSectionAndMethod = (events, section, method) => {
const evt = events.find(({ event }) => event.section === section && event.method === method);
return evt?.event;
};
function getIntentProposalTransaction(api, signerAccountKeys, nonce, intentDeploy) {
// Propose to create
const promise = new Promise((resolve, reject) => {
api.tx.schemas
.proposeToCreateIntent(
intentDeploy.payload_location,
intentDeploy.settings,
intentDeploy.name,
)
.signAndSend(signerAccountKeys, { nonce }, ({ status, events, dispatchError }) => {
if (dispatchError) {
console.error("ERROR: ", dispatchError.toHuman());
console.log("Might already have a proposal with the same hash?");
reject(dispatchError.toHuman());
} else if (status.isInBlock || status.isFinalized) {
const evt = eventWithSectionAndMethod(events, "council", "Proposed");
if (evt) {
const id = evt?.data[1];
const hash = evt?.data[2].toHex();
console.log(
"SUCCESS: " +
`${intentDeploy.name}` +
" intent proposed with id of " +
id +
" and hash of " +
hash,
);
resolve([id, hash]);
} else {
const err = "Proposed event not found";
console.error(`ERROR: ${err}`);
reject(err);
}
}
});
});
return promise;
}
function getSchemaProposalTransaction(api, signerAccountKeys, nonce, schemaDeploy, intentId) {
// Propose to create
const promise = new Promise((resolve, reject) => {
api.tx.schemas
.proposeToCreateSchemaV3(
intentId,
schemaDeploy.model,
schemaDeploy.model_type,
)
.signAndSend(signerAccountKeys, { nonce }, ({ status, events, dispatchError }) => {
if (dispatchError) {
console.error("ERROR: ", dispatchError.toHuman());
console.log("Might already have a proposal with the same hash?");
reject(dispatchError.toHuman());
} else if (status.isInBlock || status.isFinalized) {
const evt = eventWithSectionAndMethod(events, "council", "Proposed");
if (evt) {
const id = evt?.data[1];
const hash = evt?.data[2].toHex();
console.log(
"SUCCESS: " +
`${schemaDeploy.intent_name}` +
" schema proposed with id of " +
id +
" and hash of " +
hash,
);
resolve([id, hash]);
} else {
const err = "Proposed event not found";
console.error(`ERROR: ${err}`);
reject(err);
}
}
});
});
return promise;
}
function getSchemaSudoTransaction(api, signerAccountKeys, nonce, schemaDeploy, intent_id) {
// Create directly via sudo
const tx = api.tx.schemas.createSchemaViaGovernanceV3(
signerAccountKeys.address,
intent_id,
schemaDeploy.model,
schemaDeploy.model_type,
);
const promise = new Promise((resolve, reject) => {
api.tx.sudo
.sudo(tx)
.signAndSend(signerAccountKeys, { nonce }, ({ status, events, dispatchError }) => {
if (dispatchError) {
console.error("Dispatch ERROR: ", dispatchError.toHuman());
reject(dispatchError.toHuman());
} else if (status.isInBlock || status.isFinalized) {
const evt = eventWithSectionAndMethod(events, "schemas", "SchemaCreated");
if (evt) {
const id = evt?.data[1];
resolve(id);
} else {
const err = "SchemaCreated event not found";
console.error(`ERROR: ${err}`);
reject(err);
}
}
});
});
return promise;
}
function getIntentSudoTransaction(api, signerAccountKeys, nonce, intentDeploy) {
// Create directly via sudo
const tx = api.tx.schemas.createIntentViaGovernance(
signerAccountKeys.address,
intentDeploy.payload_location,
intentDeploy.settings,
intentDeploy.name,
);
const promise = new Promise((resolve, reject) => {
api.tx.sudo
.sudo(tx)
.signAndSend(signerAccountKeys, { nonce }, ({ status, events, dispatchError }) => {
if (dispatchError) {
console.error("ERROR: ", dispatchError.toHuman());
reject(dispatchError.toHuman());
} else if (status.isInBlock || status.isFinalized) {
const evt = eventWithSectionAndMethod(events, "schemas", "IntentCreated");
if (evt) {
const id = evt?.data[1];
console.log(
"SUCCESS: " + intentDeploy.name + " intent created with id of " + id,
);
resolve(id);
} else {
const err = "IntentCreated event not found";
console.error(`ERROR: ${err}`);
reject(err);
}
}
});
});
return promise;
}
async function main() {
try {
console.log("Uploading Intents & schemas");
const args = process.argv.slice(2);
if (args.length < 2) {
console.log(
`Usage: node index.mjs <intents-and-schemas.json> <${MAINNET}|${PASEO}|${LOCAL}> [${INTENT}|${SCHEMA}]`,
);
process.exit(1);
}
const inputFileName = args[0];
const chainType = args[1].toUpperCase().trim();
if (chainType !== MAINNET && chainType !== PASEO && chainType !== LOCAL) {
console.log(`Please specify the chain type: ${MAINNET} or ${PASEO} or ${LOCAL}`);
process.exit(1);
}
let operationType = "ALL";
if (chainType === MAINNET) {
if (args.length < 3) {
console.log(`For Mainnet you must specify the operation type: ${INTENT} or ${SCHEMA}`);
process.exit(1);
}
operationType = args[2].toUpperCase().trim();
if (operationType !== INTENT && operationType !== SCHEMA) {
console.log(`For Mainnet you must specify the operation type: ${INTENT} or ${SCHEMA}`);
process.exit(1);
}
}
const { intents, schemas } = await loadIntentsAndSchemas(inputFileName);
await deploy(chainType, operationType, intents, schemas);
process.exit(0);
} catch (error) {
console.error("Error:", error);
process.exit(1);
}
}
main();