diff --git a/docs/availability.md b/docs/availability.md deleted file mode 100644 index 29074f8..0000000 --- a/docs/availability.md +++ /dev/null @@ -1,60 +0,0 @@ -# Availability Management - -> **Note**: This functionality is not implemented yet. Use these guidelines to review potential future features. - -Supplier's services availability management is not a part of the protocol, but the information from such systems is the foundation of offer generation. Every offer should represent the availability of a service to the buyer. - -The following are common use cases of availability management systems that can be implemented within the protocol: - -- **Availability Lookup**: Allows searching for available services. -- **Temporary Locking**: Allows locking an available service to prevent double booking. -- **Booking/Selling**: Allows booking or selling the service and making it unavailable according to the supplier's use case logic. -- **Change**: Allows changing a booked service. -- **Canceling**: Allows canceling an already booked service. - -The protocol's supplier node instances have tools that automate access and communication with external availability management systems. To support the aforementioned use cases, the node configuration has special options to define callback functions. - -```typescript -import { GenericQuery, GenericAvailabilityResponse, GenericAvailabilityLockQuery, GenericAvailabilityBookQuery, GenericAvailabilityCancelQuery, NodeOptions, createNode } from '@windingtree/sdk'; - -interface AvailabilityManagerApiOptions { - async lookup(query: RequestQuery): Promise; - async lock(query: LockQuery): Promise; - async unlock(query: LockQuery): Promise; - async book(query: BookQuery): Promise; - async change(query: BookQuery): Promise; - async cancel(query: CancelQuery): Promise; -} - -interface AvailabilityManagerOptions { - lockPeriod: number; // temporary locking time in seconds - api: AvailabilityManagerApiOptions; -} - -// Your set of custom callbacks -const lookup = async (query: RequestQuery): Promise => {/**/}; -const lock = async (query: LockQuery): Promise => {/**/}; -const unlock = async (query: LockQuery): Promise => {/**/}; -const book = async (query: BookQuery): Promise => {/**/}; -const change = async (query: BookQuery): Promise => {/**/}; -const cancel = async (query: CancelQuery): Promise {/**/}; - -// The supplier node configuration -const options: NodeOptions = { - /* other options */ - availabilityManager: { - lockPeriod: 60 * 30, // 30 min - api: { - lock, - unlock, - book, - change, - cancel, - } - }, -}; - -const node = createNode(options); -``` - -Once the properly configured node is started, the registered API functions become available under `node.availabilityManager`. These API functions can then be used to manage the availability of services and support various availability-related use cases within the WindingTree market protocol. diff --git a/docs/clients.md b/docs/clients.md index 905a1b9..8bab3e6 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -32,10 +32,12 @@ Next, we need to create industry-specific TypeScript types for the requests data ```typescript import { GenericQuery, GenericOfferOptions } from '@windingtree/sdk-types'; +// A request model export interface RequestQuery extends GenericQuery { greeting: string; // This is a very simple request, just for testing } +// An offer options model export interface OfferOptions extends GenericOfferOptions { date?: string; buongiorno: boolean; // Yes, we expect that a supplier may propose us a good day @@ -104,7 +106,7 @@ Now we are able to instantiate managers. ```typescript import { ClientRequestsManager, ClientDealsManager } from '@windingtree/sdk-client'; -import { polygonZkEvmTestnet } from 'viem/chains'; +import { gnosisChiado } from 'viem/chains'; const requestsManager = new ClientRequestsManager< RequestQuery, @@ -121,7 +123,7 @@ const dealsManager = new ClientDealsManager< storage: store, prefix: 'wt_deals_', checkInterval: '5s', // Interval for deal state change check - chain: polygonZkEvmTestnet, // Target blockchain network we will use + chain: gnosisChiado, // Target blockchain network we will use contracts: contractsConfig, publicClient, // See https://viem.sh/docs/clients/public.html }); diff --git a/docs/index.md b/docs/index.md index 2ec13bd..6aab2cc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,21 +4,21 @@ The WindingTree Market Protocol facilitates coordination and deal management for buyers and sellers. This SDK provides essential software tools to configure and construct the protocol actors, streamlining the implementation of its workflow. For a comprehensive understanding of the protocol's operation, explore the detailed documentation available at this [link](/docs/protocol.md). -## Protocol Smart Contracts - Polygon zkEVM +## Protocol Smart Contracts - Gnosis Chiado ### Smart Contract Instances -- Config: [0x098b1d12cAfE7315C77b6d308A62ce02806260Ee](https://explorer.public.zkevm-test.net/address/0x098b1d12cAfE7315C77b6d308A62ce02806260Ee/read-proxy#address-tabs) - Protocol configuration smart contract -- EntitiesRegistry: [0x4bB51528C83844b509E1152EEb05260eE1bf60e6](https://explorer.public.zkevm-test.net/address/0x4bB51528C83844b509E1152EEb05260eE1bf60e6/read-proxy#address-tabs) - Protocol identity management -- Market: [0xDd5B6ffB3585E109ECddec5293e31cdc1e9DeD57](https://explorer.public.zkevm-test.net/address/0xDd5B6ffB3585E109ECddec5293e31cdc1e9DeD57/read-proxy#address-tabs) - Protocol entry point -- LIF: [0x4d60F4483BaA654CdAF1c5734D9E6B16735efCF8](https://explorer.public.zkevm-test.net/address/0x4d60F4483BaA654CdAF1c5734D9E6B16735efCF8/read-proxy#address-tabs) - Test version of LIF token +- Config ([0x4556d5C1486d799f67FA96c84F1d0552486CAAF4](https://gnosis-chiado.blockscout.com/address/0x4556d5C1486d799f67FA96c84F1d0552486CAAF4?tab=read_proxy)): the protocol configuration smart contract +- EntitiesRegistry ([0x4EcB659060Da61D795D777bb21BAe3599b301C66](https://gnosis-chiado.blockscout.com/address/0x4EcB659060Da61D795D777bb21BAe3599b301C66?tab=read_proxy)): the protocol identity management +- Market ([0xF54784206A53EF19fd3024D8cdc7A6251A4A0d67](https://gnosis-chiado.blockscout.com/address/0xF54784206A53EF19fd3024D8cdc7A6251A4A0d67?tab=read_proxy)): the protocol entry point +- LIF ([0x8CB96383609C56af1Fe44DB7591F94AEE2fa43b2](https://gnosis-chiado.blockscout.com/address/0x8CB96383609C56af1Fe44DB7591F94AEE2fa43b2?tab=read_proxy)): Test version of LIF token -### Testing Tokens +#### Testing tokens -- `STABLE6`: [ERC20, 6 decimals, no permit](https://explorer.public.zkevm-test.net/address/0x8CB96383609C56af1Fe44DB7591F94AEE2fa43b2/read-proxy#address-tabs) -- `STABLE6PERMIT`: [ERC20, 6 decimals, with permit](https://explorer.public.zkevm-test.net/address/0x4556d5C1486d799f67FA96c84F1d0552486CAAF4/read-proxy#address-tabs) -- `STABLE18`: [ERC20, 18 decimals, no permit](https://explorer.public.zkevm-test.net/address/0x4EcB659060Da61D795D777bb21BAe3599b301C66/read-proxy#address-tabs) -- `STABLE18PERMIT`: [ERC20, 18 decimals, with permit](https://explorer.public.zkevm-test.net/address/0xF54784206A53EF19fd3024D8cdc7A6251A4A0d67/read-proxy#address-tabs) +- `STABLE6`: [ERC20, 6 decimals, no permit](https://gnosis-chiado.blockscout.com/address/0xcC28A4e6DEF318A1b88CF34c4F2Eeb2489995513?tab=read_proxy) +- `STABLE6PERMIT`: [ERC20, 6 decimals, with permit](https://gnosis-chiado.blockscout.com/address/0x78F924A7C70213D502E6110567AC556c2EFBBF73?tab=read_proxy) +- `STABLE18`: [ERC20, 18 decimals, no permit](https://gnosis-chiado.blockscout.com/address/0x7067fC74fFCf4096796454747461D098E6bF7241?tab=read_proxy) +- `STABLE18PERMIT`: [ERC20, 18 decimals, with permit](https://gnosis-chiado.blockscout.com/address/0x44947d69A9F06EF48170BD41Da9B27E74ecd0891?tab=read_proxy) ## Protocol Addresses @@ -53,10 +53,10 @@ Once you have generated a peer key for your server, you can create a server addr To generate a server address, use the following script: ```bash -pnpm gen:address --ip 127.0.0.1 --port 3333 --id QmQkjfoGnUGdq...8o75N89opSfgBeM +pnpm gen:address --env local --id QmXH7wT21maJx9TrAk3neP45CeD3X5E8QnPLUH6AEYFxRt --address 127.0.0.1 --port 33333 ``` -The resulting server address will have the format: `/ip4/127.0.0.1/tcp/3333/ws/p2p/QmQkjfoGnUGdq...8o75N89opSfgBeM`. +The resulting server address will have the format: `/ip4/127.0.0.1/tcp/33333/ws/p2p/QmXH7wT21maJx9TrAk3neP45CeD3X5E8QnPLUH6AEYFxRt`. The address components are as follows: diff --git a/docs/nodes.md b/docs/nodes.md index 3da41ca..868a275 100644 --- a/docs/nodes.md +++ b/docs/nodes.md @@ -322,6 +322,29 @@ With the `ProtocolContracts` utility, you have a powerful tool to work with the Tasks for checking deal state changes can be implemented in the same way as monitoring the creation of deals (requests processing). For more details, refer to the previous section on "Requests Processing." +Also, monitoring the status of deals can be performed using the `subscribeMarket` method of the `ProtocolContracts` class. Here is a brief example: + +```typescript +interface StatusEventLog { + offerId?: `0x${string}` | undefined; + status?: DealStatus | number | undefined; + sender?: `0x${string}` | undefined; +}; + +const unsubscribe = contractsManager.subscribeMarket( + 'Status', // Event name + async (logs, maxBlockNumber) => { + // Process logs here + logs.forEach((log) => { + const { offerId, status } = log.args as StatusEventLog; + // ... + }); + // Save `maxBlockNumber` for later use eq re-subscription + }, + blockNumber, // Block number to listen from (0 by default) + ); +``` + With this information, you have a better understanding of how to configure the supplier node, manage incoming requests, build and publish offers, and handle deal state changes. ## The Node Management API @@ -370,6 +393,104 @@ const apiServer = new NodeApiServer({ apiServer.start(appRouter); ``` +### Extending the Node API + +You can add your custom routes to the Node API. When creating API routes for your application, following specific guidelines can facilitate the development, maintenance, and use of your API. Below a guide for creating API routes: + +#### 1. **Structure of Routes** + +- **Naming**: Name your routes in a way that clearly reflects the actions they perform and the resources they handle. For example, use `add`, `update`, `delete`, `get`, and `getAll` for operations related to airplanes. +- **Grouping**: Organize routes into logical groups. In the example, all routes are grouped under `airplanesRouter`, which simplifies understanding their purpose. + +```typescript +export const airplanesRouter = router({ + add: authAdminProcedure + // Implementation... + update: authAdminProcedure + // Implementation... + delete: authAdminProcedure + // Implementation... + get: authProcedure + // Implementation... + getAll: authProcedure + // Implementation... +}); +``` + +#### 2. **Authentication and Authorization** + +- Differentiate access levels for different operations. In the example, `authProcedure` is used for basic authentication and `authAdminProcedure` for operations requiring admin rights. +- Explicitly specify authentication and authorization requirements for each route. + +#### 3. **Input Validation** + +- Use validation libraries, such as `zod`, to ensure inputs match expected types and formats. This helps prevent errors and vulnerabilities. +- Define schemas for input data, like `AirplaneInputSchema` and `AirplaneUpdateSchema`, and use them in route procedures. + +```typescript +.add: authAdminProcedure + .input(AirplaneInputSchema) + .mutation(async ({ input, ctx }) => { + // Implementation... + }), +``` + +#### 4. **Error Handling** + +- Handle exceptions and errors within each route to return understandable error messages. +- Use standardized HTTP error codes, such as `BAD_REQUEST` for validation errors and `NOT_FOUND` for missing resources. + +```typescript +.mutation(async ({ input, ctx }) => { + try { + // Operation... + } catch (error) { + throw new TRPCError({ + code: 'BAD_REQUEST', + message: (error as Error).message, + }); + } +}), +``` + +#### 5. **Logging** + +- Log key operations and errors. This facilitates debugging and monitoring your API. +- Use a created logger, such as `logger`, to record events. + +```typescript +logger.trace(`Airplane ${input.name} registered with id ${id}`); +``` + +#### Integrate Your Custom Route Into the Node API + +The following code snippet demonstrates how to set up and start a Node API server using the `@windingtree/sdk-node-api/server` package, integrating multiple routers for different parts of an application. It includes default routers like `adminRouter`, `dealsRouter`, `serviceRouter`, and `userRouter` provided by the `@windingtree/sdk-node-api/router` package, **along with a custom router defined by the developer (`customRouter`)**. The code creates a combined router that aggregates these individual routers under specific namespaces, making it easier to manage and organize routes according to their functionality. Finally, the code initializes a `NodeApiServer` instance with optional server configuration (`apiServerConfig`) and starts the server with the combined router, making the API ready to handle requests. This approach facilitates the modular development of API services, allowing for scalability and ease of maintenance. + +```typescript +import { NodeApiServer, router } from '@windingtree/sdk-node-api/server'; +import { + adminRouter, + dealsRouter, + serviceRouter, + userRouter, +} from '@windingtree/sdk-node-api/router'; +import { customRouter } from '../api/customRoute.js'; + +// Create the combined router +const appRouter = router({ + service: serviceRouter, // Default route + admin: adminRouter, // Default route + user: userRouter, // Default route + deals: dealsRouter, // Default route + custom: customRouter, // Your custom router +}); + +// Create the Node API server +const apiServer = new NodeApiServer({ /* apiServerConfig */ }); + +apiServer.start(appRouter); // Initialize the combined router +``` + ### Remote Node API Usage Here's a simple example of how to use the `@windingtree/sdk-node-api/client` in a React application: diff --git a/docs/sidebar.md b/docs/sidebar.md index d3af0d4..7969d3c 100644 --- a/docs/sidebar.md +++ b/docs/sidebar.md @@ -6,5 +6,4 @@ - [Clients](clients.md) - [Nodes](nodes.md) - [Storage](storage.md) -- [Availability management](availability.md) - [Contribution](contribution.md)