From 1a96293333b18bfb93f949889d8ef10e313a4b0e Mon Sep 17 00:00:00 2001 From: Arslan Kibria Date: Tue, 16 Apr 2024 15:16:03 +0500 Subject: [PATCH 1/2] README.md added in folder structure --- src/README.md | 0 src/constants/README.md | 0 src/controllers/README.md | 0 src/crons/README.md | 0 src/interfaces/README.md | 0 src/middlewares/README.md | 0 src/routes/README.md | 0 src/services/README.md | 0 8 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/README.md create mode 100644 src/constants/README.md create mode 100644 src/controllers/README.md create mode 100644 src/crons/README.md create mode 100644 src/interfaces/README.md create mode 100644 src/middlewares/README.md create mode 100644 src/routes/README.md create mode 100644 src/services/README.md diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/constants/README.md b/src/constants/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/controllers/README.md b/src/controllers/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/crons/README.md b/src/crons/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/interfaces/README.md b/src/interfaces/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/middlewares/README.md b/src/middlewares/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/routes/README.md b/src/routes/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/services/README.md b/src/services/README.md new file mode 100644 index 0000000..e69de29 From a3b8effbf733d9f02024988eb4807c502edccbe9 Mon Sep 17 00:00:00 2001 From: Arslan Kibria Date: Tue, 30 Apr 2024 15:34:21 +0500 Subject: [PATCH 2/2] all folders doc --- src/README.md | 85 ++++++++++++++ src/constants/README.md | 204 +++++++++++++++++++++++++++++++++ src/controllers/README.md | 3 + src/crons/README.md | 42 +++++++ src/interfaces/README.md | 119 ++++++++++++++++++++ src/middlewares/README.md | 193 ++++++++++++++++++++++++++++++++ src/routes/README.md | 3 + src/services/README.md | 229 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 878 insertions(+) diff --git a/src/README.md b/src/README.md index e69de29..10c7ffb 100644 --- a/src/README.md +++ b/src/README.md @@ -0,0 +1,85 @@ +# index.ts + +1. Import Statements: + + - `dotenv`: Module to load environment variables from a `.env` file. + - `app`: The main Express application imported from `./app`. + - `transactionsJob`: A function imported from `./crons/transactionsJob` that likely handles scheduled or recurring tasks related to transactions. +2. Environment Configuration: + + - `dotenv.config();`: This line loads the environment variables from a `.env` file into `process.env`, making them accessible throughout the application. +3. Transactions Job Initialization: + + - A self-invoking asynchronous function is defined and immediately executed to start the `transactionsJob`. If an error occurs during its execution, it is caught and logged to the console. +4. Server Initialization: + + - The Express `app` listens on a port defined by the `PORT` environment variable. Upon successful listening, it logs a message indicating that the server is listening on the specified port. + +This file primarily sets up and starts the server along with a job for handling transactions, all while ensuring that the necessary environment variables are loaded. + +# app.ts + +1. Importing Modules and Initial Setup: + + typescript + + Copy code + + `import express, { Request, Response, NextFunction, Application } from 'express'; + import response from './middlewares/response/responseAppender'; + const app: Application = express();` + + - `express`: This imports the express framework, which is essential for creating the server. + - `Request, Response, NextFunction, Application`: These are type imports from Express to help with typing of function parameters and the application instance. + - `response`: This imports a middleware function from `responseAppender` module, used to append data or modify the response. + - `app`: An instance of an Express application, used to configure the server. +2. Middleware for Parsing JSON and URL-Encoded Request Bodies: + + typescript + + Copy code + + `// parse json request body + app.use(express.json()); + + // parse urlencoded request body + app.use(express.urlencoded({ extended: true }));` + + - This sets up middleware in the Express app to parse JSON and URL-encoded request bodies. The `extended: true` option allows parsing of rich objects and arrays. +3. Custom Middleware - `responseAppender`: + + typescript + + Copy code + + `// responseAppender + async function responseAppender(req: any, res: any, next: any) { + await response(req, res, next); + next(); + } + app.use(responseAppender);` + + - A custom asynchronous middleware function that processes the request using another `response` middleware imported at the beginning. It ensures that the next middleware is called after its operation completes. +4. 404 Error Handling for Unknown API Requests: + + typescript + + Copy code + + `// send back a 404 error for any unknown api request + app.use((req: Request, res: Response, next: NextFunction) => { + next(Error('Not found')); + });` + + - This middleware intercepts any requests that did not match previous routes or middleware and forwards a new error with the message 'Not found', which can be used by error handling middleware to send a 404 response. +5. Exporting the Configured App: + + typescript + + Copy code + + `export default app;` + + - The configured Express application is exported, allowing it to be imported and used in other parts of the application, typically where the server is started. + +This breakdown details how the application is structured and handles requests, providing insights into middleware usage and request handling in an Express.js application. \ No newline at end of file diff --git a/src/constants/README.md b/src/constants/README.md index e69de29..04ff198 100644 --- a/src/constants/README.md +++ b/src/constants/README.md @@ -0,0 +1,204 @@ +# constants.ts + +### Constants + +- `NAME`: A string constant representing the name of the fund manager ('FUND_MANAGER'). +- `VERSION`: A string constant that holds the version number ('000.004'). +- `CONTRACT_ADDRESS`: Ethereum contract address as a string. +- `BEARER`: Prefix for authorization headers as a string ('Bearer '). +- `RANDOM_KEY`: A string key used for cryptographic operations. +- `CUDOS_CHAIN_ID`: A string representing the chain ID for Cudos network ('cudos-1'). +- `FOUNDARY`, `ONE_INCH`: String constants representing specific service names. +- `NUMBER_OF_VALIDATORS_SHOULD_BE`: Numeric constant defining the required number of validators (1). + +### Networks Configuration + +- `NETWORKS`: An array of objects, each containing network-specific addresses and identifiers for different blockchain networks. + +### Functions + +- `getAllowedPublicAddress()`: Retrieves a list of allowed public addresses from an environment variable and returns it as an array. If no addresses are provided, it returns an empty array. + +- `isAllowedPublicAddress(nodeAddress: string)`: Checks if a given node address is in the list of allowed addresses. It performs a case-insensitive comparison and returns `true` if the address is allowed, otherwise `false`. + +- `isUniqueAddressesArray(arr: [any])`: Verifies that all addresses in the given array are unique. Returns `true` if all addresses are unique, `false` otherwise. + +- `checkForNumberOfValidators(arr: any)`: Checks if the number of items in the provided array matches the number of allowed validators. Returns `true` if they match, otherwise `false`. + +- `createAuthTokenForMultiswapBackend()`: Generates a time-bound authentication token for the Multiswap backend. It uses cryptographic functions to ensure the token's integrity and confidentiality. + +- `getPrivateKey()`: Retrieves and decrypts a private key stored in environment variables using another security key. + +- `encrypt(data: string, key: String)`: Encrypts the given data using AES with the provided key and returns the ciphertext. If an error occurs during encryption, it logs the error and returns an empty string. + +- `decrypt(data: string, key: string)`: Decrypts the given data using AES with the provided key and returns the original text. If decryption fails, it logs the error and returns an empty string. + +- `delay()`: Returns a promise that resolves after 30 seconds. This function can be used to introduce artificial delays. + +- `getThreshold(threshold: number)`: Calculates and returns twice the value of the provided threshold. + +- `getRpcNodesData()`: Fetches RPC node data from environment variables, parses it from JSON, and returns it. + +These constants and functions are essential for the operations of a fund management system on blockchain networks, providing functionalities like authentication, configuration, and data integrity. + +# IERC20 + +The IERC20.json file defines the interface for a standard ERC20 token, adhering to the Ethereum token standard specification. This interface includes essential functionalities for token transactions, including transfers, approvals, and balance checks. + +# FiberRouter.json +Overview + +The FiberRouter.json file from the ferrumnet/multiswap-node repository contains a JSON object representing a smart contract interface for a "Fiber Router." This interface is likely used to interact with blockchain networks, facilitating operations such as swapping, liquidity provision, or routing transactions across different platforms. + +Interface Details + +Contract Name: The JSON is an interface for a contract named FiberRouter. + +Compiler Version: The interface was compiled with Solidity version 0.8.0. + +Optimization Enabled: Yes, with 200 runs. + +EVM Version: The target EVM version for this contract is specified as Default. + +Methods + +1. swapExactTokensForTokens + +Type: Function + +Inputs: + +amountIn: The amount of input tokens to swap. + +amountOutMin: The minimum amount of output tokens that must be received for the transaction not to revert. + +path: An array of token addresses used to determine the swap route. + +to: The address to send the output tokens to. + +deadline: A timestamp by which the transaction must be completed, or it will revert. + +Outputs: + +Array: Returns an array of numbers indicating the amounts of tokens received for each swap in the path. + +State Mutability: Nonpayable + +Details: This method facilitates a token swap operation, ensuring that the number of output tokens received is at least the amountOutMin specified, following the swap path provided. + +2. swapTokensForExactTokens + +Type: Function + +Inputs: + +amountOut: The exact amount of output tokens to receive. + +amountInMax: The maximum amount of input tokens that can be swapped. + +path: The route of token addresses for the swap. + +to: The recipient address for the output tokens. + +deadline: The transaction deadline. + +Outputs: + +Array: Outputs the amounts of tokens spent for each swap in the path. + +State Mutability: Nonpayable + +Details: Allows users to specify the exact amount of tokens they want to receive, the method calculates and limits the input to amountInMax. + +Events + +1. Swap + +Inputs: + +sender: The address initiating the swap. + +amountIn: The amount of input tokens provided for the swap. + +amountOut: The amount of output tokens received from the swap. + +tokenIn: The address of the input token. + +tokenOut: The address of the output token. + +to: The recipient address. + +Details: This event is emitted after a successful swap operation, detailing the swap amounts and the addresses involved. + +Conclusion + +The FiberRouter.json file defines an interface for a contract facilitating token swaps on a blockchain network, providing methods for exact or minimum token swaps along specified paths. It also includes an event to log swap operations. This documentation should assist auditors in understanding the contract's functionalities and intended behaviors. + +# utils.ts + +### Function: `amountToHuman` + +- Purpose: Converts a machine-readable token amount to a human-readable format by adjusting for the token's decimal places. +- Parameters: + - `web3`: An instance of a web3 library to interact with Ethereum nodes. + - `token`: The contract address of the token. + - `amount`: The amount in machine format (usually in smallest unit, like wei). +- Returns: The human-readable string of the amount, or null if conversion fails. + +### Function: `amountToMachine` + +- Purpose: Converts a human-readable token amount to a machine-readable format by accounting for the token's decimal places. +- Parameters: + - `web3`: An instance of a web3 library. + - `token`: The contract address of the token. + - `amount`: The amount in human-readable format. +- Returns: The machine-readable string of the amount, adjusted for decimals. + +### Function: `erc20` + +- Purpose: Creates a new ERC20 contract instance using the provided web3 instance and token address. +- Parameters: + - `web3`: An instance of a web3 library. + - `token`: The contract address of the token. +- Returns: An instance of the ERC20 contract. + +### Function: `decimals` + +- Purpose: Fetches the number of decimal places for a given token using its contract. +- Parameters: + - `web3`: An instance of a web3 library. + - `token`: The contract address of the token. +- Returns: The number of decimals as a number, or null if unable to fetch. + +### Function: `removeExponential` + +- Purpose: Converts a number from exponential format to a plain string without exponential notation. +- Parameters: + - `n`: The number in exponential format. +- Returns: The formatted number as a string. + +### Function: `numberIntoDecimals` + +- Purpose: Converts a number into a string representation with a specified number of decimals. +- Parameters: + - `amount`: The number to convert. + - `decimal`: The number of decimal places. +- Returns: The number formatted as a string with the specified number of decimals. + +### Function: `decimalsIntoNumber` + +- Purpose: Converts a string with decimals into a number format. +- Parameters: + - `amount`: The string containing the number. + - `decimal`: The number of decimal places. +- Returns: The number as a formatted string based on the specified decimals. + +### Function: `withSlippage` + +- Purpose: Adjusts a given value by a specified percentage to account for potential slippage in transactions. +- Parameters: + - `value`: The original value. + - `slippage`: The slippage percentage to apply. +- Returns: The value adjusted for slippage as a string. + +These utility functions are crucial for handling and formatting blockchain-related numerical values, ensuring accurate calculations and displays for end-users. \ No newline at end of file diff --git a/src/controllers/README.md b/src/controllers/README.md index e69de29..a4a7ad4 100644 --- a/src/controllers/README.md +++ b/src/controllers/README.md @@ -0,0 +1,3 @@ +# index.ts + +The `index.ts` file within the `src/controllers` directory of the `ferrumnet/multiswap-node` repository serves as a central point for exporting modules. This file essentially organizes and makes accessible the defined modules in the project for periodic tasks. \ No newline at end of file diff --git a/src/crons/README.md b/src/crons/README.md index e69de29..46a67a4 100644 --- a/src/crons/README.md +++ b/src/crons/README.md @@ -0,0 +1,42 @@ +# index.ts + +The `index.ts` file within the `src/crons` directory of the `ferrumnet/multiswap-node` repository serves as a central point for exporting cron job modules. This file essentially organizes and makes accessible the cron jobs defined in the project for periodic tasks. + +Here's a detailed documentation of each function in the file `transactionsJob.ts` from the repository: + +# transactionsJob.ts + +1. Module Imports and Initializations: + + - `node-cron` is required for scheduling tasks. + - Services like `axiosService` and `transactionService` are imported from the `../services` directory. + - `isProccessRunning` is a boolean flag to prevent overlapping job executions. + - `localTransactionHashes` stores transaction hashes locally to avoid reprocessing. +2. `transactionsJob` Function: + + - An asynchronous function that triggers the `start` function to initiate the job. +3. `start` Function: + + - Schedules a recurring task every 5 seconds. + - If `isProccessRunning` is false, it calls `triggerJobs` to process transactions. + - Handles errors by logging them. +4. `triggerJobs` Function: + + - Retrieves transactions through `axiosService.getTransactions()`. + - If transactions are present, sets `isProccessRunning` to true, processes each transaction via `handleJob`, and then sets `isProccessRunning` to false. +5. `handleJob` Function: + + - Processes an individual transaction. + - Checks if the transaction hash is in the local list using `isHashInLocalList`. + - If not, adds it to the list with `addTransactionHashInLocalList` and then processes the transaction using `transactionService.prepareObjectsAndVerifySignatures`. +6. `addTransactionHashInLocalList` Function: + + - Adds a new hash to the `localTransactionHashes` array to keep track of processed transactions. +7. `removeTransactionHashFromLocalList` Function: + + - Removes a hash from the `localTransactionHashes` array, used when a transaction no longer needs to be tracked. +8. `isHashInLocalList` Function: + + - Checks if a given hash is already in the `localTransactionHashes` array. + +Each function is designed to handle specific aspects of transaction processing within a job that runs every few seconds, ensuring that transactions are not processed multiple times and handling errors gracefully. \ No newline at end of file diff --git a/src/interfaces/README.md b/src/interfaces/README.md index e69de29..4782711 100644 --- a/src/interfaces/README.md +++ b/src/interfaces/README.md @@ -0,0 +1,119 @@ +# index.ts + +The `index.ts` file within the `src/interfaces` directory of the `ferrumnet/multiswap-node` repository serves as a central point for exporting modules. This file essentially organizes and makes accessible the defined modules in the project for periodic tasks. + +# job.interface.ts + +### 1\. `JobRequestBody` + +This interface is used for defining the structure of a job request body. It contains the following properties: + +- name: `string` - The name of the job. +- isSourceNonEVM: `boolean` - Indicates if the source is a non-EVM (Ethereum Virtual Machine) chain. +- destinationRpcURL: `string` - The RPC URL of the destination chain. +- isDestinationNonEVM: `boolean` - Indicates if the destination is a non-EVM chain. +- bridgeAmount: `string` - The amount to bridge. +- txId: `string` - Transaction ID associated with the job. +- threshold: `number` - The threshold value for the job to be considered successful. +- sourceAssetType: `string` - The type of asset at the source. +- destinationAssetType: `string` - The type of asset at the destination. +- destinationAmountIn: `string` - The input amount at the destination. +- destinationAmountOut: `string` - The output amount at the destination. +- sourceOneInchData: `string` - Data related to one inch service at the source. +- destinationOneInchData: `string` - Data related to one inch service at the destination. +- expiry: `number` - Expiry time for the job. +- withdrawalData: `string` - Data related to the withdrawal process. +- sourceChainId: `string` - Chain ID of the source. +- destinationChainId: `string` - Chain ID of the destination. +- slippage: `number` - Slippage percentage allowed for the transaction. + +### 2\. `SignatureData` + +This interface defines the structure for signature data used in transactions: + +- from: `string` - The originating address. +- token: `string` - The token involved in the transaction. +- amount: `string` - The amount of the token. +- sourceChainId: `string` - The chain ID of the source. +- targetChainId: `string` - The chain ID of the target. +- targetToken: `string` - The target token in the swap. +- sourceAddress: `string` - The address at the source. +- targetAddress: `string` - The address at the target. +- swapBridgeAmount: `string` - The amount for the bridge swap. +- settledAmount: `string` - The amount that was settled in the transaction. +- withdrawalData: `string` - Data related to the withdrawal process. + +### 3\. `UpdateJobRequestBody` + +This interface is utilized for updating a job request with transaction details: + +- transaction: `Transaction` - The transaction details. +- transactionReceipt: `TransactionReceipt` - The receipt of the transaction. + +### 4\. `RpcNode` + +Defines the basic structure of an RPC node: + +- url: `string` - URL of the RPC node. +- chainId: `string` - Chain ID associated with the RPC node. + +This interface file helps in managing various aspects of job processing, signature verification, and RPC node interaction within the `multiswap-node` project. + +# web3.interface.ts + +### Interface: `Transaction` + +- hash: A string representing the hash of the transaction. +- nonce: A number indicating the nonce of the transaction, which is a counter of the number of transactions sent from the sender's address. +- blockHash: A string or null, representing the hash of the block in which this transaction was included. +- blockNumber: A number or null, indicating the block number in which this transaction was included. +- transactionIndex: A number or null, representing the transaction's index position in the block. +- from: A string indicating the address from which the transaction was sent. +- to: A string or null, representing the recipient's address of the transaction. +- value: A string representing the value transferred in the transaction, in wei. +- gasPrice: A string representing the gas price set by the sender, in wei. +- maxPriorityFeePerGas: An optional number, string, or any, representing the maximum priority fee per gas that can be added to the transaction fee. +- maxFeePerGas: An optional number, string, or any, indicating the maximum fee per gas that the sender is willing to pay. +- gas: A number indicating the amount of gas used by the transaction. +- input: A string representing additional data sent along with the transaction. + +### Interface: `TransactionReceipt` + +- status: A boolean indicating whether the transaction was successful. +- transactionHash: A string representing the hash of the transaction. +- transactionIndex: A number representing the transaction's index within the block. +- blockHash: A string representing the hash of the block in which the transaction was included. +- blockNumber: A number indicating the block number of the transaction. +- from: A string indicating the sender's address. +- to: A string representing the recipient's address. +- contractAddress: An optional string representing the contract address created, if the transaction was a contract creation. +- cumulativeGasUsed: A number representing the total gas used in the block up until this transaction. +- gasUsed: A number indicating the amount of gas used by this specific transaction. +- effectiveGasPrice: A number representing the effective gas price paid for the transaction. +- logs: An array of `Log` objects representing the logs generated by the transaction. +- logsBloom: A string representing the bloom filter for the logs. +- events: An optional object mapping event names to `EventLog` objects, representing events triggered during the transaction. + +### Interface: `EventLog` + +- event: A string representing the name of the event. +- address: A string indicating the address where the event occurred. +- returnValues: Any type representing the values returned by the event. +- logIndex: A number indicating the log's index in the block. +- transactionIndex: A number representing the transaction's index within the block. +- transactionHash: A string representing the hash of the transaction. +- blockHash: A string representing the hash of the block. +- blockNumber: A number indicating the block number. +- raw: An optional object containing raw data (`data` as a string and `topics` as an array) associated with the event. + +### Interface: `Log` + +- address: A string representing the address where the log originated. +- data: A string representing the data contained in the log. +- topics: An array of strings representing the topics associated with the log. +- logIndex: A number indicating the log's index within the block. +- transactionIndex: A number representing the transaction's index within the block. +- transactionHash: A string representing the hash of the transaction. +- blockHash: A string representing the hash of the block. +- blockNumber: A number indicating the block number. +- removed: A boolean indicating whether the log was removed from the blockchain (due to chain reorganization). \ No newline at end of file diff --git a/src/middlewares/README.md b/src/middlewares/README.md index e69de29..6967c8e 100644 --- a/src/middlewares/README.md +++ b/src/middlewares/README.md @@ -0,0 +1,193 @@ +# asyncMiddleware.ts + +Description: The `asyncMiddlewareLayer` function is a higher-order function designed to handle asynchronous operations within middleware by wrapping another function. It ensures any thrown errors are caught and handled appropriately, simplifying error handling across asynchronous middleware functions. + +Parameters: + +- `fn`: A function that represents the middleware operation. It takes three parameters: + - `req`: The request object. + - `res`: The response object. + - `next`: A callback function to pass control to the next middleware function. + +Returns: + +- A function that takes `req`, `res`, and `next` as arguments. This returned function uses `Promise.resolve` to execute the middleware function `fn` and handles any errors that occur during its execution. + +Error Handling: + +- If an error is caught during the execution of `fn`, the error object is inspected and transformed to provide a meaningful error message. The function checks several properties (`message`, `msg`, `errors`) to determine the appropriate error message. +- If an error occurs while handling the initial error (in the catch block), the catch error is sent as a 400 HTTP response using `res.http400` + +# responseAppender.ts + +### `responseAppender(req: any, res: any, next: any)` + +Description: This middleware function is designed to append standard HTTP response methods to the `res` (response) object in an Express.js application. It enables the application to use standardized response formats across different routes and controllers, ensuring a consistent API behavior. + +Parameters: + +- `req` (any): The HTTP request object. This function does not use `req` directly, but it is included to adhere to the middleware signature in Express.js. +- `res` (any): The HTTP response object. This is augmented with several methods for returning standard responses. +- `next` (any): The callback argument to the middleware function. This function does not use `next` as it does not need to pass control to subsequent middleware. + +Appended Methods to `res`: + +- `res.http200`: A method set by importing from `standardResponses` module. Typically used to send a 200 OK response. +- `res.http400`: A method set by importing from `standardResponses` module. Typically used to send a 400 Bad Request response. +- `res.http401`: A method set by importing from `standardResponses` module. Typically used to send a 401 Unauthorized response. +- `res.http404`: A method set by importing from `standardResponses` module. Typically used to send a 404 Not Found response. + +Usage: This middleware should be used in the application setup, typically before defining routes, to ensure that all response objects in route handlers are equipped with these methods. It helps in maintaining a clean and consistent structure for handling API responses. + +# standardResponses.ts + +The file `standardResponses.ts` from the `ferrumnet/multiswap-node` repository contains several utility functions to standardize HTTP responses in a middleware setup. Here's a detailed breakdown of each function documented within this file: + +### Function: `http200(data: any)` + +This function is used to send a successful HTTP response with a status code of 200. It expects a parameter `data` which can include any data to be returned as part of the response body. The function: + +- Extracts a message from the `data` object if available and deletes the message property from the object. +- Constructs a response object with a status code and message, and includes the rest of the data as the response body. + +### Function: `http400(err: any, key: string = "")` + +This function handles the HTTP 400 (Bad Request) responses. It takes an error object `err` and an optional string `key` to provide additional context. It: + +- Returns a response with a status code of 400 and includes the error message in the response status. + +### Function: `http401(err: any)` + +This function is used for handling HTTP 401 (Unauthorized) responses. It accepts an error object `err` and: + +- Sends a response with a status code of 401, incorporating the error message in the response status. + +### Function: `http404(err: any, key: string = "")` + +This function handles HTTP 404 (Not Found) responses. Similar to `http400`, it takes an error object `err` and an optional `key` for additional context. It: + +- Returns a response with a status code of 404 and includes the error message in the response status. + +These functions are part of a module that likely gets used across the server to ensure consistency in how HTTP responses are formatted and sent back to clients, making it easier to handle different types of HTTP response scenarios consistently. + +# standardStatuses.ts + +The file `standardStatuses.ts` within the `middlewares/response` directory of the `multiswap-node` repository contains a module that exports several functions, each associated with different HTTP response statuses. Here's a detailed documentation of each function: + +1. status200(data: any) + + - Purpose: Constructs a successful response object. + - Parameters: + - `data`: The payload to be included in the response. + - Returns: An object with a status code of `200` and the provided data. + - Usage: Used to send a successful response to the client with the specified data. + - Code: + + typescriptCopy code + + `return { + code: 200, + data: data + }` + +2. status400(data: any) + + - Purpose: Constructs a client error response object. + - Parameters: + - `data`: The error message or data to be included in the response. + - Returns: An object with a status code of `400` and the error message. + - Usage: Used to indicate that the client made an incorrect request. + - Code: + + typescriptCopy code + + `return { + code: 400, + message: data + }` + +3. status401(data: any) + + - Purpose: Constructs a response object for authentication errors. + - Parameters: + - `data`: The error message or data indicating the authentication failure. + - Returns: An object with a status code of `401` and the error message. + - Usage: Used to indicate that the request requires user authentication. + - Code: + + typescriptCopy code + + `return { + code: 401, + message: data + }` + +These functions provide a standardized way to handle HTTP responses across the application, ensuring consistency in how responses are structured and sent to clients. + + +# auth.middleware.ts + +Here's a detailed breakdown of each function within the `auth.middleware.ts` file: + +#### Middleware `auth` + +- Purpose: This middleware function is designed to handle authorization checks for API requests. It allows for the enforcement of specific rights required to access various parts of an application. +- Parameters: + - `...requiredRights`: An array of strings that specifies the rights needed to access the function. +- Behavior: + - Checks if the authorization header is present in the request. If not, it sends a 401 response with the message "Authorization header missing". + - If the authorization header is present, it attempts to validate the token extracted from the header. + - If the token is valid, it calls `next()` to pass control to the next middleware function. Otherwise, it sends a 401 response with "Invalid token". +- Error Handling: + - Catches and logs any error that occurs during the token validation process, then sends a 401 response with "Invalid token". + +#### Function `validateAuth` + +- Purpose: Validates the token based on the request's URL to determine the type of API being accessed. +- Parameters: + - `token`: The token extracted from the authorization header. + - `req`: The request object. +- Returns: Boolean indicating whether the token is valid for the requested API. +- Behavior: + - Checks if the request URL includes "securityKey" and calls `authSecurityKeyApis` or `authJobApis` accordingly. + +#### Function `authSecurityKeyApis` + +- Purpose: Validates tokens specifically for security key related APIs. +- Parameters: + - `token`: The token to be validated. +- Returns: Boolean indicating if the token matches the expected security key after decryption. +- Behavior: + - Decrypts the token using a key from the environment configuration and compares it to the expected key. + +#### Function `authJobApis` + +- Purpose: Validates tokens specifically for job related APIs. +- Parameters: + - `token`: The token to be validated. +- Returns: Boolean indicating if the token is valid for job APIs. +- Behavior: + - Validates the token by checking if it meets specific job-related authorization criteria. + +#### Function `isAuthJobTokenValid` + +- Purpose: Checks the validity of a job API token. +- Parameters: + - `token`: The token to be validated. + - `key`: The key used for token decryption. +- Returns: Boolean indicating whether the token is valid. +- Behavior: + - Decrypts the token and checks if the decrypted token corresponds to a valid JSON object with valid date constraints. + +#### Function `validateDates` + +- Purpose: Validates date constraints within the token data. +- Parameters: + - `data`: Data object containing start and end date-time fields. +- Returns: Boolean indicating whether the current date falls between the start and end dates specified in the token data. +- Behavior: + - Compares the current date to the start and end dates provided within the token data, checking if it falls within the specified range. + +These functions collectively provide robust authorization middleware for different types of API requests based on token validation and time constraints. + + diff --git a/src/routes/README.md b/src/routes/README.md index e69de29..312224b 100644 --- a/src/routes/README.md +++ b/src/routes/README.md @@ -0,0 +1,3 @@ +# index.ts + +The `index.ts` file within the `src/routes` directory of the `ferrumnet/multiswap-node` repository serves as a central point for exporting modules. This file essentially organizes and makes accessible the defined modules in the project for periodic tasks. \ No newline at end of file diff --git a/src/services/README.md b/src/services/README.md index e69de29..7e95f3f 100644 --- a/src/services/README.md +++ b/src/services/README.md @@ -0,0 +1,229 @@ +# index.ts + +The `index.ts` file within the `src/services` directory of the `ferrumnet/multiswap-node` repository serves as a central point for exporting modules. This file essentially organizes and makes accessible the defined modules in the project for periodic tasks. + +# axios.service.ts + +### Function: `getTransactions` + +Purpose:\ +Fetches a list of transactions from the Multiswap backend with a specific status, limit, and node type. The function also considers the running environment to adjust the API endpoint accordingly. + +Parameters:\ +None. + +Returns: + +- `Array` of transactions if the request is successful. +- `null` if an error occurs during the request. + +Details: + +1. Determines the base URL based on the environment. If it's a local environment, it uses a local URL. Otherwise, it uses the URL from the environment variable `GATEWAY_BACKEND_URL`. +2. Configures the request headers to include authorization generated by the `createAuthTokenForMultiswapBackend` function. +3. Constructs a URL with query parameters including status, limit, node type, and a public key. +4. Makes a GET request to the constructed URL and returns the transactions if successful or `null` if an error occurs. + +Example Use: + +javascript + +Copy code + +`getTransactions().then(transactions => { + console.log(transactions); +}).catch(error => { + console.error("Failed to fetch transactions:", error); +});` + +### Function: `updateTransaction` + +Purpose:\ +Updates a transaction status on the Multiswap backend. This function is especially useful for handling transaction validations. + +Parameters: + +- `txHash` (string): The transaction hash to identify the transaction to be updated. +- `body` (any): The body of the request containing the updated transaction details. +- `isValidationFailed` (boolean): A flag indicating whether the validation failed. + +Returns:\ +The response from the axios PUT request, which will typically be a success or error message from the backend. + +Details: + +1. Similar to `getTransactions`, it sets the base URL based on the environment. +2. Constructs headers with authorization as done in `getTransactions`. +3. Builds the URL with query parameters to include the transaction hash, public key, and validation failure status. +4. Sends a PUT request to the backend with the body and configuration, and returns the response. + +Example Use: + +javascript + +Copy code + +`const transactionBody = { /* transaction details here */ }; +updateTransaction("tx12345", transactionBody, false).then(response => { + console.log("Transaction updated:", response); +}).catch(error => { + console.error("Error updating transaction:", error); +});` + +These functions are part of the `axios.service.ts` module, designed to interact with the Multiswap backend API, handling both fetching and updating transaction data based on the application's needs. + +# signature.service.ts + +### 1\. `getDataForSignature(job: any): Promise` + +This function constructs transaction data suitable for signature based on the job's details and decoded signature data. It integrates with services to fetch necessary addresses and computes the transaction data which includes from address, token, amount, contract addresses, chain IDs, signatures, salt, asset types, amounts in/out, and expiry data. + +### 2\. `getValidWithdrawalData(data: any, decodedData: any): Promise` + +Extracts valid withdrawal data from a transaction by verifying its integrity against the latest transaction hash and settled amount criteria. It ensures that the data provided is still valid and hasn't been tampered with or outdated. + +### 3\. `isValidSettledAmount(slippage: number, sourceChainId: string, destinationChainId: string, destinationAmountIn: any, settledAmount: any): Promise` + +Calculates whether the settled amount is valid based on the slippage parameters and chain IDs. It checks if the settled amount meets or exceeds the expected amount after accounting for slippage. + +### 4\. `createSignedPayment(...)` + +Generates a signed payment, crafting a hash of the transaction details and then signing it using the private key. The specifics of the hash depend on the asset type involved (either `FOUNDARY` or `ONE_INCH`). + +### 5\. `produceFoundaryHash(...)` + +Produces a hash specific to `FOUNDARY` type transactions by serializing and hashing transaction details. It uses the Ethereum standard EIP712 for structured data hashing and signing. + +### 6\. `produceOneInchHash(...)` + +Produces a hash for `ONE_INCH` type transactions. Similar to `produceFoundaryHash`, but specific to the OneInch exchange transactions involving additional parameters such as `amountIn` and `amountOut`. + +### 7\. `domainSeparator(web3: Web3, chainId: string, contractAddress: string)` + +Generates a domain separator which is a unique hash for a set of transactions from a specific contract on a given chain, used to prevent certain types of replay attacks in different environments. + +### 8\. `validateSignature(job: any, localSignatures: any): Promise` + +Validates a set of signatures against expected transaction details. It ensures all provided signatures are valid and correspond to the address they claim to represent. + +### 9\. `isRecoverAddressValid(signature: string, hash: string, publicAddress: string): boolean` + +Checks if the recovered address from a signature matches the provided public address. It is a security check to ensure the signer of a transaction is the claimant of the transaction. + +### 10\. `getDataForSalt(hash: string, txData: any, decodedData: any): string` + +Generates a unique salt string from transaction and decoded data, ensuring uniqueness and preventing replay attacks. + +### 11\. `getDecodedLogsDataIntoString(decodedData: any): string` + +Helper function to serialize decoded log data into a string format, used for generating hashes or for logging purposes. + +These functions together provide a robust suite for managing blockchain transactions and their security, particularly focused on signature verification and data integrity in a decentralized environment. + +# transaction.service.ts + +### Function: `prepareObjectsAndVerifySignatures(tx: any)` + +This function prepares the necessary data objects from a transaction `tx` and verifies signatures. It organizes transaction information into two structured objects, `JobRequestBody` and `SignatureData`, and a combined object `job`. After assembling the data, it calls `verifySignatures` to handle the signature verification. + +- Parameters: + - `tx`: The transaction object containing various transaction details. +- Operations: + - Extract and structure transaction data. + - Call `verifySignatures` with the assembled job data. + +### Function: `verifySignatures(job: any)` + +Verifies the signatures associated with a job. It handles the logic to verify signatures based on whether the destination is a non-EVM (Ethereum Virtual Machine) network or not. If verification fails, it updates the transaction status as failed. + +- Parameters: + - `job`: A job object containing transaction and signature data. +- Operations: + - Conditional checks for EVM and non-EVM transactions. + - Signature validation and transaction updates based on the outcome. + +### Function: `createWithdrawalSignature(job: any)` + +Creates a withdrawal signature for a transaction job. It decides the process based on whether the destination is a non-EVM network or not, and updates the transaction accordingly. + +- Parameters: + - `job`: A job object that includes data necessary for generating a signature. +- Operations: + - Transaction signature creation and update based on network type. + +### Function: `updateTransaction(txId: string, signedData: any, isValidationFailed: boolean)` + +Updates a transaction in the database with the new signed data or flags it as failed based on the validation results. Also removes the transaction hash from the local list after updating. + +- Parameters: + - `txId`: Transaction ID to update. + - `signedData`: Signed data for the transaction. + - `isValidationFailed`: A boolean indicating if the signature validation failed. +- Operations: + - Update the transaction in the database and handle local list cleanup. + +### Function: `getGeneratorHash(tx: any): string` + +Extracts and returns the hash from the generator signatures of a transaction. Handles errors gracefully. + +- Parameters: + - `tx`: The transaction object that might contain generator signatures. +- Returns: + - The hash string extracted from the first signature or an empty string if not available or on error. + +Each function is designed to handle specific aspects of transaction processing and signature management, contributing to the transaction workflow in a blockchain network environment. + +# web3.service.ts + +1. getTransactionReceipt: + + - Purpose: Asynchronously retrieves a transaction receipt for a given transaction ID and chain ID. + - Parameters: + - `txId`: The transaction ID as a string. + - `chainId`: The blockchain chain ID as a string. + - `threshold`: The maximum number of retries for fetching the transaction receipt. + - `tries`: (Optional) Current number of attempts, defaults to 0. + - Returns: A promise that resolves to a `TransactionReceipt` object. + - Description: This function attempts to fetch the transaction receipt from the blockchain. If the transaction or its status is not available, it delays and retries until the threshold is met. +2. getTransactionByHash: + + - Purpose: Fetches a transaction from the blockchain using its hash. + - Parameters: + - `txHash`: The hash of the transaction. + - `chainId`: The chain ID of the blockchain. + - Returns: A promise that resolves to a `Transaction` object. +3. signedTransaction: + + - Purpose: Processes and signs a transaction based on provided job details and hash. + - Parameters: + - `job`: An object containing details about the job. + - `hash`: A string representing the hash for which the signature is to be created. + - Returns: A promise that resolves to an object containing transaction details and signatures. + - Description: This function handles the process of signing a transaction, including preparing the data for signing, creating the signature, and returning the signed transaction details. +4. getFundManagerAddress: + + - Purpose: Retrieves the fund manager address for a given chain ID. + - Parameters: + - `chainId`: The chain ID to lookup. + - Returns: A string representing the fund manager's address. + - Description: Looks up the fund manager address from a predefined list of networks based on the chain ID. +5. getFiberRouterAddress: + + - Purpose: Retrieves the fiber router address for a given chain ID. + - Parameters: + - `chainId`: The chain ID to lookup. + - Returns: A string representing the fiber router's address. + - Description: Looks up the fiber router address from a predefined list of networks based on the chain ID. +6. getFoundaryTokenAddress: + + - Purpose: Retrieves the foundary token address for a specific target chain ID. + - Parameters: + - `targetChainId`: The target chain ID for which the token address is needed. + - Returns: A string representing the foundary token's address. + - Description: Searches through a predefined list of networks to find and return the foundary token address corresponding to the target chain ID. +7. getDestinationAmount: + + - Purpose: Asynchronously calculates the destination amount based on input data. + - Parameters: + - `data`: An object containing the swap bridge amount. + - Returns: A promise that resolves to the swap bridge amount. \ No newline at end of file