Multi-chain decentralized messaging system with USDC fees, revenue sharing, and delegation management. Unified TypeScript client for EVM chains and Solana.
npm install @sudobility/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.md and CLAUDE.md for AI development guides.
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.
- ๐ 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)
``bashInstall the unified multi-chain TypeScript client library
npm install @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 |$3
`typescript
// Works everywhere - auto-detects platform
import { OnchainMailerClient } from '@sudobility/contracts';
`$3
`typescript
// 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';
`$3
React Native requires polyfills to be imported first in your app entry point:
`typescript
// 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:
`typescript
// 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:
`bash
npm install react-native-get-random-values buffer react-native-url-polyfill text-encoding
`docs/REACT_NATIVE.md for complete React Native setup guide.๐ Quick Start - Unified Multi-Chain Client
$3
The simplest way to initialize clients using API keys - all chain information is automatically derived:
`typescript
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
examples/config-usage.ts for complete examples.$3
`typescript
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
$3
`typescript
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();
`$3
`typescript
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();
`$3
Full TypeScript support with auto-generated contract types:
`typescript
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
$3
- Node.js 16+
- npm or yarn
$3
`bash
Clone and install dependencies
npm installCompile contracts and generate types
npm run compileRun comprehensive test suite (116 tests)
npm testDeploy to local network
npm run deploy:local
`๐ Smart Contracts
$3
Purpose: Domain registration and delegation management
Key Functions:
-
delegateTo(address) - Delegate email handling (10 USDC fee)
- rejectDelegation(address) - Reject unwanted delegations
- registerDomain(string, bool) - Register domains (100 USDC fee)
- setRegistrationFee(uint256) - Owner fee managementFees:
- Domain Registration: 100 USDC
- Delegation: 10 USDC
$3
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:
`bash
Run all tests
npm testTest categories:
โ
EVM Tests (75 tests) - Contract functionality, fees, revenue sharing
โ
Unified Tests (41 tests) - Cross-chain client, validation, wallet detection
`$3
- Fee calculation verification
- Event emission testing
- Revenue sharing mechanics
- Time-based claim expiration
- Error condition handling
- Edge cases and security
๐ง Development Commands
`bash
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 filesAI-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 validationDevelopment
npx hardhat node # Start local blockchain
npm run deploy:local # Deploy to local network
npm run clean # Clean artifacts
`๐ Architecture
$3
1. Priority Message: User pays 0.1 USDC
2. Revenue Split: 90% claimable by sender, 10% to owner
3. Claim Period: 60 days to claim revenue share
4. Expiration: Unclaimed shares go to contract owner
$3
1. Delegate: Pay 10 USDC to delegate email handling
2. Reject: Delegates can reject unwanted delegations
3. Clear: Set delegate to address(0) to clear
๐ ๏ธ TypeScript Integration
Full TypeScript support with auto-generated types:
`typescript
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
onlyOwner modifier
- 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:
$3
AI_ASSISTANT_QUICKSTART.md - Essential guide for AI development
2. Reference: CLAUDE.md - Comprehensive AI assistant documentation
3. Patterns: docs/AI_DEVELOPMENT_PATTERNS.md - Development patterns and examples
4. Config: .ai-config.json - AI tool configuration$3
- ๐ง AI Commands:
npm run ai:dev for 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:check for TypeScript + ESLint
- ๐ Project Status: npm run ai:status for health check$3
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
1. Fork the repository
2. Create feature branch:
git checkout -b feature/new-feature
3. Add comprehensive tests for new functionality
4. Ensure all 116 tests pass: npm test`MIT License - see LICENSE file for details.
---
Built with: Hardhat, TypeScript, Solidity ^0.8.24, Ethers v6, React Native