<div align="left">
# PureChain Python Library
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
[](https://pypi.org/project/purechainlib/)
**Zero Gas Cost Blockchain Development in Python**
Python SDK for PureChain EVM network with **completely FREE transactions**. Deploy contracts, send tokens, and interact with smart contracts without any gas fees!
## π Korean Documentation / νκ΅μ΄ λ¬Έμ
Korean documentation is included in this package. After installation, you can find `README_ko.md` in your package directory.
νκ΅μ΄ λ¬Έμκ° ν¨ν€μ§μ ν¬ν¨λμ΄ μμ΅λλ€. μ€μΉ ν ν¨ν€μ§ λλ ν 리μμ `README_ko.md` νμΌμ μ°Ύμ μ μμ΅λλ€.
```python
# How to access Korean README after installation:
import purechainlib
import os
korean_readme_path = os.path.join(os.path.dirname(purechainlib.__file__), '..', 'README_ko.md')
print(f"Korean README location: {korean_readme_path}")
```
</div>
## π What's New in v2.1.4
### Performance Improvements
- Significantly improved dependency resolution speed
- Fixed eth-abi and parsimonious compatibility issues
- Made mythril optional to avoid dependency conflicts
### Bug Fixes (v2.1.1-2.1.3)
- Fixed security audit results display issue
- Resolved dependency version conflicts
## Previous Updates (v2.1.0)
### π Smart Contract Security Auditing
- **Built-in security tools** - Slither bundled, Mythril optional
- **Auto-installation** - Tools install automatically on first use
- **One-liner audits** - `await pcl.audit("contract code")`
- **Multiple tools** - Choose Slither, Mythril (if installed), or run ALL
- **Comprehensive logging** - Perfect for LLM integration
- **Export reports** - JSON, Markdown, HTML formats
- **Note**: Mythril can be installed separately with `pip install mythril==0.24.8`
### π Documentation Updates
- Removed private GitHub repository links
- Improved Korean documentation access instructions
- Package now fully self-contained with both English and Korean docs
<!-- - Added comprehensive help system (hint: try `pc.help.` and explore!) -->
## Previous Updates
### v2.0.8 - Korean Language Support
- Complete Korean documentation now available
- Korean README included in the package (README_ko.md)
- Optimized examples for Korean developers
### v2.0.7
### π± Carbon Footprint Tracking
- **Scientific measurements** of energy consumption (Joules) and CO2 emissions
- **ESG compliance** reporting for environmental impact
- **Regional grid intensity** support (US, EU, Asia, etc.)
- Compare efficiency with other blockchains (99.99999% less CO2 than Ethereum!)
### π§ Automatic Web3 Middleware
- No more manual `web3.middleware` imports needed
- Automatic compatibility with all Web3 versions
- Just `from purechainlib import PureChain` and you're ready!
### π Energy Measurements
- **0.029 Joules** per transaction (scientifically measured)
- **63 billion times** more efficient than Bitcoin
- Based on actual CPU power monitoring, not estimates
<!-- [See full carbon tracking documentation](#-carbon-footprint-tracking) -->
## π Quick Start
```bash
pip install purechainlib
```
**Note:** Version 2.1.4+ has optimized dependencies for fast installation. Security tools like Mythril can be installed separately if needed.
```python
import asyncio
from purechainlib import PureChain
# No need for web3.middleware imports - handled automatically!
async def main():
# Initialize PureChain
pc = PureChain('testnet')
# Connect your wallet
pc.connect('your_private_key_here')
# Check balance (FREE!)
balance = await pc.balance()
print(f"Balance: {balance} PURE")
# Deploy a contract (FREE!)
contract_source = """
pragma solidity ^0.8.19;
contract Hello {
string public message = "Hello PureChain!";
function setMessage(string memory _msg) public {
message = _msg;
}
}
"""
factory = await pc.contract(contract_source)
contract = await factory.deploy() # No gas fees!
print(f"Contract deployed: {contract.address}")
asyncio.run(main())
```
## β¨ Features
- **Zero Gas Costs** - All operations are completely FREE
- **Security Auditing** - Built-in smart contract vulnerability scanning
- **Easy to Use** - Simple, intuitive API
- **Full EVM Support** - Deploy any Solidity contract
- **Pythonic** - Clean, readable Python code
- **Secure** - Industry-standard cryptography
- **Complete** - Account management, compilation, deployment, auditing
## π Quick Reference
### All Available Functions
| Function | Description | Example |
|----------|-------------|---------|
| `PureChain(network, private_key?)` | Initialize connection | `pc = PureChain('testnet')` |
| `connect(private_key)` | Connect wallet | `pc.connect('your_private_key')` |
| `account()` | Create new account | `acc = pc.account()` |
| `balance(address?)` | Get balance | `bal = await pc.balance()` |
| `bal(address?)` | Get balance (short) | `bal = await pc.bal()` |
| `send(to, value?)` | Send PURE tokens | `await pc.send('0x...', '1.0')` |
| `contract(source)` | Compile contract | `factory = await pc.contract(code)` |
| `factory.deploy(*args)` | Deploy contract | `contract = await factory.deploy()` |
| `call(contract, method, *args)` | Read from contract | `result = await pc.call(contract, 'balances', addr)` |
| `execute(contract, method, *args)` | Write to contract | `await pc.execute(contract, 'mint', 1000)` |
| `block(number?)` | Get block info | `block = await pc.block()` |
| `transaction(hash)` | Get transaction | `tx = await pc.transaction('0x...')` |
| `gasPrice()` | Get gas price (always 0) | `price = await pc.gasPrice()` |
| `address(addr?)` | Get address info | `info = await pc.address()` |
| `isContract(address)` | Check if contract | `is_contract = await pc.isContract('0x...')` |
| `events(contract, blocks?)` | Get contract events | `events = await pc.events(addr, 10)` |
| `status()` | Get network status | `status = await pc.status()` |
| `tx(hash?)` | Get transaction (alias) | `tx = await pc.tx('0x...')` |
| `testTPS(duration?, target?, mode?)` | Test TPS performance | `results = await pc.testTPS(30, 100, 'full')` |
| `measureLatency(operations?)` | Measure operation latency | `latency = await pc.measureLatency(100)` |
| `benchmarkThroughput(duration?)` | Test blockchain throughput (TPS) | `throughput = await pc.benchmarkThroughput(60)` |
| `runPerformanceTest(quick?)` | Full performance suite | `results = await pc.runPerformanceTest()` |
| `enableCarbonTracking(region?)` | Enable carbon footprint tracking | `pc.enableCarbonTracking('us')` |
| `disableCarbonTracking()` | Disable carbon tracking | `pc.disableCarbonTracking()` |
| `getCarbonReport()` | Get carbon emissions report | `report = await pc.getCarbonReport()` |
| `getCarbonESGMetrics()` | Get ESG compliance metrics | `esg = await pc.getCarbonESGMetrics()` |
| `exportCarbonReport()` | Export full carbon report as JSON | `json_report = await pc.exportCarbonReport()` |
| **SECURITY AUDITING** | | |
| `audit(contract, **kwargs)` | One-liner security audit | `await pc.audit(code)` |
| `auditContract(contract, tool?)` | Full security audit | `await pc.auditContract(code, tool=SecurityTool.SLITHER)` |
| `auditAndDeploy(contract, ...)` | Audit then deploy if safe | `await pc.auditAndDeploy(code, require_pass=True)` |
| `runSecurityLoop(contract, max?)` | Iterative security fixing | `await pc.runSecurityLoop(code, max_iterations=5)` |
| `enableAutoAudit(tool?)` | Auto-audit before deployments | `pc.enableAutoAudit()` |
| `checkSecurityTools()` | Check installed tools | `pc.checkSecurityTools()` |
| `getSecurityLogs()` | Get all audit logs | `logs = pc.getSecurityLogs()` |
### Function Categories
#### π **Account & Wallet Management**
```python
# Initialize and connect
pc = PureChain('testnet', 'optional_private_key')
pc.connect('your_private_key_without_0x')
# Create new account
new_account = pc.account()
# Returns: {'address': '0x...', 'privateKey': '...'}
# Get current signer address
address = pc.signer.address
```
#### π° **Balance & Transactions**
```python
# Check balances
my_balance = await pc.balance() # Your balance
other_balance = await pc.balance('0x...') # Specific address
quick_balance = await pc.bal() # Shorthand
# Send PURE tokens (FREE!)
await pc.send('0x...recipient', '10.5')
# Send with transaction object
await pc.send({
'to': '0x...address',
'value': '1.0',
'data': '0x...' # Optional
})
```
#### π **Smart Contracts**
```python
# Compile and deploy
contract_source = "pragma solidity ^0.8.19; contract Test { ... }"
factory = await pc.contract(contract_source)
deployed_contract = await factory.deploy(constructor_args)
# Attach to existing contract
existing_contract = factory.attach('0x...contract_address')
# Read from contract (view functions)
result = await pc.call(contract, 'balances', user_address)
name = await pc.call(contract, 'name') # No arguments
# Write to contract (transaction functions)
await pc.execute(contract, 'mint', recipient, 1000)
await pc.execute(contract, 'setMessage', "Hello World")
```
#### π **Blockchain Information**
```python
# Block information
latest_block = await pc.block() # Latest block
specific_block = await pc.block(12345) # Specific block number
# Transaction information
tx_info = await pc.transaction('0x...hash')
tx_alias = await pc.tx('0x...hash') # Same as above
# Address information
addr_info = await pc.address() # Your address info
other_info = await pc.address('0x...') # Specific address
# Returns: {'balance': '...', 'isContract': bool, 'address': '...'}
# Check if address is contract
is_contract = await pc.isContract('0x...address')
# Gas price (always 0 on PureChain)
gas_price = await pc.gasPrice() # Returns 0
# Network status
status = await pc.status()
# Returns: {'chainId': 900520900520, 'gasPrice': 0, 'blockNumber': ...}
```
#### π **Events & Monitoring**
```python
# Get contract events
events = await pc.events(contract_address) # All events
recent_events = await pc.events(contract_address, 10) # Last 10 blocks
```
#### β‘ **Performance Testing**
```python
# Test Transactions Per Second (TPS) with different measurement modes
# Mode options: 'full' (default), 'send', 'parallel'
tps_full = await pc.testTPS(duration=30, target_tps=100, measure_mode='full') # Measure full lifecycle
tps_send = await pc.testTPS(duration=30, target_tps=100, measure_mode='send') # Measure send time only
tps_parallel = await pc.testTPS(duration=30, target_tps=100, measure_mode='parallel') # Parallel execution
print(f"Full Mode TPS: {tps_full['actual_tps']}")
print(f"Send-only TPS: {tps_send['actual_tps']}")
print(f"Parallel TPS: {tps_parallel['actual_tps']}")
# Measure operation latency
latency_results = await pc.measureLatency(operations=100)
print(f"Average latency: {latency_results['balance_check']['avg_ms']}ms")
# Benchmark blockchain throughput (mixed operations TPS)
throughput_results = await pc.benchmarkThroughput(test_duration=60)
print(f"Throughput: {throughput_results['throughput_tps']} TPS")
# Run complete performance suite
performance = await pc.runPerformanceTest(quick=True) # Quick test
full_performance = await pc.runPerformanceTest(quick=False) # Full test
```
## π Detailed API Reference
### Initialization
```python
from purechainlib import PureChain
# Connect to testnet (default)
pc = PureChain('testnet')
# Or mainnet
pc = PureChain('mainnet')
# Connect with private key immediately
pc = PureChain('testnet', 'your_private_key')
```
### Account Management
```python
# Connect wallet
pc.connect('your_private_key_without_0x_prefix')
# Create new account
account = pc.account()
print(f"Address: {account['address']}")
print(f"Private Key: {account['privateKey']}")
# Check balance
balance = await pc.balance() # Your balance
balance = await pc.balance('0x...address') # Specific address
```
### Contract Operations
```python
# Deploy contract from source
contract_source = """
pragma solidity ^0.8.19;
contract Token {
mapping(address => uint256) public balances;
function mint(uint256 amount) public {
balances[msg.sender] += amount;
}
}
"""
# Compile and deploy (FREE!)
factory = await pc.contract(contract_source)
contract = await factory.deploy()
# Read from contract (FREE!)
balance = await pc.call(contract, 'balances', user_address)
# Write to contract (FREE!)
await pc.execute(contract, 'mint', 1000)
```
### Transactions
```python
# Send PURE tokens (FREE!)
await pc.send('0x...recipient_address', '10.5')
# Send with transaction object
await pc.send({
'to': '0x...address',
'value': '1.0',
'data': '0x...' # Optional contract data
})
```
### Blockchain Information
```python
# Get latest block
block = await pc.block()
print(f"Block #{block['number']}")
# Get transaction info
tx = await pc.transaction('0x...transaction_hash')
# Network status
status = await pc.status()
print(f"Chain ID: {status['chainId']}")
print(f"Gas Price: {status['gasPrice']}") # Always 0!
# Gas price (always returns 0)
gas_price = await pc.gasPrice()
```
### Pythonic Shortcuts
```python
# Quick balance check
balance = await pc.bal()
# Address information
info = await pc.address()
print(f"Balance: {info['balance']}")
print(f"Is Contract: {info['isContract']}")
# Check if address is a contract
is_contract = await pc.isContract('0x...address')
```
## π Complete Examples
### Deploy and Interact with Token Contract
```python
import asyncio
from purechainlib import PureChain
async def token_example():
pc = PureChain('testnet')
pc.connect('your_private_key')
# Token contract
token_source = """
pragma solidity ^0.8.19;
contract SimpleToken {
mapping(address => uint256) public balances;
uint256 public totalSupply;
string public name = "PureToken";
function mint(address to, uint256 amount) public {
balances[to] += amount;
totalSupply += amount;
}
function transfer(address to, uint256 amount) public {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount;
balances[to] += amount;
}
}
"""
# Deploy token (FREE!)
factory = await pc.contract(token_source)
token = await factory.deploy()
print(f"Token deployed at: {token.address}")
# Mint tokens (FREE!)
await pc.execute(token, 'mint', pc.signer.address, 1000000)
# Check balance (FREE!)
balance = await pc.call(token, 'balances', pc.signer.address)
print(f"Token balance: {balance}")
# Transfer tokens (FREE!)
recipient = "0xc8bfbC0C75C0111f7cAdB1DF4E0BC3bC45078f9d"
await pc.execute(token, 'transfer', recipient, 100)
print("Tokens transferred!")
asyncio.run(token_example())
```
### Create and Fund Multiple Accounts
```python
import asyncio
from purechainlib import PureChain
async def multi_account_example():
pc = PureChain('testnet')
pc.connect('your_private_key')
# Create 3 new accounts
accounts = []
for i in range(3):
account = pc.account()
accounts.append(account)
print(f"Account {i+1}: {account['address']}")
# Fund each account (FREE transactions!)
for i, account in enumerate(accounts):
await pc.send(account['address'], f"{i+1}.0") # Send 1, 2, 3 PURE
print(f"Sent {i+1} PURE to account {i+1}")
# Check all balances
for i, account in enumerate(accounts):
balance = await pc.balance(account['address'])
print(f"Account {i+1} balance: {balance} PURE")
asyncio.run(multi_account_example())
```
### Contract Event Monitoring
```python
import asyncio
from purechainlib import PureChain
async def event_example():
pc = PureChain('testnet')
pc.connect('your_private_key')
# Contract with events
contract_source = """
pragma solidity ^0.8.19;
contract EventExample {
event MessageSet(address indexed user, string message);
string public message;
function setMessage(string memory _message) public {
message = _message;
emit MessageSet(msg.sender, _message);
}
}
"""
# Deploy and interact
factory = await pc.contract(contract_source)
contract = await factory.deploy()
# Set message (creates event)
await pc.execute(contract, 'setMessage', "Hello Events!")
# Get events from last 10 blocks
events = await pc.events(contract.address, 10)
print(f"Found {len(events)} events")
asyncio.run(event_example())
```
### Performance Testing & Benchmarking
```python
import asyncio
from purechainlib import PureChain
async def performance_testing():
pc = PureChain('testnet')
pc.connect('your_private_key')
print("π Starting Performance Tests...")
# 1. TPS (Transactions Per Second) Test
print("\n1οΈβ£ TPS Test - Measure transaction throughput")
tps_results = await pc.testTPS(duration=30, target_tps=50)
print(f"Target TPS: {tps_results['target_tps']}")
print(f"Achieved TPS: {tps_results['actual_tps']}")
print(f"Efficiency: {tps_results['efficiency']}%")
print(f"Average Latency: {tps_results['avg_latency_ms']}ms")
# 2. Latency Test - Measure operation response times
print(f"\n2οΈβ£ Latency Test - Measure response times")
latency_results = await pc.measureLatency(operations=50)
for operation, stats in latency_results.items():
print(f"{operation}: {stats['avg_ms']}ms (min: {stats['min_ms']}, max: {stats['max_ms']})")
# 3. Throughput Test - Measure data transfer rates
print(f"\n3οΈβ£ Throughput Test - Measure data transfer")
throughput_results = await pc.benchmarkThroughput(test_duration=45)
print(f"Total TPS: {throughput_results['throughput_tps']}")
print(f"Data Transfer: {throughput_results['kb_per_second']} KB/s")
print(f"Success Rate: {throughput_results['success_rate']}%")
# 4. Complete Performance Suite
print(f"\n4οΈβ£ Complete Performance Suite")
full_results = await pc.runPerformanceTest(quick=False)
print(f"π Performance Summary:")
print(f"Network: {full_results['network']['networkName']}")
print(f"Block: #{full_results['network']['blockNumber']}")
print(f"Latency: {full_results['latency']['balance_check']['avg_ms']}ms")
print(f"TPS: {full_results['tps']['actual_tps']}")
print(f"Throughput: {full_results['throughput']['throughput_tps']} TPS")
asyncio.run(performance_testing())
```
### Quick Performance Check
```python
import asyncio
from purechainlib import PureChain
async def quick_performance_check():
pc = PureChain('testnet')
pc.connect('your_private_key')
# Quick 15-second test suite
results = await pc.runPerformanceTest(quick=True)
print("β‘ Quick Performance Results:")
print(f"TPS: {results['tps']['actual_tps']}")
print(f"Latency: {results['latency']['balance_check']['avg_ms']}ms")
print(f"Throughput: {results['throughput']['throughput_tps']} TPS")
asyncio.run(quick_performance_check())
```
## π Network Information
| Network | RPC URL | Chain ID | Gas Price |
|---------|---------|----------|-----------|
| **Testnet** | `https://purechainnode.com:8547` | `900520900520` | `0` (FREE!) |
| **Mainnet** | `https://purechainnode.com:8547` | `900520900520` | `0` (FREE!) |
## β‘ Performance Metrics Guide
### Understanding Performance Results
When you run performance tests, here's what each metric means:
#### π **TPS (Transactions Per Second)**
- **Target TPS**: The rate you want to achieve
- **Actual TPS**: The rate PureChain actually delivered
- **Efficiency**: How close you got to your target (%)
- **Measurement Modes**:
- **`full`**: Measures complete transaction lifecycle (send + wait for confirmation)
- **`send`**: Measures only sending time (doesn't wait for confirmation)
- **`parallel`**: Sends transactions concurrently and measures both phases
**Timing Breakdown:**
- **Send Time**: Time to build, sign, and broadcast transaction to network
- **Confirmation Time**: Time from broadcast to mining/confirmation
- **Total Latency**: Send Time + Confirmation Time
```python
# Example TPS results
{
'duration': 30.0,
'successful_transactions': 1487,
'failed_transactions': 0,
'actual_tps': 49.57,
'target_tps': 50,
'efficiency': 99.14,
'avg_latency_ms': 523.2,
'contract_address': '0x...'
}
```
#### π **Latency Measurements**
- **Balance Check**: Time to query account balance
- **Block Fetch**: Time to get latest block info
- **Contract Call**: Time to read from smart contract
- **Transaction Send**: Time to send and confirm transaction
```python
# Example latency results
{
'balance_check': {'avg_ms': 21.45, 'min_ms': 12.3, 'max_ms': 45.2},
'block_fetch': {'avg_ms': 19.8, 'min_ms': 11.1, 'max_ms': 38.9},
'contract_call': {'avg_ms': 23.1, 'min_ms': 14.5, 'max_ms': 52.3},
'transaction_send': {'avg_ms': 487.3, 'min_ms': 234.1, 'max_ms': 892.1}
}
```
#### β‘ **Throughput Metrics**
- **Throughput TPS**: Mixed operations per second (writes + reads)
- **Write TPS**: Write transactions per second
- **Read TPS**: Read operations per second
- **Data Transfer**: Secondary metric showing KB/s of data moved
- **Success Rate**: Percentage of operations that completed successfully
### Performance Best Practices
#### π― **Optimize Your Applications**
```python
# 1. Batch operations when possible
async def batch_operations():
pc = PureChain('testnet')
pc.connect('your_key')
# Instead of multiple single calls
# for user in users:
# balance = await pc.balance(user)
# Use concurrent execution
import asyncio
balances = await asyncio.gather(*[
pc.balance(user) for user in users
])
# 2. Use read operations efficiently
async def efficient_reads():
pc = PureChain('testnet')
# Cache frequently accessed data
latest_block = await pc.block()
# Use the block number for multiple queries
for contract in contracts:
# Process using cached block data
pass
# 3. Monitor performance in production
async def production_monitoring():
pc = PureChain('mainnet')
pc.connect('production_key')
# Run quick performance checks periodically
health_check = await pc.runPerformanceTest(quick=True)
if health_check['tps']['actual_tps'] < 20:
# Alert: Performance degradation detected
send_alert("PureChain performance below threshold")
```
<!-- #### π **Expected Performance Ranges**
Based on our testing, here are typical performance ranges for PureChain:
| Metric | Typical Range | Excellent |
|--------|---------------|-----------|
| **Latency (reads)** | 15-50ms | <20ms |
| **Latency (writes)** | 200-800ms | <400ms |
| **TPS (single client)** | 30-100 | 80+ |
| **Throughput (mixed TPS)** | 50-150 | 120+ |
| **Data Transfer** | 10-100 KB/s | >50 KB/s | -->
### Performance Testing Tips
```python
# 1. Warm up the network first
async def performance_with_warmup():
pc = PureChain('testnet')
pc.connect('your_key')
# Warm up - send a few transactions first
print("π₯ Warming up network...")
for _ in range(5):
await pc.balance()
# Now run actual performance test
results = await pc.testTPS(30, 50)
# 2. Test different times of day
# Network performance may vary based on usage
# 3. Compare mainnet vs testnet
testnet_results = await PureChain('testnet').runPerformanceTest()
mainnet_results = await PureChain('mainnet').runPerformanceTest()
# 4. Monitor over time
performance_history = []
for day in range(7):
daily_results = await pc.runPerformanceTest(quick=True)
performance_history.append(daily_results)
```
## π Smart Contract Security Auditing (NEW!)
**One-liner security audits with built-in tools!** No setup required - tools auto-install on first use.
### Quick Start - Pythonic One-Liners
```python
# SIMPLEST: One-liner audit
import purechainlib as pcl
result = await pcl.audit("contract code here")
# That's it! Security audit complete! π
```
### Security Audit Examples
```python
import asyncio
from purechainlib import PureChain
async def security_examples():
pc = PureChain('testnet')
# 1. Simple audit (Pythonic!)
result = await pc.audit(contract_code)
if result['summary']['critical'] == 0:
print("β
Contract is safe!")
# 2. Choose your tool
await pc.audit(contract_code, tool="slither") # Fast static analysis
await pc.audit(contract_code, tool="mythril") # Deep symbolic execution
await pc.audit(contract_code, tool="all") # Run everything!
# 3. Audit & Deploy (only deploys if safe)
safe_contract = await pc.auditAndDeploy(
contract_code,
require_pass=True # Won't deploy if vulnerabilities found
)
# 4. Auto-audit all deployments
pc.enableAutoAudit() # Every deployment is now audited first!
# 5. Security loop for LLM integration
result = await pc.runSecurityLoop(
vulnerable_contract,
max_iterations=5 # Keep trying until secure
)
# 6. Export logs for analysis
logs = pc.getSecurityLogs() # Get all audit history
pc.exportSecurityLogs('audit_logs.json') # For LLM processing
asyncio.run(security_examples())
```
<!--
### LLM Integration Pattern
```python
# Perfect for automated security fixing with LLMs!
async def llm_security_loop():
pc = PureChain('testnet')
# Run security loop
result = await pc.runSecurityLoop(contract_code, max_iterations=5)
# Get detailed logs for LLM
logs = pc.getSecurityLogs()
# Feed to your LLM
prompt = f"Fix these vulnerabilities: {json.dumps(logs)}"
# fixed_code = llm.generate(prompt)
# Audit the fixed code
final_audit = await pc.audit(fixed_code)
# Deploy if safe
if final_audit['summary']['critical'] == 0:
contract = await factory.deploy()
``` -->
### Available Security Tools
| Tool | Type | Speed | Detection |
|------|------|-------|-----------|
| **Slither** | Static Analysis | Fast | 80+ vulnerability patterns |
| **Mythril** | Symbolic Execution | Slower | Deep analysis, finds edge cases |
| **Solhint** | Linter | Very Fast | Code quality & best practices |
| **ALL** | Combined | Slowest | Most comprehensive |
### Security Report Formats
```python
# Export in different formats
await pc.auditContract(code, export_report=True, report_format='json') # For APIs
await pc.auditContract(code, export_report=True, report_format='markdown') # For docs
await pc.auditContract(code, export_report=True, report_format='html') # For web
```
## π± Carbon Footprint Tracking
PureChain SDK includes **Carbon footprint tracking**
### Why Carbon Tracking?
Even though PureChain uses **zero gas fees** and is extremely efficient, every computational operation still has an environmental impact. We provide transparent, scientific measurements to help you:
- Track environmental impact for ESG reporting
- Compare efficiency with other blockchains
- Make informed decisions about blockchain usage
- Generate compliance reports
### How to Use Carbon Tracking
```python
# Enable carbon tracking for your region
pc = PureChain('testnet')
pc.enableCarbonTracking('us') # Options: 'global', 'us', 'eu', 'asia', 'renewable'
# Send transaction with carbon data
result = await pc.send(address, amount, include_carbon=True)
print(f"Carbon footprint: {result['carbon_footprint']['carbon']['gCO2']} gCO2")
# Deploy contract with carbon tracking
contract = await factory.deploy(track_carbon=True)
# Get carbon report
report = await pc.getCarbonReport()
print(f"Total emissions: {report['total_emissions']['kgCO2']} kg CO2")
# Get ESG metrics for reporting
esg = await pc.getCarbonESGMetrics()
print(f"Environmental metrics: {esg['environmental']}")
# Export full report
json_report = await pc.exportCarbonReport()
```
### π¬ Scientific Methodology
Our carbon calculations are based on **actual measurements**, not estimates:
#### Energy Measurement
- **Direct CPU power monitoring** using Intel PowerTOP and turbostat
- **Measured on**: Intel Xeon E5-2686 v4 @ 2.30GHz (typical cloud server)
- **Energy per transaction**: ~0.029 Joules (8.1 Γ 10β»βΉ kWh)
- **Accuracy**: Β±5% based on measurement variance
#### Carbon Calculation
```
Carbon (gCO2) = Energy (kWh) Γ Grid Carbon Intensity (gCO2/kWh)
```
**Grid Carbon Intensity Sources:**
- US: EPA eGRID 2023 (420 gCO2/kWh average)
- EU: EEA 2023 (295 gCO2/kWh average)
- Global: IEA 2023 (475 gCO2/kWh average)
### π Measured Performance
| Operation | Energy (Joules) | Carbon (gCO2) | vs Ethereum |
|-----------|-----------------|---------------|-------------|
| Transaction | 0.029 | 0.000003 | 99.99999% less |
| Contract Deploy | 0.517 | 0.000054 | 99.9998% less |
| Contract Execute | 0.010 | 0.000001 | 99.99999% less |
### Comparison with Other Blockchains
```python
# PureChain measurements (per transaction)
{
'purechain': {
'energy_kwh': 0.000000008,
'co2_g': 0.000003,
'comparison': 'Baseline'
},
'ethereum_pow': {
'energy_kwh': 30,
'co2_g': 30000,
'times_worse': 3750000000 # 3.75 billion times
},
'ethereum_pos': {
'energy_kwh': 0.01,
'co2_g': 10,
'times_worse': 1250000 # 1.25 million times
},
'bitcoin': {
'energy_kwh': 511,
'co2_g': 500000,
'times_worse': 63875000000 # 63.9 billion times
}
}
```
### Carbon Tracking API Reference
#### Enable/Disable Tracking
```python
# Enable with specific region
pc.enableCarbonTracking('us') # US grid intensity
pc.enableCarbonTracking('eu') # EU grid intensity
pc.enableCarbonTracking('renewable') # Renewable energy
# Disable tracking
pc.disableCarbonTracking()
```
#### Transaction Carbon Data
```python
# Include carbon in transaction
result = await pc.send(to, value, include_carbon=True)
# Carbon data structure
{
'carbon': {
'gCO2': 0.000003, # Grams of CO2
'kgCO2': 0.000000003, # Kilograms
'tonnesCO2': 3e-12 # Metric tonnes
},
'comparison': {
'vs_ethereum': '0.00001%',
'savings_kg': 30.0
},
'environmental': {
'trees_equivalent': 0.0000001
},
'offset': {
'cost_usd': 0.00000003
}
}
```
#### ESG Reporting
```python
# Get ESG-compliant metrics
esg = await pc.getCarbonESGMetrics()
# Returns
{
'environmental': {
'total_emissions_kg_co2': 0.000001,
'emissions_per_transaction_g_co2': 0.000003,
'carbon_efficiency_vs_ethereum': '99.99%+ reduction',
'renewable_energy_compatible': True
},
'sustainability': {
'zero_gas_operations': True,
'energy_efficient': True
},
'reporting': {
'methodology': 'ISO 14064-1 compatible',
'verification': 'Automated tracking with PureChain SDK'
}
}
```
### π Environmental Impact
Using PureChain instead of Ethereum for 1,000 transactions saves:
- **Energy**: 30 kWh (enough to power a home for 1 day)
- **Carbon**: 30 kg CO2 (equivalent to 1.4 trees for a year)
- **Cost**: $3.60 in electricity
### References
1. Sedlmeir et al. (2020): "The Energy Consumption of Blockchain Technology"
2. Cambridge Bitcoin Electricity Consumption Index (2023)
3. EPA eGRID Power Profiler (2023)
4. IEA Global Energy & CO2 Status Report (2023)
## β FAQ
**Q: Are transactions really free?**
A: Yes! PureChain has zero gas costs. All operations cost 0 PURE.
**Q: Can I deploy any Solidity contract?**
A: Yes! PureChain is fully EVM compatible.
<!-- **Q: How do I get PURE tokens?**
A: Contact the PureChain team or use the testnet faucet. -->
**Q: Is this compatible with Web3?**
A: Yes! Built on Web3.py with PureChain-specific optimizations.
## π Links
- **NPM Package**: https://www.npmjs.com/package/purechainlib
<!-- - **GitHub**: https://github.com/purechainlib/purechainlib-python -->
<!-- - **Documentation**: https://docs.purechain.network -->
## π License
MIT License - Free to use in any project!
---
**Zero Gas. Full EVM. Pure Innovation.** π
*Built for the PureChain ecosystem - where blockchain development costs nothing!*
Raw data
{
"_id": null,
"home_page": null,
"name": "purechainlib",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.8",
"maintainer_email": null,
"keywords": "blockchain, ethereum, web3, smart-contracts, zero-gas, purechain, evm, solidity, defi",
"author": "PureChain Team",
"author_email": "dev@purechain.network",
"download_url": "https://files.pythonhosted.org/packages/56/41/6b6e120671f2e60596fac89371bea6f24250c28fedc3df4915d7527b6523/purechainlib-2.1.4.tar.gz",
"platform": null,
"description": "<div align=\"left\">\n \n # PureChain Python Library\n\n [](https://www.python.org/downloads/)\n [](https://opensource.org/licenses/MIT)\n [](https://pypi.org/project/purechainlib/)\n\n **Zero Gas Cost Blockchain Development in Python**\n\n Python SDK for PureChain EVM network with **completely FREE transactions**. Deploy contracts, send tokens, and interact with smart contracts without any gas fees!\n \n ## \ud83d\udcd6 Korean Documentation / \ud55c\uad6d\uc5b4 \ubb38\uc11c\n \n Korean documentation is included in this package. After installation, you can find `README_ko.md` in your package directory.\n \n \ud55c\uad6d\uc5b4 \ubb38\uc11c\uac00 \ud328\ud0a4\uc9c0\uc5d0 \ud3ec\ud568\ub418\uc5b4 \uc788\uc2b5\ub2c8\ub2e4. \uc124\uce58 \ud6c4 \ud328\ud0a4\uc9c0 \ub514\ub809\ud1a0\ub9ac\uc5d0\uc11c `README_ko.md` \ud30c\uc77c\uc744 \ucc3e\uc744 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n \n ```python\n # How to access Korean README after installation:\n import purechainlib\n import os\n korean_readme_path = os.path.join(os.path.dirname(purechainlib.__file__), '..', 'README_ko.md')\n print(f\"Korean README location: {korean_readme_path}\")\n ```\n</div>\n\n## \ud83c\udd95 What's New in v2.1.4\n\n### Performance Improvements\n- Significantly improved dependency resolution speed\n- Fixed eth-abi and parsimonious compatibility issues\n- Made mythril optional to avoid dependency conflicts\n\n### Bug Fixes (v2.1.1-2.1.3)\n- Fixed security audit results display issue\n- Resolved dependency version conflicts\n\n## Previous Updates (v2.1.0)\n\n### \ud83d\udd12 Smart Contract Security Auditing\n- **Built-in security tools** - Slither bundled, Mythril optional\n- **Auto-installation** - Tools install automatically on first use\n- **One-liner audits** - `await pcl.audit(\"contract code\")`\n- **Multiple tools** - Choose Slither, Mythril (if installed), or run ALL\n- **Comprehensive logging** - Perfect for LLM integration\n- **Export reports** - JSON, Markdown, HTML formats\n- **Note**: Mythril can be installed separately with `pip install mythril==0.24.8`\n\n### \ud83d\udcda Documentation Updates\n- Removed private GitHub repository links\n- Improved Korean documentation access instructions\n- Package now fully self-contained with both English and Korean docs\n<!-- - Added comprehensive help system (hint: try `pc.help.` and explore!) -->\n\n## Previous Updates\n\n### v2.0.8 - Korean Language Support\n- Complete Korean documentation now available\n- Korean README included in the package (README_ko.md)\n- Optimized examples for Korean developers\n\n### v2.0.7\n\n### \ud83c\udf31 Carbon Footprint Tracking\n- **Scientific measurements** of energy consumption (Joules) and CO2 emissions\n- **ESG compliance** reporting for environmental impact\n- **Regional grid intensity** support (US, EU, Asia, etc.)\n- Compare efficiency with other blockchains (99.99999% less CO2 than Ethereum!)\n\n### \ud83d\udd27 Automatic Web3 Middleware\n- No more manual `web3.middleware` imports needed\n- Automatic compatibility with all Web3 versions\n- Just `from purechainlib import PureChain` and you're ready!\n\n### \ud83d\udcca Energy Measurements\n- **0.029 Joules** per transaction (scientifically measured)\n- **63 billion times** more efficient than Bitcoin\n- Based on actual CPU power monitoring, not estimates\n\n<!-- [See full carbon tracking documentation](#-carbon-footprint-tracking) -->\n\n## \ud83d\ude80 Quick Start\n\n```bash\npip install purechainlib\n```\n\n**Note:** Version 2.1.4+ has optimized dependencies for fast installation. Security tools like Mythril can be installed separately if needed.\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n# No need for web3.middleware imports - handled automatically!\n\nasync def main():\n # Initialize PureChain\n pc = PureChain('testnet')\n \n # Connect your wallet\n pc.connect('your_private_key_here')\n \n # Check balance (FREE!)\n balance = await pc.balance()\n print(f\"Balance: {balance} PURE\")\n \n # Deploy a contract (FREE!)\n contract_source = \"\"\"\n pragma solidity ^0.8.19;\n contract Hello {\n string public message = \"Hello PureChain!\";\n function setMessage(string memory _msg) public {\n message = _msg;\n }\n }\n \"\"\"\n \n factory = await pc.contract(contract_source)\n contract = await factory.deploy() # No gas fees!\n print(f\"Contract deployed: {contract.address}\")\n\nasyncio.run(main())\n```\n\n## \u2728 Features\n\n- **Zero Gas Costs** - All operations are completely FREE\n- **Security Auditing** - Built-in smart contract vulnerability scanning\n- **Easy to Use** - Simple, intuitive API\n- **Full EVM Support** - Deploy any Solidity contract\n- **Pythonic** - Clean, readable Python code\n- **Secure** - Industry-standard cryptography\n- **Complete** - Account management, compilation, deployment, auditing\n\n## \ud83d\udcda Quick Reference\n\n### All Available Functions\n\n| Function | Description | Example |\n|----------|-------------|---------|\n| `PureChain(network, private_key?)` | Initialize connection | `pc = PureChain('testnet')` |\n| `connect(private_key)` | Connect wallet | `pc.connect('your_private_key')` |\n| `account()` | Create new account | `acc = pc.account()` |\n| `balance(address?)` | Get balance | `bal = await pc.balance()` |\n| `bal(address?)` | Get balance (short) | `bal = await pc.bal()` |\n| `send(to, value?)` | Send PURE tokens | `await pc.send('0x...', '1.0')` |\n| `contract(source)` | Compile contract | `factory = await pc.contract(code)` |\n| `factory.deploy(*args)` | Deploy contract | `contract = await factory.deploy()` |\n| `call(contract, method, *args)` | Read from contract | `result = await pc.call(contract, 'balances', addr)` |\n| `execute(contract, method, *args)` | Write to contract | `await pc.execute(contract, 'mint', 1000)` |\n| `block(number?)` | Get block info | `block = await pc.block()` |\n| `transaction(hash)` | Get transaction | `tx = await pc.transaction('0x...')` |\n| `gasPrice()` | Get gas price (always 0) | `price = await pc.gasPrice()` |\n| `address(addr?)` | Get address info | `info = await pc.address()` |\n| `isContract(address)` | Check if contract | `is_contract = await pc.isContract('0x...')` |\n| `events(contract, blocks?)` | Get contract events | `events = await pc.events(addr, 10)` |\n| `status()` | Get network status | `status = await pc.status()` |\n| `tx(hash?)` | Get transaction (alias) | `tx = await pc.tx('0x...')` |\n| `testTPS(duration?, target?, mode?)` | Test TPS performance | `results = await pc.testTPS(30, 100, 'full')` |\n| `measureLatency(operations?)` | Measure operation latency | `latency = await pc.measureLatency(100)` |\n| `benchmarkThroughput(duration?)` | Test blockchain throughput (TPS) | `throughput = await pc.benchmarkThroughput(60)` |\n| `runPerformanceTest(quick?)` | Full performance suite | `results = await pc.runPerformanceTest()` |\n| `enableCarbonTracking(region?)` | Enable carbon footprint tracking | `pc.enableCarbonTracking('us')` |\n| `disableCarbonTracking()` | Disable carbon tracking | `pc.disableCarbonTracking()` |\n| `getCarbonReport()` | Get carbon emissions report | `report = await pc.getCarbonReport()` |\n| `getCarbonESGMetrics()` | Get ESG compliance metrics | `esg = await pc.getCarbonESGMetrics()` |\n| `exportCarbonReport()` | Export full carbon report as JSON | `json_report = await pc.exportCarbonReport()` |\n| **SECURITY AUDITING** | | |\n| `audit(contract, **kwargs)` | One-liner security audit | `await pc.audit(code)` |\n| `auditContract(contract, tool?)` | Full security audit | `await pc.auditContract(code, tool=SecurityTool.SLITHER)` |\n| `auditAndDeploy(contract, ...)` | Audit then deploy if safe | `await pc.auditAndDeploy(code, require_pass=True)` |\n| `runSecurityLoop(contract, max?)` | Iterative security fixing | `await pc.runSecurityLoop(code, max_iterations=5)` |\n| `enableAutoAudit(tool?)` | Auto-audit before deployments | `pc.enableAutoAudit()` |\n| `checkSecurityTools()` | Check installed tools | `pc.checkSecurityTools()` |\n| `getSecurityLogs()` | Get all audit logs | `logs = pc.getSecurityLogs()` |\n\n### Function Categories\n\n#### \ud83d\udd10 **Account & Wallet Management**\n```python\n# Initialize and connect\npc = PureChain('testnet', 'optional_private_key')\npc.connect('your_private_key_without_0x')\n\n# Create new account\nnew_account = pc.account()\n# Returns: {'address': '0x...', 'privateKey': '...'}\n\n# Get current signer address\naddress = pc.signer.address\n```\n\n#### \ud83d\udcb0 **Balance & Transactions**\n```python\n# Check balances\nmy_balance = await pc.balance() # Your balance\nother_balance = await pc.balance('0x...') # Specific address\nquick_balance = await pc.bal() # Shorthand\n\n# Send PURE tokens (FREE!)\nawait pc.send('0x...recipient', '10.5')\n\n# Send with transaction object\nawait pc.send({\n 'to': '0x...address',\n 'value': '1.0',\n 'data': '0x...' # Optional\n})\n```\n\n#### \ud83d\udcc4 **Smart Contracts**\n```python\n# Compile and deploy\ncontract_source = \"pragma solidity ^0.8.19; contract Test { ... }\"\nfactory = await pc.contract(contract_source)\ndeployed_contract = await factory.deploy(constructor_args)\n\n# Attach to existing contract\nexisting_contract = factory.attach('0x...contract_address')\n\n# Read from contract (view functions)\nresult = await pc.call(contract, 'balances', user_address)\nname = await pc.call(contract, 'name') # No arguments\n\n# Write to contract (transaction functions)\nawait pc.execute(contract, 'mint', recipient, 1000)\nawait pc.execute(contract, 'setMessage', \"Hello World\")\n```\n\n#### \ud83d\udd0d **Blockchain Information**\n```python\n# Block information\nlatest_block = await pc.block() # Latest block\nspecific_block = await pc.block(12345) # Specific block number\n\n# Transaction information\ntx_info = await pc.transaction('0x...hash')\ntx_alias = await pc.tx('0x...hash') # Same as above\n\n# Address information\naddr_info = await pc.address() # Your address info\nother_info = await pc.address('0x...') # Specific address\n# Returns: {'balance': '...', 'isContract': bool, 'address': '...'}\n\n# Check if address is contract\nis_contract = await pc.isContract('0x...address')\n\n# Gas price (always 0 on PureChain)\ngas_price = await pc.gasPrice() # Returns 0\n\n# Network status\nstatus = await pc.status()\n# Returns: {'chainId': 900520900520, 'gasPrice': 0, 'blockNumber': ...}\n```\n\n#### \ud83d\udcca **Events & Monitoring**\n```python\n# Get contract events\nevents = await pc.events(contract_address) # All events\nrecent_events = await pc.events(contract_address, 10) # Last 10 blocks\n```\n\n#### \u26a1 **Performance Testing**\n```python\n# Test Transactions Per Second (TPS) with different measurement modes\n# Mode options: 'full' (default), 'send', 'parallel'\ntps_full = await pc.testTPS(duration=30, target_tps=100, measure_mode='full') # Measure full lifecycle\ntps_send = await pc.testTPS(duration=30, target_tps=100, measure_mode='send') # Measure send time only\ntps_parallel = await pc.testTPS(duration=30, target_tps=100, measure_mode='parallel') # Parallel execution\n\nprint(f\"Full Mode TPS: {tps_full['actual_tps']}\")\nprint(f\"Send-only TPS: {tps_send['actual_tps']}\")\nprint(f\"Parallel TPS: {tps_parallel['actual_tps']}\")\n\n# Measure operation latency\nlatency_results = await pc.measureLatency(operations=100)\nprint(f\"Average latency: {latency_results['balance_check']['avg_ms']}ms\")\n\n# Benchmark blockchain throughput (mixed operations TPS)\nthroughput_results = await pc.benchmarkThroughput(test_duration=60)\nprint(f\"Throughput: {throughput_results['throughput_tps']} TPS\")\n\n# Run complete performance suite\nperformance = await pc.runPerformanceTest(quick=True) # Quick test\nfull_performance = await pc.runPerformanceTest(quick=False) # Full test\n```\n\n## \ud83d\udcda Detailed API Reference\n\n### Initialization\n\n```python\nfrom purechainlib import PureChain\n\n# Connect to testnet (default)\npc = PureChain('testnet')\n\n# Or mainnet\npc = PureChain('mainnet')\n\n# Connect with private key immediately\npc = PureChain('testnet', 'your_private_key')\n```\n\n### Account Management\n\n```python\n# Connect wallet\npc.connect('your_private_key_without_0x_prefix')\n\n# Create new account\naccount = pc.account()\nprint(f\"Address: {account['address']}\")\nprint(f\"Private Key: {account['privateKey']}\")\n\n# Check balance\nbalance = await pc.balance() # Your balance\nbalance = await pc.balance('0x...address') # Specific address\n```\n\n### Contract Operations\n\n```python\n# Deploy contract from source\ncontract_source = \"\"\"\npragma solidity ^0.8.19;\ncontract Token {\n mapping(address => uint256) public balances;\n \n function mint(uint256 amount) public {\n balances[msg.sender] += amount;\n }\n}\n\"\"\"\n\n# Compile and deploy (FREE!)\nfactory = await pc.contract(contract_source)\ncontract = await factory.deploy()\n\n# Read from contract (FREE!)\nbalance = await pc.call(contract, 'balances', user_address)\n\n# Write to contract (FREE!)\nawait pc.execute(contract, 'mint', 1000)\n```\n\n### Transactions\n\n```python\n# Send PURE tokens (FREE!)\nawait pc.send('0x...recipient_address', '10.5')\n\n# Send with transaction object\nawait pc.send({\n 'to': '0x...address',\n 'value': '1.0',\n 'data': '0x...' # Optional contract data\n})\n```\n\n### Blockchain Information\n\n```python\n# Get latest block\nblock = await pc.block()\nprint(f\"Block #{block['number']}\")\n\n# Get transaction info\ntx = await pc.transaction('0x...transaction_hash')\n\n# Network status\nstatus = await pc.status()\nprint(f\"Chain ID: {status['chainId']}\")\nprint(f\"Gas Price: {status['gasPrice']}\") # Always 0!\n\n# Gas price (always returns 0)\ngas_price = await pc.gasPrice()\n```\n\n### Pythonic Shortcuts\n\n```python\n# Quick balance check\nbalance = await pc.bal()\n\n# Address information\ninfo = await pc.address()\nprint(f\"Balance: {info['balance']}\")\nprint(f\"Is Contract: {info['isContract']}\")\n\n# Check if address is a contract\nis_contract = await pc.isContract('0x...address')\n```\n\n## \ud83d\udcdd Complete Examples\n\n### Deploy and Interact with Token Contract\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n\nasync def token_example():\n pc = PureChain('testnet')\n pc.connect('your_private_key')\n \n # Token contract\n token_source = \"\"\"\n pragma solidity ^0.8.19;\n \n contract SimpleToken {\n mapping(address => uint256) public balances;\n uint256 public totalSupply;\n string public name = \"PureToken\";\n \n function mint(address to, uint256 amount) public {\n balances[to] += amount;\n totalSupply += amount;\n }\n \n function transfer(address to, uint256 amount) public {\n require(balances[msg.sender] >= amount);\n balances[msg.sender] -= amount;\n balances[to] += amount;\n }\n }\n \"\"\"\n \n # Deploy token (FREE!)\n factory = await pc.contract(token_source)\n token = await factory.deploy()\n print(f\"Token deployed at: {token.address}\")\n \n # Mint tokens (FREE!)\n await pc.execute(token, 'mint', pc.signer.address, 1000000)\n \n # Check balance (FREE!)\n balance = await pc.call(token, 'balances', pc.signer.address)\n print(f\"Token balance: {balance}\")\n \n # Transfer tokens (FREE!)\n recipient = \"0xc8bfbC0C75C0111f7cAdB1DF4E0BC3bC45078f9d\"\n await pc.execute(token, 'transfer', recipient, 100)\n print(\"Tokens transferred!\")\n\nasyncio.run(token_example())\n```\n\n### Create and Fund Multiple Accounts\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n\nasync def multi_account_example():\n pc = PureChain('testnet')\n pc.connect('your_private_key')\n \n # Create 3 new accounts\n accounts = []\n for i in range(3):\n account = pc.account()\n accounts.append(account)\n print(f\"Account {i+1}: {account['address']}\")\n \n # Fund each account (FREE transactions!)\n for i, account in enumerate(accounts):\n await pc.send(account['address'], f\"{i+1}.0\") # Send 1, 2, 3 PURE\n print(f\"Sent {i+1} PURE to account {i+1}\")\n \n # Check all balances\n for i, account in enumerate(accounts):\n balance = await pc.balance(account['address'])\n print(f\"Account {i+1} balance: {balance} PURE\")\n\nasyncio.run(multi_account_example())\n```\n\n### Contract Event Monitoring\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n\nasync def event_example():\n pc = PureChain('testnet')\n pc.connect('your_private_key')\n \n # Contract with events\n contract_source = \"\"\"\n pragma solidity ^0.8.19;\n \n contract EventExample {\n event MessageSet(address indexed user, string message);\n \n string public message;\n \n function setMessage(string memory _message) public {\n message = _message;\n emit MessageSet(msg.sender, _message);\n }\n }\n \"\"\"\n \n # Deploy and interact\n factory = await pc.contract(contract_source)\n contract = await factory.deploy()\n \n # Set message (creates event)\n await pc.execute(contract, 'setMessage', \"Hello Events!\")\n \n # Get events from last 10 blocks\n events = await pc.events(contract.address, 10)\n print(f\"Found {len(events)} events\")\n\nasyncio.run(event_example())\n```\n\n### Performance Testing & Benchmarking\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n\nasync def performance_testing():\n pc = PureChain('testnet')\n pc.connect('your_private_key')\n \n print(\"\ud83d\ude80 Starting Performance Tests...\")\n \n # 1. TPS (Transactions Per Second) Test\n print(\"\\n1\ufe0f\u20e3 TPS Test - Measure transaction throughput\")\n tps_results = await pc.testTPS(duration=30, target_tps=50)\n \n print(f\"Target TPS: {tps_results['target_tps']}\")\n print(f\"Achieved TPS: {tps_results['actual_tps']}\")\n print(f\"Efficiency: {tps_results['efficiency']}%\")\n print(f\"Average Latency: {tps_results['avg_latency_ms']}ms\")\n \n # 2. Latency Test - Measure operation response times\n print(f\"\\n2\ufe0f\u20e3 Latency Test - Measure response times\")\n latency_results = await pc.measureLatency(operations=50)\n \n for operation, stats in latency_results.items():\n print(f\"{operation}: {stats['avg_ms']}ms (min: {stats['min_ms']}, max: {stats['max_ms']})\")\n \n # 3. Throughput Test - Measure data transfer rates\n print(f\"\\n3\ufe0f\u20e3 Throughput Test - Measure data transfer\")\n throughput_results = await pc.benchmarkThroughput(test_duration=45)\n \n print(f\"Total TPS: {throughput_results['throughput_tps']}\")\n print(f\"Data Transfer: {throughput_results['kb_per_second']} KB/s\")\n print(f\"Success Rate: {throughput_results['success_rate']}%\")\n \n # 4. Complete Performance Suite\n print(f\"\\n4\ufe0f\u20e3 Complete Performance Suite\")\n full_results = await pc.runPerformanceTest(quick=False)\n \n print(f\"\ud83d\udcca Performance Summary:\")\n print(f\"Network: {full_results['network']['networkName']}\")\n print(f\"Block: #{full_results['network']['blockNumber']}\")\n print(f\"Latency: {full_results['latency']['balance_check']['avg_ms']}ms\")\n print(f\"TPS: {full_results['tps']['actual_tps']}\")\n print(f\"Throughput: {full_results['throughput']['throughput_tps']} TPS\")\n\nasyncio.run(performance_testing())\n```\n\n### Quick Performance Check\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n\nasync def quick_performance_check():\n pc = PureChain('testnet')\n pc.connect('your_private_key')\n \n # Quick 15-second test suite\n results = await pc.runPerformanceTest(quick=True)\n \n print(\"\u26a1 Quick Performance Results:\")\n print(f\"TPS: {results['tps']['actual_tps']}\")\n print(f\"Latency: {results['latency']['balance_check']['avg_ms']}ms\")\n print(f\"Throughput: {results['throughput']['throughput_tps']} TPS\")\n\nasyncio.run(quick_performance_check())\n```\n\n## \ud83c\udf10 Network Information\n\n| Network | RPC URL | Chain ID | Gas Price |\n|---------|---------|----------|-----------|\n| **Testnet** | `https://purechainnode.com:8547` | `900520900520` | `0` (FREE!) |\n| **Mainnet** | `https://purechainnode.com:8547` | `900520900520` | `0` (FREE!) |\n\n## \u26a1 Performance Metrics Guide\n\n### Understanding Performance Results\n\nWhen you run performance tests, here's what each metric means:\n\n#### \ud83d\ude80 **TPS (Transactions Per Second)**\n- **Target TPS**: The rate you want to achieve\n- **Actual TPS**: The rate PureChain actually delivered\n- **Efficiency**: How close you got to your target (%)\n- **Measurement Modes**:\n - **`full`**: Measures complete transaction lifecycle (send + wait for confirmation)\n - **`send`**: Measures only sending time (doesn't wait for confirmation)\n - **`parallel`**: Sends transactions concurrently and measures both phases\n\n**Timing Breakdown:**\n- **Send Time**: Time to build, sign, and broadcast transaction to network\n- **Confirmation Time**: Time from broadcast to mining/confirmation\n- **Total Latency**: Send Time + Confirmation Time\n\n```python\n# Example TPS results\n{\n 'duration': 30.0,\n 'successful_transactions': 1487,\n 'failed_transactions': 0,\n 'actual_tps': 49.57,\n 'target_tps': 50,\n 'efficiency': 99.14,\n 'avg_latency_ms': 523.2,\n 'contract_address': '0x...'\n}\n```\n\n#### \ud83d\udcca **Latency Measurements**\n- **Balance Check**: Time to query account balance\n- **Block Fetch**: Time to get latest block info\n- **Contract Call**: Time to read from smart contract\n- **Transaction Send**: Time to send and confirm transaction\n\n```python\n# Example latency results\n{\n 'balance_check': {'avg_ms': 21.45, 'min_ms': 12.3, 'max_ms': 45.2},\n 'block_fetch': {'avg_ms': 19.8, 'min_ms': 11.1, 'max_ms': 38.9},\n 'contract_call': {'avg_ms': 23.1, 'min_ms': 14.5, 'max_ms': 52.3},\n 'transaction_send': {'avg_ms': 487.3, 'min_ms': 234.1, 'max_ms': 892.1}\n}\n```\n\n#### \u26a1 **Throughput Metrics**\n- **Throughput TPS**: Mixed operations per second (writes + reads)\n- **Write TPS**: Write transactions per second\n- **Read TPS**: Read operations per second \n- **Data Transfer**: Secondary metric showing KB/s of data moved\n- **Success Rate**: Percentage of operations that completed successfully\n\n### Performance Best Practices\n\n#### \ud83c\udfaf **Optimize Your Applications**\n\n```python\n# 1. Batch operations when possible\nasync def batch_operations():\n pc = PureChain('testnet')\n pc.connect('your_key')\n \n # Instead of multiple single calls\n # for user in users:\n # balance = await pc.balance(user)\n \n # Use concurrent execution\n import asyncio\n balances = await asyncio.gather(*[\n pc.balance(user) for user in users\n ])\n\n# 2. Use read operations efficiently\nasync def efficient_reads():\n pc = PureChain('testnet')\n \n # Cache frequently accessed data\n latest_block = await pc.block()\n \n # Use the block number for multiple queries\n for contract in contracts:\n # Process using cached block data\n pass\n\n# 3. Monitor performance in production\nasync def production_monitoring():\n pc = PureChain('mainnet')\n pc.connect('production_key')\n \n # Run quick performance checks periodically\n health_check = await pc.runPerformanceTest(quick=True)\n \n if health_check['tps']['actual_tps'] < 20:\n # Alert: Performance degradation detected\n send_alert(\"PureChain performance below threshold\")\n```\n\n<!-- #### \ud83d\udcc8 **Expected Performance Ranges**\n\nBased on our testing, here are typical performance ranges for PureChain:\n\n| Metric | Typical Range | Excellent |\n|--------|---------------|-----------|\n| **Latency (reads)** | 15-50ms | <20ms |\n| **Latency (writes)** | 200-800ms | <400ms |\n| **TPS (single client)** | 30-100 | 80+ |\n| **Throughput (mixed TPS)** | 50-150 | 120+ |\n| **Data Transfer** | 10-100 KB/s | >50 KB/s | -->\n\n### Performance Testing Tips\n\n```python\n# 1. Warm up the network first\nasync def performance_with_warmup():\n pc = PureChain('testnet')\n pc.connect('your_key')\n \n # Warm up - send a few transactions first\n print(\"\ud83d\udd25 Warming up network...\")\n for _ in range(5):\n await pc.balance()\n \n # Now run actual performance test\n results = await pc.testTPS(30, 50)\n\n# 2. Test different times of day\n# Network performance may vary based on usage\n\n# 3. Compare mainnet vs testnet\ntestnet_results = await PureChain('testnet').runPerformanceTest()\nmainnet_results = await PureChain('mainnet').runPerformanceTest()\n\n# 4. Monitor over time\nperformance_history = []\nfor day in range(7):\n daily_results = await pc.runPerformanceTest(quick=True)\n performance_history.append(daily_results)\n```\n\n## \ud83d\udd12 Smart Contract Security Auditing (NEW!)\n\n**One-liner security audits with built-in tools!** No setup required - tools auto-install on first use.\n\n### Quick Start - Pythonic One-Liners\n\n```python\n# SIMPLEST: One-liner audit\nimport purechainlib as pcl\nresult = await pcl.audit(\"contract code here\")\n\n# That's it! Security audit complete! \ud83c\udf89\n```\n\n### Security Audit Examples\n\n```python\nimport asyncio\nfrom purechainlib import PureChain\n\nasync def security_examples():\n pc = PureChain('testnet')\n \n # 1. Simple audit (Pythonic!)\n result = await pc.audit(contract_code)\n if result['summary']['critical'] == 0:\n print(\"\u2705 Contract is safe!\")\n \n # 2. Choose your tool\n await pc.audit(contract_code, tool=\"slither\") # Fast static analysis\n await pc.audit(contract_code, tool=\"mythril\") # Deep symbolic execution\n await pc.audit(contract_code, tool=\"all\") # Run everything!\n \n # 3. Audit & Deploy (only deploys if safe)\n safe_contract = await pc.auditAndDeploy(\n contract_code,\n require_pass=True # Won't deploy if vulnerabilities found\n )\n \n # 4. Auto-audit all deployments\n pc.enableAutoAudit() # Every deployment is now audited first!\n \n # 5. Security loop for LLM integration\n result = await pc.runSecurityLoop(\n vulnerable_contract,\n max_iterations=5 # Keep trying until secure\n )\n \n # 6. Export logs for analysis\n logs = pc.getSecurityLogs() # Get all audit history\n pc.exportSecurityLogs('audit_logs.json') # For LLM processing\n\nasyncio.run(security_examples())\n```\n<!-- \n### LLM Integration Pattern\n\n```python\n# Perfect for automated security fixing with LLMs!\nasync def llm_security_loop():\n pc = PureChain('testnet')\n \n # Run security loop\n result = await pc.runSecurityLoop(contract_code, max_iterations=5)\n \n # Get detailed logs for LLM\n logs = pc.getSecurityLogs()\n \n # Feed to your LLM\n prompt = f\"Fix these vulnerabilities: {json.dumps(logs)}\"\n # fixed_code = llm.generate(prompt)\n \n # Audit the fixed code\n final_audit = await pc.audit(fixed_code)\n \n # Deploy if safe\n if final_audit['summary']['critical'] == 0:\n contract = await factory.deploy()\n``` -->\n\n### Available Security Tools\n\n| Tool | Type | Speed | Detection |\n|------|------|-------|-----------|\n| **Slither** | Static Analysis | Fast | 80+ vulnerability patterns |\n| **Mythril** | Symbolic Execution | Slower | Deep analysis, finds edge cases |\n| **Solhint** | Linter | Very Fast | Code quality & best practices |\n| **ALL** | Combined | Slowest | Most comprehensive |\n\n### Security Report Formats\n\n```python\n# Export in different formats\nawait pc.auditContract(code, export_report=True, report_format='json') # For APIs\nawait pc.auditContract(code, export_report=True, report_format='markdown') # For docs\nawait pc.auditContract(code, export_report=True, report_format='html') # For web\n```\n\n## \ud83c\udf31 Carbon Footprint Tracking\n\nPureChain SDK includes **Carbon footprint tracking**\n\n### Why Carbon Tracking?\n\nEven though PureChain uses **zero gas fees** and is extremely efficient, every computational operation still has an environmental impact. We provide transparent, scientific measurements to help you:\n- Track environmental impact for ESG reporting\n- Compare efficiency with other blockchains\n- Make informed decisions about blockchain usage\n- Generate compliance reports\n\n### How to Use Carbon Tracking\n\n```python\n# Enable carbon tracking for your region\npc = PureChain('testnet')\npc.enableCarbonTracking('us') # Options: 'global', 'us', 'eu', 'asia', 'renewable'\n\n# Send transaction with carbon data\nresult = await pc.send(address, amount, include_carbon=True)\nprint(f\"Carbon footprint: {result['carbon_footprint']['carbon']['gCO2']} gCO2\")\n\n# Deploy contract with carbon tracking\ncontract = await factory.deploy(track_carbon=True)\n\n# Get carbon report\nreport = await pc.getCarbonReport()\nprint(f\"Total emissions: {report['total_emissions']['kgCO2']} kg CO2\")\n\n# Get ESG metrics for reporting\nesg = await pc.getCarbonESGMetrics()\nprint(f\"Environmental metrics: {esg['environmental']}\")\n\n# Export full report\njson_report = await pc.exportCarbonReport()\n```\n\n### \ud83d\udd2c Scientific Methodology\n\nOur carbon calculations are based on **actual measurements**, not estimates:\n\n#### Energy Measurement\n- **Direct CPU power monitoring** using Intel PowerTOP and turbostat\n- **Measured on**: Intel Xeon E5-2686 v4 @ 2.30GHz (typical cloud server)\n- **Energy per transaction**: ~0.029 Joules (8.1 \u00d7 10\u207b\u2079 kWh)\n- **Accuracy**: \u00b15% based on measurement variance\n\n#### Carbon Calculation\n```\nCarbon (gCO2) = Energy (kWh) \u00d7 Grid Carbon Intensity (gCO2/kWh)\n```\n\n**Grid Carbon Intensity Sources:**\n- US: EPA eGRID 2023 (420 gCO2/kWh average)\n- EU: EEA 2023 (295 gCO2/kWh average)\n- Global: IEA 2023 (475 gCO2/kWh average)\n\n### \ud83d\udcca Measured Performance\n\n| Operation | Energy (Joules) | Carbon (gCO2) | vs Ethereum |\n|-----------|-----------------|---------------|-------------|\n| Transaction | 0.029 | 0.000003 | 99.99999% less |\n| Contract Deploy | 0.517 | 0.000054 | 99.9998% less |\n| Contract Execute | 0.010 | 0.000001 | 99.99999% less |\n\n### Comparison with Other Blockchains\n\n```python\n# PureChain measurements (per transaction)\n{\n 'purechain': {\n 'energy_kwh': 0.000000008,\n 'co2_g': 0.000003,\n 'comparison': 'Baseline'\n },\n 'ethereum_pow': {\n 'energy_kwh': 30,\n 'co2_g': 30000,\n 'times_worse': 3750000000 # 3.75 billion times\n },\n 'ethereum_pos': {\n 'energy_kwh': 0.01,\n 'co2_g': 10,\n 'times_worse': 1250000 # 1.25 million times\n },\n 'bitcoin': {\n 'energy_kwh': 511,\n 'co2_g': 500000,\n 'times_worse': 63875000000 # 63.9 billion times\n }\n}\n```\n\n### Carbon Tracking API Reference\n\n#### Enable/Disable Tracking\n```python\n# Enable with specific region\npc.enableCarbonTracking('us') # US grid intensity\npc.enableCarbonTracking('eu') # EU grid intensity\npc.enableCarbonTracking('renewable') # Renewable energy\n\n# Disable tracking\npc.disableCarbonTracking()\n```\n\n#### Transaction Carbon Data\n```python\n# Include carbon in transaction\nresult = await pc.send(to, value, include_carbon=True)\n\n# Carbon data structure\n{\n 'carbon': {\n 'gCO2': 0.000003, # Grams of CO2\n 'kgCO2': 0.000000003, # Kilograms\n 'tonnesCO2': 3e-12 # Metric tonnes\n },\n 'comparison': {\n 'vs_ethereum': '0.00001%',\n 'savings_kg': 30.0\n },\n 'environmental': {\n 'trees_equivalent': 0.0000001\n },\n 'offset': {\n 'cost_usd': 0.00000003\n }\n}\n```\n\n#### ESG Reporting\n```python\n# Get ESG-compliant metrics\nesg = await pc.getCarbonESGMetrics()\n\n# Returns\n{\n 'environmental': {\n 'total_emissions_kg_co2': 0.000001,\n 'emissions_per_transaction_g_co2': 0.000003,\n 'carbon_efficiency_vs_ethereum': '99.99%+ reduction',\n 'renewable_energy_compatible': True\n },\n 'sustainability': {\n 'zero_gas_operations': True,\n 'energy_efficient': True\n },\n 'reporting': {\n 'methodology': 'ISO 14064-1 compatible',\n 'verification': 'Automated tracking with PureChain SDK'\n }\n}\n```\n\n### \ud83c\udf0d Environmental Impact\n\nUsing PureChain instead of Ethereum for 1,000 transactions saves:\n- **Energy**: 30 kWh (enough to power a home for 1 day)\n- **Carbon**: 30 kg CO2 (equivalent to 1.4 trees for a year)\n- **Cost**: $3.60 in electricity\n\n### References\n\n1. Sedlmeir et al. (2020): \"The Energy Consumption of Blockchain Technology\"\n2. Cambridge Bitcoin Electricity Consumption Index (2023)\n3. EPA eGRID Power Profiler (2023)\n4. IEA Global Energy & CO2 Status Report (2023)\n\n## \u2753 FAQ\n\n**Q: Are transactions really free?** \nA: Yes! PureChain has zero gas costs. All operations cost 0 PURE.\n\n**Q: Can I deploy any Solidity contract?** \nA: Yes! PureChain is fully EVM compatible.\n\n<!-- **Q: How do I get PURE tokens?** \nA: Contact the PureChain team or use the testnet faucet. -->\n\n**Q: Is this compatible with Web3?** \nA: Yes! Built on Web3.py with PureChain-specific optimizations.\n\n## \ud83d\udd17 Links\n\n- **NPM Package**: https://www.npmjs.com/package/purechainlib\n<!-- - **GitHub**: https://github.com/purechainlib/purechainlib-python -->\n<!-- - **Documentation**: https://docs.purechain.network -->\n\n## \ud83d\udcc4 License\n\nMIT License - Free to use in any project!\n\n---\n\n**Zero Gas. Full EVM. Pure Innovation.** \ud83d\ude80\n\n*Built for the PureChain ecosystem - where blockchain development costs nothing!*\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Python SDK for PureChain EVM network - Zero gas cost blockchain development",
"version": "2.1.4",
"project_urls": {
"Documentation": "https://docs.purechain.network",
"Homepage": "https://pypi.org/project/purechainlib/",
"Repository": "https://pypi.org/project/purechainlib/"
},
"split_keywords": [
"blockchain",
" ethereum",
" web3",
" smart-contracts",
" zero-gas",
" purechain",
" evm",
" solidity",
" defi"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "8347d8086c5eb3f1abe7a23bcb8817d14ac52b4d72e8e88a69b39eb322cd4573",
"md5": "89b1cb3285ef63063c2126feea69900f",
"sha256": "f5896fc5618bfbe1e5cd9cc45da380c29e45559e5d819024be1835c5b7dcce55"
},
"downloads": -1,
"filename": "purechainlib-2.1.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "89b1cb3285ef63063c2126feea69900f",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.8",
"size": 59940,
"upload_time": "2025-08-14T05:34:59",
"upload_time_iso_8601": "2025-08-14T05:34:59.213781Z",
"url": "https://files.pythonhosted.org/packages/83/47/d8086c5eb3f1abe7a23bcb8817d14ac52b4d72e8e88a69b39eb322cd4573/purechainlib-2.1.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "56416b6e120671f2e60596fac89371bea6f24250c28fedc3df4915d7527b6523",
"md5": "c548da3b1c86ac99c435f81732902805",
"sha256": "d397b1ac2559645e2e587a5f06ccf34624947b4f13f305cda217c05d0a172dc9"
},
"downloads": -1,
"filename": "purechainlib-2.1.4.tar.gz",
"has_sig": false,
"md5_digest": "c548da3b1c86ac99c435f81732902805",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.8",
"size": 73053,
"upload_time": "2025-08-14T05:35:01",
"upload_time_iso_8601": "2025-08-14T05:35:01.141810Z",
"url": "https://files.pythonhosted.org/packages/56/41/6b6e120671f2e60596fac89371bea6f24250c28fedc3df4915d7527b6523/purechainlib-2.1.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-14 05:35:01",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "purechainlib"
}