Skip to content

Commit

Permalink
Tweaks + update scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
olegnn committed Oct 31, 2024
1 parent 07e2449 commit 3abf6cf
Show file tree
Hide file tree
Showing 6 changed files with 157 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { ensureInstanceOf } from '../../utils';
import AbstractStatusListCredentialModule from '../../modules/abstract/status-list-credential/module';
import { Resolver } from '../generic';
import { ensureInstanceOf } from "../../utils";

Check failure on line 1 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

Check failure on line 1 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
import AbstractStatusListCredentialModule from "../../modules/abstract/status-list-credential/module";

Check failure on line 2 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

Check failure on line 2 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
import {
HEX_ID_REG_EXP_PATTERN,
METHOD_REG_EXP_PATTERN,
Resolver,
} from "../generic";

Check failure on line 7 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

Check failure on line 7 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

const STATUS_LIST_ID_MATCHER = new RegExp(
`^status-list2021:${METHOD_REG_EXP_PATTERN}:${HEX_ID_REG_EXP_PATTERN}$`

Check failure on line 10 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma

Check failure on line 10 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
);

class StatusListResolver extends Resolver {
prefix = 'status-list2021';
prefix = "status-list2021";

Check failure on line 14 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

Check failure on line 14 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

get method() {
return this.statusListCredentialModule.methods();
Expand All @@ -21,13 +29,21 @@ class StatusListResolver extends Resolver {
*/
this.statusListCredentialModule = ensureInstanceOf(
statusListCredentialModule,
AbstractStatusListCredentialModule,
AbstractStatusListCredentialModule

Check failure on line 32 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma

Check failure on line 32 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
);
}

async resolve(id) {
async resolve(statusListId) {
const match = statusListId.match(STATUS_LIST_ID_MATCHER);
if (!match) {
throw new Error(
`Invalid \`StatusList2021Credential\` id: \`${statusListId}\``

Check failure on line 40 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma

Check failure on line 40 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
);
}
const [, _, id] = statusListId.match(STATUS_LIST_ID_MATCHER);

const cred = await this.statusListCredentialModule.getStatusListCredential(
id,
id

Check failure on line 46 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma

Check failure on line 46 in packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js

View workflow job for this annotation

GitHub Actions / lint

Missing trailing comma
);

return cred?.value.list.toJSON();
Expand Down
26 changes: 26 additions & 0 deletions packages/dock-blockchain-api/scripts/loader.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const solutions = [
(s) => s,
(s) => `${s}/index.js`,
(s) => `${s}.js`,
(s) => `${s}/lib/index.js`,
];

export async function resolve(specifier, context, defaultResolve) {
for (const solve of solutions) {
const resolvedPath = solve(specifier);

try {
return await defaultResolve(resolvedPath, context, defaultResolve);
} catch (err) {
if (
err.code !== "ERR_MODULE_NOT_FOUND" &&
err.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED" &&
err.code !== "ERR_UNSUPPORTED_DIR_IMPORT"
) {
console.error(`Error resolving path: ${resolvedPath}`, err);
}
}
}

throw new Error(`Module not found: ${specifier}`);
}
9 changes: 2 additions & 7 deletions packages/dock-blockchain-api/scripts/slack.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { curry } from "ramda";
import fetch from "node-fetch";
import { envObj, notNilAnd } from "./helpers";

const { SlackNotificationWebhookUrl } = envObj({
SlackNotificationWebhookUrl: notNilAnd(String),
});

export const TYPES = {
WARNING: "warning",
Expand All @@ -15,7 +10,7 @@ export const TYPES = {
/**
* Posts a message to Slack.
*/
export const postMessage = curry(async (type, header, fields) => {
export const postMessage = curry(async (url, type, header, fields) => {
const body = Buffer.from(
JSON.stringify({
text: header,
Expand All @@ -33,7 +28,7 @@ export const postMessage = curry(async (type, header, fields) => {
"Content-Length": body.byteLength,
};

return await fetch(SlackNotificationWebhookUrl, {
return await fetch(url, {
headers,
method: "POST",
body,
Expand Down
111 changes: 104 additions & 7 deletions packages/dock-blockchain-api/scripts/watch-essential-events.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ import {
finiteNumber,
timestampLogger,
blockByNumber,
accountIdentity,
} from "./helpers";
import dock from "../src";
import { DockAPI } from "../src";
import { sendAlarmEmailText } from "./email_utils";
import { TYPES, postMessage } from "./slack";

Expand All @@ -96,6 +97,8 @@ const {
BlockProcessingTimeOut,
RetryDelay,
RetryAttempts,
SlackNotificationsWebhookMainUrl,
SlackNotificationsWebhookMigrationUrl,
} = envObj({
// Email to send alarm emails to.
TxWatcherAlarmEmailTo: notNilAnd(split(",")),
Expand Down Expand Up @@ -124,6 +127,8 @@ const {
RetryDelay: o(finiteNumber, defaultTo(3e4)),
// Amount of retry attempts before exiting with 1 code.
RetryAttempts: o(finiteNumber, defaultTo(3)),
SlackNotificationsWebhookMainUrl: notNilAnd(String),
SlackNotificationsWebhookMigrationUrl: notNilAnd(String),
});

const main = async (dock, startBlock) => {
Expand Down Expand Up @@ -159,6 +164,7 @@ const main = async (dock, startBlock) => {
(error) =>
void timestampLogger.error(error) ||
sendMessage(
SlackNotificationsWebhookMainUrl,
"Mainnet watcher was restarted",
`Due to either connection or node API problems, the dock blockchain essential notifications watcher was restarted with the last unprocessed block ${minUnprocessed}.`
)
Expand Down Expand Up @@ -267,8 +273,33 @@ const processBlocks = (dock, startBlock) => {
events$.pipe(applyFilters(eventFilters))
).pipe(
batchNotifications(BatchNoficationTimeout),
tap((email) => timestampLogger.log("Sending email: ", email)),
mergeMap(o(from, sendMessage("Mainnet alarm notification")))
tap((email) => timestampLogger.log("Sending message: ", email)),
mergeMap((message) => {
if (!message.includes("migrated")) {
return from(
sendMessage(
SlackNotificationsWebhookMainUrl,
"Mainnet alarm notification",
message
)
);
} else {
return from(
postMessage(
SlackNotificationsWebhookMigrationUrl,
TYPES.SUCCESS,
"Token migration",
[
{
title: "Summary",
value: message,
short: false,
},
]
)
);
}
})
);

const number = block.block.header.number.toNumber();
Expand Down Expand Up @@ -404,10 +435,10 @@ const syncPrevousBlocks = curry((dock, startBlock, currentBlocks$) => {
* @param {string} message
* @returns {Observable<*>}
*/
const sendMessage = curry((header, message) =>
const sendMessage = curry((url, header, message) =>
merge(
from(
postMessage(TYPES.DANGER, header, [
postMessage(url, TYPES.DANGER, header, [
{
title: "Summary",
value: message,
Expand Down Expand Up @@ -574,6 +605,16 @@ const technicalCommitteeMembershipEvent = eventByMethodFilter(
*/
const electionsEvent = eventByMethodFilter("elections");

/**
* Filter events produced by `staking` pallet.
*/
const stakingEvent = eventByMethodFilter("staking");

/**
* Filter events produced by `cheqdMigration` pallet.
*/
const cheqdMigrationEvent = eventByMethodFilter("cheqdMigration");

/**
* Filter extrinsics produced by `technicalCommitteeMembership` pallet.
*/
Expand Down Expand Up @@ -763,6 +804,62 @@ const eventFilters = [
}) => of(`Council member renounced: ${member.toString()}`)
),

checkMap(
stakingEvent("Unbonded"),
(
{
event: {
data: [account, balance],
},
},
dock
) =>
of({ account, balance }).pipe(
filterRx(({ balance }) => balance.toNumber() > 1e12),
concatMap(({ account, balance }) =>
from(accountIdentity(dock.api, account)).pipe(
mapRx((acc) => `Account ${acc} unbonded ${formatDock(balance)}`)
)
)
)
),

checkMap(
stakingEvent("Chilled"),
(
{
event: {
data: [account],
},
},
dock
) =>
from(accountIdentity(dock.api, account)).pipe(
mapRx((account) => `Account ${account} chilled`)
)
),

checkMap(
cheqdMigrationEvent("Migrated"),
(
{
event: {
data: [dockAccount, cheqdAccount, tokensAmount],
},
},
dock
) =>
from(accountIdentity(dock.api, dockAccount)).pipe(
mergeMap((account) =>
of(
`${account} migrated \`${formatDock(
tokensAmount
)}\` to \`${cheqdAccount}\``
)
)
)
),

// Council members changed
checkMap(
electionsEvent("NewTerm"),
Expand Down Expand Up @@ -903,7 +1000,7 @@ const createTxWithEventsCombinator = (dock) => {
* @param {Array<*>} events
* @param {*} tx
* @param {{config: number, rootTx: *}} param2
* @returns Promise<*>
* @returns
*/
const pickEventsForExtrinsic = (events, tx, { config, rootTx }) => {
let batchIdx = -1;
Expand Down Expand Up @@ -1020,7 +1117,7 @@ const createTxWithEventsCombinator = (dock) => {
return mergeEventsWithExtrs;
};

main(dock, StartBlock)
main(new DockAPI(), StartBlock)
.then(() => process.exit(0))
.catch((err) => {
timestampLogger.error(err);
Expand Down
2 changes: 1 addition & 1 deletion packages/dock-blockchain-modules/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"docs": "rm -rf out && mkdir out && touch out/.nojekyll && jsdoc src -r -c ../../.jsdoc -d out/reference",
"prepublishOnly": "yarn build",
"dev-node": "../../scripts/run_dock_node_in_docker --dev --rpc-external --ws-external --rpc-cors=all",
"test": "LOG_STATE_CHANGE=1 NODE_ENV=production jest --verbose --runInBand --forceExit ./tests/integration/*",
"test": "LOG_STATE_CHANGE=1 NODE_ENV=production jest --verbose --runInBand --forceExit ./tests/integration/status-list-credential.test.js",
"test-with-node": "../../scripts/with_dock_docker_test_node yarn test",
"test-with-all-nodes": "../../scripts/with_all_dock_docker_test_nodes yarn test-integration"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ describe("StatusList2021Credential", () => {
resolver,
compactProof: true,
});

console.log(result.error);
expect(result.verified).toBe(true);

// Revoke the credential
Expand Down

0 comments on commit 3abf6cf

Please sign in to comment.