@premia/commons-ts
Overview
@premia/commons-ts is a shared TypeScript utility library that provides common functionality, constants, types, and helpers used across Kyan Exchange services. It includes tools for authentication, logging, signature verification, and standardized configurations.
💡 Beginner Tip: Think of this library as the "toolbox" used by all of our services. It contains the shared code that would otherwise be duplicated across projects.
Features
- Safe Signature Verification - Verify cryptographic signatures for wallets and transactions
- Standardized Logging - Consistent logging format with Winston integration
- Type Definitions - Shared TypeScript types and interfaces for consistent data models
- Constants Repository - Centralized constants for chains, tokens, errors, and configuration
- Authentication Middleware - Express middleware for user authentication
- Utility Functions - Common helper functions for dates, strings, errors, and more
Technical Specifications
Core Technology Stack
- Language: TypeScript 5.x
- Module Format: ESM (ECMAScript Modules)
- Build System: NX with TypeScript compiler
- Package Type: Internal Library
- Version: 0.2.0
Dependencies
- Core:
- winston - Logging framework
- zod - Runtime type validation
- ethers - Ethereum library for signature verification
-
Testing:
-
Vitest - Test runner
-
MSW - API mocking
-
Internal Dependencies:
- None (this is a foundational library)
Getting Started
Prerequisites
- Node.js 22.x
- Yarn 4.x
Installation
Within the monorepo, this package is available as a workspace dependency:
To build the library:
Usage
Import functionality from the library:
// Import specific functionality
import { getLogger } from '@premia/commons-ts';
import { CHAIN_ID } from '@premia/commons-ts/constants';
import { validateSignature } from '@premia/commons-ts/validators';
// Use the imported functionality
const logger = getLogger({ service: 'my-service' });
logger.info('Hello world');
Testing
Architecture
Module Overview
The commons-ts library is organized into several focused modules that provide specific functionality.
┌──────────────────┐ ┌──────────────────┐
│ │ │ │
│ Constants │ │ Types │
│ │ │ │
└──────────────────┘ └──────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ │ │ │
│ Validators │◄────►│ Utilities │
│ │ │ │
└──────────────────┘ └──────────────────┘
│ │
└─────────────┬───────────┘
│
▼
┌──────────────────┐
│ │
│ Middleware │
│ │
└──────────────────┘
Core Modules
-
Constants (src/constants/)
-
Defines shared constants used across services
-
Includes chain IDs, error codes, token addresses, etc.
-
Types (src/types/)
-
TypeScript interfaces and type definitions
-
Zod schemas for runtime validation
-
Utilities (src/utils/)
-
Helper functions for common tasks
- Logger configuration
-
Date and time formatting
-
Validators (src/validators/)
-
Data validation functions
-
Signature verification
-
Middleware (src/middleware/)
- Express middleware components
- Authentication and request processing
Project Structure
commons-ts/
├── src/
│ ├── constants/
│ │ ├── abi/ # Contract ABIs
│ │ ├── chains.ts # Chain definitions
│ │ ├── contracts.ts # Contract addresses
│ │ ├── errors.ts # Error constants
│ │ ├── index.ts # Exports
│ │ └── tokens.ts # Token constants
│ ├── middleware/
│ │ ├── auth.ts # Authentication middleware
│ │ └── index.ts # Exports
│ ├── types/
│ │ ├── index.ts # Type exports
│ │ ├── signature.ts # Signature types
│ │ ├── utils.ts # Utility types
│ │ └── zod.ts # Zod schemas
│ ├── utils/
│ │ ├── getChain.ts # Chain utilities
│ │ ├── index.ts # Exports
│ │ ├── logger.ts # Logging utilities
│ │ ├── regex.ts # Regular expressions
│ │ └── utcTimestamp.ts # Date utilities
│ ├── validators/
│ │ ├── index.ts # Exports
│ │ └── signature.ts # Signature validation
│ └── index.ts # Main exports
├── tests/ # Test files
├── tsconfig.json # TypeScript configuration
└── package.json # Package metadata
API Reference
Logger
import { LogLevel, getLogger } from '@premia/commons-ts';
// Create a logger with default options
const logger = getLogger({ service: 'my-service' });
// Log at different levels
logger.info('This is an info message', { metadata: 'value' });
logger.error('An error occurred', { error: new Error('Something went wrong') });
logger.debug('Debug information', { data: { key: 'value' } });
// Configure logger with custom options
const customLogger = getLogger({
service: 'custom-service',
level: LogLevel.DEBUG,
enableConsole: true,
enableGoogleCloud: false,
});
Constants
import { CHAIN_ID, ERROR_CODES, SUPPORTED_CHAINS, TOKEN_ADDRESSES } from '@premia/commons-ts/constants';
// Access chain constants
const arbitrumChainId = CHAIN_ID.ARBITRUM; // 42161
// Check if a chain is supported
const isSupported = SUPPORTED_CHAINS.includes(someChainId);
// Access error codes
throw new Error(ERROR_CODES.UNAUTHORIZED);
// Get token address for a specific chain
const usdcAddress = TOKEN_ADDRESSES.USDC[CHAIN_ID.ARBITRUM];
Authentication Middleware
import { authMiddleware } from '@premia/commons-ts/middleware';
import express from 'express';
const app = express();
// Add authentication middleware
app.use(authMiddleware({ required: true }));
// Protected route
app.get('/protected', (req, res) => {
// req.user is available if auth passed
res.json({ message: 'Authenticated route', user: req.user });
});
Signature Validation
import { validateSignature } from '@premia/commons-ts/validators';
import { z } from 'zod/v4';
// Create a schema with signature validation
const schema = z.object({
address: z.string(),
message: z.string(),
signature: z.string(),
});
// Validate and verify a signature
const result = await validateSignature(schema.parse(data));
if (result.valid) {
console.log('Signature is valid');
} else {
console.error('Invalid signature:', result.error);
}
Date Utilities
import { formatUtcTimestamp, utcNow } from '@premia/commons-ts/utils';
// Get current UTC timestamp
const now = utcNow();
// Format a timestamp
const formatted = formatUtcTimestamp(now);
Infrastructure
Package Publishing
This package is published to GitHub Packages registry.
When updating:
- Use conventional commit messages
- Bump version according to semver
- Publish using the publish script:
yarn publish:commons[:patch|:minor|:major]
Troubleshooting
Common Issues
Issue | Possible Cause | Solution |
---|---|---|
"Module not found" errors | Incorrect imports or missing build | 1. Ensure the library is built with nx build commons-ts 2. Check import paths (use @premia/commons-ts/... )3. Verify package.json dependencies |
Type errors when importing | Version mismatch or outdated types | 1. Rebuild the library 2. Check TypeScript version compatibility 3. Clear TypeScript cache |
Signature validation fails | Incorrect chain or message format | 1. Verify chain ID matches the wallet network 2. Ensure message follows EIP-191 standard 3. Check address case (use checksum addresses) |
Debugging Tips
- Enable DEBUG logs with
DEBUG=commons-ts:* node your-script.js
- Use TypeScript paths for better IDE integration
- For signature issues, check the chain ID and message format
- Verify logger configuration matches environment expectations
Contributing
For guidelines on contributing to this project, please see the CONTRIBUTING.md file in the repository root.
Related Projects
- Connections-TS - Database and service connections
- Orderbook - Uses commons-ts for authentication and logging
- Datastream - Uses commons-ts for logging and types
License
Proprietary - All rights reserved