@the_library/core-adapter
v1.0.1
Published
TypeScript API adapter for CORE blockchain storage contracts with ethers v6 tree-shaking support
Maintainers
Readme
Ether Adapter
A TypeScript library providing ethers v6 compatible adapters for Ethereum smart contracts with full tree-shaking support. This package offers clean, type-safe interfaces for interacting with BackupStorage, BouncerStorage, and ScientistStorage contracts.
Features
- 🌳 Tree-shakable: Import only what you need
- 📝 TypeScript: Full type safety with comprehensive TypeScript definitions
- ⚡ Ethers v6: Built on the latest ethers.js version with modern JavaScript features
- 🔒 Read-only: Focus on view functions for safe contract interaction
- 📦 Multiple Contracts: Support for BackupStorage, BouncerStorage, and ScientistStorage
- 🎯 Zero Dependencies: Minimal bundle size impact
Installation
npm install ethers
# Install from the monorepo packages directoryQuick Start
import { JsonRpcProvider } from 'ethers';
import { createEtherAdapter } from '@the_library/ether-adapter';
const provider = new JsonRpcProvider('https://your-rpc-endpoint.com');
const adapter = createEtherAdapter({
provider,
addresses: {
backupStorage: '0x...',
bouncerStorage: '0x...',
scientistStorage: '0x...'
}
});
// Access contract methods
const admin = await adapter.backupStorage.admin();
const userCount = await adapter.bouncerStorage.nbAccounts();
const deployDate = await adapter.scientistStorage.getDeploymentDate();Tree Shaking Support
Import only the contracts you need:
import { contractFactories } from '@the_library/ether-adapter';
// Only import BouncerStorage
const bouncer = contractFactories.createBouncerStorage(address, provider);
const userCount = await bouncer.nbAccounts();API Reference
BackupStorage Contract
The BackupStorage contract manages user data backup and authorization.
Methods
admin(): Promise<string>- Get the contract admin addressisAuthorized(address: string): Promise<boolean>- Check if an address is authorizednbWrites(userId: number): Promise<bigint>- Get number of writes for a userloadActions(userId: number): Promise<string[]>- Load all actions for a userloadActionsSince(userId: number, index: number): Promise<string[]>- Load actions since a specific index
Example Usage
const backupStorage = adapter.backupStorage;
// Check admin
const adminAddress = await backupStorage.admin();
console.log('Admin:', adminAddress);
// Check authorization
const isAuth = await backupStorage.isAuthorized(adminAddress);
console.log('Is authorized:', isAuth);
// Load user data
const userId = 123;
const writeCount = await backupStorage.nbWrites(userId);
console.log('Write count:', writeCount);
if (writeCount > 0n) {
const actions = await backupStorage.loadActions(userId);
console.log('Actions:', actions);
}BouncerStorage Contract
The BouncerStorage contract manages user accounts, locations, and identity verification.
Methods
admin(): Promise<string>- Get the contract admin addressnbAccounts(): Promise<bigint>- Get total number of registered accountsgetActiveLocationCount(): Promise<bigint>- Get count of active locationsactiveLocations(index: number): Promise<{locationCode: number, count: number, locationString: string}>- Get location info by indexusernameExists(username: string): Promise<boolean>- Check if username existsgetAddressByUsername(username: string): Promise<string>- Get address by usernameuserInfos(address: string): Promise<{username: string, userId: number, country: string, language: string}>- Get user informationtoLowercase(input: string): Promise<string>- Convert string to lowercasenextCountryCode(): Promise<number>- Get next available country codecountryCodeToString(code: number): Promise<string>- Convert country code to stringcountryStringToCode(country: string): Promise<number>- Convert country string to code
Example Usage
const bouncerStorage = adapter.bouncerStorage;
// Get user statistics
const totalUsers = await bouncerStorage.nbAccounts();
const activeLocations = await bouncerStorage.getActiveLocationCount();
console.log(`${totalUsers} users across ${activeLocations} locations`);
// Check username
const username = 'alice';
const exists = await bouncerStorage.usernameExists(username);
if (exists) {
const address = await bouncerStorage.getAddressByUsername(username);
const userInfo = await bouncerStorage.userInfos(address);
console.log(`User: ${userInfo.username} (ID: ${userInfo.userId})`);
}
// Get location info
for (let i = 0; i < 5; i++) {
try {
const location = await bouncerStorage.activeLocations(i);
console.log(`${location.locationString}: ${location.count} users`);
} catch {
break; // No more locations
}
}ScientistStorage Contract
The ScientistStorage contract manages scientific data, statistics, and monthly tracking.
Methods
admin(): Promise<string>- Get the contract admin addressgetDeploymentDate(): Promise<[number, number]>- Get deployment year and monthgetLastMonthId(): Promise<number>- Get the last month IDgetStatsSize(action: number, objectType: number, monthId: number): Promise<bigint>- Get statistics sizegetStatsRaw(action: number, objectType: number, monthId: number): Promise<[string[], bigint[]]>- Get raw statistics datagetMinimumScore(action: number, objectType: number, monthId: number): Promise<bigint>- Get minimum score for top 500isInTop500(action: number, objectType: number, monthId: number, hash: string): Promise<boolean>- Check if hash is in top 500loadMonthStat(monthId: number): Promise<string[]>- Load month statistics
Example Usage
const scientistStorage = adapter.scientistStorage;
// Get deployment info
const [year, month] = await scientistStorage.getDeploymentDate();
console.log(`Deployed: ${year}-${month.toString().padStart(2, '0')}`);
// Get latest statistics
const lastMonthId = await scientistStorage.getLastMonthId();
const action = 1;
const objectType = 1;
const statsSize = await scientistStorage.getStatsSize(action, objectType, lastMonthId);
console.log(`Stats size: ${statsSize}`);
if (statsSize > 0) {
const [hashes, scores] = await scientistStorage.getStatsRaw(action, objectType, lastMonthId);
const minScore = await scientistStorage.getMinimumScore(action, objectType, lastMonthId);
console.log(`${hashes.length} entries, min score for top 500: ${minScore}`);
}
// Load month data
const monthStats = await scientistStorage.loadMonthStat(lastMonthId);
console.log(`Month ${lastMonthId} has ${monthStats.length} stat entries`);Contract Factory Functions
For tree-shaking support, you can create individual contract instances:
import { contractFactories } from '@the_library/ether-adapter';
// Create individual contracts
const backupStorage = contractFactories.createBackupStorage(address, provider);
const bouncerStorage = contractFactories.createBouncerStorage(address, provider);
const scientistStorage = contractFactories.createScientistStorage(address, provider);Error Handling
All contract methods can throw errors. Always wrap calls in try-catch blocks:
try {
const result = await adapter.bouncerStorage.userInfos(address);
console.log('User found:', result);
} catch (error) {
if (error.message.includes('ErrNoAccount')) {
console.log('User not found');
} else {
console.error('Unexpected error:', error);
}
}TypeScript Support
The library provides comprehensive TypeScript definitions:
import type {
BackupStorageContract,
BouncerStorageContract,
ScientistStorageContract,
EtherAdapter
} from '@the_library/ether-adapter';
// All methods are fully typed
const adapter: EtherAdapter = createEtherAdapter(config);
const userInfo: {username: string, userId: number, country: string, language: string} =
await adapter.bouncerStorage.userInfos(address);Development
Building
npm run buildStructure
packages/ether-adapter/
├── src/
│ ├── contracts.ts # Contract wrapper implementations
│ ├── index.ts # Main exports
│ └── types.ts # TypeScript definitions
├── abi/ # Contract ABI files
│ ├── backupstorage-abi.json
│ ├── bouncerstorage-abi.json
│ └── scientiststorage-abi.json
├── examples/ # Usage examples
└── dist/ # Compiled outputLicense
MIT
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
