Socket
Book a DemoInstallSign in
Socket

stakefy-usage-envelope

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

stakefy-usage-envelope

Drop-in usage-based budget enforcement layer for enterprises. Plugs into Stripe for top-ups, Postgres for reporting, and x402 for capital-layer budget enforcement.

latest
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

Stakefy Usage Envelope Engine

Drop-in usage-based budget enforcement layer for enterprises. Plugs into Stripe for top-ups, Postgres for reporting, and x402 for capital-layer budget enforcement.

Architecture

  • Backend: Node.js + TypeScript + Express
  • Database: PostgreSQL + Prisma ORM
  • Payments: Stripe Billing (PaymentIntents)
  • Budget Ledger: x402-stakefy-sdk (source of truth)
  • Identity: Username, email, phone, or API key mapped to envelopes

Core Concept

Envelopes are usage budgets with time windows (hourly/daily/weekly/monthly/annual). Users stake capital via Stripe, which tops up their x402 envelope. Each usage request drains from the envelope atomically - if x402 drain fails, usage is blocked.

Quick Start (Local Development)

Prerequisites

  • Node.js 20+
  • Docker Desktop
  • PostgreSQL (via Docker)

Setup

# Clone and install
cd stakefy-usage-envelope
npm install

# Start Postgres
docker compose up -d postgres

# Configure environment
cp .env.example .env
# Edit .env with your keys

# Run migrations
npm run prisma:migrate

# Start dev server
npm run dev

Server runs on http://localhost:3000

Test the API

# Health check
curl http://localhost:3000/health

# Run full test suite
./test-api.sh

Docker Compose (Full Stack)

# Build and start everything
docker compose up -d

# Check health
curl http://localhost:3000/health

# View logs
docker compose logs -f api

# Stop
docker compose down

API Endpoints

Envelopes

POST /envelopes - Create envelope

curl -X POST http://localhost:3000/envelopes \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production API Budget",
    "timeWindow": "MONTHLY",
    "capacity": 1000,
    "currency": "USD",
    "ownerAccountId": "acct_123"
  }'

POST /envelopes/:id/authorize - Authorize identity

curl -X POST http://localhost:3000/envelopes/{ENVELOPE_ID}/authorize \
  -H "Content-Type: application/json" \
  -d '{
    "type": "API_KEY",
    "value": "sk_prod_xyz"
  }'

GET /envelopes/:id/status - Check remaining capacity

curl http://localhost:3000/envelopes/{ENVELOPE_ID}/status

Usage

POST /usage - Drain from envelope (atomic)

curl -X POST http://localhost:3000/usage \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 10,
    "identity": "sk_prod_xyz",
    "identityType": "API_KEY",
    "metadata": {
      "requestId": "req_abc",
      "endpoint": "/api/v1/query"
    }
  }'

Top-ups

POST /stripe/topup - Create payment intent

curl -X POST http://localhost:3000/stripe/topup \
  -H "Content-Type: application/json" \
  -d '{
    "envelopeId": "{ENVELOPE_ID}",
    "amount": 500
  }'

POST /stripe/webhook - Stripe webhook handler

  • Configure in Stripe Dashboard: https://your-domain.com/stripe/webhook
  • Events: payment_intent.succeeded, payment_intent.payment_failed

Environment Variables

# Server
PORT=3000
NODE_ENV=development

# Database
DATABASE_URL="postgresql://user:pass@localhost:5432/stakefy_usage"

# Stripe
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

# x402
X402_API_KEY=your_api_key
X402_ENV=sandbox  # or prod

# Security
APP_SIGNING_SECRET=random_secret_min_32_chars

# Logging
LOG_LEVEL=info  # debug|info|warn|error

How x402 Drain Works

  • Request arrives at /usage with identity + amount
  • Validate identity - lookup envelope mapping in DB
  • Atomic drain - call x402Service.drain(envelopeId, amount)
    • If x402 drain succeeds → persist SUCCESS event, allow usage
    • If x402 drain fails (insufficient balance) → persist BLOCKED event, return 402
  • DB is mirror - x402 is source of truth for balances

Database Schema

  • Envelope - Budget container with time window
  • IdentityMapping - Maps API keys/emails/usernames to envelopes
  • UsageEvent - Every drain attempt (SUCCESS/BLOCKED/ERROR)
  • TopUpEvent - Stripe payments (PENDING/SUCCEEDED/FAILED)
  • AuditLog - Immutable audit trail

Development Commands

# Development
npm run dev              # Start with hot reload
npm run build            # Compile TypeScript
npm start                # Run production build

# Database
npm run prisma:generate  # Generate Prisma Client
npm run prisma:migrate   # Run migrations
npm run prisma:studio    # Open Prisma Studio GUI

# Testing
./test-api.sh           # Run integration tests

Production Deployment

Docker

# Build image
docker build -t stakefy-usage-envelope:latest .

# Run with env file
docker run -d \
  --name stakefy-api \
  -p 3000:3000 \
  --env-file .env.production \
  stakefy-usage-envelope:latest

Migrations

# Run migrations in production
docker exec stakefy-api npx prisma migrate deploy

Security Notes

  • Always use HTTPS in production
  • Rotate APP_SIGNING_SECRET regularly
  • Verify Stripe webhook signatures (handled automatically)
  • Rate limit /usage endpoint (see Step 10)
  • Use environment-specific x402 API keys

Troubleshooting

"x402 client not initialized"

  • Set X402_API_KEY in .env
  • Currently runs in mock mode without key

"Connection refused" to Postgres

  • Ensure Docker Postgres is running: docker compose up -d postgres
  • Check DATABASE_URL in .env

Stripe webhook fails

  • Verify STRIPE_WEBHOOK_SECRET matches Stripe Dashboard
  • Test with Stripe CLI: stripe listen --forward-to localhost:3000/stripe/webhook

License

MIT

Built by Stakefy - Web3 Payment Infrastructure

FAQs

Package last updated on 05 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts