sdk-blockchain-circuits-ts
v1.2.2
Published
TypeScript SDK for interacting with the Fidelity Project smart contracts. Provides a type-safe interface for managing circuits, users, and decentralized governance on Ethereum-compatible blockchains.
Downloads
635
Maintainers
Readme
sdk-blockchain-circuits-ts
TypeScript SDK for interacting with the Fidelity Project smart contracts. Provides a type-safe interface for managing circuits, users, and decentralized governance on Ethereum-compatible blockchains.
Features
✅ Circuit Management - Create, activate, and manage circuits with full lifecycle control ✅ User Management - Activate, deactivate, and manage users in the system ✅ Circuit Participation - Join and leave circuits with comprehensive tracking ✅ Governance System - Propose, vote on, and execute governance actions ✅ Compressed Proposals - Auto-compress/decompress proposal descriptions with gzip ✅ Role-Based Access Control - RBAC for administrative operations ✅ Type Safety - Full TypeScript support with generated contract bindings ✅ Comprehensive Testing - 80+ test cases across 7 test suites ✅ Well Documented - Complete API documentation and usage examples
Table of Contents
- Installation
- Quick Start
- API Reference
- Usage Examples
- Error Handling
- Testing
- Documentation
- Contributing
- License
Installation
npm install sdk-blockchain-circuits-tsPrerequisites
- Node.js 14.0.0 or higher
- npm 6.0.0 or higher
- TypeScript 5.0+
- Access to an Ethereum-compatible blockchain (local node, testnet, or mainnet)
Quick Start
import { ethers } from "ethers";
import { CircuitsManager } from "sdk-blockchain-circuits-ts";
// Setup provider and wallet
const provider = new ethers.providers.JsonRpcProvider("http://localhost:8545");
const wallet = new ethers.Wallet("0x...", provider);
// Initialize CircuitsManager
const circuitsAddress = "0x..."; // Your deployed Circuits contract address
const manager = new CircuitsManager(circuitsAddress, wallet);
// Get circuit information
const count = await manager.getNumberOfCircuits();
console.log(`Total circuits: ${count.toNumber()}`);
// Check if a circuit is active
const isActive = await manager.isCircuitActive(1);
console.log(`Circuit 1 is active: ${isActive}`);API Reference
CircuitsManager
The primary class for interacting with the Circuits smart contract.
Constructor
constructor(contractAddress: string, signer: Signer)Circuit Management
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| createCircuit() | - | Transaction | Create a new circuit (requires CIRCUIT_ADMIN_ROLE) |
| changeCircuitStatus(circuitId, status) | number, number | Transaction | Change circuit status |
| isCircuitActive(circuitId) | number | boolean | Check if circuit is active |
| getNumberOfCircuits() | - | BigNumber | Get total number of circuits |
| getCircuits() | - | BigNumber[] | Get all circuit IDs |
| getCircuitSize(circuitId) | number | BigNumber | Get number of participants |
User Management
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| activateUser(userId, userAddress) | number, string | Transaction | Activate a user (requires CIRCUIT_ADMIN_ROLE) |
| deactivateUser(userId) | number | Transaction | Deactivate a user |
| isRegistered(userId) | number | boolean | Check if user is registered |
| getUserCircuit(userId) | number | BigNumber | Get user's current circuit |
Circuit Participation
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| joinCircuit(userId, circuitId) | number, number | Transaction | Join a circuit |
| leaveCircuit(userId) | number | Transaction | Leave current circuit |
| isRegisteredToCircuit(userId, circuitId) | number, number | boolean | Check circuit membership |
| getCircuitPartecipants(circuitId) | number | BigNumber[] | Get all participants |
| getCircuitPartecipantsAndStatus(circuitId) | number | object[] | Get participants with status |
| getPartecipant(userId) | number | ICircuits.PartecipantStruct | Get participant details |
Governance
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| propose(userAffected, proposerId, circuitId, proposalType, description?) | number, number, number, number, string? | Transaction | Create a proposal with optional description (auto-compressed) |
| getProposalDescription(proposalId) | number | Promise<string> | Get proposal description (auto-decompressed) |
| castVote(userId, proposalId) | number, number | Transaction | Cast a vote |
| removeVote(userId, proposalId) | number, number | Transaction | Remove a vote |
| closePropose(userId, proposalId) | number, number | Transaction | Close a proposal |
| isVotationPassed(proposalId) | number | boolean | Check if proposal passed |
| getAllCircuitPartecipantsAndStatus() | - | object[] | Get all participants across circuits |
Utility Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| getContract() | - | Circuits | Get underlying contract instance |
| getContractAddress() | - | string | Get contract address |
| getSigner() | - | Signer | Get current signer |
| setSigner(newSigner) | Signer | void | Switch to different signer |
Usage Examples
Circuit Management
// Create a new circuit (requires CIRCUIT_ADMIN_ROLE)
const createTx = await manager.createCircuit();
await createTx.wait();
// Change circuit status
await manager.changeCircuitStatus(1, 0); // circuitId=1, status=0
// Get all circuit IDs
const circuitIds = await manager.getCircuits();
console.log("Circuit IDs:", circuitIds.map(id => id.toNumber()));
// Check circuit size
const size = await manager.getCircuitSize(1);
console.log("Circuit 1 has", size.toNumber(), "participants");User Management
// Activate a new user
const userAddress = "0x1234567890123456789012345678901234567890";
const activateTx = await manager.activateUser(1, userAddress);
await activateTx.wait();
// Check user registration status
const userId = 1;
const isRegistered = await manager.isRegistered(userId);
console.log(`User ${userId} is registered:`, isRegistered);
// Get user information
const participant = await manager.getPartecipant(userId);
console.log("Participant info:", participant);Circuit Participation
// Join a circuit
const joinTx = await manager.joinCircuit(1, 1); // userId=1, circuitId=1
await joinTx.wait();
// Check if user is in circuit
const isInCircuit = await manager.isRegisteredToCircuit(1, 1);
console.log("User is in circuit:", isInCircuit);
// Get all participants
const participants = await manager.getCircuitPartecipants(1);
console.log("Participants:", participants.map(id => id.toNumber()));
// Leave circuit
const leaveTx = await manager.leaveCircuit(1);
await leaveTx.wait();Governance
// Create a proposal
const proposeTx = await manager.propose(
2, // userAffected
1, // proposerId
1, // circuitId
0 // proposalType (0=remove, 1=ban, etc.)
);
await proposeTx.wait();
// Cast a vote
const voteTx = await manager.castVote(1, 0); // userId=1, proposalId=0
await voteTx.wait();
// Check if proposal passed
const passed = await manager.isVotationPassed(0);
console.log("Proposal 0 passed:", passed);
// Close a proposal
const closeTx = await manager.closePropose(1, 0);
await closeTx.wait();Compressed Proposals
The SDK automatically handles gzip compression and decompression of proposal descriptions.
// Create proposal with description (automatically compressed with gzip)
const proposeTx = await manager.propose(
badUserId, // userAffected
proposerId, // proposerId
circuitId, // circuitId
1, // proposalType = BAN_USER
"User violated community guidelines: spam and harassment" // Auto-compressed!
);
await proposeTx.wait();
// Get the proposal ID
const proposals = await manager.getAllProposals();
const proposalId = proposals.length - 1;
// Retrieve and decompress description automatically
const reason = await manager.getProposalDescription(proposalId);
console.log("Ban reason:", reason); // "User violated community guidelines: spam and harassment"
// Backward compatible: proposals without description still work
const simpleTx = await manager.propose(
newUserId,
proposerId,
circuitId,
0 // No description parameter - uses empty bytes automatically
);Features:
- ✅ Automatic gzip compression (pako library)
- ✅ Automatic decompression when retrieving
- ✅ Validates: max 2KB compressed, gzip format (magic bytes: 0x1f 0x8b)
- ✅ Clear error messages if limits exceeded
- ✅ Backward compatible with proposals without descriptions
Compression Example:
// Original: "A".repeat(5000) = 5000 bytes
// Compressed: ~150 bytes
// Ratio: 97% reduction! 🎉Error Handling
try {
await manager.joinCircuit(1, 1);
} catch (error) {
if (error.code === "CALL_EXCEPTION") {
console.error("Contract execution failed:", error.reason);
} else if (error.code === "INSUFFICIENT_FUNDS") {
console.error("Insufficient funds for transaction");
} else if (error.message.includes("AccessControl")) {
console.error("Access denied: check user roles");
} else {
console.error("Unknown error:", error.message);
}
}Role-Based Access Control
The contract uses role-based access control (RBAC):
- DEFAULT_ADMIN_ROLE - Can grant/revoke roles
- DEVELOPER_ROLE - For developers
- CIRCUIT_ADMIN_ROLE - Can create circuits, manage users
Check that your signer has the necessary roles before calling restricted operations.
Testing
The SDK includes a comprehensive test suite with 80+ tests:
# Run all tests
npm run test_all
# Run specific test suites
npm run test_circuits_manager # Basic CircuitsManager tests
npm run test_advanced # Advanced circuit operations
npm run test_governance # Governance operations
npm run test_governance_integration # Governance integration
npm run test_compressed_proposals # Compressed proposals & compression feature
npm run test_integration # Full integration tests
npm run test_edge_cases # Edge case handlingTest coverage includes:
- Circuit lifecycle management
- User registration and activation
- Circuit participation flows
- Governance proposal workflows
- Compressed proposals with gzip compression/decompression
- Size limits validation (2KB max)
- Gzip format validation (magic bytes)
- Backward compatibility (proposals without descriptions)
- Role-based access control
- Edge cases and error handling
Documentation
For detailed documentation and advanced usage, see:
- CircuitsManager Usage Guide - Complete API reference with examples
- Test Suite Documentation - Overview of all test cases
- Running Tests Guide - Guide for running and debugging tests
- Quick Start Guide - Get started quickly
Project Structure
packages/fidelity-sdk/
├── src/
│ ├── CircuitsManager.ts # Main SDK class
│ ├── index.ts # Package exports
│ └── typechain/ # Auto-generated contract types
├── build/ # Compiled JavaScript
├── test/ # Test suites
│ ├── CircuitsManager.spec.ts
│ ├── CircuitsManager.Advanced.spec.ts
│ ├── Governance.spec.ts
│ ├── GovernanceIntegration.spec.ts
│ ├── CompressedProposals.spec.ts # Gzip compression tests
│ ├── Integration.spec.ts
│ └── EdgeCases.spec.ts
├── build/ # Compiled JavaScript (generated)
├── tsconfig.json # TypeScript configuration
├── package.json # Package metadata
└── README.md # This fileBuilding
# Install dependencies
npm install
# Compile TypeScript to JavaScript
npm run compile
# Build for npm publishing
npm run prepublishOnlyTypeScript Support
Full TypeScript support with auto-generated types:
import { CircuitsManager } from "sdk-blockchain-circuits-ts";
import { BigNumber } from "ethers";
const manager = new CircuitsManager(address, signer);
// Full type inference
const size: BigNumber = await manager.getCircuitSize(1);
const ids: BigNumber[] = await manager.getCircuits();
const isActive: boolean = await manager.isCircuitActive(1);Contributing
Contributions are welcome! Please ensure:
- All tests pass (
npm run test_all) - Code follows the existing style
- New features include tests
- Documentation is updated
- TypeScript types are properly maintained
License
ISC License - see LICENSE file for details.
Repository
- Git: https://bitbucket.org/omniadev/sdk-blockchain-fidelity-ts.git
- Issues: https://bitbucket.org/omniadev/sdk-blockchain-fidelity-ts/issues
Author
OmniaGroup
Support
For questions and support, please open an issue in the repository.
