open-index/open-npm huggingface dataset:
npm package: @smartforge/auth-core
Description: SmartForge Authentication Engine - SIWE, JWT, and role-based permissions.
Latest version: 2.0.0

# @smartforge/auth-core

SmartForge Authentication Engine - SIWE, JWT, and role-based permissions.

## Installation

```bash
npm install @smartforge/auth-core
# or
pnpm add @smartforge/auth-core
```

## Usage

### Basic Setup

```typescript
import { AuthService } from "@smartforge/auth-core";

const authService = new AuthService({
  jwt: {
    secret: process.env.JWT_SECRET!,
    expiresIn: "7d",
  },
  domain: "https://yourdomain.com",
});
```

### Sign In with Wallet (SIWE)

```typescript
import { generateSIWEMessage, verifySIWE } from "@smartforge/auth-core";

// Generate SIWE message
const message = generateSIWEMessage({
  domain: "yourdomain.com",
  address: "0x...",
  statement: "Sign in to SmartForge",
  uri: "https://yourdomain.com",
  version: "1",
  chainId: 8453,
  nonce: "random-nonce",
  issuedAt: new Date(),
});

// Verify SIWE message and signature
const result = verifySIWE(message, signature);
if (result.valid) {
  console.log("Verified address:", result.parsed?.address);
}
```

### JWT Token Management

```typescript
import {
  issueToken,
  verifyToken,
  hasRole,
  UserRole,
} from "@smartforge/auth-core";

// Issue a JWT token
const token = issueToken(
  {
    userId: "user-id",
    walletAddress: "0x...",
    role: UserRole.ADMIN,
  },
  {
    secret: process.env.JWT_SECRET!,
    expiresIn: "7d",
  }
);

// Verify token
const verification = verifyToken(token, {
  secret: process.env.JWT_SECRET!,
  expiresIn: "7d",
});

// Check role permissions
const canWrite = hasRole(UserRole.WRITER, UserRole.READER); // true
const canAdmin = hasRole(UserRole.READER, UserRole.ADMIN); // false
```

### Complete Authentication Flow

```typescript
const result = await authService.signInWithWallet(
  message,
  signature,
  async (address) => {
    // Get user by address from database
    return await db.getUserByAddress(address);
  },
  async (address) => {
    // Create new user if doesn't exist
    return await db.createUser({ address });
  }
);

if (result.success) {
  console.log("Token:", result.token);
  console.log("User:", result.user);
}
```

## API

### `AuthService`

Main authentication service class.

**Methods:**

- `signInWithWallet()` - Authenticate with SIWE
- `signInWithEmail()` - Email authentication (stub)
- `verifyToken()` - Verify JWT token
- `checkPermission()` - Check role permissions
- `generateSignInMessage()` - Generate SIWE message

### `UserRole`

Enum of user roles:

- `UserRole.ADMIN` - Full access
- `UserRole.WRITER` - Can create/modify
- `UserRole.READER` - Read-only access

### SIWE Functions

- `generateSIWEMessage()` - Generate SIWE message
- `parseSIWEMessage()` - Parse SIWE message string
- `verifySIWE()` - Verify SIWE message and signature

### JWT Functions

- `issueToken()` - Create JWT token
- `verifyToken()` - Verify JWT token
- `decodeToken()` - Decode token without verification
- `hasRole()` - Check role hierarchy

## License

ISC
npm package: @smartforge/config
Description: Shared configuration utilities for SmartForge packages.
Latest version: 1.0.1

# @smartforge/config

Shared configuration utilities for SmartForge packages.

## Installation

```bash
npm install @smartforge/config
# or
pnpm add @smartforge/config
```

## Usage

```typescript
import { getEnv, CHAINS, DEFAULT_CHAIN } from "@smartforge/config";

// Get validated environment variables
const env = getEnv();
console.log(env.JWT_SECRET);
console.log(env.DATABASE_URL);

// Access chain configurations
const baseChain = CHAINS.BASE;
console.log(baseChain.id); // 8453
console.log(baseChain.rpcUrl);
```

## API

### `getEnv()`

Returns validated environment variables. Throws if required variables are missing.

**Required Environment Variables:**

- `JWT_SECRET` - Minimum 32 characters
- `JWT_EXPIRES_IN` - Default: "7d"
- `PORT` - Default: "4000"
- `NODE_ENV` - Default: "development"

**Optional:**

- `DATABASE_URL`
- `API_URL`
- `BASE_RPC_URL`
- `GASLESS_RELAYER_PRIVATE_KEY`
- `GASLESS_MONTHLY_LIMIT` - Default: "1000000000000000000" (1 ETH in wei)

### `CHAINS`

Pre-configured chain objects:

- `CHAINS.BASE` - Base mainnet
- `CHAINS.BASE_SEPOLIA` - Base Sepolia testnet

### `DEFAULT_CHAIN`

Default chain configuration (Base mainnet).

## License

ISC
npm package: @smartforge/contracts
Description: Smart contract templates and compilation utilities for Contract Studio.
Latest version: 1.0.1

# @smartforge/contracts

Smart contract templates and compilation utilities for Contract Studio.

## Installation

```bash
npm install @smartforge/contracts
# or
pnpm add @smartforge/contracts
```

## Usage

### Get Contract Templates

```typescript
import { getAllTemplates, getTemplate } from "@smartforge/contracts";

// Get all available templates
const templates = getAllTemplates();
console.log(templates); // ERC20, ERC721, etc.

// Get specific template
const erc20Template = getTemplate("erc20");
if (erc20Template) {
  console.log(erc20Template.name); // "ERC20 Token"
  console.log(erc20Template.baseCode); // Solidity code
}
```

### Validate Contract Code

```typescript
import { validateContractCode } from "@smartforge/contracts";

const validation = validateContractCode(sourceCode);
if (validation.valid) {
  console.log("Contract code is valid");
} else {
  console.error("Errors:", validation.errors);
}
```

### Compile Contract

```typescript
import { compileContract } from "@smartforge/contracts";

const result = await compileContract({
  sourceCode: solidityCode,
  contractName: "MyContract",
  optimize: true,
  optimizerRuns: 200,
});

if (result.success) {
  console.log("ABI:", result.abi);
  console.log("Bytecode:", result.bytecode);
} else {
  console.error("Compilation errors:", result.errors);
}
```

### Estimate Gas

```typescript
import { estimateGas } from "@smartforge/contracts";

const estimate = await estimateGas(
  "0x...", // contract address
  "mint", // function name
  [to, amount], // function arguments
  8453 // chain ID
);

if (estimate.success) {
  console.log("Gas estimate:", estimate.gasEstimate?.toString());
}
```

## Available Templates

### ERC20 Token

Template ID: `erc20`

Standard fungible token with:

- Transfer functionality
- Approval/allowance system
- Customizable name, symbol, decimals, initial supply

### ERC721 NFT

Template ID: `erc721`

Non-fungible token with:

- Minting functionality
- Transfer functionality
- Owner controls
- Pausable functionality

## API

### Template Functions

- `getAllTemplates()` - Get all available templates
- `getTemplate(id)` - Get template by ID

### Compiler Functions

- `compileContract()` - Compile Solidity contract (stub)
- `validateContractCode()` - Validate contract syntax
- `estimateGas()` - Estimate gas for function call (stub)

## Template Structure

```typescript
interface ContractTemplate {
  id: string;
  name: string;
  description: string;
  category: "nft" | "token" | "marketplace" | "custom";
  blocks: ContractBlock[];
  baseCode: string;
}
```

## License

ISC
npm package: @smartforge/crypto
Description: Cryptographic utilities for Ethereum signatures and address handling.
Latest version: 1.0.1

# @smartforge/crypto

Cryptographic utilities for Ethereum signatures and address handling.

## Installation

```bash
npm install @smartforge/crypto
# or
pnpm add @smartforge/crypto
```

## Usage

```typescript
import {
  hashMessage,
  verifySignature,
  recoverAddress,
  formatAddress,
  isValidAddress,
} from "@smartforge/crypto";

// Hash a message using EIP-191
const message = "Hello, World!";
const hash = hashMessage(message);

// Verify a signature
const signature = "0x...";
const address = "0x...";
const isValid = verifySignature(message, signature, address);

// Recover address from signature
const recovered = recoverAddress(message, signature);

// Format address with checksum
const checksummed = formatAddress("0x1234...");

// Validate address format
const valid = isValidAddress("0x1234...");
```

## API

### `hashMessage(message: string): Uint8Array`

Hashes a message using EIP-191 standard (Ethereum Signed Message prefix).

### `verifySignature(message: string, signature: string, address: string): boolean`

Verifies that a signature was created by the given address for the message.

### `recoverAddress(message: string, signature: string): string`

Recovers the Ethereum address from a message and signature.

### `formatAddress(address: string): string`

Formats an address with EIP-55 checksum encoding.

### `isValidAddress(address: string): boolean`

Validates that a string is a valid Ethereum address format.

## License

ISC
npm package: @smartforge/db
Description: Database schema and client for SmartForge using Drizzle ORM.
Latest version: 1.0.1

# @smartforge/db

Database schema and client for SmartForge using Drizzle ORM.

## Installation

```bash
npm install @smartforge/db
# or
pnpm add @smartforge/db
```

## Usage

### Setup Database Client

```typescript
import { createDbClient } from "@smartforge/db";

const db = createDbClient(process.env.DATABASE_URL!);
```

### Database Schema

The package exports the following tables:

- `users` - User accounts
- `projects` - SmartForge projects
- `projectMembers` - Project membership and roles
- `contracts` - Smart contracts
- `transactions` - Transaction records
- `gasUsage` - Gas usage tracking
- `contractEvents` - Contract event logs

### Example Queries

```typescript
import { db, users, projects } from "@smartforge/db";
import { eq } from "drizzle-orm";

// Get user by wallet address
const user = await db
  .select()
  .from(users)
  .where(eq(users.walletAddress, "0x..."))
  .limit(1);

// Create a project
const [project] = await db
  .insert(projects)
  .values({
    name: "My Project",
    ownerId: user.id,
    apiKey: "sf_...",
  })
  .returning();

// Get user's projects
const userProjects = await db
  .select()
  .from(projects)
  .where(eq(projects.ownerId, user.id));
```

## Database Migrations

### Generate Migrations

```bash
cd packages/db
pnpm generate
```

### Run Migrations

```bash
pnpm migrate
```

## Schema Overview

### Users

- `id` - UUID primary key
- `walletAddress` - Ethereum address (unique)
- `email` - Optional email
- `role` - User role (admin, writer, reader)
- `createdAt`, `updatedAt` - Timestamps

### Projects

- `id` - UUID primary key
- `name` - Project name
- `ownerId` - User ID (foreign key)
- `apiKey` - Unique API key
- `createdAt`, `updatedAt` - Timestamps

### Contracts

- `id` - UUID primary key
- `projectId` - Project ID (foreign key)
- `name` - Contract name
- `address` - Deployed contract address
- `chainId` - Chain ID (default: 8453 for Base)
- `abi` - Contract ABI (JSON)
- `bytecode` - Contract bytecode
- `sourceCode` - Solidity source code
- `deploymentStatus` - Status (pending, deployed, failed)
- `createdAt`, `updatedAt` - Timestamps

### Transactions

- `id` - UUID primary key
- `projectId` - Project ID
- `contractId` - Contract ID (optional)
- `txHash` - Transaction hash (unique)
- `from`, `to` - Addresses
- `chainId` - Chain ID
- `functionName` - Called function
- `args` - Function arguments (JSON)
- `gasUsed`, `gasPrice` - Gas information
- `status` - Transaction status
- `isGasless` - Whether transaction was sponsored
- `error` - Error message (if failed)
- `createdAt` - Timestamp

## License

ISC
npm package: @smartforge/gasless
Description: Gasless transaction engine for sponsored transactions with usage limits.
Latest version: 2.0.0

# @smartforge/gasless

Gasless transaction engine for sponsored transactions with usage limits.

## Installation

```bash
npm install @smartforge/gasless
# or
pnpm add @smartforge/gasless
```

## Usage

### Setup

```typescript
import { GaslessEngine } from "@smartforge/gasless";

const gaslessEngine = new GaslessEngine({
  relayerPrivateKey: process.env.RELAYER_PRIVATE_KEY!,
  monthlyLimit: BigInt("1000000000000000000"), // 1 ETH in wei
  chainId: 8453, // Base
  rpcUrl: "https://mainnet.base.org",
});
```

### Check Gas Budget

```typescript
const month = gaslessEngine.getCurrentMonth(); // "2024-12"

const budget = await gaslessEngine.checkGasBudget(
  projectId,
  month,
  async (projectId, month) => {
    // Fetch usage from database
    return await db.getGasUsage(projectId, month);
  }
);

if (budget.allowed) {
  console.log("Remaining gas:", budget.remaining.toString());
} else {
  console.error("Budget exceeded:", budget.error);
}
```

### Check if Transaction Can Be Sponsored

```typescript
const canSponsor = await gaslessEngine.canSponsor(
  {
    projectId: "project-id",
    contractAddress: "0x...",
    functionName: "mint",
    args: [to, amount],
    from: "0x...",
    gasEstimate: 100000n,
  },
  async (projectId, month) => {
    return await db.getGasUsage(projectId, month);
  }
);

if (canSponsor.allowed) {
  // Proceed with sponsored transaction
} else {
  console.error(canSponsor.error);
}
```

### Submit Sponsored Transaction

```typescript
const result = await gaslessEngine.submitSponsoredTransaction({
  projectId: "project-id",
  contractAddress: "0x...",
  functionName: "mint",
  args: [to, amount],
  from: "0x...",
  gasEstimate: 100000n,
});

if (result.success) {
  console.log("Transaction hash:", result.txHash);
} else {
  console.error("Error:", result.error);
}
```

## API

### `GaslessEngine`

Main gasless transaction engine.

**Methods:**

- `checkGasBudget()` - Check remaining gas budget
- `estimateGas()` - Estimate gas for transaction
- `canSponsor()` - Check if transaction can be sponsored
- `submitSponsoredTransaction()` - Submit sponsored transaction
- `getCurrentMonth()` - Get current month string (YYYY-MM)

## Configuration

- `relayerPrivateKey` - Private key of the relayer wallet
- `monthlyLimit` - Monthly gas limit in wei
- `chainId` - Chain ID (default: 8453 for Base)
- `rpcUrl` - RPC endpoint URL

## License

ISC
npm package: @smartforge/observability
Description: Contract observability service for monitoring events, transactions, and gas usage.
Latest version: 1.0.1

# @smartforge/observability

Contract observability service for monitoring events, transactions, and gas usage.

## Installation

```bash
npm install @smartforge/observability
# or
pnpm add @smartforge/observability
```

## Usage

### Setup

```typescript
import { ObservabilityService } from "@smartforge/observability";
import { createDbClient } from "@smartforge/db";

const db = createDbClient(process.env.DATABASE_URL!);
const observability = new ObservabilityService(db);
```

### Index Contract Events

```typescript
await observability.indexEvent({
  contractId: "contract-id",
  eventName: "Transfer",
  txHash: "0x...",
  blockNumber: 12345,
  blockHash: "0x...",
  logIndex: 0,
  args: {
    from: "0x...",
    to: "0x...",
    tokenId: "123",
  },
});
```

### Get Contract Events

```typescript
const events = await observability.getEvents(
  {
    contractId: "contract-id",
    eventName: "Transfer",
    fromBlock: 10000,
    toBlock: 20000,
  },
  100 // limit
);
```

### Record Transaction

```typescript
await observability.recordTransaction({
  projectId: "project-id",
  contractId: "contract-id",
  txHash: "0x...",
  from: "0x...",
  to: "0x...",
  chainId: 8453,
  functionName: "mint",
  args: { to: "0x...", amount: "100" },
  gasUsed: "21000",
  gasPrice: "20000000000",
  status: "success",
  isGasless: true,
});
```

### Get Transactions

```typescript
const transactions = await observability.getTransactions(
  {
    projectId: "project-id",
    contractId: "contract-id",
    status: "success",
    isGasless: true,
  },
  100 // limit
);
```

### Track Gas Usage

```typescript
await observability.trackGasUsage({
  projectId: "project-id",
  contractId: "contract-id",
  functionName: "mint",
  gasAmount: "21000",
  month: "2024-12",
});
```

### Get Gas Usage Stats

```typescript
const stats = await observability.getGasUsageStats("project-id", "2024-12");

console.log("Total gas:", stats.total.toString());
console.log("By function:", stats.byFunction);
console.log("Transaction count:", stats.transactions);
```

## API

### `ObservabilityService`

Main observability service class.

**Methods:**

- `indexEvent()` - Index contract event
- `getEvents()` - Get contract events with filters
- `recordTransaction()` - Record transaction
- `getTransactions()` - Get transactions with filters
- `trackGasUsage()` - Track gas usage
- `getGasUsageStats()` - Get gas usage statistics

### Filters

**EventFilter:**

- `contractId` - Filter by contract
- `eventName` - Filter by event name
- `fromBlock` - Start block number
- `toBlock` - End block number

**TransactionFilter:**

- `projectId` - Filter by project
- `contractId` - Filter by contract
- `status` - Filter by status
- `isGasless` - Filter gasless transactions

## License

ISC