PureChain Python Library

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
νμΌμ μ°Ύμ μ μμ΅λλ€.
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}")
π What's New in v2.1.1
Bug Fixes
- Fixed security audit results display issue
Previous Updates (v2.1.0)
π Smart Contract Security Auditing
- Built-in security tools - Slither & Mythril bundled with SDK
- Auto-installation - Tools install automatically on first use
- One-liner audits -
await pcl.audit("contract code")
- Multiple tools - Choose Slither, Mythril, or run ALL
- Comprehensive logging - Perfect for LLM integration
- Export reports - JSON, Markdown, HTML formats
π Documentation Updates
- Removed private GitHub repository links
- Improved Korean documentation access instructions
- Package now fully self-contained with both English and Korean docs
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
- 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
π Quick Start
pip install purechainlib
Note: Version 2.0.9+ automatically handles Web3 middleware configuration. No manual imports or patches needed!
import asyncio
from purechainlib import PureChain
async def main():
pc = PureChain('testnet')
pc.connect('your_private_key_here')
balance = await pc.balance()
print(f"Balance: {balance} PURE")
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()
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
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
pc = PureChain('testnet', 'optional_private_key')
pc.connect('your_private_key_without_0x')
new_account = pc.account()
address = pc.signer.address
π° Balance & Transactions
my_balance = await pc.balance()
other_balance = await pc.balance('0x...')
quick_balance = await pc.bal()
await pc.send('0x...recipient', '10.5')
await pc.send({
'to': '0x...address',
'value': '1.0',
'data': '0x...'
})
π Smart Contracts
contract_source = "pragma solidity ^0.8.19; contract Test { ... }"
factory = await pc.contract(contract_source)
deployed_contract = await factory.deploy(constructor_args)
existing_contract = factory.attach('0x...contract_address')
result = await pc.call(contract, 'balances', user_address)
name = await pc.call(contract, 'name')
await pc.execute(contract, 'mint', recipient, 1000)
await pc.execute(contract, 'setMessage', "Hello World")
π Blockchain Information
latest_block = await pc.block()
specific_block = await pc.block(12345)
tx_info = await pc.transaction('0x...hash')
tx_alias = await pc.tx('0x...hash')
addr_info = await pc.address()
other_info = await pc.address('0x...')
is_contract = await pc.isContract('0x...address')
gas_price = await pc.gasPrice()
status = await pc.status()
π Events & Monitoring
events = await pc.events(contract_address)
recent_events = await pc.events(contract_address, 10)
β‘ Performance Testing
tps_full = await pc.testTPS(duration=30, target_tps=100, measure_mode='full')
tps_send = await pc.testTPS(duration=30, target_tps=100, measure_mode='send')
tps_parallel = await pc.testTPS(duration=30, target_tps=100, measure_mode='parallel')
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']}")
latency_results = await pc.measureLatency(operations=100)
print(f"Average latency: {latency_results['balance_check']['avg_ms']}ms")
throughput_results = await pc.benchmarkThroughput(test_duration=60)
print(f"Throughput: {throughput_results['throughput_tps']} TPS")
performance = await pc.runPerformanceTest(quick=True)
full_performance = await pc.runPerformanceTest(quick=False)
π Detailed API Reference
Initialization
from purechainlib import PureChain
pc = PureChain('testnet')
pc = PureChain('mainnet')
pc = PureChain('testnet', 'your_private_key')
Account Management
pc.connect('your_private_key_without_0x_prefix')
account = pc.account()
print(f"Address: {account['address']}")
print(f"Private Key: {account['privateKey']}")
balance = await pc.balance()
balance = await pc.balance('0x...address')
Contract Operations
contract_source = """
pragma solidity ^0.8.19;
contract Token {
mapping(address => uint256) public balances;
function mint(uint256 amount) public {
balances[msg.sender] += amount;
}
}
"""
factory = await pc.contract(contract_source)
contract = await factory.deploy()
balance = await pc.call(contract, 'balances', user_address)
await pc.execute(contract, 'mint', 1000)
Transactions
await pc.send('0x...recipient_address', '10.5')
await pc.send({
'to': '0x...address',
'value': '1.0',
'data': '0x...'
})
Blockchain Information
block = await pc.block()
print(f"Block #{block['number']}")
tx = await pc.transaction('0x...transaction_hash')
status = await pc.status()
print(f"Chain ID: {status['chainId']}")
print(f"Gas Price: {status['gasPrice']}")
gas_price = await pc.gasPrice()
Pythonic Shortcuts
balance = await pc.bal()
info = await pc.address()
print(f"Balance: {info['balance']}")
print(f"Is Contract: {info['isContract']}")
is_contract = await pc.isContract('0x...address')
π Complete Examples
Deploy and Interact with Token Contract
import asyncio
from purechainlib import PureChain
async def token_example():
pc = PureChain('testnet')
pc.connect('your_private_key')
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;
}
}
"""
factory = await pc.contract(token_source)
token = await factory.deploy()
print(f"Token deployed at: {token.address}")
await pc.execute(token, 'mint', pc.signer.address, 1000000)
balance = await pc.call(token, 'balances', pc.signer.address)
print(f"Token balance: {balance}")
recipient = "0xc8bfbC0C75C0111f7cAdB1DF4E0BC3bC45078f9d"
await pc.execute(token, 'transfer', recipient, 100)
print("Tokens transferred!")
asyncio.run(token_example())
Create and Fund Multiple Accounts
import asyncio
from purechainlib import PureChain
async def multi_account_example():
pc = PureChain('testnet')
pc.connect('your_private_key')
accounts = []
for i in range(3):
account = pc.account()
accounts.append(account)
print(f"Account {i+1}: {account['address']}")
for i, account in enumerate(accounts):
await pc.send(account['address'], f"{i+1}.0")
print(f"Sent {i+1} PURE to account {i+1}")
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
import asyncio
from purechainlib import PureChain
async def event_example():
pc = PureChain('testnet')
pc.connect('your_private_key')
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);
}
}
"""
factory = await pc.contract(contract_source)
contract = await factory.deploy()
await pc.execute(contract, 'setMessage', "Hello Events!")
events = await pc.events(contract.address, 10)
print(f"Found {len(events)} events")
asyncio.run(event_example())
Performance Testing & Benchmarking
import asyncio
from purechainlib import PureChain
async def performance_testing():
pc = PureChain('testnet')
pc.connect('your_private_key')
print("π Starting Performance Tests...")
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")
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']})")
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']}%")
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
import asyncio
from purechainlib import PureChain
async def quick_performance_check():
pc = PureChain('testnet')
pc.connect('your_private_key')
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
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
{
'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
{
'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
async def batch_operations():
pc = PureChain('testnet')
pc.connect('your_key')
import asyncio
balances = await asyncio.gather(*[
pc.balance(user) for user in users
])
async def efficient_reads():
pc = PureChain('testnet')
latest_block = await pc.block()
for contract in contracts:
pass
async def production_monitoring():
pc = PureChain('mainnet')
pc.connect('production_key')
health_check = await pc.runPerformanceTest(quick=True)
if health_check['tps']['actual_tps'] < 20:
send_alert("PureChain performance below threshold")
Performance Testing Tips
async def performance_with_warmup():
pc = PureChain('testnet')
pc.connect('your_key')
print("π₯ Warming up network...")
for _ in range(5):
await pc.balance()
results = await pc.testTPS(30, 50)
testnet_results = await PureChain('testnet').runPerformanceTest()
mainnet_results = await PureChain('mainnet').runPerformanceTest()
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
import purechainlib as pcl
result = await pcl.audit("contract code here")
Security Audit Examples
import asyncio
from purechainlib import PureChain
async def security_examples():
pc = PureChain('testnet')
result = await pc.audit(contract_code)
if result['summary']['critical'] == 0:
print("β
Contract is safe!")
await pc.audit(contract_code, tool="slither")
await pc.audit(contract_code, tool="mythril")
await pc.audit(contract_code, tool="all")
safe_contract = await pc.auditAndDeploy(
contract_code,
require_pass=True
)
pc.enableAutoAudit()
result = await pc.runSecurityLoop(
vulnerable_contract,
max_iterations=5
)
logs = pc.getSecurityLogs()
pc.exportSecurityLogs('audit_logs.json')
asyncio.run(security_examples())
Available Security Tools
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
await pc.auditContract(code, export_report=True, report_format='json')
await pc.auditContract(code, export_report=True, report_format='markdown')
await pc.auditContract(code, export_report=True, report_format='html')
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
pc = PureChain('testnet')
pc.enableCarbonTracking('us')
result = await pc.send(address, amount, include_carbon=True)
print(f"Carbon footprint: {result['carbon_footprint']['carbon']['gCO2']} gCO2")
contract = await factory.deploy(track_carbon=True)
report = await pc.getCarbonReport()
print(f"Total emissions: {report['total_emissions']['kgCO2']} kg CO2")
esg = await pc.getCarbonESGMetrics()
print(f"Environmental metrics: {esg['environmental']}")
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
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
{
'purechain': {
'energy_kwh': 0.000000008,
'co2_g': 0.000003,
'comparison': 'Baseline'
},
'ethereum_pow': {
'energy_kwh': 30,
'co2_g': 30000,
'times_worse': 3750000000
},
'ethereum_pos': {
'energy_kwh': 0.01,
'co2_g': 10,
'times_worse': 1250000
},
'bitcoin': {
'energy_kwh': 511,
'co2_g': 500000,
'times_worse': 63875000000
}
}
Carbon Tracking API Reference
Enable/Disable Tracking
pc.enableCarbonTracking('us')
pc.enableCarbonTracking('eu')
pc.enableCarbonTracking('renewable')
pc.disableCarbonTracking()
Transaction Carbon Data
result = await pc.send(to, value, include_carbon=True)
{
'carbon': {
'gCO2': 0.000003,
'kgCO2': 0.000000003,
'tonnesCO2': 3e-12
},
'comparison': {
'vs_ethereum': '0.00001%',
'savings_kg': 30.0
},
'environmental': {
'trees_equivalent': 0.0000001
},
'offset': {
'cost_usd': 0.00000003
}
}
ESG Reporting
esg = await pc.getCarbonESGMetrics()
{
'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
- Sedlmeir et al. (2020): "The Energy Consumption of Blockchain Technology"
- Cambridge Bitcoin Electricity Consumption Index (2023)
- EPA eGRID Power Profiler (2023)
- 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: Is this compatible with Web3?
A: Yes! Built on Web3.py with PureChain-specific optimizations.
π Links
π 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!