@super-protocol/provider-client
v0.1.9
Published
Provider client for Super Protocol
Maintainers
Keywords
Readme
@super-protocol/provider-client
Type-safe client for SuperProtocol Provider API, built on top of openapi-fetch.
Features
- ✅ Type Safety - Automatic type generation from OpenAPI schema
- ✅ Modern API - Uses native fetch API
- ✅ Minimal Size - Only 6kb + openapi-fetch
- ✅ Auto Updates - Types generated on every build
- ✅ Auth Middleware - Automatic token injection in headers
Installation
npm install @super-protocol/provider-clientQuick Start
import { createProviderClient } from '@super-protocol/provider-client';
const client = createProviderClient({
baseUrl: process.env.SP_BASE_URL || 'https://cp.dev.superprotocol.com',
accessToken: process.env.SP_ACCESS_TOKEN // Get token through authentication
});
// Get current user information
const { data, error } = await client.GET('/api/auth/me');
if (data) {
console.log('User ID:', data.id);
}Environment Setup
Getting Your Access Token
Authenticate with SuperProtocol:
- Visit SuperProtocol Console
- Connect your wallet (MetaMask, WalletConnect, etc.)
- Your access token will be generated automatically
Alternative: Use the OAuth API:
- Use the
/api/auth/tokenendpoint to get a token programmatically - See the OAuth documentation for details
- Use the
Set Environment Variable:
# Option 1: Export in your shell export SP_ACCESS_TOKEN="your-jwt-token-here" # Option 2: Create .env file (recommended) echo "SP_ACCESS_TOKEN=your-jwt-token-here" > .env # Option 3: Copy from example and edit cp example.env .env # Then edit .env with your actual tokenRun the Example:
# The .env file will be loaded automatically (Node.js 20+) npm run start:example # Or run directly with token SP_ACCESS_TOKEN="your-token" npm run start:example
Automatic .env File Loading
Starting with Node.js 20+, environment variables from .env files are automatically loaded using the --env-file flag. This package is configured to use this feature.
Create a .env file in your project root:
# SuperProtocol API Configuration
# Get your token from https://console.superprotocol.com after connecting wallet
SP_ACCESS_TOKEN=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...your-full-token-here
# Optional: Override default base URL (uncomment to use different environment)
# SP_BASE_URL=https://cp.dev.superprotocol.com # Development environment
# SP_BASE_URL=https://cp.staging.superprotocol.com # Staging environment
# SP_BASE_URL=https://cp.superprotocol.com # Production environmentQuick setup options:
# Option 1: Create directly
echo "SP_ACCESS_TOKEN=your-token-here" > .env
# Option 2: Copy from example
cp .env.template .env
# Then edit .env file with your actual tokenThe start:example script uses --env-file-if-exists=.env flag, which means:
- ✅ If
.envfile exists, variables are loaded automatically - ✅ If
.envfile doesn't exist, no error is thrown - ✅ Environment variables take precedence over
.envfile values
For more details, see the Node.js documentation on environment variables.
Running the Demo
This package includes a working example that demonstrates all major API endpoints:
# Clone the repository
git clone https://github.com/super-protocol/sp-providers
cd sp-providers/packages/provider-client
# Install dependencies
npm install
# Set your access token (choose one method):
# Method 1: Create .env file (recommended)
echo "SP_ACCESS_TOKEN=your-token-here" > .env
# Method 2: Export environment variable
export SP_ACCESS_TOKEN="your-token-here"
# Method 3: Copy from example
cp example.env .env
# Then edit .env with your actual token
# Run the example (automatically loads .env if present)
npm run start:exampleThe example will show you:
- ✅ Current user information
- ✅ User settings and storage configuration
- ✅ Wallet balance and address
- ✅ Available workflows
- ✅ Provider information
- ✅ Example POST request (workflow replenishment)
API Reference
createProviderClient(options)
Creates a configured openapi-fetch client with auth middleware.
Parameters:
baseUrl?- API base URL (default:https://cp.dev.superprotocol.com)accessToken?- Authorization token (automatically added to headers)headers?- Additional HTTP headers
Returns: Configured openapi-fetch client with typed GET, POST, PUT, DELETE, etc. methods.
Environment Variables:
SP_ACCESS_TOKEN- Access token for authentication (loaded from.envfile automatically with Node.js 20+)SP_BASE_URL- Optional base URL override (defaults tohttps://cp.dev.superprotocol.com)
Example environment configurations:
# Development environment (default)
SP_BASE_URL=https://cp.dev.superprotocol.com
# Staging environment
SP_BASE_URL=https://cp.staging.superprotocol.com
# Production environment
SP_BASE_URL=https://cp.superprotocol.comUsage Examples
Basic Requests
import { createProviderClient } from '@super-protocol/provider-client';
// With Node.js 20+ and --env-file flag, .env variables are automatically loaded
const client = createProviderClient({
baseUrl: process.env.SP_BASE_URL || 'https://cp.dev.superprotocol.com',
accessToken: process.env.SP_ACCESS_TOKEN // Loaded from .env file automatically
});
// GET request
const { data: userData, error } = await client.GET('/api/auth/me');
// POST request
const { data: workflow, error: workflowError } = await client.POST('/api/workflows', {
body: {
parentOrderInfo: { /* ... */ },
parentOrderSlot: { /* ... */ },
// All fields are typed automatically!
}
});
// PUT request with path parameters
const { data, error } = await client.PUT('/api/offers/{id}', {
params: {
path: { id: 'offer-id' }
},
body: {
name: 'Updated Offer Name'
}
});Working with Parameters
// Query parameters
const { data: offers } = await client.GET('/api/offers', {
params: {
query: {
limit: 10,
offset: 0
}
}
});
// Path parameters
const { data: offer } = await client.GET('/api/offers/{id}', {
params: {
path: { id: 'specific-offer-id' }
}
});
// Combined path and query parameters
const { data: workflows } = await client.GET('/api/workflows/{id}', {
params: {
path: { id: 'workflow-id' },
query: { includeDetails: true }
}
});Error Handling
const { data, error, response } = await client.GET('/api/auth/me');
if (error) {
// Typed errors based on endpoint
console.error('Status:', response.status);
console.error('Error:', error);
return;
}
// data is guaranteed to exist if no error
console.log('User:', data.id);Middleware and Customization
// Create client with custom headers
const client = createProviderClient({
baseUrl: process.env.SP_BASE_URL || 'https://cp.dev.superprotocol.com',
accessToken: 'your-token',
headers: {
'X-Custom-Header': 'value',
'User-Agent': 'MyApp/1.0'
}
});
// Add additional middleware
client.use({
onRequest({ request }) {
console.log(`Making request to ${request.url}`);
return request;
},
onResponse({ response }) {
console.log(`Response status: ${response.status}`);
return response;
}
});Supported Endpoints
The client supports all SuperProtocol API endpoints with full typing:
🔐 Authentication
GET /api/auth/me- Current user informationPOST /api/auth/token- Get tokensPOST /api/auth/refresh-access- Refresh tokenGET /api/auth/logout- Logout
👤 Users
GET /api/users/nonce/{address}- Get noncePOST /api/users- Register user
💰 Wallet
GET /api/users/me/wallet- Wallet informationPOST /api/users/me/wallet/withdraw- Withdraw funds
⚙️ Workflows
GET /api/workflows- List workflowsGET /api/workflows/{id}- Get specific workflowPOST /api/workflows- Create workflowPATCH /api/workflows/{id}- Update workflowPOST /api/workflows/{orderId}/replenish- Replenish workflowPOST /api/workflows/{orderId}/cancel- Cancel workflow
🏢 Providers
GET /api/providers- Provider informationPOST /api/providers- Create providerPATCH /api/providers/{id}- Update provider
📊 Offers
POST /api/offers- Create offerGET /api/offers/{id}- Get offerPATCH /api/offers/{id}- Update offerPOST /api/offers/{offerId}/publish- Publish offerPOST /api/offers/{id}/slots- Add slot
📁 Files & Contents
POST /api/files- Upload filePOST /api/files/list- List filesGET /api/files/{id}- Get filePOST /api/contents- Create contentGET /api/contents/{id}- Get content
🏪 Storages & Settings
GET /api/storages- List storagesGET /api/storages/{id}- Get specific storageGET /api/user-settings- User settingsPATCH /api/user-settings- Update settings
🎯 Faucet & Health
POST /api/faucet/request-tokens- Request faucet tokensGET /health/liveness- Health checkGET /health/readiness- Readiness check
Type Generation
Types are automatically generated from OpenAPI schema during build:
npm run generate-types # Manual type generation
npm run build # Includes type generationType Safety
Thanks to openapi-typescript integration, the client provides:
- ✅ Autocomplete for all available endpoints
- ✅ Type validation for request/response
- ✅ Parameter checking at compile time
- ✅ IntelliSense in VS Code and other IDEs
- ✅ Typed errors for each endpoint
Performance
| Library | Size (min) | Performance | | -------------------------- | ---------- | -------------------- | | @super-protocol/provider-client | 6 kB | 300k ops/s (fastest) | | axios | 32 kB | 225k ops/s (slower) | | superagent | 55 kB | 50k ops/s (6× slower) |
License
BSL-1.1
Built with ❤️ by SuperProtocol team
