Skill: kaiyuelv/blockchain-web3-toolkit (version 1.0.0)

# blockchain-web3-toolkit ## 名称 / Name - **中文**: 区块链Web3工具包 - **English**: Blockchain Web3 Toolkit ## 描述 / Description - **中文**: 一站式区块链开发工具，支持以太坊钱包管理、智能合约交互、NFT操作、Gas费用监控等功能 - **English**: All-in-one blockchain development toolkit supporting Ethereum wallet management, smart contract interaction, NFT operations, and gas fee monitoring ## 版本 / Version 1.0.0 ## 作者 / Author Kimi Claw ## 分类 / Category Blockchain, Web3, Crypto ## 依赖 / Dependencies - web3.py >= 6.0.0 - eth-account >= 0.8.0 - cryptography >= 3.4.8 ## 使用场景 / Use Cases - 以太坊钱包创建与管理 - 智能合约部署与调用 - NFT铸造与转移 - Gas费用实时监控 - 代币余额查询 ## 命令 / Commands ```bash # 创建新钱包 python scripts/create_wallet.py # 查询ETH余额 python scripts/get_balance.py --address 0x... # 部署合约 python scripts/deploy_contract.py --abi abi.json --bytecode bytecode.bin # 铸造NFT python scripts/mint_nft.py --contract 0x... --to 0x... --token-uri ipfs://... # 监控Gas价格 python scripts/gas_monitor.py ``` ## 触发词 / Triggers - blockchain, web3, ethereum, smart contract, NFT, wallet, crypto, gas fee - 区块链、智能合约、以太、钱包、加密、代币

path: README.md
content: # Blockchain Web3 Toolkit

## 简介 / Introduction

一站式区块链开发工具包，为开发者和用户提供便捷的以太坊生态系统交互能力。

An all-in-one blockchain development toolkit providing convenient interaction with the Ethereum ecosystem for developers and users.

## 功能特性 / Features

- **钱包管理 / Wallet Management**: 创建、导入、备份以太坊钱包
- **合约交互 / Contract Interaction**: 部署和调用智能合约
- **NFT操作 / NFT Operations**: 铸造、转移、查询NFT
- **Gas监控 / Gas Monitoring**: 实时追踪网络Gas价格
- **代币工具 / Token Tools**: ERC20代币余额查询与转账

## 安装 / Installation

```bash
pip install -r requirements.txt
```

## 快速开始 / Quick Start

```python
from scripts.wallet_manager import WalletManager

# 创建新钱包
wallet = WalletManager.create_wallet()
print(f"Address: {wallet.address}")
print(f"Private Key: {wallet.private_key}")

# 查询余额
balance = WalletManager.get_balance("0x...")
print(f"Balance: {balance} ETH")
```

## 配置 / Configuration

在 `.env` 文件中设置以下环境变量：

```
INFURA_API_KEY=your_infura_key
ETHERSCAN_API_KEY=your_etherscan_key
DEFAULT_NETWORK=mainnet
```

## API文档 / API Documentation

### WalletManager

```python
class WalletManager:
    @staticmethod
    def create_wallet() -> Wallet
    @staticmethod
    def import_from_private_key(private_key: str) -> Wallet
    @staticmethod
    def get_balance(address: str, network: str = "mainnet") -> float
```

### ContractInterface

```python
class ContractInterface:
    def deploy(self, abi: dict, bytecode: str, *args) -> str
    def call(self, contract_address: str, function_name: str, *args)
    def send_transaction(self, contract_address: str, function_name: str, *args) -> str
```

## 安全提示 / Security Notes

⚠️ **警告**: 永远不要将私钥提交到版本控制或分享给他人！

⚠️ **Warning**: Never commit private keys to version control or share them with others!

## 许可证 / License

MIT License


path: examples/basic_usage.py
content: #!/usr/bin/env python3
"""
Basic Usage Example - 基础使用示例
"""

import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'scripts'))

from wallet_manager import WalletManager


def main():
    print("=" * 60)
    print("Blockchain Web3 Toolkit - Basic Usage Example")
    print("=" * 60)
    
    # 1. Create a new wallet
    print("\n[Step 1] Creating a new Ethereum wallet...")
    wallet = WalletManager.create_wallet()
    print(f"✓ Address: {wallet.address}")
    print(f"✓ Private Key: {wallet.private_key[:20]}...{wallet.private_key[-10:]}")
    print("  ⚠️  IMPORTANT: Save this private key securely!")
    
    # 2. Validate the address
    print("\n[Step 2] Validating the address...")
    is_valid = WalletManager.validate_address(wallet.address)
    print(f"✓ Address is valid: {is_valid}")
    
    # 3. Import wallet from private key
    print("\n[Step 3] Importing wallet from private key...")
    imported = WalletManager.import_from_private_key(wallet.private_key)
    print(f"✓ Imported address: {imported.address}")
    print(f"✓ Addresses match: {wallet.address.lower() == imported.address.lower()}")
    
    # 4. Save to file (example)
    print("\n[Step 4] Saving wallet information...")
    wallet_data = wallet.to_dict()
    print(f"✓ Wallet data ready for storage")
    print(f"  Keys: {list(wallet_data.keys())}")
    
    print("\n" + "=" * 60)
    print("Example completed successfully!")
    print("=" * 60)
    print("\nNext steps:")
    print("  - Use get_balance() to check ETH balance")
    print("  - Use ContractInterface to interact with smart contracts")
    print("  - Use NFTTools for NFT operations")
    print("=" * 60)


if __name__ == "__main__":
    main()


path: requirements.txt
content: web3>=6.0.0
eth-account>=0.8.0
cryptography>=3.4.8
python-dotenv>=0.19.0
requests>=2.28.0


path: scripts/contract_interface.py
content: #!/usr/bin/env python3
"""
Contract Interface - 智能合约交互接口
"""

import os
import json
from typing import Any, List
from web3 import Web3
from eth_account import Account


class ContractInterface:
    """智能合约交互类 / Smart Contract Interface"""
    
    def __init__(self, network: str = "sepolia", private_key: str = None):
        """
        初始化合约接口
        Initialize contract interface
        
        Args:
            network: 网络名称 (mainnet/sepolia/goerli)
            private_key: 用于发送交易的私钥
        """
        from wallet_manager import NETWORKS
        
        self.network = network
        self.rpc_url = NETWORKS.get(network, NETWORKS["sepolia"])
        self.w3 = Web3(Web3.HTTPProvider(self.rpc_url))
        
        if not self.w3.is_connected():
            raise ConnectionError(f"Cannot connect to {network}")
        
        self.account = None
        if private_key:
            self.account = Account.from_key(private_key)
    
    def deploy(self, abi: list, bytecode: str, *args) -> str:
        """
        部署智能合约 / Deploy smart contract
        
        Returns:
            合约地址 / Contract address
        """
        if not self.account:
            raise ValueError("Private key required for deployment")
        
        Contract = self.w3.eth.contract(abi=abi, bytecode=bytecode)
        
        # Build transaction
        tx = Contract.constructor(*args).build_transaction({
            'from': self.account.address,
            'nonce': self.w3.eth.get_transaction_count(self.account.address),
            'gas': 5000000,
            'gasPrice': self.w3.eth.gas_price
        })
        
        # Sign and send
        signed_tx = self.w3.eth.account.sign_transaction(tx, self.account.key)
        tx_hash = self.w3.eth.send_raw_transaction(signed_tx.rawTransaction)
        
        # Wait for receipt
        receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
        
        return receipt.contractAddress
    
    def call(self, contract_address: str, abi: list, function_name: str, *args):
        """
        调用只读函数 / Call view function
        """
        contract = self.w3.eth.contract(
            address=Web3.to_checksum_address(contract_address),
            abi=abi
        )
        
        func = getattr(contract.functions, function_name)
        return func(*args).call()
    
    def send_transaction(self, contract_address: str, abi: list, function_name: str, *args) -> str:
        """
        发送状态变更交易 / Send state-changing transaction
        
        Returns:
            交易哈希 / Transaction hash
        """
        if not self.account:
            raise ValueError("Private key required for transactions")
        
        contract = self.w3.eth.contract(
            address=Web3.to_checksum_address(contract_address),
            abi=abi
        )
        
        func = getattr(contract.functions, function_name)
        
        tx = func(*args).build_transaction({
            'from': self.account.address,
            'nonce': self.w3.eth.get_transaction_count(self.account.address),
            'gas': 500000,
            'gasPrice': self.w3.eth.gas_price
        })
        
        signed_tx = self.w3.eth.account.sign_transaction(tx, self.account.key)
        tx_hash = self.w3.eth.send_raw_transaction(signed_tx.rawTransaction)
        
        return tx_hash.hex()


def main():
    """示例用法 / Example usage"""
    print("Contract Interface Demo")
    print("This module provides smart contract interaction capabilities.")
    print("\nUsage:")
    print("  interface = ContractInterface('sepolia', 'your_private_key')")
    print("  address = interface.deploy(abi, bytecode)")
    print("  result = interface.call(address, abi, 'functionName', arg1, arg2)")


if __name__ == "__main__":
    main()


path: scripts/gas_monitor.py
content: #!/usr/bin/env python3
"""
Gas Monitor - Gas费用监控
"""

import time
from web3 import Web3


class GasMonitor:
    """Gas费用监控器 / Gas Fee Monitor"""
    
    def __init__(self, network: str = "mainnet"):
        from wallet_manager import NETWORKS
        
        self.network = network
        self.rpc_url = NETWORKS.get(network, NETWORKS["mainnet"])
        self.w3 = Web3(Web3.HTTPProvider(self.rpc_url))
    
    def get_gas_prices(self) -> dict:
        """获取当前Gas价格 / Get current gas prices"""
        if not self.w3.is_connected():
            raise ConnectionError("Cannot connect to network")
        
        # Get latest block to estimate gas prices
        latest_block = self.w3.eth.get_block('latest')
        base_fee = latest_block.get('baseFeePerGas', 0)
        
        # Standard gas price
        gas_price = self.w3.eth.gas_price
        
        # Estimate priority fees
        slow = int(gas_price * 0.8)
        standard = gas_price
        fast = int(gas_price * 1.2)
        
        return {
            "slow": {
                "gwei": self.w3.from_wei(slow, 'gwei'),
                "eth": self.w3.from_wei(slow, 'ether')
            },
            "standard": {
                "gwei": self.w3.from_wei(standard, 'gwei'),
                "eth": self.w3.from_wei(standard, 'ether')
            },
            "fast": {
                "gwei": self.w3.from_wei(fast, 'gwei'),
                "eth": self.w3.from_wei(fast, 'ether')
            },
            "base_fee_gwei": self.w3.from_wei(base_fee, 'gwei') if base_fee else 0
        }
    
    def monitor(self, interval: int = 60, callback=None):
        """
        持续监控Gas价格 / Continuously monitor gas prices
        
        Args:
            interval: 检查间隔(秒)
            callback: 价格变化时的回调函数
        """
        print(f"Starting gas price monitor on {self.network}...")
        print(f"Update interval: {interval}s")
        print("-" * 50)
        
        last_prices = None
        
        try:
            while True:
                prices = self.get_gas_prices()
                
                if last_prices != prices:
                    print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}]")
                    print(f"Slow: {prices['slow']['gwei']:.2f} Gwei")
                    print(f"Standard: {prices['standard']['gwei']:.2f} Gwei")
                    print(f"Fast: {prices['fast']['gwei']:.2f} Gwei")
                    
                    if callback:
                        callback(prices)
                    
                    last_prices = prices
                
                time.sleep(interval)
                
        except KeyboardInterrupt:
            print("\nMonitor stopped.")


def main():
    """示例用法 / Example usage"""
    print("=" * 50)
    print("Ethereum Gas Price Monitor")
    print("=" * 50)
    
    monitor = GasMonitor("mainnet")
    prices = monitor.get_gas_prices()
    
    print("\nCurrent Gas Prices:")
    print(f"  Slow: {prices['slow']['gwei']:.2f} Gwei")
    print(f"  Standard: {prices['standard']['gwei']:.2f} Gwei")
    print(f"  Fast: {prices['fast']['gwei']:.2f} Gwei")
    
    print("\n" + "=" * 50)
    print("\nTo start continuous monitoring:")
    print("  monitor.monitor(interval=60)")


if __name__ == "__main__":
    main()


path: scripts/nft_tools.py
content: #!/usr/bin/env python3
"""
NFT Tools - NFT工具集
"""

from typing import Dict, List
from contract_interface import ContractInterface

# Standard ERC721 ABI (partial)
ERC721_ABI = [
    {
        "inputs": [{"name": "tokenId", "type": "uint256"}],
        "name": "ownerOf",
        "outputs": [{"name": "", "type": "address"}],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [{"name": "tokenId", "type": "uint256"}],
        "name": "tokenURI",
        "outputs": [{"name": "", "type": "string"}],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [
            {"name": "to", "type": "address"},
            {"name": "tokenId", "type": "uint256"}
        ],
        "name": "mint",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [
            {"name": "from", "type": "address"},
            {"name": "to", "type": "address"},
            {"name": "tokenId", "type": "uint256"}
        ],
        "name": "transferFrom",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "anonymous": False,
        "inputs": [
            {"indexed": True, "name": "from", "type": "address"},
            {"indexed": True, "name": "to", "type": "address"},
            {"indexed": True, "name": "tokenId", "type": "uint256"}
        ],
        "name": "Transfer",
        "type": "event"
    }
]


class NFTTools:
    """NFT工具类 / NFT Tools"""
    
    def __init__(self, network: str = "sepolia", private_key: str = None):
        self.interface = ContractInterface(network, private_key)
    
    def get_owner(self, contract_address: str, token_id: int) -> str:
        """查询NFT持有者 / Get NFT owner"""
        return self.interface.call(contract_address, ERC721_ABI, "ownerOf", token_id)
    
    def get_token_uri(self, contract_address: str, token_id: int) -> str:
        """查询NFT元数据URI / Get NFT metadata URI"""
        return self.interface.call(contract_address, ERC721_ABI, "tokenURI", token_id)
    
    def mint_nft(self, contract_address: str, to_address: str, token_id: int) -> str:
        """铸造NFT / Mint NFT"""
        return self.interface.send_transaction(
            contract_address, ERC721_ABI, "mint", to_address, token_id
        )
    
    def transfer_nft(self, contract_address: str, from_address: str, to_address: str, token_id: int) -> str:
        """转移NFT / Transfer NFT"""
        return self.interface.send_transaction(
            contract_address, ERC721_ABI, "transferFrom", from_address, to_address, token_id
        )


def main():
    """示例用法 / Example usage"""
    print("NFT Tools Demo")
    print("\nExample: Query NFT owner")
    print("  nft = NFTTools('mainnet')")
    print("  owner = nft.get_owner('0x...', 1234)")


if __name__ == "__main__":
    main()


path: scripts/wallet_manager.py
content: #!/usr/bin/env python3
"""
Wallet Manager - 钱包管理器
"""

import os
import json
from typing import Optional, Dict
from eth_account import Account
from web3 import Web3
from dotenv import load_dotenv

load_dotenv()

# Network RPC endpoints
NETWORKS = {
    "mainnet": f"https://mainnet.infura.io/v3/{os.getenv('INFURA_API_KEY', '')}",
    "sepolia": f"https://sepolia.infura.io/v3/{os.getenv('INFURA_API_KEY', '')}",
    "goerli": f"https://goerli.infura.io/v3/{os.getenv('INFURA_API_KEY', '')}",
}


class Wallet:
    """以太坊钱包类 / Ethereum Wallet Class"""
    
    def __init__(self, address: str, private_key: str):
        self.address = address
        self.private_key = private_key
    
    def to_dict(self) -> Dict:
        return {
            "address": self.address,
            "private_key": self.private_key
        }
    
    @classmethod
    def from_dict(cls, data: Dict) -> "Wallet":
        return cls(data["address"], data["private_key"])


class WalletManager:
    """钱包管理器 / Wallet Manager"""
    
    @staticmethod
    def create_wallet() -> Wallet:
        """创建新钱包 / Create new wallet"""
        account = Account.create()
        return Wallet(account.address, account.key.hex())
    
    @staticmethod
    def import_from_private_key(private_key: str) -> Wallet:
        """从私钥导入钱包 / Import wallet from private key"""
        account = Account.from_key(private_key)
        return Wallet(account.address, private_key)
    
    @staticmethod
    def import_from_mnemonic(mnemonic: str) -> Wallet:
        """从助记词导入钱包 / Import wallet from mnemonic"""
        Account.enable_unaudited_hdwallet_features()
        account = Account.from_mnemonic(mnemonic)
        return Wallet(account.address, account.key.hex())
    
    @staticmethod
    def get_balance(address: str, network: str = "mainnet") -> float:
        """查询ETH余额 / Get ETH balance"""
        rpc_url = NETWORKS.get(network, NETWORKS["mainnet"])
        w3 = Web3(Web3.HTTPProvider(rpc_url))
        
        if not w3.is_connected():
            raise ConnectionError(f"Cannot connect to {network}")
        
        checksum_address = Web3.to_checksum_address(address)
        balance_wei = w3.eth.get_balance(checksum_address)
        balance_eth = w3.from_wei(balance_wei, 'ether')
        
        return float(balance_eth)
    
    @staticmethod
    def validate_address(address: str) -> bool:
        """验证地址格式 / Validate address format"""
        try:
            return Web3.is_address(address)
        except:
            return False


def main():
    """示例用法 / Example usage"""
    print("=" * 50)
    print("Blockchain Web3 Toolkit - Wallet Manager")
    print("=" * 50)
    
    # 创建新钱包
    print("\n[1] Creating new wallet...")
    wallet = WalletManager.create_wallet()
    print(f"Address: {wallet.address}")
    print(f"Private Key: {wallet.private_key[:20]}...{wallet.private_key[-10:]}")
    
    # 验证地址
    print(f"\n[2] Validating address...")
    is_valid = WalletManager.validate_address(wallet.address)
    print(f"Valid: {is_valid}")
    
    print("\n" + "=" * 50)
    print("Done! Remember to save your private key securely.")
    print("=" * 50)


if __name__ == "__main__":
    main()


path: tests/test_wallet.py
content: #!/usr/bin/env python3
"""
Wallet Manager Tests - 钱包管理器测试
"""

import unittest
import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'scripts'))

from wallet_manager import WalletManager, Wallet


class TestWalletManager(unittest.TestCase):
    """测试钱包管理器 / Test Wallet Manager"""
    
    def test_create_wallet(self):
        """测试创建钱包 / Test wallet creation"""
        wallet = WalletManager.create_wallet()
        
        self.assertIsNotNone(wallet.address)
        self.assertIsNotNone(wallet.private_key)
        self.assertTrue(wallet.address.startswith('0x'))
        self.assertEqual(len(wallet.address), 42)  # 0x + 40 hex chars
    
    def test_import_from_private_key(self):
        """测试从私钥导入 / Test import from private key"""
        # Generate a wallet first
        original = WalletManager.create_wallet()
        
        # Import it
        imported = WalletManager.import_from_private_key(original.private_key)
        
        self.assertEqual(original.address.lower(), imported.address.lower())
    
    def test_validate_address(self):
        """测试地址验证 / Test address validation"""
        # Valid address
        self.assertTrue(WalletManager.validate_address([REDACTED_SECRET]))
        
        # Invalid address (too short)
        self.assertFalse(WalletManager.validate_address("0x123"))
        
        # Invalid address (no 0x prefix)
        self.assertFalse(WalletManager.validate_address([REDACTED_SECRET]))
    
    def test_wallet_serialization(self):
        """测试钱包序列化 / Test wallet serialization"""
        wallet = WalletManager.create_wallet()
        
        # Convert to dict
        data = wallet.to_dict()
        self.assertIn('address', data)
        self.assertIn('private_key', data)
        
        # Convert back
        restored = Wallet.from_dict(data)
        self.assertEqual(wallet.address, restored.address)
        self.assertEqual(wallet.private_key, restored.private_key)


class TestWallet(unittest.TestCase):
    """测试钱包类 / Test Wallet class"""
    
    def test_wallet_creation(self):
        """测试钱包对象创建 / Test wallet object creation"""
        wallet = Wallet([REDACTED_SECRET], "0x1234567890abcdef")
        
        self.assertEqual(wallet.address, [REDACTED_SECRET])
        self.assertEqual(wallet.private_key, "0x1234567890abcdef")


if __name__ == '__main__':
    unittest.main()


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)