Skip to content

Commit

Permalink
update: api ledger doc
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreaDiazCorreia committed Dec 7, 2023
1 parent 7462ff8 commit 05dc7fb
Show file tree
Hide file tree
Showing 14 changed files with 290 additions and 3 deletions.
3 changes: 1 addition & 2 deletions pages/wallet-provider/ledger/_meta.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"index" : "Intro",
"api": "API",
"models": "Models",
"events": "Events"
"models": "Models"
}
8 changes: 8 additions & 0 deletions pages/wallet-provider/ledger/api/_meta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"lib" : "Lib",
"events": "Nostr Events",
"services": "Services",
"type": "Type",
"serverConfiguration": "Server Configuration"
}

74 changes: 74 additions & 0 deletions pages/wallet-provider/ledger/api/lib.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Lib

The `lib` folder contains various modules and utilities essential for the operation of the `Ledger` module. Below are the main files and folders:

## `events.ts`

The `events.ts` file defines functions for creating custom Nostr events. These events are crucial for communicating transactions and states to the Nostr system. Here are some key functions:

### `txOkEvent(tx: ITransaction): NostrEvent`

Creates a Nostr event after successfully processing a transaction.

```typescript
const tx = { /* ... */ };
const nostrEvent = txOkEvent(tx);
```

## `lastHandled.ts`

The `lastHandled.ts` file contains a `LastHandledTracker` class that keeps track of the most recent handled Nostr events. This is essential to avoid duplicate event processing. Here's how to use it:

### `LastHandledTracker`

```typescript
const tracker = new LastHandledTracker(readNDK, writeNDK, ['handler1', 'handler2']);
await tracker.fetchLastHandled();
```

## `transactions.ts`

The `transactions.ts` file defines functions and types related to transactions. Some key functions include:

### `getTxHandler(ctx: Context, ntry: number, txType: TransactionType, handler: Function)`

Creates an event handler for a specific transaction.

```typescript
const handler = getTxHandler(ctx, 0, TransactionType.INBOUND, myTransactionHandler);
```

## `utils.ts`

The utils.ts file contains general-purpose functions and utilities used throughout the module. Some of the functions include:

### `setUpRoutes(router: Router, path: string): Router`

Configures Express router paths based on files in a specific location.

```typescript
const router = express.Router();
setUpRoutes(router, './routes');
```

## Middlewares

The middlewares folder contains common middleware functions. Some of them are:

### `error.middleware.ts`

```typescript
import { errorHandler } from '@lib/middlewares/error.middleware';

app.use(errorHandler);

```

### `not-found.middleware.ts`

```typescript
import { notFound } from '@lib/middlewares/not-found.middleware';

app.use(notFound);
```

29 changes: 29 additions & 0 deletions pages/wallet-provider/ledger/api/serverConfiguration.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Server Configuration Guide

This guide provides an overview of the server configuration and startup process in the application. It covers key files such as `app.ts` and `index.ts` that play a crucial role in setting up the Express server, connecting to external services, and initializing critical components.

## `app.ts`

`app.ts` serves as the central configuration file for the Express server. It initializes key middleware and sets up security headers, logging, and CORS handling. This file plays a crucial role in defining how the server processes incoming requests and enhances security and development experience through various middleware.

Key Features:
- Initialization of Express application.
- Configuration of logging using Morgan.
- Security enhancements through Helmet middleware.
- JSON body parsing using `express.json()`.
- Cross-Origin Resource Sharing (CORS) configuration.

This file provides a consolidated view of the middleware stack and server setup.

## `index.ts`

`index.ts` acts as the main entry point of the application. It imports and executes the necessary logic to start the server, connect to databases, and set up routes. This file plays a critical role in launching the application and initializing key components.

Key Features:
- Importing and executing server setup logic from `app.ts`.
- Handling environment variable configurations.
- Connecting to databases or external services (e.g., Nostr and Prisma).
- Setting up routes and error handling middleware.
- Starting the Express server to handle incoming requests.

This file provides an overview of the application's startup process and critical dependencies.
5 changes: 5 additions & 0 deletions pages/wallet-provider/ledger/api/services/_meta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"ndk" : "NDK",
"outbox": "Outbox Service",
"prisma": "Prisma Service"
}
36 changes: 36 additions & 0 deletions pages/wallet-provider/ledger/api/services/ndk.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
## NDK Service

This service module provides functions for managing NDK (Nostr Development Kit) instances.

### Functions:

#### `getReadNDK()`

Returns the NDK instance for fetching events from relays. Creates it if it does not exist.

#### `getWriteNDK()`

Returns the NDK instance for publishing events to the relay. Creates it if it does not exist.

#### `getSignerNDK()`

Returns an NDK instance with a private key signer.

#### `connectToTempRelays(relayUrls: string[], ndk: NDK): NDKRelaySet`

Returns a set of connected relays for publishing. Reuses connections to known relays.

### Usage Example:

```typescript
import { getReadNDK, getWriteNDK, connectToTempRelays } from '@services/ndk';
import NDKRelaySet from '@nostr-dev-kit/ndk';

const readNDK = getReadNDK();
const writeNDK = getWriteNDK();
const relayUrls = ['https://relay1.com', 'https://relay2.com'];

const relaySet = connectToTempRelays(relayUrls, readNDK);

// Use readNDK, writeNDK, and relaySet as needed
```
35 changes: 35 additions & 0 deletions pages/wallet-provider/ledger/api/services/outbox.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
## Outbox Service

This service module provides an `OutboxService` class for publishing events using NDK.

### Classes:

#### `OutboxService`

- **Constructor:** `constructor(ndk: NDK)`

Creates an instance of `OutboxService` with the provided NDK instance.

- **Method:** `publish(event: NostrEvent, relaySet?: NDKRelaySet): Promise<void>`

Publishes a Nostr event using the NDK instance and an optional relay set.

### Usage Example:

```typescript
import { OutboxService } from '@services/outbox';
import NDK from '@nostr-dev-kit/ndk';

const ndk = new NDK();
const outboxService = new OutboxService(ndk);

const event = {
content: 'Event content',
created_at: Date.now(),
// Other event properties...
};

outboxService.publish(event)
.then(() => console.log('Event published successfully'))
.catch((error) => console.error('Error publishing event', error));
```
21 changes: 21 additions & 0 deletions pages/wallet-provider/ledger/api/services/prisma.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
## Prisma Service

This service module provides a function for managing the Prisma client instance.

### Functions:

#### `getPrisma(): PrismaClient`

Returns the Prisma client instance. Creates it if it does not exist.

### Usage Example:

```typescript
import { getPrisma } from '@services/prisma';
import { PrismaClient } from '@prisma/client';

const prisma: PrismaClient = getPrisma();

// Use prisma as needed for database operations

```
80 changes: 80 additions & 0 deletions pages/wallet-provider/ledger/api/type.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Type

The type folder contains TypeScript type definitions, contracts, and interfaces that play a crucial role in ensuring type safety and well-defined data structures throughout the project.

## Error Response Contract

This contract defines the structure of an error response, extending the `MessageResponseContract`.

### Properties:

- **`message`** (string): The error message.
- **`stack`** (string, optional): The stack trace associated with the error.

### Usage Example:

```typescript
import { ErrorResponseContract } from '@types/responses/error-response.contract';

const errorResponse: ErrorResponseContract = {
message: 'An error occurred',
stack: 'Error stack trace...',
};

// Use errorResponse as needed
```

## Message Response Contract

This contract defines the structure of a generic message response.

### Properties:

- **`message`** (string): The message content.

### Usage Example:

```typescript
import { MessageResponseContract } from '@types/responses/message-response.contract';

const messageResponse: MessageResponseContract = {
message: 'Operation completed successfully',
};

// Use messageResponse as needed
```

## Extended Request Interface

This module defines an extended request interface for Express applications.

### Interfaces:

#### `Context`

- **`prisma`** (PrismaClient): The Prisma client instance.
- **`outbox`** (Outbox): The outbox service instance.

#### `ExtendedRequest`

- Extends Express `Request`.
- **`context`** (Context): The context object containing Prisma and outbox instances.

### Usage Example:

```typescript
import { ExtendedRequest, Context } from '@types/request';
import express from 'express';

const app = express();

app.use((req: ExtendedRequest, res, next) => {
// Access Prisma and outbox through the context object
const prismaInstance = req.context.prisma;
const outboxInstance = req.context.outbox;

// Your middleware logic here

next();
});
```
2 changes: 1 addition & 1 deletion pages/wallet-provider/ledger/index.mdx
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# Ledger Module
The Ledger module serves as the foundational NOSTR-connected component for managing accounts, balances, and transactions within the Nostr platform.
The Ledger module serves as the foundational [NOSTR](https://nostr.com)-connected component for managing accounts, balances, and transactions within the Nostr platform.

0 comments on commit 05dc7fb

Please sign in to comment.