@sudobility/contracts
v1.17.32
Published
Multi-chain decentralized messaging system with USDC fees, revenue sharing, and delegation management. Unified TypeScript client for EVM chains and Solana.
Downloads
2,366
Maintainers
Readme
Multi-Chain Decentralized Messaging Contracts
A comprehensive multi-chain decentralized messaging system supporting both EVM chains and Solana with USDC fee integration, delegation management, and revenue sharing capabilities.
🤖 AI-Optimized: This project includes comprehensive documentation, patterns, and tooling specifically designed for AI-assisted development. See
AI_ASSISTANT_QUICKSTART.mdandCLAUDE.mdfor AI development guides.
🏗️ Project Overview
This messaging system enables decentralized communication with built-in economic incentives through a two-tier fee system and revenue sharing mechanism. The system automatically detects your wallet type and routes to the appropriate blockchain implementation.
🌟 Core Features
- 🔗 Multi-Chain Support: Works seamlessly on EVM chains (Ethereum, Polygon, etc.) and Solana
- 🤖 Automatic Chain Detection: Detects wallet type and routes to appropriate implementation
- 👥 Delegation System: Delegate message handling with rejection capability
- 📧 Two-Tier Messaging: Priority (revenue share) vs Standard (fee-only) tiers
- 💰 Revenue Sharing: 90% back to senders, 10% to platform
- ⏰ Time-based Claims: 60-day claim period for revenue shares
- 🛡️ Type-Safe: Full TypeScript support across all chains
- ⬆️ Upgradeable: UUPS proxy pattern (EVM) and native upgradeability (Solana)
📦 NPM Package Installation
# Install the unified multi-chain TypeScript client library
npm install @johnqh/mail_box_contracts
# Or with yarn
yarn add @johnqh/mail_box_contracts📱 Platform Support
The package automatically detects your platform and loads the appropriate implementation:
| Environment | Import | Resolves to |
|-------------|--------|-------------|
| React Native (Metro) | @sudobility/contracts | React Native build |
| Browser (webpack/vite) | @sudobility/contracts | Web build |
| Node.js | @sudobility/contracts | Web build |
Auto-Detection (Recommended)
// Works everywhere - auto-detects platform
import { OnchainMailerClient } from '@sudobility/contracts';Explicit Imports
// Force specific platform
import { OnchainMailerClient } from '@sudobility/contracts/web';
import { OnchainMailerClient } from '@sudobility/contracts/react-native';
// Chain-specific imports
import { EVMMailerClient } from '@sudobility/contracts/evm';
import { SolanaMailerClient } from '@sudobility/contracts/solana';React Native Setup
React Native requires polyfills to be imported first in your app entry point:
// index.js (MUST be the first import)
import '@sudobility/contracts/react-native/polyfills';
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('YourApp', () => App);Then use the client normally in your app:
// App.tsx - auto-detected as React Native
import { OnchainMailerClient, verifyPolyfills } from '@sudobility/contracts';
// Optional: verify polyfills loaded correctly
const { success, missing } = verifyPolyfills();
if (!success) console.error('Missing polyfills:', missing);Required React Native dependencies:
npm install react-native-get-random-values buffer react-native-url-polyfill text-encodingSee docs/REACT_NATIVE.md for complete React Native setup guide.
🚀 Quick Start - Unified Multi-Chain Client
Option 1: Using ChainConfig with RpcHelpers (Recommended)
The simplest way to initialize clients using API keys - all chain information is automatically derived:
import { Chain, ChainConfig } from '@sudobility/types';
import { RpcHelpers } from '@sudobility/configs';
import { buildChainConfig } from '@johnqh/mail_box_contracts';
import { MailerClient } from '@johnqh/mail_box_contracts';
// Step 1: Create config with just chain enum and API keys
const chainConfig: ChainConfig = {
chain: Chain.ETH_MAINNET,
alchemyApiKey: process.env.ALCHEMY_API_KEY,
etherscanApiKey: process.env.ETHERSCAN_MULTICHAIN_API_KEY
};
// Step 2: All chain info is automatically derived!
const chainInfo = RpcHelpers.deriveChainInfo(chainConfig);
console.log('Using:', chainInfo.name, 'at', chainInfo.rpcUrl);
console.log('USDC:', chainInfo.usdcAddress);
// Step 3: Build unified config and initialize client
const config = buildChainConfig(chainConfig, '0x...'); // Your mailer contract
const client = new MailerClient(config.evm.contracts.mailer, publicClient);
// Works with any chain - just change the Chain enum!
// Chain.BASE_MAINNET, Chain.POLYGON_MAINNET, Chain.SOLANA_MAINNET, etc.Benefits:
- ✅ Single source of truth (Chain enum + API keys)
- ✅ No hardcoded RPC URLs or addresses
- ✅ Easy to switch between networks
- ✅ Type-safe with full IDE autocomplete
- ✅ Consistent across EVM and Solana
See examples/config-usage.ts for complete examples.
Option 2: Using Pre-configured Configs
import { OnchainMailerClient, TESTNET_CHAIN_CONFIG } from '@johnqh/mail_box_contracts';
// Works with ANY wallet - automatically detects chain!
const client = new OnchainMailerClient(wallet, TESTNET_CHAIN_CONFIG);
// Same API works for both EVM and Solana
await client.sendMessage("Hello Multi-Chain!", "This works on any blockchain!", true);
await client.delegateTo("delegate-address"); // Format automatically validated
await client.claimRevenue(); // Chain-agnostic revenue claiming
console.log('Running on:', client.getChainType()); // 'evm' or 'solana'🔧 Chain-Specific Usage
EVM Chains (Ethereum, Polygon, Arbitrum, etc.)
import { OnchainMailerClient } from '@johnqh/mail_box_contracts';
import { ethers } from 'ethers';
// The unified client automatically detects EVM wallets
const wallet = {
address: "0x...",
request: async () => {},
signTransaction: async (tx: any) => tx
};
const client = new OnchainMailerClient(wallet, EVM_CHAIN_CONFIG);
// Send priority message with revenue sharing
await client.sendMessage("Hello EVM!", "Decentralized message", true);
// Delegate to another address
await client.delegateTo("0x...");
// Claim revenue share
await client.claimRevenue();Solana
import { OnchainMailerClient, Wallet } from '@johnqh/mail_box_contracts';
import { Keypair, Transaction } from '@solana/web3.js';
// Create a wallet from keypair
const keypair = Keypair.generate();
const wallet: Wallet = {
publicKey: keypair.publicKey,
signTransaction: async (tx) => { tx.partialSign(keypair); return tx; },
signAllTransactions: async (txs) => { txs.forEach(tx => tx.partialSign(keypair)); return txs; },
};
const client = new OnchainMailerClient(wallet, SOLANA_CHAIN_CONFIG);
// Send priority message with revenue sharing
await client.sendMessage("Hello Solana!", "Decentralized message", true);
// Delegate to another address
await client.delegateTo("...");
// Claim revenue share
await client.claimRevenue();TypeScript Support
Full TypeScript support with auto-generated contract types:
import type {
Mailer,
MockUSDC
} from 'mail_box_contracts/typechain-types';
// Fully typed contract interactions
const tx: ContractTransaction = await mailer.sendPriority(to, subject, body);
const receipt: ContractReceipt = await tx.wait();📁 Project Structure
mail_box_contracts/
├── contracts/ # EVM smart contracts (Solidity)
│ ├── MailService.sol # EVM delegation management
│ ├── Mailer.sol # EVM messaging with revenue sharing
│ └── MockUSDC.sol # Test USDC token
├── programs/ # Solana programs (Rust)
│ └── mailer/ # Solana messaging and delegation program
├── src/ # Multi-chain TypeScript clients
│ ├── evm/ # EVM-specific clients
│ ├── solana/ # Solana-specific clients
│ ├── unified/ # Cross-chain unified client
│ ├── react-native/ # React Native entry point & polyfills
│ └── utils/ # Shared utilities & validation
├── test/ # Comprehensive test suites (116 tests)
│ ├── evm/ # EVM contract tests (75 tests)
│ ├── solana/ # Solana program tests
│ └── unified/ # Cross-chain client tests (41 tests)
├── typechain-types/ # Auto-generated TypeScript types
├── examples/ # Complete usage examples
└── CLAUDE.md # AI assistant documentation🚀 Quick Start
Prerequisites
- Node.js 16+
- npm or yarn
Installation
# Clone and install dependencies
npm install
# Compile contracts and generate types
npm run compile
# Run comprehensive test suite (116 tests)
npm test
# Deploy to local network
npm run deploy:local📋 Smart Contracts
MailService Contract
Purpose: Domain registration and delegation management
Key Functions:
delegateTo(address)- Delegate email handling (10 USDC fee)rejectDelegation(address)- Reject unwanted delegationsregisterDomain(string, bool)- Register domains (100 USDC fee)setRegistrationFee(uint256)- Owner fee management
Fees:
- Domain Registration: 100 USDC
- Delegation: 10 USDC
Mailer Contract
Purpose: Message sending with revenue sharing
Message Types:
- Priority Messages: Full fee (0.1 USDC) + 90% revenue share
sendPriority(subject, body)sendPriorityPrepared(mailId)
- Standard Messages: 10% fee only (0.01 USDC)
send(subject, body)sendPrepared(mailId)
Revenue Model:
- Senders pay fees to send messages to themselves
- Priority senders get 90% back as claimable revenue
- 60-day claim period for revenue shares
- Expired shares go to contract owner
🧪 Testing
Comprehensive test coverage with 116 passing tests:
# Run all tests
npm test
# Test categories:
# ✅ EVM Tests (75 tests) - Contract functionality, fees, revenue sharing
# ✅ Unified Tests (41 tests) - Cross-chain client, validation, wallet detectionTest Highlights
- Fee calculation verification
- Event emission testing
- Revenue sharing mechanics
- Time-based claim expiration
- Error condition handling
- Edge cases and security
🔧 Development Commands
# Essential commands (run these frequently!)
npm run compile # Compile contracts + generate TypeScript types
npm test # Run all 116 tests (75 EVM + 41 Unified)
npm run build # Build TypeScript files
# AI-Optimized commands
npm run ai:dev # Show AI helper commands + status
npm run ai:status # Quick project health check
npm run ai:build # Clean build everything
npm run ai:test # Run comprehensive test suite (116 tests)
npm run ai:check # TypeScript + ESLint validation
# Development
npx hardhat node # Start local blockchain
npm run deploy:local # Deploy to local network
npm run clean # Clean artifacts📊 Architecture
Revenue Sharing Flow
- Priority Message: User pays 0.1 USDC
- Revenue Split: 90% claimable by sender, 10% to owner
- Claim Period: 60 days to claim revenue share
- Expiration: Unclaimed shares go to contract owner
Delegation System
- Delegate: Pay 10 USDC to delegate email handling
- Reject: Delegates can reject unwanted delegations
- Clear: Set delegate to address(0) to clear
🛠️ TypeScript Integration
Full TypeScript support with auto-generated types:
import { OnchainMailerClient } from "@johnqh/mail_box_contracts";
// Type-safe contract interactions using unified client
const client = new OnchainMailerClient(wallet, chainConfig);
await client.delegateTo(delegateAddress);
await client.sendMessage("Subject", "Body", true); // priority message
await client.claimRevenue();🔐 Security Features
- Owner-only functions protected by
onlyOwnermodifier - USDC transfer validation - operations only proceed if payment succeeds
- Time-based expiration for revenue claims
- Address validation for delegation rejection
- Comprehensive error handling with custom errors
🤖 AI-Assisted Development
This project is optimized for AI-assisted development with comprehensive documentation, patterns, and tooling:
Quick Start for AI Assistants
- Read:
AI_ASSISTANT_QUICKSTART.md- Essential guide for AI development - Reference:
CLAUDE.md- Comprehensive AI assistant documentation - Patterns:
docs/AI_DEVELOPMENT_PATTERNS.md- Development patterns and examples - Config:
.ai-config.json- AI tool configuration
AI Development Features
- 🔧 AI Commands:
npm run ai:devfor AI-optimized development workflows - 📊 Test Coverage: 116 tests with detailed patterns for AI reference
- 📝 Rich Documentation: Comprehensive JSDoc comments and inline examples
- 🎯 Success Metrics: Clear validation criteria and checklists
- ⚡ Quick Validation:
npm run ai:checkfor TypeScript + ESLint - 🔍 Project Status:
npm run ai:statusfor health check
Documentation Structure
- Primary Guide:
CLAUDE.md- Main AI assistant documentation - Quick Reference:
AI_ASSISTANT_QUICKSTART.md- Fast setup - Development Patterns:
docs/AI_DEVELOPMENT_PATTERNS.md- Code examples - Upgradeability Guide:
docs/UPGRADEABILITY.md- Contract upgrade procedures - Examples:
examples/- Working code samples
🤝 Contributing
- Fork the repository
- Create feature branch:
git checkout -b feature/new-feature - Add comprehensive tests for new functionality
- Ensure all 116 tests pass:
npm test - Submit pull request
📄 License
MIT License - see LICENSE file for details.
Built with: Hardhat, TypeScript, Solidity ^0.8.24, Ethers v6, React Native
