trust-sdk-ts
v1.1.0
Published
TypeScript SDK for the Eco-trust blockchain - Decentralized trust network contract
Downloads
369
Maintainers
Readme
Trust Contract SDK - TypeScript
A powerful TypeScript SDK for interacting with the Eco-trust blockchain's TrustContract - a decentralized trust network platform built on Ethereum.
Overview
The Trust Contract SDK provides a simple, type-safe interface to build blockchain-based trust networks. Create trust relationships, manage permissions, and query trust networks with pagination support.
Key Features:
- 🔐 Trust Network Management - Create and manage trust relationships between users
- 📄 Pagination Support - Efficient querying of large trust networks with offset/limit
- 🔔 Event Listeners - Real-time monitoring of trust events
- ⛽ Gas Estimation - Predict transaction costs before submitting
- 🔗 Type-Safe - Full TypeScript support with auto-generated contract bindings
- 📦 Lightweight - Minimal dependencies, built on ethers.js v6
Installation
NPM
npm install trust-sdk-tsYarn
yarn add trust-sdk-tsPNPM
pnpm add trust-sdk-tsQuick Start
1. Initialize the SDK
import { TrustContractSDK } from 'trust-sdk-ts';
import { ethers } from 'ethers';
// Connect to your blockchain provider
const provider = new ethers.JsonRpcProvider('http://localhost:8545');
const signer = await provider.getSigner();
// Initialize SDK with contract address and signer
const sdk = new TrustContractSDK('0x...CONTRACT_ADDRESS...', signer);2. Register Users
// Register the connected user
await sdk.register(await signer.getAddress());
// Register another user (requires sender permissions)
await sdk.register('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
// Check if user is registered
const isRegistered = await sdk.isRegistered('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
console.log(isRegistered); // true3. Create Trust Relationships
// Give trust to another user
await sdk.giveTrust('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
// Remove trust
await sdk.removeTrust('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');4. Query Trust Networks
const userAddress = '0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8';
// Get all users that this address trusts
const trusted = await sdk.getTrusted(userAddress, 0n, BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'));
console.log('Trusted by user:', trusted);
// Get all users who trust this address
const trusters = await sdk.getTruster(userAddress, 0n, BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'));
console.log('Users who trust this address:', trusters);Advanced Usage
Pagination Support
Efficiently paginate through large trust networks:
const userAddress = '0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8';
// Get first 10 trusted addresses
const page1 = await sdk.getTrusted(userAddress, 0n, 10n);
console.log('Page 1:', page1);
// Get next 10
const page2 = await sdk.getTrusted(userAddress, 10n, 10n);
console.log('Page 2:', page2);
// Get single result
const first = await sdk.getTrusted(userAddress, 0n, 1n);
console.log('First trusted:', first[0]);Parameters:
offset(bigint): Starting index (0-based)limit(bigint): Number of results to return
Real-Time Event Monitoring
// Listen for trust given events
const unsubscribeTrust = sdk.onTrustGiven((from, to, event) => {
console.log(`${from} now trusts ${to}`);
});
// Listen for trust removed events
const unsubscribeRemove = sdk.onTrustRemoved((from, to, event) => {
console.log(`${from} removed trust from ${to}`);
});
// Listen for user registration
const unsubscribeRegister = sdk.onUserRegistered((user, event) => {
console.log(`${user} has been registered`);
});
// Stop listening when done
unsubscribeTrust();
unsubscribeRemove();
unsubscribeRegister();Gas Estimation
Estimate transaction costs before submitting:
// Estimate gas for registration
const registerGas = await sdk.estimateRegisterGas('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
console.log('Registration gas:', registerGas.toString());
// Estimate gas for giving trust
const trustGas = await sdk.estimateGiveTrustGas('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
console.log('Give trust gas:', trustGas.toString());
// Estimate gas for removing trust
const removeGas = await sdk.estimateRemoveTrustGas('0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
console.log('Remove trust gas:', removeGas.toString());Access Control
// Get role constants
const developerRole = await sdk.getDeveloperRole();
const adminRole = await sdk.getDefaultAdminRole();
// Check if account has a role
const isDeveloper = await sdk.hasRole(developerRole, '0x742d35Cc6634C0532925a3b844Bc9e7595f42bE8');
console.log('Is developer:', isDeveloper);Contract Utilities
// Get contract address
const contractAddress = await sdk.getAddress();
console.log('Contract deployed at:', contractAddress);
// Remove all event listeners
sdk.removeAllListeners();API Reference
Methods
Write Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| register(user) | user: string | Promise<void> | Register a user in the trust network |
| giveTrust(friend) | friend: string | Promise<void> | Give trust to another user |
| removeTrust(exFriend) | exFriend: string | Promise<void> | Remove trust from a user |
Read Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| getTrusted(user, offset, limit) | user: string, offset: bigint, limit: bigint | Promise<string[]> | Get addresses trusted by a user (paginated) |
| getTruster(user, offset, limit) | user: string, offset: bigint, limit: bigint | Promise<string[]> | Get addresses that trust a user (paginated) |
| isRegistered(user) | user: string | Promise<boolean> | Check if a user is registered |
Gas Estimation Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| estimateRegisterGas(user) | user: string | Promise<bigint> | Estimate gas for registration |
| estimateGiveTrustGas(friend) | friend: string | Promise<bigint> | Estimate gas for giving trust |
| estimateRemoveTrustGas(exFriend) | exFriend: string | Promise<bigint> | Estimate gas for removing trust |
Access Control Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| hasRole(role, account) | role: string, account: string | Promise<boolean> | Check if account has a role |
| getDeveloperRole() | - | Promise<string> | Get DEVELOPER_ROLE constant |
| getDefaultAdminRole() | - | Promise<string> | Get DEFAULT_ADMIN_ROLE constant |
Event Listener Methods
| Method | Callback Parameters | Returns | Description |
|--------|-------------------|---------|-------------|
| onUserRegistered(callback) | (user: string, event: ethers.Log) => void | () => void | Listen for user registration events |
| onTrustGiven(callback) | (from: string, to: string, event: ethers.Log) => void | () => void | Listen for trust given events |
| onTrustRemoved(callback) | (from: string, to: string, event: ethers.Log) => void | () => void | Listen for trust removed events |
| removeAllListeners() | - | void | Remove all active event listeners |
Utility Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| getAddress() | - | Promise<string> | Get the contract address |
Examples
Complete Application Example
import { TrustContractSDK } from 'trust-sdk-ts';
import { ethers } from 'ethers';
async function main() {
// Setup
const provider = new ethers.JsonRpcProvider('http://localhost:8545');
const [adminSigner, userSigner] = await provider.getSigners();
const contractAddress = '0x...';
const sdk = new TrustContractSDK(contractAddress, adminSigner);
// Register users
const adminAddress = await adminSigner.getAddress();
const userAddress = await userSigner.getAddress();
await sdk.register(adminAddress);
await sdk.register(userAddress);
console.log('✓ Users registered');
// Set up event listeners
sdk.onTrustGiven((from, to) => {
console.log(`📍 Trust event: ${from.slice(0, 6)}... → ${to.slice(0, 6)}...`);
});
// Admin gives trust to user
await sdk.giveTrust(userAddress);
console.log('✓ Admin trusts user');
// Switch to user signer
const userSdk = new TrustContractSDK(contractAddress, userSigner);
// Query trust network
const adminsTrusters = await sdk.getTruster(adminAddress, 0n, 100n);
console.log(`✓ ${adminsTrusters.length} users trust the admin`);
// Clean up
sdk.removeAllListeners();
}
main().catch(console.error);Monitor Trust Network Activity
async function monitorTrustActivity(contractAddress: string, provider: ethers.Provider) {
const signer = await provider.getSigner();
const sdk = new TrustContractSDK(contractAddress, signer);
console.log('🔍 Monitoring trust network activity...\n');
sdk.onUserRegistered((user) => {
console.log(`[REGISTER] ${user}`);
});
sdk.onTrustGiven((from, to) => {
console.log(`[TRUST+] ${from} → ${to}`);
});
sdk.onTrustRemoved((from, to) => {
console.log(`[TRUST-] ${from} ✗ ${to}`);
});
// Keep listening
await new Promise(() => {});
}Configuration
Contract Address
Get the contract address from deployment:
const deploymentInfo = require('./deployment_info.json');
const contractAddress = deploymentInfo.address;
const sdk = new TrustContractSDK(contractAddress, signer);Network Configuration
Customize your provider for different networks:
// Local development
const localProvider = new ethers.JsonRpcProvider('http://localhost:8545');
// Testnet
const testnetProvider = new ethers.JsonRpcProvider('https://sepolia-rpc.example.com');
// Mainnet
const mainnetProvider = new ethers.JsonRpcProvider('https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY');
const sdk = new TrustContractSDK(contractAddress, signer);Error Handling
try {
await sdk.giveTrust(friendAddress);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('Cannot trust yourself')) {
console.error('Cannot create trust relationship with self');
} else if (error.message.includes('Already in the list')) {
console.error('Trust relationship already exists');
} else {
console.error('Transaction failed:', error.message);
}
}
}Performance Considerations
- Pagination: Use pagination for networks with many trust relationships to avoid timeout
- Gas Limits: Always estimate gas before submitting transactions
- Event Listeners: Remove unused listeners to prevent memory leaks
- Batch Operations: Group related operations to reduce network calls
// ✓ Good: Use pagination for large datasets
const batch1 = await sdk.getTrusted(user, 0n, 50n);
const batch2 = await sdk.getTrusted(user, 50n, 50n);
// ✗ Avoid: Loading all at once
const all = await sdk.getTrusted(user, 0n, BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'));Testing
Run the test suite:
npm run testDeploy contracts and run integration tests:
# Terminal 1: Start Hardhat node
cd packages/contracts
npx hardhat node
# Terminal 2: Deploy contracts
cd packages/contracts
npm run deploy:evm
# Terminal 3: Run tests
cd packages/test
npx jestSecurity Considerations
- ✓ Always validate addresses before use
- ✓ Use checksummed addresses (ethers.js handles this)
- ✓ Never expose private keys or secret recovery phrases
- ✓ Test thoroughly in development before mainnet deployment
- ✓ Monitor event logs for unauthorized activity
- ✓ Implement rate limiting for production applications
Contributing
We welcome contributions! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Roadmap
- [ ] Batch trust operations
- [ ] Advanced filtering for trust queries
- [ ] Trust relationship weighting
- [ ] Trust expiration support
- [ ] Multi-signature support
- [ ] GraphQL API wrapper
Support
- 📖 Documentation: Check the docs
- 🐛 Issues: Report bugs on GitHub Issues
- 💬 Discussions: Join our GitHub Discussions
- 📧 Email: [email protected]
License
This project is licensed under the GPLv2 License - see the LICENSE file for details.
Changelog
[1.0.0] - 2026-03-02
- ✨ Initial release with trust network functionality
- 📄 Added pagination support (offset/limit) for getTrusted and getTruster
- 🔔 Full event listener support
- ⛽ Gas estimation methods
- 🔐 Access control integration
- 📦 Type-safe TypeChain bindings
Built with ❤️ for the Eco-trust blockchain community
