purechainlib
v2.0.8
Published
SDK for PureChain EVM network - Zero gas blockchain with performance monitoring, ABI support, and PoA/PoA² consensus
Readme
PureChainLib v2.0.8
Production-ready SDK for the PureChain EVM network - a zero gas fee blockchain with full Ethereum compatibility. Now with modular architecture for optimized browser usage, flexible imports, and complete NFT functionality.
🚀 v2.0.8 Modular Architecture
New: Modular imports for smaller bundle sizes and browser compatibility. Import only what you need!
🔗 Real Network Connection
All functions connect to the REAL PureChain blockchain:
- RPC Endpoint:
https://purechainnode.com:8547 - Chain ID:
900520900520 - Network: PureChain Testnet (Live)
- Current Block: 78,000+ and growing
- Gas Price: 0 (Zero gas fees!)
✨ What's New in v2.0.8
- 🚀 Modular Architecture - Import only what you need for smaller bundles
- 🌐 Browser-Ready - Client and NFT modules work in browsers without configuration
- 📦 Selective Imports - Choose from client, compiler, or NFT modules
- 🌳 Tree-Shaking - Full support for bundler optimizations
- ✅ Backward Compatible - All existing code continues to work
- 🎨 Complete NFT System - Full NFT deployment and management capabilities
- ✅ Zero Breaking Changes - Safe upgrade from v2.0.7
🚀 Key Features
- ✅ Zero Gas Fees - All transactions cost 0 gas
- 🎨 NFT Support - Complete NFT deployment and management system
- ✅ Flexible Imports - Use
require('purechainlib')orconst { PureChain } = require('purechainlib') - ✅ Real Blockchain - Direct connection to PureChain network
- ✅ Performance Monitoring - Track latency and TPS with microsecond precision
- ✅ Complete ABI Support - Full ethers.js v6 compatibility
- ✅ Solidity Compiler - Built-in contract compilation
- ✅ OpenZeppelin Support - Import and use OpenZeppelin contracts
- ✅ Direct Explorer - No external API dependencies
- ✅ Production Ready - Used in real applications
Installation
npm install purechainlibQuick Start
Traditional Import (Full SDK)
// Both import styles work!
const PureChain = require('purechainlib'); // ✅ Direct import
// OR
const { PureChain } = require('purechainlib'); // ✅ Destructured import
// Initialize
const purechain = new PureChain('testnet');
// Connect with private key
purechain.connect('your_private_key_here');
// Check balance
const balance = await purechain.balance();
console.log('Balance:', balance, 'ETH');Modular Imports (NEW in v2.0.8)
// Browser-compatible client (no compiler)
import { PureChainClient } from 'purechainlib/client';
const client = new PureChainClient('testnet');
await client.balance();
// NFT operations (browser-compatible)
import { PureChainNFT } from 'purechainlib/nft';
const nft = new PureChainNFT(provider);
await nft.mint(contractAddress, recipientAddress);
// Solidity compiler (Node.js only)
import { PureChainCompiler } from 'purechainlib/compiler';
const compiler = new PureChainCompiler();
await compiler.compile(sources);API Reference
Initialize
// Connect to testnet (default)
const purechain = new PureChain('testnet');
// Connect to mainnet
const purechain = new PureChain('mainnet');
// Custom network configuration
const purechain = new PureChain({
name: 'Custom Network',
chainId: 1337,
rpcUrl: 'http://localhost:8545'
});Account Management
Create Account
// Generate new account
const account = purechain.account();
console.log(account.address);
console.log(account.privateKey);
console.log(account.mnemonic);Connect Account
// Connect with private key
purechain.connect('0x...');
// Connect with mnemonic
purechain.connect('word1 word2 word3...');NFT Deployment and Management
Quick NFT Deployment
// Deploy pctestdkim NFT
const nftContract = `
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract PCTestDKIM {
string public name = "pctestdkim";
string public symbol = "PCDKIM";
string public metadata = "One of the BEST professor in the world!";
mapping(uint256 => address) private owners;
mapping(address => uint256) private balances;
uint256 private tokenId;
event Transfer(address indexed from, address indexed to, uint256 indexed id);
function mint(address to) public returns (uint256) {
uint256 id = tokenId++;
owners[id] = to;
balances[to]++;
emit Transfer(address(0), to, id);
return id;
}
function balanceOf(address owner) public view returns (uint256) {
return balances[owner];
}
function ownerOf(uint256 id) public view returns (address) {
return owners[id];
}
}
`;
const factory = await purechain.contract(nftContract);
const nft = await factory.deploy();
console.log('NFT deployed at:', await nft.getAddress());
// Mint NFT
const mintTx = await nft.mint(walletAddress);
await mintTx.wait();
console.log('NFT minted!');NFT Helper Methods
// Mint NFT using SDK helper
await purechain.mintNFT(contractAddress, recipientAddress);
// Check NFT balance
const balance = await purechain.nftBalance(contractAddress, ownerAddress);
// Get NFT info
const info = await purechain.nftInfo(contractAddress, tokenId);
// Get collection info
const collection = await purechain.nftCollection(contractAddress);
// Transfer NFT
await purechain.transferNFT(contractAddress, toAddress, tokenId);NFT Template Helper
// Use the template helper for quick deployment
const { getSimpleNFTTemplate } = require('purechainlib/templates');
const nftCode = getSimpleNFTTemplate(
'MyCollection', // name
'MYC', // symbol
'My awesome NFT!' // metadata
);
const factory = await purechain.contract(nftCode);
const nft = await factory.deploy();
console.log('NFT deployed at:', await nft.getAddress());Advanced NFT Features (Future)
// Modular NFT system (in development for full ERC721 compliance)
const { NFTModularManager } = require('purechainlib/modular');
const manager = new NFTModularManager(provider, signer);
const deployment = await manager.deployFullNFT({
name: 'Full Featured NFT',
symbol: 'FFN',
baseURI: 'https://api.example.com/',
maxSupply: 1000,
royaltyBps: 250 // 2.5% royalty
});⚠️ NFT Gas Limit Considerations
PureChain has an 8M gas computational limit that affects NFT deployment:
| Approach | Gas Usage | Status | Recommendation | |----------|-----------|--------|----------------| | Simple Templates | ~1.5M | ✅ Working | ✅ Use Now | | Modular Architecture | ~7.5M | ⏳ Development | ⏳ Future | | OpenZeppelin Imports | >10M | ❌ Fails | ❌ Avoid |
Current Limitation: The purechain.nft() convenience method may hit gas limits.
Working Solution: Use purechain.contract() + templates (proven to work!)
📚 Complete NFT Documentation | Quick Reference | Gas Analysis
✅ Browser Compatibility (v2.0.8)
FIXED in v2.0.8: The SDK now offers modular imports for browser compatibility. Use purechainlib/client or purechainlib/nft for browser applications without any configuration needed!
For Web Applications: Add webpack configuration to handle Node.js modules:
// next.config.js or webpack.config.js
module.exports = {
webpack: (config) => {
config.resolve.fallback = {
fs: false,
path: false,
crypto: false,
stream: false,
util: false,
os: false
};
return config;
}
};Alternative: Use dynamic imports for client-side usage:
// Client-side dynamic loading
const loadPureChain = async () => {
if (typeof window !== 'undefined') {
const { PureChain } = await import('purechainlib');
return PureChain;
}
};Future Enhancement: v3.0.0 will include dedicated browser-compatible builds.
📚 Browser Compatibility Guide | v3.0.0 Roadmap
Contract Deployment
From Solidity File
// Compile and deploy from .sol file
const factory = await purechain.contract('contracts/Token.sol');
const contract = await factory.deploy(constructorArg1, constructorArg2);
console.log('Contract address:', await contract.getAddress());From Solidity Source
// Compile from source code
const source = `
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 public value;
function setValue(uint256 _value) public {
value = _value;
}
}
`;
const factory = await purechain.contract(source);
const contract = await factory.deploy();With OpenZeppelin Imports
// Deploy an OpenZeppelin ERC20 token
const source = `
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
constructor() ERC20("MyToken", "MTK") {
_mint(msg.sender, 1000000 * 10**18);
}
}
`;
const factory = await purechain.contract(source);
const token = await factory.deploy();
console.log('OpenZeppelin token deployed:', await token.getAddress());Contract Interaction
Read Methods (Call)
// Call read-only methods
const result = await purechain.call(contract, 'getValue');
const balance = await purechain.call(contract, 'balanceOf', accountAddress);Write Methods (Execute)
// Execute state-changing methods
await purechain.execute(contract, 'setValue', 100);
await purechain.execute(contract, 'transfer', recipientAddress, amount);Transactions
Send ETH
// Simple send
await purechain.send('0x...recipientAddress', '1.0');
// With transaction object
await purechain.send({
to: '0x...',
value: '1.0',
data: '0x...'
});Check Balance
// Current account balance
const myBalance = await purechain.balance();
// Any address balance
const balance = await purechain.balance('0x...');Blockchain Queries
Get Block
// Latest block
const block = await purechain.block();
// Specific block
const block = await purechain.block(12345);Get Transaction
// Get transaction by hash
const tx = await purechain.transaction('0x...');
// Wait for transaction
const receipt = await purechain.waitForTransaction('0x...', 1);Core Classes
PureChain
Main class providing the Pythonic-style API for all blockchain operations.
ContractFactory
Returned by purechain.contract(), used to deploy contracts.
const factory = await purechain.contract('Token.sol');
const contract = await factory.deploy();
const abi = factory.getABI();
const bytecode = factory.getBytecode();ContractManager
Internal class that handles Solidity compilation using solc.
AccountManager
Internal class that manages account creation and signing.
TransactionBuilder
Internal class that builds transactions with zero gas configuration.
Network Configuration
Testnet (Default)
- Chain ID: 900520900520
- RPC URL: https://purechainnode.com:8547
- Gas Price: 0 (zero gas fees)
Mainnet
- Chain ID: 900520900520
- RPC URL: https://purechainnode.com:8547
- Gas Price: 0 (zero gas fees)
Examples
Deploy ERC20 Token
const PureChain = require('purechainlib'); // Direct import now works!
async function deployToken() {
const purechain = new PureChain('testnet');
// Create account
const account = purechain.account();
purechain.connect(account.privateKey);
// Deploy token contract
const factory = await purechain.contract('contracts/Token.sol');
const token = await factory.deploy('MyToken', 'MTK', 1000000);
console.log('Token deployed at:', await token.getAddress());
// Interact with token
await purechain.execute(token, 'transfer', recipientAddress, 100);
const balance = await purechain.call(token, 'balanceOf', recipientAddress);
console.log('Recipient balance:', balance);
}Complete Transaction Flow
async function transactionExample() {
const purechain = new PureChain('testnet');
// Create or import account
purechain.connect('your_private_key');
// Check balance
const balance = await purechain.balance();
console.log('Balance:', balance);
// Send transaction
const receipt = await purechain.send('0x...recipient', '0.1');
console.log('Transaction hash:', receipt.hash);
// Get transaction details
const tx = await purechain.transaction(receipt.hash);
console.log('Transaction:', tx);
}Performance Monitoring
PureChainLib includes built-in performance monitoring with microsecond precision timing and TPS tracking.
Performance Tracking Methods
// Track transaction performance
const { receipt, metrics } = await purechain.sendWithMetrics('0x...', '1.0');
console.log('Latency:', metrics.duration, 'ms');
// Track deployment performance
const { contract, metrics } = await purechain.deployWithMetrics(factory);
console.log('Deployment time:', metrics.duration, 'ms');
// Track contract execution
const { receipt, metrics } = await purechain.executeWithMetrics(
contract, 'methodName', arg1, arg2
);
// Get performance statistics
const stats = purechain.getPerformanceStats();
console.log('Average latency:', stats.averageLatency, 'ms');
console.log('Current TPS:', stats.currentTPS);
console.log('Peak TPS:', stats.peakTPS);
console.log('P95 latency:', stats.p95Latency, 'ms');
// Get performance report
const report = purechain.getPerformanceReport(true);
console.log(report);
// Reset metrics
purechain.resetPerformanceMetrics();Blockchain Explorer (Pythonic One-Liners)
PureChainLib provides direct blockchain access through RPC with Pythonic-style one-liner methods. No external API needed - connects directly to PureChain nodes.
Quick Explorer Methods
// Get transaction - no args uses last tx from connected account
const tx = await purechain.tx(); // Last transaction
const tx = await purechain.tx('0x...hash'); // Specific transaction
// Get address info - no args uses connected account
const info = await purechain.address(); // Current account
const info = await purechain.address('0x...'); // Specific address
// Quick balance check in PURE
const bal = await purechain.bal(); // Current account balance
const bal = await purechain.bal('0x...'); // Specific address balance
// Transaction history
const txs = await purechain.txHistory(); // Last 10 txs for current account
const txs = await purechain.txHistory('0x...', 50); // 50 txs for address
// Check if address is contract
const isContract = await purechain.isContract('0x...');
// Get contract events
const events = await purechain.events('0x...'); // Latest block events
const events = await purechain.events('0x...', 100); // Last 100 blocks
// Transaction receipt
const receipt = await purechain.txReceipt('0x...hash');
// Network status
const network = await purechain.status();
console.log('Chain ID:', network.chainId);
console.log('Peers:', network.peerCount);Direct Blockchain Explorer
// Get direct explorer for advanced usage
const explorer = purechain.directExplorer();
// Get block information
const block = await explorer.getBlock('latest');
const block = await explorer.getBlock(12345);
// Get transaction with full details
const tx = await explorer.getTransaction('0x...hash');
console.log('Status:', tx.status);
console.log('Confirmations:', tx.confirmations);
// Get address details with balance in Ether
const addr = await explorer.getAddress('0x...');
console.log('Balance:', addr.balanceInEther, 'PURE');
console.log('Is Contract:', addr.isContract);
console.log('Nonce:', addr.nonce);
// Verify payment
const valid = await explorer.verifyPayment(
'0x...hash',
'0x...from',
'0x...to',
'100.0' // Amount in PURE
);
// Get network info
const network = await explorer.getNetworkInfo();
console.log('Chain ID:', network.chainIdNumber);
console.log('Gas Price:', network.gasPrice); // Always 0 on PureChain!Zero Gas Configuration
All transactions on PureChain have zero gas fees. The library automatically sets:
gasPrice: 0gasLimit: 8000000for contract deploymentsgasLimit: 1000000for regular transactions
You don't need to configure or worry about gas fees.
Requirements
- Node.js >= 16.0.0
- npm >= 8.0.0
Dependencies
ethers- Ethereum library for interacting with EVMsolc- Solidity compiler- Other standard dependencies (see package.json)
Complete Function Reference
Core Methods
Initialization & Connection
new PureChain(network) // Initialize with 'testnet', 'mainnet', or config object
.connect(privateKeyOrMnemonic) // Connect wallet (returns this for chaining)
.account() // Generate new account {address, privateKey, mnemonic}
.network() // Get current network configuration
.getProvider() // Get ethers JsonRpcProvider instance
.getSigner() // Get ethers Signer instance (if connected)Account & Balance
.balance(address?) // Get balance in ETH (current account if no address)
.bal(address?) // Quick balance check in PURE (Pythonic style)
.address(address?) // Get address info (current account if no address)
.isContract(address) // Check if address is a contractContract Operations
.contract(pathOrSource) // Compile Solidity (.sol file or source code)
.compile(sources) // Compile multiple files {filename: source}
.call(contract, method, ...args) // Call read-only contract method
.execute(contract, method, ...args) // Execute state-changing contract methodTransactions
.send(addressOrTx, value?) // Send transaction (simple or object)
.waitForTransaction(hash, confirmations?) // Wait for transaction confirmation
.gasPrice() // Get gas price (always 0n on PureChain)
.estimateGas(tx) // Estimate gas for transactionBlockchain Queries
.block(number?) // Get block ('latest' or number)
.transaction(hash) // Get transaction by hash
.getLogs(filter) // Get event logs
.on(event, callback) // Listen to events
.off(event, callback) // Stop listening to eventsExplorer Methods (Pythonic One-Liners)
Transaction Explorer
.tx(hash?) // Get transaction (current account's last tx if no hash)
.txHistory(address?, limit?) // Get transaction history (default: 10 txs)
.txReceipt(hash) // Get transaction receipt
.verify(txHash) // Verify transaction statusAddress & Contract Explorer
.addressInfo(address, limit?) // Get address info with transaction history
.history(address, limit?) // Get transaction history (up to 100)
.contractEvents(contractAddress) // Monitor smart contract events
.events(contract, blocks?) // Get contract events (latest block or X blocks)
.status() // Get network status and infoReceipt & Verification
.receipt(txHash, format?) // Get receipt ('html' or 'json')
.receiptURL(txHash) // Get URL for HTML receipt
.saveReceipt(txHash, filepath, format?) // Save receipt to file (Node.js only)
.verifyPayment(txHash, from, to, value?) // Verify payment between addresses
.explorerBalance(address) // Get balance from explorer API
.explorer() // Get ExplorerAPI instance
.directExplorer() // Get BlockchainExplorer instancePerformance Monitoring
Performance Tracking
.sendWithMetrics(tx, value?) // Send transaction with performance tracking
.deployWithMetrics(factory, ...args) // Deploy contract with performance tracking
.executeWithMetrics(contract, method, ...args) // Execute with performance trackingPerformance Analysis
.getPerformanceStats(operation?, period?) // Get performance statistics
.getPerformanceReport(detailed?) // Get formatted performance report
.resetPerformanceMetrics() // Reset all performance metrics
.performance() // Get PerformanceMonitor instanceContractFactory Methods
Deployment & Management
factory.deploy(...args) // Deploy contract with zero gas
factory.attach(address) // Attach to existing contract
factory.getABI() // Get contract ABI array
factory.getBytecode() // Get contract bytecode stringAdvanced Usage
Direct Instances
// Get manager instances for advanced usage
purechain.explorer() // ExplorerAPI for REST endpoints
purechain.directExplorer() // BlockchainExplorer for direct RPC
purechain.performance() // PerformanceMonitor for metricsNetwork Configuration Examples
// Testnet (default)
const purechain = new PureChain('testnet');
// Mainnet
const purechain = new PureChain('mainnet');
// Custom network
const purechain = new PureChain({
name: 'Custom Network',
chainId: 1337,
rpcUrl: 'http://localhost:8545',
explorerUrl: 'http://localhost:4000'
});Chaining Examples
// Method chaining for initialization
const purechain = new PureChain('testnet').connect(privateKey);
// Quick deployment and interaction
const factory = await purechain.contract(source);
const contract = await factory.deploy();
await purechain.execute(contract, 'setValue', 123);
const value = await purechain.call(contract, 'getValue');Performance Examples
// Track deployment performance
const { contract, metrics } = await purechain.deployWithMetrics(factory);
console.log(`Deployed in ${metrics.duration}ms`);
// Track execution performance
const { receipt, metrics } = await purechain.executeWithMetrics(contract, 'transfer', to, amount);
console.log(`Executed in ${metrics.duration}ms, Gas: ${receipt.gasUsed}`);
// Get performance statistics
const stats = purechain.getPerformanceStats();
console.log(`Average latency: ${stats.averageLatency}ms`);
console.log(`Current TPS: ${stats.currentTPS}`);
console.log(`Peak TPS: ${stats.peakTPS}`);License
MIT
Support
For issues and questions:
- GitHub Issues: https://github.com/islarpee000/purechainlib/issues
- Documentation: This README
