Skip to content

New libp2p version, new Queue #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ on:
push:
branches:
- develop
pull_request:
branches:
- develop
jobs:
test:
name: Test
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ temp
coverage
typedoc
typechain

#ide
.idea
41 changes: 29 additions & 12 deletions examples/client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ export const App = () => {
const requestsManager = useRef<
ClientRequestsManager<RequestQuery, OfferOptions> | undefined
>();
const dealsManager = useRef<ClientDealsManager<
RequestQuery,
OfferOptions
>>();
const dealsManager = useRef<ClientDealsManager<RequestQuery, OfferOptions>>();
const { publicClient } = useWallet();
const [connected, setConnected] = useState<boolean>(false);
const [selectedTab, setSelectedTab] = useState<number>(0);
Expand Down Expand Up @@ -105,19 +102,27 @@ export const App = () => {
);
};

const onRequestSubscribe: EventHandler<CustomEvent<ClientRequestRecord>> = ({ detail }) => {
const onRequestSubscribe: EventHandler<
CustomEvent<ClientRequestRecord>
> = ({ detail }) => {
client.current?.subscribe(detail.data.id);
};

const onRequestUnsubscribe: EventHandler<CustomEvent<ClientRequestRecord>> = ({ detail }) => {
const onRequestUnsubscribe: EventHandler<
CustomEvent<ClientRequestRecord>
> = ({ detail }) => {
client.current?.unsubscribe(detail.data.id);
};

const onRequestPublish: EventHandler<CustomEvent<RequestData<RequestQuery>>> = ({ detail }) => {
const onRequestPublish: EventHandler<
CustomEvent<RequestData<RequestQuery>>
> = ({ detail }) => {
requestsManager.current?.add(detail);
};

const onOffer: EventHandler<CustomEvent<OfferData<RequestQuery, OfferOptions>>> = ({ detail }) => {
const onOffer: EventHandler<
CustomEvent<OfferData<RequestQuery, OfferOptions>>
> = ({ detail }) => {
requestsManager.current?.addOffer(detail);
};

Expand Down Expand Up @@ -168,8 +173,14 @@ export const App = () => {
requestsManager.current.addEventListener('delete', updateRequests);
requestsManager.current.addEventListener('clear', updateRequests);
requestsManager.current.addEventListener('offer', updateRequests);
requestsManager.current.addEventListener('subscribe', onRequestSubscribe);
requestsManager.current.addEventListener('unsubscribe', onRequestUnsubscribe);
requestsManager.current.addEventListener(
'subscribe',
onRequestSubscribe,
);
requestsManager.current.addEventListener(
'unsubscribe',
onRequestUnsubscribe,
);

dealsManager.current.addEventListener('changed', updateDeals);

Expand Down Expand Up @@ -200,8 +211,14 @@ export const App = () => {
requestsManager.current?.removeEventListener('delete', updateRequests);
requestsManager.current?.removeEventListener('clear', updateRequests);
requestsManager.current?.removeEventListener('offer', updateRequests);
requestsManager.current?.removeEventListener('subscribe', onRequestSubscribe);
requestsManager.current?.removeEventListener('unsubscribe', onRequestUnsubscribe);
requestsManager.current?.removeEventListener(
'subscribe',
onRequestSubscribe,
);
requestsManager.current?.removeEventListener(
'unsubscribe',
onRequestUnsubscribe,
);

dealsManager.current?.removeEventListener('changed', updateDeals);

Expand Down
28 changes: 9 additions & 19 deletions examples/client/src/components/Deals.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { useState, useCallback, useEffect } from 'react';
import { DateTime } from 'luxon';
import { Address } from 'viem';
import { ClientDealsManager, DealRecord, DealStatus } from '../../../../src/index.js'; // @windingtree/sdk
import {
ClientDealsManager,
DealRecord,
DealStatus,
} from '../../../../src/index.js'; // @windingtree/sdk
import { RequestQuery, OfferOptions } from '../../../shared/index.js';
import { centerEllipsis, formatBalance, parseWalletError } from '../utils.js';
import { useWallet } from '../providers/WalletProvider/WalletProviderContext.js';
Expand All @@ -12,27 +16,18 @@ export type DealsRegistryRecord = Required<

export interface DealsProps {
deals: DealsRegistryRecord[];
manager?: ClientDealsManager<
RequestQuery,
OfferOptions
>;
manager?: ClientDealsManager<RequestQuery, OfferOptions>;
}

export interface TransferFormProps {
deal?: DealsRegistryRecord;
manager?: ClientDealsManager<
RequestQuery,
OfferOptions
>;
manager?: ClientDealsManager<RequestQuery, OfferOptions>;
onClose: () => void;
}

export interface CancelProps {
deal?: DealsRegistryRecord;
manager?: ClientDealsManager<
RequestQuery,
OfferOptions
>;
manager?: ClientDealsManager<RequestQuery, OfferOptions>;
onClose: () => void;
}

Expand Down Expand Up @@ -68,12 +63,7 @@ export const TransferForm = ({ deal, manager, onClose }: TransferFormProps) => {
throw new Error('Ethereum client not ready');
}

await manager.transfer(
deal.offer,
to as Address,
walletClient,
setTx,
);
await manager.transfer(deal.offer, to as Address, walletClient, setTx);
setLoading(false);
setSuccess(true);
} catch (err) {
Expand Down
13 changes: 2 additions & 11 deletions examples/client/src/components/MakeDeal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ import { ConnectButton } from '../providers/WalletProvider/ConnectButton.js';

interface MakeDealProps {
offer?: OfferData<RequestQuery, OfferOptions>;
manager?: ClientDealsManager<
RequestQuery,
OfferOptions
>;
manager?: ClientDealsManager<RequestQuery, OfferOptions>;
}

/**
Expand Down Expand Up @@ -56,13 +53,7 @@ export const MakeDeal = ({ offer, manager }: MakeDealProps) => {
throw new Error('Invalid deal configuration');
}

await manager.create(
offer,
paymentId,
ZeroHash,
walletClient,
setTx,
);
await manager.create(offer, paymentId, ZeroHash, walletClient, setTx);
setLoading(false);
setSuccess(true);
} catch (err) {
Expand Down
45 changes: 33 additions & 12 deletions examples/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import {
NodeOptions,
NodeRequestManager,
Queue,
JobHandler,
createNode,
createJobHandler,
} from '../../src/index.js';
import { OfferData } from '../../src/shared/types.js';
import { DealStatus, ProtocolContracts } from '../../src/shared/contracts.js';
Expand Down Expand Up @@ -63,6 +63,14 @@ process.once('unhandledRejection', (error) => {
process.exit(1);
});

const createJobHandler =
<JobData = unknown, HandlerOptions = unknown>(
handler: JobHandler<JobData, HandlerOptions>,
) =>
(options: HandlerOptions = {} as HandlerOptions) =>
(data: JobData) =>
handler(data, options);

/**
* This is interface of object that you want to pass to the job handler as options
*/
Expand All @@ -76,8 +84,18 @@ interface DealHandlerOptions {
const dealHandler = createJobHandler<
OfferData<RequestQuery, OfferOptions>,
DealHandlerOptions
>(async ({ name, id, data: offer }, { contracts }) => {
logger.trace(`Job "${name}" #${id} Checking for a deal. Offer #${offer.id}`);
>(async (offer, options) => {
if (!offer || !options) {
throw new Error('Invalid job execution configuration');
}

const { contracts } = options;

if (!contracts) {
throw new Error('Contracts manager must be provided to job handler config');
}

logger.trace(`Checking for a deal. Offer #${offer.id}`);

// Check for a deal
const [, , , buyer, , , status] = await contracts.getDeal(offer);
Expand All @@ -98,10 +116,10 @@ const dealHandler = createJobHandler<
},
);

return true; // Returning true means that the job must be stopped
return false; // Returning true means that the job must be stopped
}

return; // Job continuing
return true; // Job continuing
});

/**
Expand Down Expand Up @@ -155,17 +173,20 @@ const createRequestsHandler =
checkOut: BigInt(nowSec() + 2000),
});

queue.addEventListener('expired', ({ detail: job }) => {
logger.trace(`Job #${job.id} is expired`);
queue.addEventListener('status', ({ detail: job }) => {
logger.trace(`Job #${job.id} status changed`, job);
});

/**
* On every published offer we expecting a deal.
* So, we add a job for detection of deals
*/
queue.addJob('deal', offer, {
queue.add({
handlerName: 'deal',
data: offer,
isRecurrent: true,
recurrenceInterval: 5000,
expire: Number(offer.expire),
every: 5000, // 5 sec
});
};

Expand Down Expand Up @@ -211,8 +232,8 @@ const main = async (): Promise<void> => {

const queue = new Queue({
storage,
hashKey: 'jobs',
concurrentJobsNumber: 3,
idsKeyName: 'jobsIds',
concurrencyLimit: 3,
});

const requestManager = new NodeRequestManager<RequestQuery>({
Expand All @@ -234,7 +255,7 @@ const main = async (): Promise<void> => {
requestManager.add(topic, data);
});

queue.addJobHandler('deal', dealHandler({ contracts: contractsManager }));
queue.registerHandler('deal', dealHandler({ contracts: contractsManager }));

/**
* Graceful Shutdown handler
Expand Down
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,12 @@
"dotenv": "^16.1.4"
},
"dependencies": {
"libp2p": "^0.43.3",
"@chainsafe/libp2p-noise": "^11.0.4",
"@chainsafe/libp2p-gossipsub": "^6.2.0",
"@libp2p/mplex": "^7.1.3",
"@libp2p/websockets": "^5.0.8",
"libp2p": "^0.45.9",
"@chainsafe/libp2p-gossipsub": "^8.0.0",
"@chainsafe/libp2p-noise": "^12.0.1",
"@chainsafe/libp2p-yamux": "^4.0.2",
"@libp2p/mplex": "^8.0.3",
"@libp2p/websockets": "^6.0.3",
"ethers": "^6.4.0",
"viem": "^1.0.7",
"luxon": "^3.3.0",
Expand Down
Loading