Skip to content

Commit

Permalink
Merge pull request #106 from windingtree/develop
Browse files Browse the repository at this point in the history
docs: Updated the SDK docs
  • Loading branch information
kostysh authored Mar 26, 2024
2 parents fb3fb64 + 27d52df commit 04e3f7d
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 75 deletions.
60 changes: 0 additions & 60 deletions docs/availability.md

This file was deleted.

6 changes: 4 additions & 2 deletions docs/clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
});
Expand Down
24 changes: 12 additions & 12 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:

Expand Down
121 changes: 121 additions & 0 deletions docs/nodes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
1 change: 0 additions & 1 deletion docs/sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,4 @@
- [Clients](clients.md)
- [Nodes](nodes.md)
- [Storage](storage.md)
- [Availability management](availability.md)
- [Contribution](contribution.md)

0 comments on commit 04e3f7d

Please sign in to comment.