├── .gitignore ├── ArbitrumBridge.py ├── LICENSE ├── README.md ├── Tutorial.py ├── transferETH.py └── zkSyncBridge.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /ArbitrumBridge.py: -------------------------------------------------------------------------------- 1 | # Web3 科学家 🧵 演示代码 2 | 3 | from web3 import Web3 4 | 5 | # Your Infura Project ID 6 | INFURA_SECRET_KEY = '7fe353dd8591489db345b657ebe5c910' 7 | 8 | 9 | # get w3 endpoint by network name 10 | def get_w3_by_network(network='mainnet'): 11 | # 接入 Infura 节点 12 | infura_url = f'https://{network}.infura.io/v3/{INFURA_SECRET_KEY}' 13 | w3 = Web3(Web3.HTTPProvider(infura_url)) 14 | return w3 15 | 16 | 17 | # bridge eth from rinkeby to arbitrum testnet 18 | def bridge_arbitrum_eth(w3, from_address, private_key, contract_address, amount_in_ether, chainId): 19 | from_address = Web3.to_checksum_address(from_address) 20 | contract_address = Web3.to_checksum_address(contract_address) 21 | 22 | ABI = '[{"inputs":[{"internalType":"uint256","name":"maxSubmissionCost","type":"uint256"}],"name":"depositEth","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"}]' 23 | 24 | amount_in_wei = w3.toWei(amount_in_ether, 'ether') 25 | maxSubmissionCost = int(amount_in_wei * 0.01) # 定义参数值 26 | nonce = w3.eth.get_transaction_count(from_address) 27 | 28 | params = { 29 | 'chainId': chainId, 30 | 'gas': 250000, 31 | 'nonce': nonce, 32 | 'from': from_address, 33 | 'value': amount_in_wei, 34 | # 'gasPrice': w3.toWei('5', 'gwei'), 35 | 'maxFeePerGas': w3.toWei(5, 'gwei'), 36 | 'maxPriorityFeePerGas': w3.toWei(5, 'gwei'), 37 | 'chainId': chainId, 38 | } 39 | contract = w3.eth.contract(address=contract_address, abi=ABI) 40 | 41 | # 调用合约的 depositEth 函数,参数为 maxSubmissionCost 42 | func = contract.functions.depositEth(maxSubmissionCost) 43 | try: 44 | tx = func.buildTransaction(params) 45 | signed_tx = w3.eth.account.sign_transaction(tx, private_key=private_key) 46 | txn = w3.eth.send_raw_transaction(signed_tx.rawTransaction) 47 | return {'status': 'succeed', 'txn_hash': w3.toHex(txn), 'task': 'Bridge ETH'} 48 | except Exception as e: 49 | return {'status': 'failed', 'error': e, 'task': 'Bridge ETH'} 50 | 51 | 52 | def main(): 53 | 54 | # 🐳 Task 3: Arbitrum 跨链 ETH 55 | 56 | # 接入 Arbiturm Rinkeby Testnet 57 | w3 = get_w3_by_network('rinkeby') 58 | 59 | # 测试地址 60 | from_address = '0x365a800a3c6a6B73B29E052fd4F7e68BFD45A086' 61 | 62 | # 测试私钥, 千万不能泄漏你自己的私钥信息 63 | private_key = 'e2facfbd1f0736318382d87b81029b05b7650ba17467c844cea5998a40e5bbc2' 64 | 65 | # Arbitrum 测试网跨链桥合约地址 66 | contract_address = '0x578BAde599406A8fE3d24Fd7f7211c0911F5B29e' 67 | 68 | # 跨链 ETH 金额 69 | amount_in_ether = 0.088 70 | 71 | # Rinkeby Chain ID 72 | chainId = 4 73 | 74 | # 查询地址 ETH余额 75 | balance = w3.eth.get_balance(from_address) / 1e18 76 | print(f'当前地址余额: {balance = } ETH') 77 | 78 | result = bridge_arbitrum_eth(w3, from_address, private_key, contract_address, amount_in_ether, chainId) 79 | print(result) 80 | 81 | 82 | 83 | if __name__ == "__main__": 84 | main() 85 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 gm365 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Web3_Tutorial 2 | 3 | Web3科学家极简入门指南 4 | 5 | 目标:学习并使用 Web3.py 模块实现链上数据查询、转账、合约交互等简单功能 6 | 7 | 8 | ## 00: 前期准备工作 9 | 10 | 1. 安装 Python3 11 | 2. 安装 web3.py 库 `pip install web3` 12 | 3. 申请 Infura API Key: https://infura.io/ 13 | 14 | 15 | ## 01: 读取链上信息 16 | 17 | * 目标:通过 Infura 接入以太坊主网并查询钱包余额信息 18 | * 代码: https://github.com/gm365/Web3_Tutorial/blob/main/Tutorial.py 19 | 20 | 21 | 22 | ## 02: Rinkeby 测试网转账 ETH 23 | 24 | * 目标:接入 Rinkeby 测试网并完成一笔转账交易 25 | 26 | * 代码: https://github.com/gm365/Web3_Tutorial/blob/main/transferETH.py 27 | 28 | * 测试地址:0x365a800a3c6a6B73B29E052fd4F7e68BFD45A086 29 | * 测试私钥:e2facfbd1f0736318382d87b81029b05b7650ba17467c844cea5998a40e5bbc2 30 | 31 | * 转账 Hash:0x70a71693e5f6158788847de8c56ab18479c47c1524c2970c2890175fb33adb58 32 | * 区块链浏览器结果查询:https://rinkeby.etherscan.io/address/0x365a800a3c6a6B73B29E052fd4F7e68BFD45A086 33 | 34 | 35 | ## 03: Arbitrum 测试网跨链桥交互 36 | 37 | * 目标: 完成 Arbitrum 测试网的跨链桥存入 ETH 的交互 38 | 39 | * 代码: https://github.com/gm365/Web3_Tutorial/blob/main/ArbitrumBridge.py 40 | * 交互记录 Hash: https://rinkeby.etherscan.io/tx/0x417f85a41d70ee619d9ff2c17051ed8ac56205e1ac232dd10966cd4b8dccdb43 41 | 42 | 43 | ## 04: zkSync 测试网跨链桥交互 44 | 45 | * 目标: 完成 zkSync 测试网的跨链桥存入 ETH 交互 46 | 47 | * 代码: https://github.com/gm365/Web3_Tutorial/blob/main/zkSyncBridge.py 48 | * 交互记录 Hash: https://goerli.etherscan.io/tx/0x4dbe6b9e52c3c401d80d5d585a03d0850d999c67a9aedbe54a23400d6b906005 49 | 50 | 51 | 52 | ## 参考资源 53 | 54 | * Mirror 版: https://mirror.xyz/gm365.eth/ad4vbp_qLFKaOrAMtE2YZ6pzMuC3ejam-y_62QogSds 55 | * Twitter 帖子地址: https://twitter.com/gm365/status/1527487356198330368 56 | -------------------------------------------------------------------------------- /Tutorial.py: -------------------------------------------------------------------------------- 1 | # Web3 科学家 🧵 演示代码 2 | 3 | from web3 import Web3 4 | 5 | # Your Infura Project ID 6 | INFURA_SECRET_KEY = '7fe353dd8591489db345b657ebe5c910' 7 | 8 | # get w3 endpoint by network name 9 | def get_w3_by_network(network='mainnet'): 10 | infura_url = f'https://{network}.infura.io/v3/{INFURA_SECRET_KEY}' # 接入 Infura 节点 11 | w3 = Web3(Web3.HTTPProvider(infura_url)) 12 | return w3 13 | 14 | 15 | def main(): 16 | 17 | # 🐳 Task 1: 接入并读取区块链信息 18 | 19 | # 接入 Web3 20 | w3 = get_w3_by_network(network='mainnet') 21 | 22 | # 检查接入状态 23 | print(w3.is_connected()) 24 | 25 | # 当前区块高度 26 | print(w3.eth.block_number) 27 | 28 | # V神 3号钱包地址 29 | vb = '0x220866b1a2219f40e72f5c628b65d54268ca3a9d' 30 | 31 | # 地址格式转换 32 | address = Web3.to_checksum_address(vb) 33 | 34 | # 查询地址 ETH余额 35 | balance = w3.eth.get_balance(address) / 1e18 36 | print(f'V神地址余额: {balance = } ETH') 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /transferETH.py: -------------------------------------------------------------------------------- 1 | # Web3 科学家 🧵 演示代码 2 | 3 | from web3 import Web3 4 | 5 | # Your Infura Project ID 6 | INFURA_SECRET_KEY = '7fe353dd8591489db345b657ebe5c910' 7 | 8 | 9 | # get w3 endpoint by network name 10 | def get_w3_by_network(network='mainnet'): 11 | infura_url = f'https://{network}.infura.io/v3/{INFURA_SECRET_KEY}' # 接入 Infura 节点 12 | w3 = Web3(Web3.HTTPProvider(infura_url)) 13 | return w3 14 | 15 | 16 | def transfer_eth(w3,from_address,private_key,target_address,amount,gas_price=5,gas_limit=21000,chainId=4): 17 | from_address = Web3.to_checksum_address(from_address) 18 | target_address = Web3.to_checksum_address(target_address) 19 | nonce = w3.eth.get_transaction_count(from_address) # 获取 nonce 值 20 | params = { 21 | 'from': from_address, 22 | 'nonce': nonce, 23 | 'to': target_address, 24 | 'value': w3.to_wei(amount, 'ether'), 25 | 'gas': gas_limit, 26 | # 'gasPrice': w3.toWei(gas_price, 'gwei'), 27 | 'maxFeePerGas': w3.to_wei(gas_price, 'gwei'), 28 | 'maxPriorityFeePerGas': w3.to_wei(gas_price, 'gwei'), 29 | 'chainId': chainId, 30 | 31 | } 32 | try: 33 | signed_tx = w3.eth.account.sign_transaction(params, private_key=private_key) 34 | txn = w3.eth.send_raw_transaction(signed_tx.rawTransaction) 35 | return {'status': 'succeed', 'txn_hash': w3.toHex(txn), 'task': 'Transfer ETH'} 36 | except Exception as e: 37 | return {'status': 'failed', 'error': e, 'task': 'Transfer ETH'} 38 | 39 | 40 | def main(): 41 | 42 | # 🐳 Task 2: ETH 转账 43 | 44 | # 接入 Rinkeby Testnet 45 | w3 = get_w3_by_network('rinkeby') 46 | 47 | # 测试地址 48 | from_address = '0x365a800a3c6a6B73B29E052fd4F7e68BFD45A086' 49 | 50 | # 测试私钥, 千万不能泄漏你自己的私钥信息 51 | private_key = 'e2facfbd1f0736318382d87b81029b05b7650ba17467c844cea5998a40e5bbc2' 52 | 53 | # 测试转入地址 54 | target_address = '0x8888a4E88f66f9C9FCE8c25F193617F3a3aB0760' 55 | 56 | # 转账 ETH 金额 57 | amount = 0.008 58 | 59 | # Rinkeby Chain ID 60 | chainId = 4 61 | 62 | # 查询地址 ETH余额 63 | balance = w3.eth.get_balance(from_address) / 1e18 64 | print(f'当前地址余额: {balance = } ETH') 65 | 66 | result = transfer_eth(w3, from_address, private_key, target_address, amount, chainId=chainId) 67 | print(result) 68 | 69 | 70 | if __name__ == "__main__": 71 | main() 72 | -------------------------------------------------------------------------------- /zkSyncBridge.py: -------------------------------------------------------------------------------- 1 | # Web3 科学家 🧵 演示代码 2 | 3 | from web3 import Web3 4 | from web3.middleware import geth_poa_middleware 5 | 6 | 7 | # Your Infura Project ID 8 | INFURA_SECRET_KEY = '7fe353dd8591489db345b657ebe5c910' 9 | 10 | 11 | # get w3 endpoint by network name 12 | def get_w3_by_network(network='goerli'): 13 | # 接入 Infura 节点 14 | infura_url = f'https://{network}.infura.io/v3/{INFURA_SECRET_KEY}' 15 | w3 = Web3(Web3.HTTPProvider(infura_url)) 16 | w3.middleware_onion.inject(geth_poa_middleware, layer=0) # goerli 需要添加这句 17 | return w3 18 | 19 | 20 | # bridge eth from goerli to zkSync 2.0 testnet 21 | def bridge_zkSync_eth(w3, from_address, private_key, contract_address, amount_in_ether, chainId): 22 | from_address = Web3.to_checksum_address(from_address) 23 | contract_address = Web3.to_checksum_address(contract_address) 24 | 25 | # Deposit ETH ABI 26 | ABI = '[{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address","name":"_zkSyncAddress","type":"address"},{"internalType":"enum Operations.QueueType","name":"_queueType","type":"uint8"},{"internalType":"enum Operations.OpTree","name":"_opTree","type":"uint8"}],"name":"depositETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"emergencyFreezeDiamond","outputs":[],"stateMutability":"nonpayable","type":"function"}]' 27 | 28 | amount_in_wei = w3.toWei(amount_in_ether, 'ether') 29 | nonce = w3.eth.get_transaction_count(from_address) 30 | 31 | # goerli链:无须设置 gas, gas price , chainId, 会自动计算并配置为 EIP 1559 类型 32 | tx_params = { 33 | 'value': amount_in_wei, 34 | "nonce": nonce, 35 | # 'gas': 150000, 36 | # 'gasPrice': w3.toWei(2, 'gwei'), 37 | # 'maxFeePerGas': w3.toWei(8, 'gwei'), 38 | # 'maxPriorityFeePerGas': w3.toWei(2, 'gwei'), 39 | # 'chainId': chainId, 40 | } 41 | 42 | contract = w3.eth.contract(address=contract_address, abi=ABI) 43 | 44 | try: 45 | raw_txn = contract.functions.depositETH(amount_in_wei, from_address, 0, 0).buildTransaction(tx_params) 46 | signed_txn = w3.eth.account.sign_transaction(raw_txn, private_key=private_key) 47 | txn = w3.eth.send_raw_transaction(signed_txn.rawTransaction) 48 | return {'status': 'succeed', 'txn_hash': w3.toHex(txn), 'task': 'zkSync Bridge ETH'} 49 | except Exception as e: 50 | return {'status': 'failed', 'error': e, 'task': 'zkSync Bridge ETH'} 51 | 52 | 53 | def main(): 54 | 55 | # 🐳 Task 4: zkSync 跨链 ETH 56 | 57 | # 接入 goerli Testnet 58 | w3 = get_w3_by_network('goerli') 59 | 60 | # 测试地址 61 | from_address = '0x365a800a3c6a6B73B29E052fd4F7e68BFD45A086' 62 | 63 | # 测试私钥, 千万不能泄漏你自己的私钥信息 64 | private_key = 'e2facfbd1f0736318382d87b81029b05b7650ba17467c844cea5998a40e5bbc2' 65 | 66 | # zkSync 测试网跨链桥合约地址 67 | contract_address = '0x0e9B63A28d26180DBf40E8c579af3aBf98aE05C5' 68 | 69 | # 跨链 ETH 金额 70 | amount_in_ether = 0.0188 71 | 72 | # goerli Testnet ChainID 73 | chainId = 5 74 | 75 | # 查询地址 ETH余额 76 | balance = w3.eth.get_balance(from_address) / 1e18 77 | print(f'当前地址余额: {balance = } ETH') 78 | 79 | result = bridge_zkSync_eth(w3, from_address, private_key, contract_address, amount_in_ether, chainId) 80 | print(result) 81 | 82 | 83 | if __name__ == "__main__": 84 | main() 85 | --------------------------------------------------------------------------------