@verii/endpoints-event-processing 1.0.0-pre.1752076816

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.
Files changed (37) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +1 -0
  3. package/README.md +42 -0
  4. package/package.json +64 -0
  5. package/src/config/abi.json +1 -0
  6. package/src/config/config.js +138 -0
  7. package/src/controllers/events-processing/controller.js +115 -0
  8. package/src/controllers/health-probes/autohooks.js +6 -0
  9. package/src/controllers/health-probes/controller.js +117 -0
  10. package/src/entities/burned-coupons/index.js +3 -0
  11. package/src/entities/burned-coupons/repo.js +29 -0
  12. package/src/entities/health-probes/domains/health-states.js +8 -0
  13. package/src/entities/health-probes/domains/index.js +3 -0
  14. package/src/entities/health-probes/index.js +3 -0
  15. package/src/entities/index.js +23 -0
  16. package/src/entities/oauth/index.js +19 -0
  17. package/src/entities/oauth/scopes.js +21 -0
  18. package/src/entities/purchases/domain/constants.js +64 -0
  19. package/src/entities/purchases/domain/index.js +3 -0
  20. package/src/entities/purchases/index.js +4 -0
  21. package/src/entities/purchases/repo.js +39 -0
  22. package/src/entities/transactions/domain/constants.js +31 -0
  23. package/src/entities/transactions/domain/index.js +3 -0
  24. package/src/entities/transactions/index.js +3 -0
  25. package/src/event-processing-endpoints.js +57 -0
  26. package/src/handlers/handle-coupons-burned-logging-event.js +58 -0
  27. package/src/handlers/handle-coupons-burned-verification-event.js +188 -0
  28. package/src/handlers/handle-coupons-minted-logging-event.js +73 -0
  29. package/src/handlers/handle-credential-issued-logging-event.js +70 -0
  30. package/src/handlers/handle-credential-issued-rewards-event.js +218 -0
  31. package/src/handlers/index.js +7 -0
  32. package/src/helpers/document-functions.js +28 -0
  33. package/src/helpers/event-decoding.js +20 -0
  34. package/src/helpers/index.js +5 -0
  35. package/src/helpers/map-coupon-burned.js +32 -0
  36. package/src/index.js +22 -0
  37. package/src/init-server.js +65 -0
@@ -0,0 +1,117 @@
1
+ const { flow, filter, first } = require('lodash/fp');
2
+
3
+ const { subSeconds } = require('date-fns');
4
+ const {
5
+ initGetSignerMetrics,
6
+ initGetBlockNumber,
7
+ initGetBlock,
8
+ } = require('@verii/blockchain-functions');
9
+ const {
10
+ toBigNumber,
11
+ fromBigNumber,
12
+ subtractBigNumbers,
13
+ } = require('@verii/math');
14
+ const { HealthStates } = require('../../entities');
15
+
16
+ const blockGraceInterval = 6;
17
+ const blocksDeltaMultiplier = 3;
18
+
19
+ const signerMetricsController = async (fastify) => {
20
+ fastify.get(
21
+ '/consensus',
22
+ {
23
+ onRequest: fastify.basicAuth,
24
+ schema: fastify.autoSchema({
25
+ response: {
26
+ 200: {
27
+ status: { type: 'string' },
28
+ },
29
+ },
30
+ }),
31
+ },
32
+ async (req) => {
33
+ const getBlockNumber = await initGetBlockNumber({
34
+ rpcUrl: req.config.rpcUrl,
35
+ authenticate: req.vnfBlockchainAuthenticate,
36
+ });
37
+ const getBlock = await initGetBlock({
38
+ rpcUrl: req.config.rpcUrl,
39
+ authenticate: req.vnfBlockchainAuthenticate,
40
+ });
41
+
42
+ const blockNumber = await getBlockNumber();
43
+ const block = await getBlock(blockNumber);
44
+
45
+ req.log.info({
46
+ blockNumber,
47
+ block,
48
+ });
49
+
50
+ const lastBLockTime = new Date(block.timestamp * 1000);
51
+ const status =
52
+ lastBLockTime < subSeconds(new Date(), blockGraceInterval)
53
+ ? { status: HealthStates.Down }
54
+ : { status: HealthStates.Up };
55
+
56
+ return status;
57
+ }
58
+ );
59
+
60
+ fastify.get(
61
+ '/node/:address',
62
+ {
63
+ onRequest: fastify.basicAuth,
64
+ schema: fastify.autoSchema({
65
+ response: {
66
+ 200: {
67
+ status: { type: 'string' },
68
+ },
69
+ },
70
+ }),
71
+ },
72
+ async (req) => {
73
+ const { address } = req.params;
74
+ const getSignerMetrics = await initGetSignerMetrics({
75
+ rpcUrl: req.config.rpcUrl,
76
+ authenticate: req.vnfBlockchainAuthenticate,
77
+ });
78
+ const getBlockNumber = await initGetBlockNumber({
79
+ rpcUrl: req.config.rpcUrl,
80
+ authenticate: req.vnfBlockchainAuthenticate,
81
+ });
82
+
83
+ const metrics = await getSignerMetrics();
84
+ const nodeMetrics = flow(
85
+ filter((metric) => metric.address === address),
86
+ first
87
+ )(metrics);
88
+ const nodesCount = metrics.length;
89
+ const blockNumber = await getBlockNumber();
90
+
91
+ req.log.info({
92
+ nodeMetrics,
93
+ blockNumber,
94
+ });
95
+
96
+ const status =
97
+ fromBigNumber(
98
+ subtractBigNumbers(
99
+ toBigNumber(blockNumber),
100
+ toBigNumber(nodeMetrics.lastProposedBlockNumber, 16)
101
+ )
102
+ ) >
103
+ nodesCount * blocksDeltaMultiplier
104
+ ? { status: HealthStates.Down }
105
+ : { status: HealthStates.Up };
106
+
107
+ req.log.info({
108
+ address,
109
+ status,
110
+ });
111
+
112
+ return status;
113
+ }
114
+ );
115
+ };
116
+
117
+ module.exports = signerMetricsController;
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ...require('./repo'),
3
+ };
@@ -0,0 +1,29 @@
1
+ const {
2
+ autoboxIdsExtension,
3
+ repoFactory,
4
+ } = require('@spencejs/spence-mongo-repos');
5
+ const {
6
+ initObjectIdAutoboxExtension,
7
+ } = require('@verii/spencer-mongo-extensions');
8
+
9
+ module.exports = (app, options, next = () => {}) => {
10
+ next();
11
+ return repoFactory(
12
+ {
13
+ name: 'burnedCoupons',
14
+ entityName: 'burnedCoupons',
15
+ defaultProjection: {
16
+ _id: 1,
17
+ purchaseId: 1,
18
+ used: 1,
19
+ at: 1,
20
+ clientId: 1,
21
+ },
22
+ extensions: [
23
+ autoboxIdsExtension,
24
+ initObjectIdAutoboxExtension('clientId'),
25
+ ],
26
+ },
27
+ app
28
+ );
29
+ };
@@ -0,0 +1,8 @@
1
+ const HealthStates = {
2
+ Up: 'UP',
3
+ Down: 'DOWN',
4
+ };
5
+
6
+ module.exports = {
7
+ HealthStates,
8
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ...require('./health-states'),
3
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ...require('./domains'),
3
+ };
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright 2025 Velocity Team
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *
16
+ */
17
+ module.exports = {
18
+ ...require('./burned-coupons'),
19
+ ...require('./health-probes'),
20
+ ...require('./oauth'),
21
+ ...require('./purchases'),
22
+ ...require('./transactions'),
23
+ };
@@ -0,0 +1,19 @@
1
+ /*
2
+ * Copyright 2025 Velocity Team
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *
16
+ */
17
+ module.exports = {
18
+ ...require('./scopes'),
19
+ };
@@ -0,0 +1,21 @@
1
+ /*
2
+ * Copyright 2025 Velocity Team
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *
16
+ */
17
+ const EventProcessingScopes = {
18
+ EventsTrigger: 'events:trigger',
19
+ };
20
+
21
+ module.exports = { EventProcessingScopes };
@@ -0,0 +1,64 @@
1
+ const PurchaseStatus = {
2
+ COUPONS_RECONCILED: 'COUPONS_RECONCILED',
3
+ COUPONS_MINTED: 'COUPONS_MINTED',
4
+ PAYMENT_SUCCEEDED: 'PAYMENT_SUCCEEDED',
5
+ CREDITS_ORDERED: 'CREDITS_ORDERED',
6
+ CREDIT_ORDER_PLACED: 'CREDIT_ORDER_PLACED',
7
+ CREDIT_ORDER_FILLED: 'CREDIT_ORDER_FILLED',
8
+ EXCHANGE_TRANSFER_COMPLETED: 'EXCHANGE_TRANSFER_COMPLETED',
9
+ CASHIER_TRANSFER_COMPLETED: 'CASHIER_TRANSFER_COMPLETED',
10
+ PAYMENT_IN_PROGRESS: 'PAYMENT_IN_PROGRESS',
11
+ PAYMENT_ERROR: 'PAYMENT_ERROR',
12
+ QUOTE_ACCEPTED: 'QUOTE_ACCEPTED',
13
+ PAYMENT_INTENT_CREATED: 'PAYMENT_INTENT_CREATED',
14
+ PAYMENT_INTENT_ERROR: 'PAYMENT_INTENT_ERROR',
15
+ QUOTE_CREATED: 'QUOTE_CREATED',
16
+ INVOICE_VOIDED: 'INVOICE_VOIDED',
17
+ FEES_RECORDED: 'FEES_RECORDED',
18
+ };
19
+
20
+ const PurchaseError = {
21
+ PAYMENT_INSUFFICIENT_FUNDS: 'PAYMENT_INSUFFICIENT_FUNDS',
22
+ PAYMENT_VERIFICATION_ERROR: 'PAYMENT_VERIFICATION_ERROR',
23
+ PAYMENT_OTHER_ERROR: 'PAYMENT_OTHER_ERROR',
24
+ PAYMENT_TIMEOUT: 'PAYMENT_TIMEOUT',
25
+ COUPONS_MINTING_FAILED: 'COUPONS_MINTING_FAILED',
26
+ COUPONS_RECONCILE_FAILED: 'COUPONS_RECONCILE_FAILED',
27
+ CASHIER_TRANSFER_FAILED: 'CASHIER_TRANSFER_FAILED',
28
+ EXCHANGE_TRANSFER_FAILED: 'EXCHANGE_TRANSFER_FAILED',
29
+ CREDITS_ORDER_FAILED: 'CREDITS_ORDER_FAILED',
30
+ CREDITS_ORDER_INSUFFICIENT_LIQUIDITY: 'CREDITS_ORDER_INSUFFICIENT_LIQUIDITY',
31
+ };
32
+
33
+ const CouponStatus = {
34
+ EXPIRED: 'EXPIRED',
35
+ ACTIVE: 'ACTIVE',
36
+ };
37
+
38
+ const PurchaseErrorMessages = {
39
+ PURCHASE_NOT_FOUND_TEMPLATE: ({ purchaseId }) =>
40
+ `Purchase ${purchaseId} not found`,
41
+ PURCHASE_WITH_QUOTE_ID_NOT_FOUND_TEMPLATE: ({ quoteId }) =>
42
+ `Quote ${quoteId} not found`,
43
+ PURCHASE_WITH_PAYMENT_METHOD_NOT_FOUND: ({ quoteId, paymentMethodId }) =>
44
+ `Can't found payment method ${paymentMethodId} for quote ${quoteId}`,
45
+ QUOTE_HAS_EXPIRED: 'Quote has expired',
46
+ QUOTE_BELOW_MINIMUM_THRESHOLD: 'Quote is below minimum threshold',
47
+ QUOTE_EXCEEDS_MAXIMUM_THRESHOLD: 'Quote is exceeds maximum threshold',
48
+ PAYMENT_METHOD_IS_NOT_SET: 'Payment method is not set',
49
+ PRICE_TOO_LOW: 'The minimum price is 5$',
50
+ };
51
+
52
+ const PurchaseSystems = {
53
+ STRIPE: 'STRIPE',
54
+ FINERACT: 'FINERACT',
55
+ EXCHANGE: 'EXCHANGE',
56
+ };
57
+
58
+ module.exports = {
59
+ PurchaseError,
60
+ PurchaseStatus,
61
+ CouponStatus,
62
+ PurchaseErrorMessages,
63
+ PurchaseSystems,
64
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ...require('./constants'),
3
+ };
@@ -0,0 +1,4 @@
1
+ module.exports = {
2
+ ...require('./repo'),
3
+ ...require('./domain'),
4
+ };
@@ -0,0 +1,39 @@
1
+ const {
2
+ repoFactory,
3
+ autoboxIdsExtension,
4
+ } = require('@spencejs/spence-mongo-repos');
5
+ const {
6
+ initObjectIdAutoboxExtension,
7
+ } = require('@verii/spencer-mongo-extensions');
8
+
9
+ module.exports = (app, options, next = () => {}) => {
10
+ next();
11
+ return repoFactory(
12
+ {
13
+ name: 'purchases',
14
+ entityName: 'purchase',
15
+ defaultProjection: {
16
+ _id: 1,
17
+ purchaseId: 1,
18
+ userId: 1,
19
+ purchaseEvents: 1,
20
+ quoteMetadata: 1,
21
+ couponBundle: 1,
22
+ creditReceipt: 1,
23
+ fiatReceipt: 1,
24
+ clientId: 1,
25
+ at: 1,
26
+ updatedAt: 1,
27
+ purchaseStatus: 1,
28
+ purchaseType: 1,
29
+ exchangeOrderId: 1,
30
+ },
31
+ timestampKeys: { createdAt: 'at', updatedAt: 'updatedAt' },
32
+ extensions: [
33
+ autoboxIdsExtension,
34
+ initObjectIdAutoboxExtension('clientId'),
35
+ ],
36
+ },
37
+ app
38
+ );
39
+ };
@@ -0,0 +1,31 @@
1
+ const TransactionTypes = {
2
+ NODE_OPERATOR_REWARD: 'NODE_OPERATOR_REWARD',
3
+ CAO_ISSUING_REWARD: 'CAO_ISSUING_REWARD',
4
+ ISSUER_ISSUING_REWARD: 'ISSUER_ISSUING_REWARD',
5
+ CAO_ISSUING_REWARD_REVERSAL: 'CAO_ISSUING_REWARD_REVERSAL',
6
+ ISSUER_ISSUING_REWARD_REVERSAL: 'ISSUER_ISSUING_REWARD_REVERSAL',
7
+ REDEEMVOUCHER: 'REDEEMVOUCHER',
8
+ REDEEMFIAT: 'REDEEMFIAT',
9
+ REWARD: 'REWARD',
10
+ REVERSAL: 'REVERSAL',
11
+ SELL: 'SELL',
12
+ STAKE: 'STAKE',
13
+ UNSTAKE: 'UNSTAKE',
14
+ HOLD: 'HOLD',
15
+ UNHOLD: 'UNHOLD',
16
+ };
17
+
18
+ const TransactionReasons = {
19
+ NODE_OPERATOR_REWARD: 'NODE_OPERATOR_REWARD',
20
+ CAO_ISSUING_REWARD: 'CAO_ISSUING_REWARD',
21
+ ISSUER_ISSUING_REWARD: 'ISSUER_ISSUING_REWARD',
22
+ CREDIT_SALE: 'CREDIT_SALE',
23
+ COUPON_PURCHASE: 'COUPON_PURCHASE',
24
+ CAO_ISSUING_REWARD_REVERSAL: 'CAO_ISSUING_REWARD_REVERSAL',
25
+ ISSUER_ISSUING_REWARD_REVERSAL: 'ISSUER_ISSUING_REWARD_REVERSAL',
26
+ };
27
+
28
+ module.exports = {
29
+ TransactionTypes,
30
+ TransactionReasons,
31
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ...require('./constants'),
3
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ ...require('./domain'),
3
+ };
@@ -0,0 +1,57 @@
1
+ /*
2
+ * Copyright 2025 Velocity Team
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *
16
+ */
17
+
18
+ /*
19
+ * Copyright 2025 Velocity Team
20
+ *
21
+ * Licensed under the Apache License, Version 2.0 (the "License");
22
+ * you may not use this file except in compliance with the License.
23
+ * You may obtain a copy of the License at
24
+ *
25
+ * http://www.apache.org/licenses/LICENSE-2.0
26
+ *
27
+ * Unless required by applicable law or agreed to in writing, software
28
+ * distributed under the License is distributed on an "AS IS" BASIS,
29
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30
+ * See the License for the specific language governing permissions and
31
+ * limitations under the License.
32
+ *
33
+ */
34
+ const AutoLoad = require('@fastify/autoload');
35
+ const fp = require('fastify-plugin');
36
+ const path = require('path');
37
+
38
+ const eventProcessingEndpoints = async (fastify) =>
39
+ fastify
40
+ .register(AutoLoad, {
41
+ dir: path.join(__dirname, 'entities'),
42
+ indexPattern: /.*repo(\.ts|\.js|\.cjs|\.mjs)$/,
43
+ scriptPattern: /.*repo(\.ts|\.js|\.cjs|\.mjs)$/,
44
+ })
45
+ .register(AutoLoad, {
46
+ dir: path.join(__dirname, 'controllers'),
47
+ indexPattern: /^.*controller(\.ts|\.js|\.cjs|\.mjs)$/,
48
+ scriptPattern: /.*controller(\.ts|\.js|\.cjs|\.mjs)$/,
49
+ routeParams: true,
50
+ autoHooks: true,
51
+ cascadeHooks: true,
52
+ options: { prefix: '/api/v0.6' },
53
+ });
54
+
55
+ module.exports = {
56
+ eventProcessingEndpoints: fp(eventProcessingEndpoints),
57
+ };
@@ -0,0 +1,58 @@
1
+ const { map, forEach } = require('lodash/fp');
2
+ const { initVerificationCoupon } = require('@verii/metadata-registration');
3
+ const { initDocumentFunctions, mapCouponBurned } = require('../helpers');
4
+
5
+ const task = 'coupons-burned-logging';
6
+
7
+ const initReadEventsFromBlock = async (context) => {
8
+ const { config } = context;
9
+ const { pullBurnCouponEvents } = await initVerificationCoupon(
10
+ {
11
+ contractAddress: config.couponContractAddress,
12
+ rpcProvider: context.rpcProvider,
13
+ },
14
+ context
15
+ );
16
+
17
+ return async (block) => {
18
+ return pullBurnCouponEvents(block);
19
+ };
20
+ };
21
+
22
+ const handleCouponsBurnedLoggingEvent = async (context) => {
23
+ const { log } = context;
24
+ const { readLastSuccessfulBlock, writeLastSuccessfulBlock } =
25
+ initDocumentFunctions({ eventName: task }, context);
26
+
27
+ const readEventsFromBlock = await initReadEventsFromBlock(context);
28
+
29
+ const lastReadBlock = await readLastSuccessfulBlock();
30
+
31
+ log.info({ task, lastReadBlock });
32
+
33
+ const { eventsCursor, latestBlock } = await readEventsFromBlock(
34
+ lastReadBlock + 1
35
+ );
36
+
37
+ let numberOfEventsRead = 0;
38
+ for await (const events of eventsCursor()) {
39
+ numberOfEventsRead += events.length;
40
+ const mappedEvents = map((evt) => mapCouponBurned(evt, context), events);
41
+ forEach((event) => {
42
+ log.info(event);
43
+ }, mappedEvents);
44
+ }
45
+
46
+ log.info({
47
+ task,
48
+ lastReadBlock,
49
+ numberOfEventsRead,
50
+ });
51
+
52
+ log.info({ task, latestBlock });
53
+ await writeLastSuccessfulBlock(latestBlock);
54
+ };
55
+
56
+ module.exports = {
57
+ handleCouponsBurnedLoggingEvent,
58
+ };