Skip to content
Last updated

PERS Developer Resources

Essential tools, libraries, and resources for PERS API integration.


Official Libraries

@explorins/pers-shared

The official TypeScript library providing type-safe contracts and DTOs for PERS API integration.

📦 Package Size vs Runtime Impact: While the npm package is 1.2 MB (includes comprehensive TypeScript definitions), modern bundlers with tree-shaking typically include only 0.44-0.67 KB in your final bundle - that's 99.9%+ elimination!

Installation

npm install @explorins/pers-shared

Library Information

  • Package Name: @explorins/pers-shared
  • Registry: npmjs.org
  • License: MIT
  • Maintainer: eXplorins Development Team

What's Included

  • DTOs: Complete type definitions for all API request/response objects
  • Interfaces: TypeScript contracts for authentication, users, campaigns, transactions
  • Types & Enums: Authentication types, error codes, transaction statuses
  • Value Objects: Immutable data structures like Address, StructuredError
  • Error Types: TypeScript error interfaces and enums for type-safe error handling

Usage Examples

Backend/Node.js Integration
import type { 
  UserDTO, 
  TransactionStatus,
  StructuredError,
  PasskeysAuthRequestDTO,
  UserAuthResponseDTO 
} from '@explorins/pers-shared';

// Type-safe API requests
const authRequest: PasskeysAuthRequestDTO = {
  authToken: "external_provider_jwt_token"
};

// Structured error handling
try {
  const response = await fetch('/auth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(authRequest)
  });
  
  if (!response.ok) {
    const error: StructuredError = await response.json();
    if (error.category === 'SECURITY') {
      console.error('Authentication failed:', error.message);
      // Handle authentication error with proper error code
    }
    return;
  }
  
  const user: UserAuthResponseDTO = await response.json();
  console.log(`Authenticated user: ${user.email}`);
} catch (error) {
  console.error('Network error:', error);
}

// Type-safe response handling
async function authenticateUser(token: string): Promise<UserAuthResponseDTO> {
  const response = await fetch('/auth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ authToken: token })
  });
  
  return response.json() as Promise<UserAuthResponseDTO>;
}
Frontend/Browser Integration
// Browser-optimized import for smaller bundle size
import { UserDTO, CampaignDTO, Address } from '@explorins/pers-shared/browser';

// Type-safe API client interface
interface PERSApiClient {
  authenticate(request: PasskeysAuthRequestDTO): Promise<UserAuthResponseDTO>;
  getBalance(userId: string): Promise<UserTokenBalancesDTO>;
  getCampaigns(): Promise<CampaignDTO[]>;
}

// React component example
import React from 'react';
import type { UserTokenBalancesDTO } from '@explorins/pers-shared/browser';

interface UserBalanceProps {
  user: UserTokenBalancesDTO;
}

const UserBalance: React.FC<UserBalanceProps> = ({ user }) => {
  return (
    <div>
      <h2>{user.email}</h2>
      <p>Wallet: {user.walletAddress?.getValue()}</p>
      {user.tokenBalances?.map(balance => (
        <div key={balance.tokenId}>
          {balance.tokenName}: {balance.balance}
        </div>
      ))}
    </div>
  );
};
Vue.js Integration
<template>
  <div>
    <h2 v-if="user">{{ user.email }}</h2>
    <div v-for="campaign in campaigns" :key="campaign.id">
      {{ campaign.name }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import type { UserDTO, CampaignDTO } from '@explorins/pers-shared/browser';

const user = ref<UserDTO | null>(null);
const campaigns = ref<CampaignDTO[]>([]);

onMounted(async () => {
  try {
    const userResponse = await fetch('/api/user/me');
    if (userResponse.ok) {
      user.value = await userResponse.json() as UserDTO;
    }
    
    const campaignsResponse = await fetch('/api/campaigns');
    if (campaignsResponse.ok) {
      campaigns.value = await campaignsResponse.json() as CampaignDTO[];
    }
  } catch (error) {
    console.error('API Error:', error);
  }
});
</script>

// Type-safe API requests const authRequest: PasskeysAuthRequestDTO = { authToken: "external_provider_jwt_token" };

// Structured error handling using ErrorFactory try { const user = await authenticate(authRequest); console.log(Authenticated user: ${user.email}); } catch (error) { if (error === Errors.authenticationRequired()) { console.error('Authentication failed:', error.message); // Handle authentication error with proper error code } }

- **Auto-completion**: All PERS types and interfaces
- **Error Detection**: TypeScript validation for API contracts
- **Quick Info**: Hover documentation for all DTOs
- **Go to Definition**: Navigate to type definitions

#### **WebStorm/IntelliJ**
Full TypeScript integration:
- **Smart Code Completion**: Context-aware suggestions
- **Refactoring Support**: Rename and restructure with confidence
- **Error Highlighting**: Real-time validation
- **Import Organization**: Auto-import management

### **Build Tool Integration**

#### **Webpack**
```javascript
// webpack.config.js - Tree shaking configuration
module.exports = {
  optimization: {
    usedExports: true,
    sideEffects: false // @explorins/pers-shared is side-effect free
  }
};

Vite

// vite.config.js - Optimized for PERS library
import { defineConfig } from 'vite';

export default defineConfig({
  optimizeDeps: {
    include: ['@explorins/pers-shared']
  }
});

Rollup

// rollup.config.js - Tree shaking optimization
export default {
  external: ['@explorins/pers-shared'],
  output: {
    format: 'es'
  }
};

API Documentation

Interactive Documentation

  • Swagger UI: Available at /swagger when running PERS API server
  • OpenAPI Spec: Complete API specification with examples
  • Postman Collection: Ready-to-use API collection for testing

Code Examples Repository

  • Integration Patterns: Common use cases and implementations
  • Sample Applications: Full working examples in different frameworks
  • Best Practices: Recommended implementation approaches

Community & Support

Official Channels

  • Documentation: Comprehensive API documentation and guides
  • API Status: Real-time API status monitoring
  • Developer Portal: Developer resources and community

Getting Help

  • Technical Support: Contact integration team for API assistance
  • Bug Reports: Submit issues through official channels
  • Feature Requests: Propose enhancements via developer portal

Getting Started with Development

Quick Setup

  1. Install the Library

    npm install @explorins/pers-shared
  2. Set Up TypeScript

    {
      "compilerOptions": {
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true
      }
    }
  3. Configure Your IDE

    • Enable TypeScript language service
    • Install PERS-specific extensions (if available)
    • Set up auto-import preferences
  4. Start Building

    import { UserDTO } from '@explorins/pers-shared';
    
    // Your PERS integration starts here!

Next Steps

  • Review the Authentication Guide for API access setup
  • Explore the Platform Overview for architectural understanding
  • Check the interactive API documentation for endpoint details
  • Join the developer community for best practices and support

Migration from Previous API Versions

V2 Performance Improvements

PERS API V2 delivers substantial performance enhancements across all operations:

  • Faster Response Times: Up to 3x improvement in API response speeds
  • Enhanced Scalability: Optimized infrastructure handles higher concurrent loads
  • Reduced Latency: Streamlined request processing with improved efficiency
  • Better Resource Usage: Optimized memory and processing patterns

Breaking Changes in V2

PERS API V2 introduces significant improvements but requires migration from previous versions:

URL Structure Changes (Major Breaking Change)

  • Plural Resource Names: All endpoints now use plural naming conventions
    • /campaign/campaigns
    • /user/users
    • /token/tokens
    • /balance/balances
    • /redemption/redemptions
  • RESTful Paths: Role-agnostic URLs with decorator-based authorization
  • Nested Resources: Improved resource relationships (e.g., /campaign-claims, /campaign-triggers)

Enhanced API Patterns

  • Unified Authentication: Streamlined /auth/token endpoint for multiple flows
  • Structured Errors: Enhanced error responses with correlation IDs and security filtering
  • Consistent DTOs: Standardized data transfer objects across all endpoints

Migration Steps

  1. Update Library: Install latest @explorins/pers-shared for new types
  2. Update URLs: Change all endpoint URLs to use plural resource names
  3. Review Authentication: Verify authentication patterns work with new endpoints
  4. Error Handling: Update error handling for new structured error format. See Error Handling for details.
  5. Testing: Validate integration in sandbox environment before production

Performance Benefits

Migrating to V2 provides immediate performance benefits with no additional configuration required. Applications typically see faster response times and improved reliability upon migration.

Backward Compatibility

Legacy endpoints remain functional during transition period. Contact support for migration timeline and assistance.

For detailed migration assistance, contact our integration team.