Metadata-Version: 2.4
Name: ruby-manager-web3
Version: 0.1.2
Summary: A Python package for Ruby Web3 interactions with POA blockchain
Author-email: rubyweb3 <rubynode89@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/rubyscan/rubyweb3-python
Project-URL: Documentation, https://github.com/rubyscan/rubyweb3-python#readme
Project-URL: Repository, https://github.com/rubyscan/rubyweb3-python.git
Project-URL: Issues, https://github.com/rubyscan/rubyweb3-python/issues
Keywords: web3,blockchain,ruby,rubyscan
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: web3>=6.0.0
Requires-Dist: eth-account>=0.8.0
Requires-Dist: requests>=2.25.0
Requires-Dist: python-dotenv>=0.19.0
Requires-Dist: cryptography>=3.4.0
Requires-Dist: eth-hash>=0.5.0
Requires-Dist: eth-typing>=3.0.0
Requires-Dist: eth-utils>=2.0.0
Requires-Dist: hexbytes>=0.2.0
Requires-Dist: protobuf>=3.19.0
Requires-Dist: pycryptodome>=3.10.0
Requires-Dist: lru-dict>=1.1.0
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: isort; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: build; extra == "dev"
Dynamic: license-file

# Ruby Manager Web3

A comprehensive Python package for Web3 interactions with Ruby, specifically designed for Ruby Chain.

## Features

- 💰 **Token Management**: Full ERC20 token support with balance checking and transfers
- 🔄 **Batch Operations**: Multicall support for efficient contract interactions
- 📊 **Event Listening**: Real-time blockchain event monitoring
- 🔐 **Wallet Management**: Create, recover, and manage wallets
- ⚡ **Gas Optimization**: Smart gas estimation and transaction management
- 🛡️ **Security**: Comprehensive input validation and error handling
- ⛓️ **POA Blockchain Support**: Optimized for Ruby Chain (Chain ID: 18359)

## Installation

### From PyPI
```bash
pip install ruby-manager-web3
```

### From Source
```bash
git clone https://github.com/rubyscan/rubyweb3-python.git
cd ruby-manager-web3
pip install -e .
```

## Quick Start

### Basic Setup
```python
from ruby_manager_web3 import RubyWeb3Manager

# Initialize with Ruby Chain RPC
manager = RubyWeb3Manager(
    provider_url="https://bridge-rpc.rubyscan.io",
    private_key="your_private_key_here",  # Optional
    chain_id=18359
)

# Check connection
if manager.is_connected:
    print("✅ Connected to Ruby Chain!")

# Get current block number
block_number = manager.get_block_number()
print(f"Current block: {block_number}")
```

### Wallet Management
```python
# Create a new wallet
wallet = manager.create_wallet()
print(f"New Ruby Address: {wallet['address']}")  # Starts with 'r'
print(f"Private Key: {wallet['private_key']}")

# Set existing account
manager.set_account("your_private_key")
ruby_address = manager.get_ruby_address()
print(f"Your Ruby Address: {ruby_address}")

# Get balance
balance = manager.get_balance_ruby()
print(f"Balance: {balance} RUBY")
```

### Send Transactions
```python
# Send native coins
tx_hash = manager.send_coin(
    to_address="rRECIPIENT_ADDRESS_HERE",
    amount=1.5,  # 1.5 RUBY
    gas_limit=21000
)
print(f"Transaction sent: {tx_hash}")

# Wait for confirmation
receipt = manager.wait_for_transaction(tx_hash)
print(f"Transaction confirmed in block: {receipt['blockNumber']}")
```

## Core Components

### 1. RubyWeb3Manager
The main manager class for blockchain operations.

```python
from ruby_manager_web3 import RubyWeb3Manager

manager = RubyWeb3Manager("https://bridge-rpc.rubyscan.io")

# Network information
network_info = manager.get_network_info()
print(f"Chain ID: {network_info['chain_id']}")
print(f"Peer Count: {network_info['peer_count']}")

# Block operations
latest_block = manager.get_block_details('latest')
print(f"Block Hash: {latest_block['hash']}")

# Transaction history
tx_history = manager.get_transaction_history("rYOUR_ADDRESS")
for tx in tx_history:
    print(f"TX: {tx['hash']} - Value: {tx['value_eth']} RUBY")
```

### 2. Token Management
```python
from ruby_manager_web3 import TokenManager

token_manager = TokenManager(manager)

# Get token information
token_info = token_manager.get_token_info("rTOKEN_CONTRACT_ADDRESS")
print(f"Token: {token_info.name} ({token_info.symbol})")
print(f"Decimals: {token_info.decimals}")

# Get token balance
balance = token_manager.get_token_balance(
    "rTOKEN_CONTRACT_ADDRESS", 
    "rYOUR_WALLET_ADDRESS"
)
print(f"Balance: {balance.readable_balance} {token_info.symbol}")

# Transfer tokens
tx_hash = token_manager.transfer_token(
    token_address="rTOKEN_CONTRACT_ADDRESS",
    to_address="rRECIPIENT_ADDRESS",
    amount=100.0
)
print(f"Token transfer TX: {tx_hash}")

```
### 4. Event Service
```python
from ruby_manager_web3 import EventService

event_service = EventService(manager)

# Listen for token transfers
def handle_transfer(event):
    print(f"Transfer: {event['args']['from']} -> {event['args']['to']}")
    print(f"Amount: {event['args']['value']}")

# Start listening in background thread
event_service.listen_for_transfers(
    token_address="rTOKEN_CONTRACT_ADDRESS",
    callback=handle_transfer,
    poll_interval=5
)

# Get pending transactions
pending_txs = event_service.get_pending_transactions()
print(f"Pending transactions: {len(pending_txs)}")
```

### 5. Multicall Service
```python
from ruby_manager_web3 import MulticallService

multicall = MulticallService(manager)

# Batch multiple contract calls
calls = [
    ("rTOKEN1_ADDRESS", "balanceOf(address)", ["rYOUR_ADDRESS"]),
    ("rTOKEN2_ADDRESS", "balanceOf(address)", ["rYOUR_ADDRESS"]),
    ("rTOKEN3_ADDRESS", "totalSupply()", [])
]

try:
    block_number, results = multicall.multicall(calls)
    print(f"Block: {block_number}")
    print(f"Results: {results}")
except Exception as e:
    print(f"Multicall not available: {e}")
```

### 6. Price Feed Service
```python
from ruby_manager_web3 import PriceFeedService

price_service = PriceFeedService()

# Get current prices
eth_price = price_service.get_token_price('ethereum')
btc_price = price_service.get_token_price('bitcoin')
print(f"ETH: ${eth_price:.2f}")
print(f"BTC: ${btc_price:.2f}")

# Get multiple prices
prices = price_service.get_multiple_prices(['ethereum', 'bitcoin', 'matic-network'])
for token, price in prices.items():
    print(f"{token}: ${price:.2f}")

# Convert between tokens
converted = price_service.convert_value('ethereum', 'bitcoin', 1.0)
print(f"1 ETH = {converted:.6f} BTC")
```

## Advanced Usage

### Contract Deployment
```python
# Deploy a new contract
contract_abi = [...]  # Your contract ABI
contract_bytecode = "0x..."  # Your contract bytecode

tx_hash = manager.deploy_contract(
    abi=contract_abi,
    bytecode=contract_bytecode,
    args=[],  # Constructor arguments
    gas_limit=2000000
)

# Get deployed contract address
receipt = manager.wait_for_transaction(tx_hash)
contract_address = manager.get_contract_address_from_tx(tx_hash)
print(f"Contract deployed at: {contract_address}")
```

### Gas Management
```python
# Get gas estimate
gas_estimate = manager.get_gas_estimate(
    to_address="rRECIPIENT_ADDRESS",
    value=1.0
)
print(f"Gas Limit: {gas_estimate.gas_limit}")
print(f"Gas Price: {gas_estimate.gas_price}")
print(f"Total Cost: {gas_estimate.total_cost_eth} RUBY")

# Cancel pending transaction
cancel_tx_hash = manager.cancel_transaction(nonce=5)
print(f"Cancel transaction: {cancel_tx_hash}")

# Speed up pending transaction
speed_tx_hash = manager.speed_up_transaction(nonce=5)
print(f"Speed up transaction: {speed_tx_hash}")
```

### Batch Operations
```python
# Send multiple transactions
transactions = [
    {'to': 'rADDRESS1', 'amount': 0.1},
    {'to': 'rADDRESS2', 'amount': 0.2},
    {'to': 'rADDRESS3', 'amount': 0.3}
]

tx_hashes = manager.send_batch_transactions(transactions)
for i, tx_hash in enumerate(tx_hashes):
    if tx_hash:
        print(f"Transaction {i+1}: {tx_hash}")
```

## Configuration

### Environment Variables
Create a `.env` file:

```env
WEB3_PROVIDER_URL=https://bridge-rpc.rubyscan.io
PRIVATE_KEY=your_private_key_here
CHAIN_ID=18359
```

### Custom Configuration
```python
from ruby_manager_web3 import RubyWeb3Manager
import os
from dotenv import load_dotenv

load_dotenv()

manager = RubyWeb3Manager(
    provider_url=os.getenv('WEB3_PROVIDER_URL'),
    private_key=os.getenv('PRIVATE_KEY'),
    chain_id=int(os.getenv('CHAIN_ID', 18359)),
    timeout=30  # Request timeout in seconds
)
```

## Error Handling

```python
from ruby_manager_web3 import RubyWeb3Error, TransactionError

try:
    tx_hash = manager.send_coin("rINVALID_ADDRESS", 1.0)
except RubyWeb3Error as e:
    print(f"Error: {e}")
    
try:
    receipt = manager.wait_for_transaction("rINVALID_HASH")
except TransactionError as e:
    print(f"Transaction error: {e}")
```

## API Reference

### Core Classes

#### RubyWeb3Manager
- `create_wallet()` - Create new wallet
- `get_balance_ruby()` - Get balance in RUBY
- `send_coin()` - Send native coins
- `send_token()` - Send ERC20 tokens
- `get_transaction_details()` - Get transaction info
- `deploy_contract()` - Deploy new contract
- `get_block_details()` - Get block information

#### TokenManager
- `get_token_info()` - Get token metadata
- `get_token_balance()` - Get token balance
- `transfer_token()` - Transfer tokens
- `approve_token()` - Approve token spending



#### EventService
- `listen_for_events()` - Listen for contract events
- `listen_for_transfers()` - Listen for token transfers
- `get_pending_transactions()` - Get mempool transactions

## Examples

Check the `examples/` directory for complete working examples:

- `basic_usage.py` - Basic wallet and transaction operations
- `wallet_management.py` - Wallet creation and management
- `token_operations.py` - ERC20 token operations
- `defi_operations.py` - DeFi protocol interactions
- `advanced_operations.py` - Advanced blockchain operations

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## Development

### Setup Development Environment
```bash
git clone https://github.com/rubyscan/rubyweb3-python.git
cd ruby-manager-web3
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -e ".[dev]"
```

### Running Tests
```bash
pytest tests/
```

### Building Documentation
```bash
pip install pdoc
pdoc --html ruby_manager_web3 --output-dir docs
```

## Security

### Private Key Safety
- Never commit private keys to version control
- Use environment variables for configuration
- Consider using hardware wallets for large amounts

### Input Validation
All user inputs are validated:
- Address format validation
- Amount validation
- Gas parameter validation
- Transaction hash validation

## Support

- 📚 [Documentation](https://github.com/rubyscan/rubyweb3-python/wiki)
- 🐛 [Issue Tracker](https://github.com/rubyscan/rubyweb3-python/issues)
- 💬 [Discussions](https://github.com/rubyscan/rubyweb3-python/discussions)
- 📧 [Email Support](rubynode89@gmail.com)

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.



**Note**: This package is in active development. Always test with small amounts first and ensure you understand the transactions you're signing.

For the latest updates and breaking changes, please check the [Release Notes](https://github.com/rubyscan/rubyweb3-python/releases).
