Skip to content

Commit f8927af

Browse files
committed
refactor: 💡 NodeRequestMnager extracted from Node class
1 parent 61e48fc commit f8927af

File tree

2 files changed

+141
-90
lines changed

2 files changed

+141
-90
lines changed

‎examples/node/index.ts

Lines changed: 69 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,16 @@ import {
1111
stableCoins,
1212
serverAddress,
1313
} from '../shared/index.js';
14-
import { createNode, Node, NodeOptions, Queue, createJobHandler } from '../../src/index.js';
14+
import {
15+
Node,
16+
NodeOptions,
17+
NodeRequestManager,
18+
Queue,
19+
createNode,
20+
createJobHandler,
21+
} from '../../src/index.js';
1522
import { OfferData } from '../../src/shared/types.js';
16-
import { DealStatus } from '../../src/shared/contracts.js';
23+
import { DealStatus, ProtocolContracts } from '../../src/shared/contracts.js';
1724
import { noncePeriod } from '../../src/constants.js';
1825
import { memoryStorage } from '../../src/storage/index.js';
1926
import { nowSec, parseSeconds } from '../../src/utils/time.js';
@@ -34,7 +41,9 @@ const signerMnemonic = process.env.EXAMPLE_ENTITY_SIGNER_MNEMONIC;
3441
const signerPk = process.env.EXAMPLE_ENTITY_SIGNER_PK as Hex;
3542

3643
if (!signerMnemonic && !signerPk) {
37-
throw new Error('Either signerMnemonic or signerPk must be provided with env');
44+
throw new Error(
45+
'Either signerMnemonic or signerPk must be provided with env',
46+
);
3847
}
3948

4049
/**
@@ -58,38 +67,42 @@ process.once('unhandledRejection', (error) => {
5867
* This is interface of object that you want to pass to the job handler as options
5968
*/
6069
interface DealHandlerOptions {
61-
node: Node<RequestQuery, OfferOptions>;
62-
[key: string]: unknown;
70+
contracts: ProtocolContracts;
6371
}
6472

6573
/**
6674
* This handler looking up for a deal
6775
*/
68-
const dealHandler = createJobHandler<OfferData<RequestQuery, OfferOptions>, DealHandlerOptions>(
69-
async ({ name, id, data: offer }, { node }) => {
70-
logger.trace(`Job "${name}" #${id} Checking for a deal. Offer #${offer.id}`);
76+
const dealHandler = createJobHandler<
77+
OfferData<RequestQuery, OfferOptions>,
78+
DealHandlerOptions
79+
>(async ({ name, id, data: offer }, { contracts }) => {
80+
logger.trace(`Job "${name}" #${id} Checking for a deal. Offer #${offer.id}`);
7181

72-
if (node) {
73-
// Check for a deal
74-
const [, , , buyer, , , status] = await node.deals.get(offer);
82+
// Check for a deal
83+
const [, , , buyer, , , status] = await contracts.getDeal(offer);
7584

76-
// Deal must be exists and not cancelled
77-
if (buyer !== zeroAddress && status === DealStatus.Created) {
78-
// check for double booking in the availability system
79-
// If double booking detected - rejects (and refunds) the deal
85+
// Deal must be exists and not cancelled
86+
if (buyer !== zeroAddress && status === DealStatus.Created) {
87+
// check for double booking in the availability system
88+
// If double booking detected - rejects (and refunds) the deal
8089

81-
// If not detected - claims the deal
82-
await node.deals.claim(offer, undefined, (txHash: string, txSubj?: string) => {
83-
logger.trace(`Offer #${offer.payload.id} ${txSubj ?? 'claim'} tx hash: ${txHash}`);
84-
});
90+
// If not detected - claims the deal
91+
await contracts.claimDeal(
92+
offer,
93+
undefined,
94+
(txHash: string, txSubj?: string) => {
95+
logger.trace(
96+
`Offer #${offer.payload.id} ${txSubj ?? 'claim'} tx hash: ${txHash}`,
97+
);
98+
},
99+
);
85100

86-
return true; // Returning true means that the job must be stopped
87-
}
88-
}
101+
return true; // Returning true means that the job must be stopped
102+
}
89103

90-
return; // Job continuing
91-
},
92-
);
104+
return; // Job continuing
105+
});
93106

94107
/**
95108
* This handler creates offer then publishes it and creates a job for deal handling
@@ -103,7 +116,7 @@ const createRequestsHandler =
103116
const handler = async () => {
104117
logger.trace(`📨 Request on topic #${detail.topic}:`, detail.data);
105118

106-
const offer = await node.buildOffer({
119+
const offer = await node.makeOffer({
107120
/** Offer expiration time */
108121
expire: '15m',
109122
/** Copy of request */
@@ -165,28 +178,17 @@ const createRequestsHandler =
165178
* @returns {Promise<void>}
166179
*/
167180
const main = async (): Promise<void> => {
168-
const storage = await memoryStorage.createInitializer()();
169-
170-
const queue = new Queue({
171-
storage,
172-
hashKey: 'jobs',
173-
concurrentJobsNumber: 3,
174-
});
175-
176181
const options: NodeOptions = {
177182
topics: ['hello'],
178183
chain,
179184
contracts: contractsConfig,
180185
serverAddress,
181-
noncePeriod: Number(parseSeconds(noncePeriod)),
182186
supplierId,
183187
signerSeedPhrase: signerMnemonic,
184188
signerPk: signerPk,
185189
};
186190
const node = createNode<RequestQuery, OfferOptions>(options);
187191

188-
queue.addJobHandler('deal', dealHandler({ node }));
189-
190192
node.addEventListener('start', () => {
191193
logger.trace('🚀 Node started at', new Date().toISOString());
192194
});
@@ -199,7 +201,36 @@ const main = async (): Promise<void> => {
199201
logger.trace('👋 Node stopped at:', new Date().toISOString());
200202
});
201203

202-
node.addEventListener('request', createRequestsHandler(node, queue));
204+
const contractsManager = new ProtocolContracts({
205+
contracts: contractsConfig,
206+
publicClient: node.publicClient,
207+
walletClient: node.walletClient,
208+
});
209+
210+
const storage = await memoryStorage.createInitializer()();
211+
212+
const queue = new Queue({
213+
storage,
214+
hashKey: 'jobs',
215+
concurrentJobsNumber: 3,
216+
});
217+
218+
const requestManager = new NodeRequestManager<RequestQuery>({
219+
noncePeriod: Number(parseSeconds(noncePeriod)),
220+
});
221+
222+
requestManager.addEventListener(
223+
'request',
224+
createRequestsHandler(node, queue),
225+
);
226+
227+
node.addEventListener('message', (e) => {
228+
const { topic, data } = e.detail;
229+
// here you are able to pre-validate arrived messages
230+
requestManager.add(topic, data);
231+
});
232+
233+
queue.addJobHandler('deal', dealHandler({ contracts: contractsManager }));
203234

204235
/**
205236
* Graceful Shutdown handler

0 commit comments

Comments
 (0)