diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 40194201177ebea55152c16a08adff33af63e3fc..0000000000000000000000000000000000000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.streamlit/config.toml b/.streamlit/config.toml deleted file mode 100644 index d99410d5806ac0bbe0b17a2ebd432db999a903a9..0000000000000000000000000000000000000000 --- a/.streamlit/config.toml +++ /dev/null @@ -1,4 +0,0 @@ -[theme] -base="light" -primaryColor="#cffd51" -font="serif" diff --git a/README.md b/README.md deleted file mode 100644 index fb1d9ffa26e5cfc93ca2dfc1a49611730b3f469d..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: eths -emoji: 🖊️ -colorFrom: blue -colorTo: yellow -python_version: 3.9.2 -sdk: streamlit -sdk_version: 1.26.0 -app_file: 🖊️EthPen-以太之笔.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/app.py b/app.py deleted file mode 100644 index f9e0430eaca300ddc4af2db113e7559a7e743a78..0000000000000000000000000000000000000000 --- a/app.py +++ /dev/null @@ -1,1514 +0,0 @@ -import streamlit as st -import requests -import re -import json -import hashlib -import pandas as pd -import base64 -import sqlite3 -import os - -infura_api_key = "9bbc614b8a1d49d59869e97d0ee3bf61" - -# Ethscriptions Mainnet API 的基础 URL -BASE_URL = "https://mainnet-api.ethscriptions.com/api" - -# 获取当前文件目录 -current_dir = os.path.dirname(os.path.abspath(__file__)) - -# 构造数据库文件路径 -eths_db_file = os.path.join(current_dir, 'data', 'eths_data.db') - -# Initialize connection to SQLite database -conn = sqlite3.connect(eths_db_file) -c = conn.cursor() - -# Create table to store ETHS data -c.execute(''' - CREATE TABLE IF NOT EXISTS eths_data - (date text, - eth_price real, - eths_price real, - eths_market_cap integer, - eths_owners integer, - eths_volume24h real, - eths_totalLocked integer, - eths_stakers integer, - eths_tvl real) - ''') - -# 查询地址所属代币铭文的 token 列表 -token_list = [{'p': 'erc-20', 'tick': 'eths', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'gwei', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'ercs', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'etch', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'dumb', 'id': 21000, 'amt': '1000'}] - -ethscrptions_logo = """ - - - - - - - - - - - - - - - - - - - - - -""" - -python_token_code = r""" -# ethpen.com -# 最后更新日期:2023 年 8 月 18 日 - -# 在使用之前,敬请仔细阅读说明,感谢您的配合。 -# 请务必访问 ethpen.com 官方网站。您可以确保这里的代码无恶意,安全地复制。 -# 你只需要掌握一些 python 相关的基础。 -# 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -# 我们建议您使用备用账号,并避免在账号中存放大额资金。 -# 若您对此代码存有疑虑,建议您利用如 ChetGPT、Bard 或 Claude 等知名 AI 平台进行查询,以判断是否含有恶意代码。 -# 如果你在使用的过程中发现 BUG 或者有什么想法和建议,欢迎与我联系。 - -# 导入运行代码所需要的库 -from web3 import Web3 # 与以太坊交互的库,安装的命令是 pip install web3 -import hashlib # 用于数据哈希,安装的命令是 pip install hashlib -import requests # 用于发送网络请求,安装的命令是 pip install requests -import re # 用于正则表达式 -import time # 用于时间相关 - -# ---------- 以下是基础配置 ---------- - -# 填写你的多个 ETH 地址及私钥,建议填写新建的钱包,用英文逗号分隔(,),如下:地址,私钥。 -accounts_str = ''' -0xa62C8d0bB4F4530b9B68a14DaF8A949Cb01dB986,4de9b2812d51ba0ebbe7c990947b12544f7926a7aa1ebac084d42f6c7c8afbc1 -0x71D10cc20Abe0af4EC16170C502a4319DE0e40B4,377f4a19719337b63d8280f0a52769a42b534343de1eccab4f6d204d1ca04815 -0xBe169Ae4AD317B5632DE6Ae0e1EfeF0b22B1f91e,24fdf2ed0b820307582b06e1ed0b2047b4371e9d682e0b32455d310e08baafc5 -''' - -# 需要题写的代币铭文内容,变动的部分文本如 id 请用 "@#" 代替,例如:'data:,{"p":"erc-20","op":"mint","tick":"eths","id":"@#","amt":"1000"}' -ethscription = 'data:,{"p":"erc-20","op":"mint","tick":"eths","id":"@#","amt":"1000"}' - -# 设置代币铭文 id 的起始和结束范围 -min_id = 100 # 开始的整数 -max_id = 888 # 结束的整数 - -# 决定是否在题写铭文之前检查该铭文有没有被题写过,如果需要检查就填写 Ture 如果不需要就填 False -check = False - -# 每次交易成功后暂停 N 秒,0 为不暂停 -sleep_sec = 0 - -# 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API -w3 = Web3(Web3.HTTPProvider('https://sepolia.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206')) - -# 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 -chain_id = 11155111 - -# ---------- 以上是基础配置 ---------- - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, # 账户的交易数 - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - print(f'{account_address} | {input_data} | Transaction Hash: {tx_hash.hex()}') - - -# 初始化当前账户索引为 0 -current_account_index = 0 -# 创建账户列表 -accounts = [] -# 使用字典来跟踪每个地址的nonce -nonces = {} - - -if accounts_str: # 如果账户列表有内容 - for line in accounts_str.strip().split('\n'): # 先去掉首尾的空白,然后根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - print(f"地址 {address} 或私钥 {key} 无效,请检查!") - exit() - else: - print(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - exit() - -# 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 -if not validate_input(ethscription): - print("请注意:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - -# 检查是否留空 -if not accounts or not ethscription: - print('请正确谨慎地填写内容,每一项都不应留空。') - exit() -else: - print('看起来你输入的内容均无没有问题!') - -# 认真检查铭文内容,如果发现错误,输入 1 结束 -print(f'铭文文本:\033[44m{ethscription}\033[m,题写 id 范围为:{min_id} - {max_id}。') -if input('请预览铭文,输入任意内容继续,输入 1 退出程序:') == '1': - exit() -print(f'开始任务,需要题写的铭文总量为:{max_id - min_id + 1}') - -# 对代币铭文 id 进行循环 -for the_id in range(min_id, max_id + 1): - # 使用当前账户发送交易 - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - input_data = ethscription.replace('@#', str(the_id)) - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - print(f'{input_data} 已经被题写!') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 sleep_sec 秒 - time.sleep(sleep_sec) - -print(f'所有任务已经完成。') - -""" - -python_name_code = r""" -# ethpen.com -# 最后更新日期:2023 年 8 月 18 日 - -# 在使用之前,敬请仔细阅读说明,感谢您的配合。 -# 请务必访问 ethpen.com 官方网站。您可以确保这里的代码无恶意,安全地复制。 -# 你只需要掌握一些 python 相关的基础。 -# 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -# 我们建议您使用备用账号,并避免在账号中存放大额资金。 -# 若您对此代码存有疑虑,建议您利用如 ChetGPT、Bard 或 Claude 等知名 AI 平台进行查询,以判断是否含有恶意代码。 -# 如果你在使用的过程中发现 BUG 或者有什么想法和建议,欢迎与我联系。 - -# 导入运行代码所需要的库 -from web3 import Web3 # 与以太坊交互的库,安装的命令是 pip install web3 -import hashlib # 用于数据哈希,安装的命令是 pip install hashlib -import requests # 用于发送网络请求,安装的命令是 pip install requests -import re # 用于正则表达式 -import time # 用于时间相关 - -# ---------- 以下是基础配置 ---------- - -# 填写你的多个 ETH 地址及私钥,建议填写新建的钱包,用英文逗号分隔(,),如下:地址,私钥。 -accounts_str = ''' -0xa62C8d0bB4F4530b9B68a14DaF8A949Cb01dB986,4de9b2812d51ba0ebbe7c990947b12544f7926a7aa1ebac084d42f6c7c8afbc1 -0x71D10cc20Abe0af4EC16170C502a4319DE0e40B4,377f4a19719337b63d8280f0a52769a42b534343de1eccab4f6d204d1ca04815 -0xBe169Ae4AD317B5632DE6Ae0e1EfeF0b22B1f91e,24fdf2ed0b820307582b06e1ed0b2047b4371e9d682e0b32455d310e08baafc5 -''' - -# 需要题写的铭文内容,在三个单引号内输入多个域名铭文,可以用空格、换行符、英文逗号(,)分开,不要带 data:, 开头 -# 不要带 data:, 开头 -# 不要带 data:, 开头 -ethscription = ''' -123 -12313131 -2131 21313 -12313 32313 -423213v ethpen.com -''' -# 你希望添加的后缀 -suffix = '.eths' -# 以空格、换行符、英文逗号分隔文本,并加上后缀 -ethscription_list = [item.strip() + suffix for item in re.split(r'[\s,]+', ethscription) if item] - -# 决定是否在题写铭文之前检查该铭文有没有被题写过,如果需要检查就填写 Ture 如果不需要就填 False -check = False - -# 每次交易成功后暂停 N 秒,0 为不暂停 -sleep_sec = 0 - -# 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API -w3 = Web3(Web3.HTTPProvider('https://sepolia.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206')) - -# 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 -chain_id = 11155111 - -# ---------- 以上是基础配置 ---------- - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已存在 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, # 账户的交易数 - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - print(f'{account_address} | {input_data} | Transaction Hash: {tx_hash.hex()}') - - -# 初始化当前账户索引为 0 -current_account_index = 0 -# 创建账户列表 -accounts = [] -# 使用字典来跟踪每个地址的nonce -nonces = {} - - -if accounts_str: # 如果账户列表有内容 - for line in accounts_str.strip().split('\n'): # 先去掉首尾的空白,然后根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - print(f"地址 {address} 或私钥 {key} 无效,请检查!") - exit() - else: - print(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - exit() - -# 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 -if not validate_input(ethscription): - print("请注意:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - -# 检查是否留空 -if not accounts or not ethscription: - print('请正确谨慎地填写内容,每一项都不应留空。') - exit() -else: - print('看起来你输入的内容均无没有问题!') - -# 认真检查铭文内容,如果发现错误,输入 1 结束 -for i in ethscription_list: - print(f'\033[44m{i}\033[m') -if input('请预览铭文,输入任意内容继续,输入 1 退出程序:') == '1': - exit() -print(f'开始任务,需要题写的铭文总量为:{len(ethscription_list)}') - -# 对代币铭文 id 进行循环 -for name_str in ethscription_list: - # 使用当前账户发送交易 - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - if not name_str.startswith('data:,'): - input_data = f'data:,{name_str}' - else: - input_data = name_str - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - print(f'{input_data} 已经被题写!') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 sleep_sec 秒 - time.sleep(sleep_sec) - -print(f'所有任务已经完成。') - -""" - -hf_token_code = r""" -# ethpen.com -# 最后更新日期:2023 年 8 月 18 日 - -# 在使用之前,敬请仔细阅读说明,感谢您的配合。 -# 请务必访问 ethpen.com 官方网站。您可以确保这里的代码无恶意,安全地复制。 -# 你只需要拥有一个 HuggingFace.co 账户。 -# 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -# 我们建议您使用备用账号,并避免在账号中存放大额资金。 -# 若您对此代码存有疑虑,建议您利用如 ChetGPT、Bard 或 Claude 等知名 AI 平台进行查询,以判断是否含有恶意代码。 -# 请查看我们的例子 https://ethscriptions-name.hf.space。 - -# 导入运行代码所需要的库 -import streamlit as st # streamlit app -from web3 import Web3 # 与以太坊交互的库 -import hashlib # 用于数据哈希 -import requests # 用于发送网络请求 -import re # 用于正则表达式 -import time # 用于时间相关 - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - st.toast(f'{input_data}', icon='✅') - # 返回铭文还有交易哈希 - return input_data, tx_hash.hex() - -# 网页前端显示 -# 网页标题 -st.markdown('# [ethpen.com](https://ethpen.com) 代币铭文批量题写') -# 提醒 -st.info('''在使用之前,敬请仔细阅读说明,感谢您的配合。 -- 请务必访问 **[ethpen.com](https://ethpen.com)** 官方网站。您可以确保这里的代码无恶意,安全地复制。 -- 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -- 我们建议您使用备用账号,并避免在账号中存放大额资金。 -- 若您对此代码存有疑虑,建议您利用如 [ChetGPT](https://chat.openai.com/)、[Bard](https://bard.google.com/) 或 [Claude](https://claude.ai/) 等知名 AI 平台进行查询,以判断是否含有恶意代码。 - ''') - -# 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 -net_options = { - '1': 'Mainnet', - '5': 'Goerli', - '11155111': 'Sepolia' -} -selected_option = st.selectbox( - '**网络 ID**', - list(net_options.keys()), - format_func=lambda x: f"{x} ({net_options[x]})" -) -chain_id = int(selected_option) - -# 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API -token_eth_prc_url = st.text_input( - f'**Ethereum PRC 链接**:选填,你可以去 [infura.io](https://app.infura.io/) 或者 [alchemy.com](https://alchemy.com/) 免费申请一个', - f'https://{net_options[str(chain_id)]}.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206') -w3 = Web3(Web3.HTTPProvider(f'{token_eth_prc_url}')) - -# 初始化当前账户索引为 0 -current_account_index = 0 -# 收集和显示所有交易的结果 -transaction_results = [] -# 创建账户列表 -accounts = [] -# 使用字典来跟踪每个地址的nonce -nonces = {} - -# 启用多账户操作 -if st.checkbox(f'启用**多账户**操作'): - # 多账户的文本框 - account_list = st.text_area(f'输入多个 **ETH 地址及其对应的私钥**,用英文逗号分隔(,),如下:地址,私钥') - if account_list: # 如果账户列表有内容 - for line in account_list.split('\n'): # 根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - st.error(f"地址 {address} 或私钥 {key} 无效,请检查!") - st.stop() - else: - st.error(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - st.stop() -else: - account_address = st.text_input('填写你的 **ETH 地址**:') - private_key = st.text_input('填写你的 **ETH 地址对应的私钥**:', type="password") - if account_address and private_key: # 如果地址和私钥有内容 - if is_valid_eth_address(account_address) and is_valid_eth_private_key(private_key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(account_address) # 获取地址的 nonce - nonces[account_address] = current_nonce # 记录地址的 nonce - accounts.append((account_address.strip(), private_key.strip())) # 保存地址和私钥还有 nonce - else: - st.error("地址或私钥无效,请检查!") - st.stop() - -# 配置铭文文本 -token_protocol = st.text_input('填写需要题写代币铭文协议 **Protocol(p)**:', 'erc-20') -token_operation = st.text_input('填写需要题写代币铭文操作 **Operation(op)**:', 'mint') -token_ticker = st.text_input('填写需要题写代币铭文简称 **Ticker(tick)**:') -token_min_id = st.number_input('填写需要题写代币铭文范围的**最小 ID(id)**:', min_value=1, value=1, step=1) -token_max_id = st.number_input('填写需要题写代币铭文范围的**最大 ID(id)**:', value=21000, step=1) -token_amount = st.number_input('填写需要题写代币铭文数量 **Amount(amt)**:', min_value=1, value=1000, step=1) -st.markdown('###### 预览你需要题写的代币铭文:') -st.code( - f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{token_min_id}","amt":"{token_amount}"}}', - language="json", line_numbers=False) -# 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 -if not validate_input( - f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{token_min_id}","amt":"{token_amount}"}}'): - st.warning("**请注意**:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - -# 题写铭文之前检查该铭文有没有被题写 -if st.checkbox(f'题写铭文之前**检查该铭文有没有被题写**'): - token_check = True -else: - token_check = False - -# 每次交易成功后暂停 3 秒 -if st.checkbox(f'每次交易完成后暂停 3 秒'): - sleep_3s = True -else: - sleep_3s = False - -# 点击发送交易开始 -if st.button(f'开始**发送交易**'): - if not accounts or not token_protocol or not token_operation or not token_ticker: # 检查是否留空 - st.error(f'请正确谨慎地填写内容,每一项都**不应留空**。') - st.stop() - else: - st.toast('看起来你输入的内容均无没有问题!', icon='🥳') - - st.toast(f'开始任务,需要题写的铭文总量为:{token_max_id - token_min_id + 1}', icon='😎') - - # 对代币铭文 id 进行循环 - for the_id in range(token_min_id, token_max_id + 1): - # 使用当前账户发送交易,获取当前账户的 nonce - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - input_data = f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{the_id}","amt":"{token_amount}"}}' - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if token_check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - st.toast(f'{input_data} 已经被题写!', icon='☹️') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 3 秒 - if sleep_3s: - time.sleep(3) # 暂停三秒 - st.toast(f'所有任务已经完成。', icon='🎉') - # 庆祝动画 - st.balloons() - # 显示所有交易的结果 - st.code('\n'.join(transaction_results)) - -""" - -hf_name_code = r""" -# ethpen.com -# 最后更新日期:2023 年 8 月 18 日 - -# 在使用之前,敬请仔细阅读说明,感谢您的配合。 -# 请务必访问 ethpen.com 官方网站。您可以确保这里的代码无恶意,安全地复制。 -# 你只需要拥有一个 HuggingFace.co 账户。 -# 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -# 我们建议您使用备用账号,并避免在账号中存放大额资金。 -# 若您对此代码存有疑虑,建议您利用如 ChetGPT、Bard 或 Claude 等知名 AI 平台进行查询,以判断是否含有恶意代码。 -# 请查看我们的例子 https://ethscriptions-name.hf.space。 - -# 导入运行代码所需要的库 -import streamlit as st # streamlit app -from web3 import Web3 # 与以太坊交互的库 -import hashlib # 用于数据哈希 -import requests # 用于发送网络请求 -import re # 用于正则表达式 -import time # 用于时间相关 - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 分隔文本函数 -def split_and_append(ethscriptions_str, name_selected_option): - separators = [' ', '\n', ','] - split_texts = [ethscriptions_str] # 初始时只有一个完整文本 - - for sep in separators: - pieces = [] - for text in split_texts: - pieces.extend(text.split(sep)) - split_texts = pieces - - # 移除空字符串 - split_texts = [text.strip() + name_selected_option for text in split_texts if text.strip() != ''] - - return split_texts - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - st.toast(f'{input_data}', icon='✅') - # 返回铭文还有交易哈希 - return input_data, tx_hash.hex() - -# 网页前端显示 -# 网页标题 -st.markdown('# [ethpen.com](https://ethpen.com) 域名铭文批量题写') -# 提醒 -st.info('''在使用之前,敬请仔细阅读说明,感谢您的配合。 -- 请务必访问 **[ethpen.com](https://ethpen.com)** 官方网站。您可以确保这里的代码无恶意,安全地复制。 -- 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -- 我们建议您使用备用账号,并避免在账号中存放大额资金。 -- 若您对此代码存有疑虑,建议您利用如 [ChetGPT](https://chat.openai.com/)、[Bard](https://bard.google.com/) 或 [Claude](https://claude.ai/) 等知名 AI 平台进行查询,以判断是否含有恶意代码。 - ''') - -# 连接的网络 ID。比如说,1 代表主网络,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 -net_options = { - '1': 'Mainnet', - '5': 'Goerli', - '11155111': 'Sepolia' -} -selected_option = st.selectbox( - '**网络 ID**', - list(net_options.keys()), - format_func=lambda x: f"{x} ({net_options[x]})" -) -chain_id = int(selected_option) - -# 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API -token_eth_prc_url = st.text_input( - f'**Ethereum PRC 链接**:选填,你可以去 [infura.io](https://app.infura.io/) 或者 [alchemy.com](https://alchemy.com/) 免费申请一个', - f'https://{net_options[str(chain_id)]}.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206') -w3 = Web3(Web3.HTTPProvider(f'{token_eth_prc_url}')) -# 初始化当前账户索引为 0 -current_account_index = 0 -# 收集和显示所有交易的结果 -transaction_results = [] -# 创建账户列表 -accounts = [] -# 使用字典来跟踪每个地址的nonce -nonces = {} - -# 启用多账户操作 -if st.checkbox(f'启用**多账户**操作'): - # 多账户的文本框 - account_list = st.text_area(f'输入多个 **ETH 地址及其对应的私钥**,用英文逗号分隔(,),如下:地址,私钥') - if account_list: # 如果账户列表有内容 - for line in account_list.split('\n'): # 根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - st.error(f"地址 {address} 或私钥 {key} 无效,请检查!") - st.stop() - else: - st.error(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - st.stop() -else: - account_address = st.text_input('填写你的 **ETH 地址**:') - private_key = st.text_input('填写你的 **ETH 地址对应的私钥**:', type="password") - if account_address and private_key: # 如果地址和私钥有内容 - if is_valid_eth_address(account_address) and is_valid_eth_private_key(private_key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(account_address) # 获取地址的 nonce - nonces[account_address] = current_nonce # 记录地址的 nonce - accounts.append((account_address.strip(), private_key.strip())) # 保存地址和私钥还有 nonce - else: - st.error("地址或私钥无效,请检查!") - st.stop() - -# 配置铭文文本 -ethscriptions_str = st.text_area(f'输入**多个域名铭文或其他**,可以用空格、换行符、英文逗号(,)分开,不要带 data:, 前缀,不要带域名后缀') -name_options = ["自定义", ".eth", ".eths", ".tree", ".honk", ".etch"] -name_selected_option = st.selectbox(f'选择**域名后缀**', name_options) -if name_selected_option == '自定义': - name_selected_option = st.text_input('输入**自定义的域名**:') -# 以空格、换行符、英文逗号分隔文本并加上后缀 -ethscription_list = split_and_append(ethscriptions_str, name_selected_option) - -# 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 -if not validate_input(''.join(ethscription_list)): - st.warning("**请注意**:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - -# 题写铭文之前检查该铭文有没有被题写 -if st.checkbox(f'题写铭文之前**检查该铭文有没有被题写**'): - token_check = True -else: - token_check = False - -# 每次交易成功后暂停 3 秒 -if st.checkbox(f'每次交易完成后暂停 3 秒'): - sleep_3s = True -else: - sleep_3s = False - -# 点击发送交易开始 -if st.button(f'开始**发送交易**'): - if not accounts or not ethscriptions_str or not name_selected_option: # 检查是否留空 - st.error(f'请正确谨慎地填写内容,每一项都**不应留空**。') - st.stop() - else: - st.toast('看起来你输入的内容均无没有问题!', icon='🥳') - - st.toast(f'开始任务,需要题写的铭文总量为:{len(ethscription_list)}', icon='😎') - - # 对代币铭文 id 进行循环 - for name_str in ethscription_list: - # 使用当前账户发送交易,获取当前账户的 nonce - address, key = accounts[current_account_index] - # 获取 gas - gas_price = w3.eth.gas_price - # 得到完整的铭文文本 - if not name_str.startswith('data:,'): - input_data = f'data:,{name_str}' - - # 根据是否检查的开关进行 - if token_check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - st.toast(f'{input_data} 已经被题写!', icon='☹️') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 3 秒 - if sleep_3s: - time.sleep(3) # 暂停三秒 - st.toast(f'所有任务已经完成。', icon='🎉') - # 庆祝动画 - st.balloons() - # 显示所有交易的结果 - st.code('\n'.join(transaction_results)) - -""" - -my_style = ''' - -''' - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 验证代币铭文函数 -def is_valid_eths(data, p, tick, id, amt): - # 构建匹配1到id-1的正则表达式 - pattern_range = "|".join([str(i) for i in range(1, id)]) - # 使用 f-string 插入参数到正则表达式 - pattern = rf'^data:,{{"p":"{p}","op":"mint","tick":"{tick}","id":"({pattern_range}|{id})","amt":"{amt}"}}$' - return bool(re.match(pattern, data)) - - -# 文本转换到十六进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# str SHA256 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 根据 TX 获取 input data -def get_input_data(tx_hash): - endpoint = f"https://mainnet.infura.io/v3/{infura_api_key}" - headers = { - "Content-Type": "application/json", - } - data = { - "jsonrpc": "2.0", - "id": 1, - "method": "eth_getTransactionByHash", - "params": [tx_hash] - } - eth_transaction = requests.post(endpoint, headers=headers, data=json.dumps(data)) - transaction_data = eth_transaction.json() - return transaction_data['result']['input'] - - -# 获取所有的 ethscriptions -def get_all_ethscriptions(page=None, per_page=None, sort_order=None): - endpoint = "/ethscriptions" - params = { - "page": page, # 页码 - "per_page": per_page, # 每页的数量 - "sort_order": sort_order # 排序顺序 - } - response = requests.get(BASE_URL + endpoint, params=params) - return response.json() - - -# 根据地址获取 ethscriptions -def get_ethscriptions_by_address(address): - all_ethscriptions = [] - page = 1 - per_page = 100 - while True: - endpoint = f"/ethscriptions/owned_by/{address}" - params = { - "page": page, - "per_page": per_page, - "sort_order": 'asc' - } - response = requests.get(BASE_URL + endpoint, params=params) - if response.status_code != 200: - print(f"Error fetching data: {response.text}") - break - ethscriptions = response.json() - all_ethscriptions.extend(ethscriptions) - if len(ethscriptions) < per_page: - break - page += 1 - return all_ethscriptions - - -# 使用ID或数字获取特定的 ethscription -def get_specific_ethscription(ethscription_identifier): - endpoint = f"/ethscriptions/{ethscription_identifier}" - response = requests.get(BASE_URL + endpoint) - return response.json() - - -# 获取特定 ethscription 的数据 -def get_ethscription_data(ethscription_identifier): - endpoint = f"/ethscriptions/{ethscription_identifier}/data" - response = requests.get(BASE_URL + endpoint) - return response.json() - - -# 使用 SHA256 值检查内容是否已被 ethscribed -def check_content_exists(sha): - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get(BASE_URL + endpoint) - if response.status_code == 200: - return response.json() - - -# 确定索引器是否落后 -def get_block_status(): - endpoint = "/block_status" - response = requests.get(BASE_URL + endpoint) - return response.json() - - -# 获取 $eths 价格 -def get_eths_price(): - params = { - 'category': 'token', - 'collectionName': 'erc-20 eths', - } - - response = requests.get( - 'https://www.etch.market/api/markets/collections/details', - params=params - ) - if response.status_code == 200: - response = response.json() - if response['message'] == 'success': - return response['data'] - return {} # 返回一个空字典作为默认值 - - -# 从 etch.market 那里获取用户地址代币余额 -def get_etch_token_amt(): - params = { - 'category': 'token', - 'tokenQuery': '', - } - - response = requests.get( - 'https://www.etch.market/api/markets/ethscriptions/collections/0x59724739940777947c56C4f2f2C9211cd5130FEf', - params=params - ) - if response.status_code == 200: - response = response.json() - if response['message'] == 'success': - return response['data'] - return {} # 返回一个空字典作为默认值 - - -# 获取 $eths 质押数据 -def get_eths_staking(): - response = requests.get('https://www.etch.market/api/staking/statistics/erc-20%20eths') - if response.status_code == 200: - response = response.json() - if response['message'] == 'success': - return response['data'] - return {} # 返回一个空字典作为默认值 - - -st.set_page_config(page_title="EthPen - 以太之笔", page_icon="🖊", layout='wide', initial_sidebar_state='expanded') - -# 首页 -st.markdown( - f'# Image :rainbow[EthPen - 以太之笔]', - unsafe_allow_html=True) -st.subheader('', anchor=False, divider='rainbow') - -# 最近新闻 -st.markdown(f'### 最近新闻') -st.markdown( - f'Image', - unsafe_allow_html=True) -st.markdown(f'> 3 周前,我们提出了 Ethscriptions 虚拟机的构想——一种通过将其解释为计算机指令来显著增强 Ethscriptions 功能的方法。今天,我们宣布了该虚拟机的首个实现。已在 Goerli 网络上线,并已在 GitHub 上完全开源!👆') - -# 广告位图片 -st.markdown(f'### 广告位') -st.markdown( - f'Image', - unsafe_allow_html=True) -st.markdown(f'> 拆分方案现在面向所有人推出!让我们一起加入权益挖矿的浪潮,并分享50%的月度服务费。') -st.markdown("### 功能专区") - - -# st.expander -search_rune_expander = st.expander("查询 Ethscriptions") -create_rune_expander = st.expander("题写 Ethscriptions") -token_no_code_expander = st.expander("一键式铭文批量题写,无需编码知识!") -trend_expander = st.expander("潮流动态") -help_expander = st.expander("教程帮助") -st.markdown("🎉 更多功能尽在菜单栏,请点击左上角的 >") -# 查询铭文页面 -search_rune_expander.info( - f"铭文数据来自 [Ethscriptions](https://ethscriptions.com/) 官方网站,当前索引器状态落后: {get_block_status()['blocks_behind']} 个区块。") -search_rune_expander.markdown("##### 查询 ETH 地址所属铭文") -user_address = search_rune_expander.text_input('输入 ETH 地址:', '') - -if search_rune_expander.button('🔍 查询', key='查询铭文'): - # 检查ETH地址 - pattern = "^0x[a-fA-F0-9]{40}$" - if re.match(pattern, user_address): - data = get_ethscriptions_by_address(user_address) - if not data: - search_rune_expander.info( - "该地址没有任何铭文,或许是区块暂时没同步过来,如果你不确定,请前往 Ethscriptions 官网再次查询!") - else: - token_total = 0 - for token in token_list: - for ethscriptions in data: - if is_valid_eths(ethscriptions['content_uri'], token['p'], token['tick'], token['id'], - token['amt']): - input_data_str = json.loads(ethscriptions['content_uri'][6:]) - token_total = token_total + int(input_data_str['amt']) - search_rune_expander.success(f"${token['tick']} 有效总量为:{token_total}") - token_total = 0 - search_rune_expander.warning( - f"只统计 etch.market 流动性较高的资产,etch.market 上架的代币不计算在内,详细更多的信息请点击[这里](https://ethscriptions.com/{user_address})") - else: - search_rune_expander.error("输入的 ETH 地址不正确!") - -search_rune_expander.markdown("##### 查询铭文的完整信息") -ethscriptions_str = search_rune_expander.text_input('输入完整的铭文文本:', '') -if search_rune_expander.button('🔍 查询', key='查询信息'): - if not ethscriptions_str.startswith('data:,'): - ethscriptions_str = f'data:,{ethscriptions_str}' - ethscriptions_all_str = sha256(ethscriptions_str) - ethscriptions_data = check_content_exists(ethscriptions_all_str) - if ethscriptions_data['result']: - search_rune_expander.markdown(f'###### :green[{ethscriptions_str}] 相关信息如下:') - selected_data = { - '当前拥有者': ethscriptions_data["ethscription"]["current_owner"], - '题写时间': ethscriptions_data["ethscription"]["creation_timestamp"], - '铭文编号': f'#{ethscriptions_data["ethscription"]["ethscription_number"]}', - '铭文完整内容': ethscriptions_data["ethscription"]["content_uri"], - } - search_rune_expander.json(selected_data) - else: - search_rune_expander.markdown(f'###### :green[{ethscriptions_str}] 铭文还没被题写!复制下方文本前去题写。') - search_rune_expander.code(f'{text_to_hex(ethscriptions_str)}', line_numbers=False) - -# 批量查询铭文是否被存在 -runes = [] -search_rune_expander.markdown("##### 批量查询铭文是否被题写") -search_rune_expander.markdown(r''' -1. **查域名**:可以用空格和换行符还有英文逗号(,)分开,不要带前缀 data:, -2. **查代币**:需要查询的代币铭文内容变动的部分文本如 id 请用 "@#" 代替,例如:`data:,{"p":"erc-20","op":"mint","tick":"eths","id":"@#","amt":"1000"}` -3. **查纯文本**:可任意填写,用空格和换行符还有英文逗号(,)分开''') -input_content = search_rune_expander.text_area(f'输入铭文文本:') -search_type = search_rune_expander.radio('选择查询类型:', ['查域名', '查代币', '查纯文本'], - label_visibility="collapsed", horizontal=True, index=2) -if search_type == '查域名': - search_dotname = search_rune_expander.text_input('填写域名后缀:') -elif search_type == '查代币': - search_token_min_id = search_rune_expander.number_input(f'填写代币铭文范围的**最小 ID(id)**:', min_value=1, value=1, - step=1) - search_token_max_id = search_rune_expander.number_input(f'填写代币铭文范围的**最大 ID(id)**:', value=10, step=1) - -if search_rune_expander.button('🔍 查询', key='批量查询铭文'): - runes = re.split(r'[\s,]+', input_content) - # 过滤掉空或仅包含空白字符的项 - runes = [r for r in runes if r.strip() != ''] - if search_type == '查域名': - runes = [r + search_dotname for r in runes] - elif search_type == '查代币': - token_runes = [] - if len(runes) != 1 and '@#' in input_content: - for the_id in range(search_token_min_id, search_token_max_id + 1): - token_runes.append(input_content.replace('@#', str(the_id))) - else: - st.stop() - runes = token_runes - # 创建一个空的结果列表 - results = [] - # 循环遍历每一个铭文并查询其存在状态 - for rune in runes: - if not rune.startswith('data:,'): - rune = f'data:,{rune}' - sha_value = sha256(rune) - response_data = check_content_exists(sha_value) - - # 根据返回的result,得到真或者假 - exists = "已题写" if response_data['result'] else "未题写" - results.append([rune, exists]) - - # 使用 st.table 显示结果 - table_data = pd.DataFrame(results, columns=['铭文', '状态']) - - # 根据状态生成一个辅助排序列 - table_data['sort_helper'] = table_data['状态'].apply(lambda x: 0 if x == "未题写" else 1) - - # 使用辅助列进行排序 - table_data.sort_values(by='sort_helper', ascending=True, inplace=True) - - # 删除辅助排序列 - table_data.drop(columns=['sort_helper'], inplace=True) - - # 定义样式和生成带有专门类名的HTML表格 - table_style = """ - - """ - search_rune_expander.markdown(table_style, unsafe_allow_html=True) - table_html = table_data.to_html(index=False, classes='styled_table', border=0, escape=False, - formatters=dict(状态=lambda x: f'{x}')) - - # 生成HTML表格但不为状态列添加特殊格式 - table_html = table_data.to_html(index=False, classes='styled_table', border=0, escape=False) - - # 使用字符串替换为状态列添加特定属性 - table_html = table_html.replace('已题写', '已题写') - table_html = table_html.replace('未题写', '未题写') - - # 使用st.write输出带样式的HTML表格 - search_rune_expander.write(table_html, unsafe_allow_html=True) - search_rune_expander.markdown('') - -# 题写铭文页面 -create_rune_expander.markdown("##### 文本转换到十六进制") -input_ethscriptions_str = create_rune_expander.text_input( - '输入需要转换的文本,默认以 "data:," 开头,换行和回车字符不应出现。', '') -if create_rune_expander.button('🔁 转换', key='文本转换到十六进制'): - if not input_ethscriptions_str.startswith('data:,'): - input_ethscriptions_str = f'data:,{input_ethscriptions_str}' - input_ethscriptions_hex = text_to_hex(input_ethscriptions_str) - create_rune_expander.markdown(f':green[{input_ethscriptions_str}] 转换到十六进制:') - create_rune_expander.code(input_ethscriptions_hex, line_numbers=False) - input_ethscriptions_sha = sha256(input_ethscriptions_str) - ethscriptions_data = check_content_exists(input_ethscriptions_sha) - if ethscriptions_data['result']: - create_rune_expander.markdown(f'###### :green[{ethscriptions_str}] 相关信息如下:') - selected_data = { - '当前拥有者': ethscriptions_data["ethscription"]["current_owner"], - '题写时间': ethscriptions_data["ethscription"]["creation_timestamp"], - '铭文编号': f'#{ethscriptions_data["ethscription"]["ethscription_number"]}', - '铭文完整内容': ethscriptions_data["ethscription"]["content_uri"], - } - create_rune_expander.json(selected_data) - else: - create_rune_expander.markdown(f'###### :green[{input_ethscriptions_str}] 铭文还没被题写!快前去题写吧。') - -create_rune_expander.markdown("##### 批量自动题写铭文") -create_rune_expander.info("""在使用之前,敬请仔细阅读说明,感谢您的配合。 -1. 请务必访问 **[ethpen.com](https://ethpen.com)** 官方网站。您可以确保这里的代码无恶意,安全地复制。 -2. 你只需要掌握一些 python 相关的基础。 -3. 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -4. 我们建议您使用备用账号,并避免在账号中存放大额资金。 -5. 若您对此代码存有疑虑,建议您利用如 [ChetGPT](https://chat.openai.com/)、[Bard](https://bard.google.com/) 或 [Claude](https://claude.ai/) 等知名 AI 平台进行查询,以判断是否含有恶意代码。 -6. 如果你在使用的过程中发现 BUG 或者有什么想法和建议,欢迎与我联系。 - """) -if create_rune_expander.button('🖨 打印代币代码', key='输出代币铭文 Python 代码'): - create_rune_expander.code(python_token_code, 'python', line_numbers=False) -if create_rune_expander.button('🖨 打印域名代码', key='输出域名铭文 Python 代码'): - create_rune_expander.code(python_name_code, 'python', line_numbers=False) - -# 全新不用懂代码的铭文批量题写页面 -token_no_code_expander.markdown("##### 安全的简易的批量自动题写铭文") -token_no_code_expander.info("""在使用之前,敬请仔细阅读说明,感谢您的配合。 -1. 请务必访问 **[ethpen.com](https://ethpen.com)** 官方网站。您可以确保这里的代码无恶意,安全地复制。 -2. 你只需要拥有一个 [HuggingFace.co](https://huggingface.co) 账户。 -3. 在使用过程中,请根据规定准确填写信息,以确保程序顺畅运行。 -4. 我们建议您使用备用账号,并避免在账号中存放大额资金。 -5. 若您对此代码存有疑虑,建议您利用如 [ChetGPT](https://chat.openai.com/)、[Bard](https://bard.google.com/) 或 [Claude](https://claude.ai/) 等知名 AI 平台进行查询,以判断是否含有恶意代码。 -6. 请查看我们的例子 [token-example](https://huggingface.co/spaces/Ethscriptions/token) / [name-example](https://huggingface.co/spaces/Ethscriptions/name)。 - """) -if token_no_code_expander.button('🖨️ 打印代币代码', key='输出 Token 铭文 Python 代码'): - token_no_code_expander.markdown( - f'**为 [HuggingFace.co](https://huggingface.co) 平台与 [Streamlit.io](https://streamlit.io/) 框架量身打造的代币铭文专业 Python 代码(app.py):**') - token_no_code_expander.code(hf_token_code, 'python', line_numbers=False) - token_no_code_expander.markdown(f"**依赖包清单(requirements.txt):**") - token_no_code_expander.code(''' -Requests -streamlit -web3 -''') -if token_no_code_expander.button('🖨️ 打印域名代码', key='输出 Name 铭文 Python 代码'): - token_no_code_expander.markdown( - f'**为 [HuggingFace.co](https://huggingface.co) 平台与 [Streamlit.io](https://streamlit.io/) 框架量身打造的域名铭文专业 Python 代码(app.py):**') - token_no_code_expander.code(hf_name_code, 'python', line_numbers=False) - token_no_code_expander.markdown(f"**依赖包清单(requirements.txt):**") - token_no_code_expander.code(''' -Requests -streamlit -web3 -''') - -# 潮流动态页面 -trend_expander.markdown("##### 开发中...") - -# 教程帮助页面 -help_expander.markdown('##### 我不懂代码,怎么做到批量题写铭文?') -# help_expander.markdown('##### 如何用 Metamask 题写 Ethscriptions 铭文?') -# help_expander.markdown('##### 如何用 Metamask 在 etch.market 上购买 $eths?') -# help_expander.markdown('##### 如何运行批量自动题写铭文 python 代码?') -# help_expander.markdown(f'', unsafe_allow_html=True) - - -# 嵌入式SVG文本(以下只是示例,替换为你的SVG文本) -twitter_svg = """ - -""" -twitter_encoded_svg = base64.b64encode(twitter_svg.encode('utf-8')).decode('utf-8') -telegram_svg = """ - -""" -telegram_encoded_svg = base64.b64encode(telegram_svg.encode('utf-8')).decode('utf-8') -discord_svg = """ - -""" -discord_encoded_svg = base64.b64encode(discord_svg.encode('utf-8')).decode('utf-8') - -# 实际的社交链接 -twitter_link = "https://twitter.com/pztuya" -telegram_link = "https://t.me/NervosCKB" -discord_link = "https://discord.gg/ethscriptions" - -# 关于页面 -eths_price_data = get_eths_price() -st.markdown("### 关于") -st.markdown(f'##### 什么是 Ethscriptions?', unsafe_allow_html=True) -st.markdown( - f'{my_style}Image Ethscriptions 是一种新的在以太坊上创建和分享数字资产的方法,它通过使用交易 calldata 存储数据而不是智能合约来实现,这使其比 NFT 更为经济。它们是完全在链上、无需许可、抗审查的,并且其成本只是 NFT 的一小部分。', - unsafe_allow_html=True) -st.markdown('') -st.markdown('##### 谁创造了 Ethscriptions?') -st.markdown( - f'首个 [Ethscription](https://ethscriptions.com/ethscriptions/0) 是在 2016 年创建的,但正式的协议是由 Tom Lehman,又名 Image @Middlemarch 开发的。除了比特币的铭文,他还受到了来自 Poly Network 黑客的著名的 “原型 - Ethscription” 的启发,你可以在[这笔交易](https://etherscan.io/tx/0x0ae3d3ce3630b5162484db5f3bdfacdfba33724ffb195ea92a6056beaa169490)中看到它。', - unsafe_allow_html=True) -st.markdown( - f'- 快来加入 @ethscriptions,与 Ethscriptions 一起成长!', - unsafe_allow_html=True) -st.markdown('##### Ethscriptions 上的龙头代币是?') -st.markdown( - f'毫无疑问,当自无愧,她必须是 Ethscriptions 上第一个代币 👉 Image **eths**', - unsafe_allow_html=True) - -# 查询eths_data表中所有数据 -c.execute('SELECT * FROM eths_data') -# 获取所有结果 -eths_data = c.fetchall() - -# 定义卡片样式 -eths_card_style = """ - -""" -st.markdown(eths_card_style, unsafe_allow_html=True) -# 创建卡片的HTML内容 -eths_card_content = f""" -
- Image -

-
- Image -
-

Ethscriptions eths

-

${eths_data[0][2]:.2f}

-
-
-

市值:${eths_data[0][3]:,.0f}

-

总量:21,000,000

-

24h 交易量:${eths_data[0][5]:,.0f}

-
INFO
-

官网:None

-

浏览器:Image Ethscriptions

-

Ethscription ID:Image 0x463654......bed2e4

-

部署时间:2023/06/18 05:46:11

-

公链:Ethereum Ethscriptions

-

持有人数:{eths_data[0][4]:,.0f}

-

社交: @ethscriptions @ethscriptions

-
Staking
-

质押总量:{eths_data[0][6]:,.0f} $eths

-

质押人数:{eths_data[0][7]:,.0f}

-

TVL:${eths_data[0][8]:,.0f}

-

立即买入 $eths

-
-""" -st.markdown(eths_card_content, unsafe_allow_html=True) - -st.markdown('') -st.markdown('##### 关于 ethpen.com') -st.markdown( - f'欢迎踏足 EthPen - 以太之笔!这里汇聚了一系列关于 Ethscriptions 的精细工具集,无论是单一查询、铭文题写,还是批量检索、编码题写,乃至深入的教程导引,以太之笔都将助您铭文题写如飞。我们立志推广 Ethscriptions 的宏大理念,期望 $eths 翱翔于星空,与月相伴!若您携手建议或创意,我们热切期待您的声音。', - unsafe_allow_html=True) -st.markdown('对了,我叫 pztuya,期待你们和我多多交流😊~') - -st.markdown(f''' - @pztuya - @NervosCKB -''', unsafe_allow_html=True) diff --git a/data/.DS_Store b/data/.DS_Store deleted file mode 100644 index 1e2701eb12902cc4b218edec23f13209a06e447e..0000000000000000000000000000000000000000 Binary files a/data/.DS_Store and /dev/null differ diff --git a/data/batch_contract_abi.json b/data/batch_contract_abi.json deleted file mode 100644 index 863e5ae563a2747167e2460db2635c037b1037a2..0000000000000000000000000000000000000000 --- a/data/batch_contract_abi.json +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint64","name":"startTime","type":"uint64"},{"internalType":"uint64","name":"endTime","type":"uint64"},{"internalType":"uint16","name":"protocolFeeDiscounted","type":"uint16"},{"internalType":"uint16","name":"creatorFee","type":"uint16"},{"internalType":"bytes","name":"params","type":"bytes"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct OrderTypes.EthscriptionOrder[]","name":"orders","type":"tuple[]"}],"name":"batchBuy","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"setMarketAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}] \ No newline at end of file diff --git a/data/config.ini b/data/config.ini deleted file mode 100644 index d31507e4771ac6021bf09be350bdd59181acbca8..0000000000000000000000000000000000000000 --- a/data/config.ini +++ /dev/null @@ -1,6 +0,0 @@ -[data_thread_start_state] -state = 0 - -[push_thread_start_state] -state = 0 - diff --git a/data/eths_data.db b/data/eths_data.db deleted file mode 100644 index ad2a6a4d49bf925a1d54bc2ba449df4c2e492302..0000000000000000000000000000000000000000 Binary files a/data/eths_data.db and /dev/null differ diff --git a/data/huggingface_name_code.py b/data/huggingface_name_code.py deleted file mode 100644 index c7c93a7c8ba299b2d3570451026a487ba785730f..0000000000000000000000000000000000000000 --- a/data/huggingface_name_code.py +++ /dev/null @@ -1,275 +0,0 @@ -# EthPen.com -# 最后更新日期:2023 年 9 月 5 日 - - -# 导入运行代码所需要的库 -import streamlit as st # streamlit app -from web3 import Web3 # 与以太坊交互的库 -import hashlib # 用于数据哈希 -import requests # 用于发送网络请求 -import re # 用于正则表达式 -import time # 用于时间相关 -import os # 用于操作系统文件 - - -# 许可使用开关 -approved_use = False - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 分隔文本函数 -def split_and_append(ethscriptions_str, name_selected_option): - separators = [' ', '\n', ','] - split_texts = [ethscriptions_str] # 初始时只有一个完整文本 - - for sep in separators: - pieces = [] - for text in split_texts: - pieces.extend(text.split(sep)) - split_texts = pieces - - # 移除空字符串 - split_texts = [text.strip() + name_selected_option for text in split_texts if text.strip() != ''] - - return split_texts - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(byte, '02x') for byte in text.encode('utf-8')) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - st.toast(f'{input_data}', icon='✅') - # 返回铭文还有交易哈希 - return input_data, tx_hash.hex() - - -# 网页前端显示 -st.set_page_config(page_title="EthPen - 批量题写域名铭文", page_icon="🆔", layout='centered', initial_sidebar_state='auto') - -# 网页标题 -st.subheader(r'🆔 :rainbow[EthPen - 域名铭文批量题写]', anchor=False, divider='rainbow') - -# 提醒 -st.markdown('### 在开始使用前,请仔细阅读相关说明,并在确认无误后打上 ✅。感谢您的理解与配合。') - -open_source = st.checkbox('我们已将网站代码完全开源。您可以访问并仔细阅读此页面的源码:[2_🆔_批量题写域名铭文.py](https://huggingface.co/spaces/Ethscriptions/eths/tree/main/pages)',) - -ask_ai = st.checkbox('如果你对此代码存有疑虑,建议你利用如 [OpenAI - ChetGPT](https://chat.openai.com/)、[Google - Bard](https://bard.google.com/)、[Anthropic - Claude](https://claude.ai/)、[抖音 - 豆包](https://www.doubao.com/)、[百度 - 文心一言](https://yiyan.baidu.com/)、[阿里 - 通义千问](https://qianwen.aliyun.com/) 等知名 AI 平台进行问询,这可以帮助你判断代码是否含有恶意内容。',) - -huggingface = st.checkbox('复制我们的代码,你同样可以在 [HuggingFace](https://HuggingFace.co) 上搭建专属于你的域名铭文批量题写工具。',) - -site = st.checkbox('请务必确保你正在访问的是 **[EthPen.com](https://ethpen.com)** 网站。我们保证站内代码不包含窃取私钥或其他恶意行为,你可以安心使用。',) - -use = st.checkbox('在使用过程中,请按照提示准确地填写信息,这样可以确保程序的顺畅运行。',) - -wallet = st.checkbox('为了安全起见,我们建议您使用备用账号(小号)并确保账号中不存放大额资金。',) - -test = st.checkbox('首次使用时,我们建议您先在测试网络中操作。确认一切无误后,再切换至主网络使用。',) - -feedback = st.checkbox('若您在使用过程中遇到问题,请及时向我们反馈。我们明白程序可能存在不完善之处,并且我们的能力也有限。真心希望得到各位程序员大佬的指导和交流。',) - -if open_source and ask_ai and huggingface and site and use and wallet and test and feedback: - approved_use = True -else: - approved_use = False - -if approved_use: - - st.markdown('## 批量题写域名铭文') - - # 连接的网络 ID。比如说,1 代表主网络,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 - net_options = { - '1': 'Mainnet', - '5': 'Goerli', - '11155111': 'Sepolia' - } - selected_option = st.selectbox( - '**网络 ID**', - list(net_options.keys()), - format_func=lambda x: f"{x} ({net_options[x]})" - ) - chain_id = int(selected_option) - - # 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API - token_eth_prc_url = st.text_input( - f'**Ethereum PRC 链接**:选填,你可以去 [infura.io](https://app.infura.io/) 或者 [alchemy.com](https://alchemy.com/) 免费申请一个', - f'https://{net_options[str(chain_id)]}.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206') - w3 = Web3(Web3.HTTPProvider(f'{token_eth_prc_url}')) - # 初始化当前账户索引为 0 - current_account_index = 0 - # 收集和显示所有交易的结果 - transaction_results = [] - # 创建账户列表 - accounts = [] - # 使用字典来跟踪每个地址的nonce - nonces = {} - - # 启用多账户操作 - multipl_accounts = st.toggle('启用**多账户**操作') - if multipl_accounts: - # 多账户的文本框 - account_list = st.text_area(f'输入多个 **ETH 地址及其对应的私钥**,用英文逗号分隔(,),如下:地址,私钥') - if account_list: # 如果账户列表有内容 - for line in account_list.split('\n'): # 根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - st.error(f"地址 {address} 或私钥 {key} 无效,请检查!") - st.stop() - else: - st.error(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - st.stop() - else: - account_address = st.text_input('填写你的 **ETH 地址**:') - private_key = st.text_input('填写你的 **ETH 地址对应的私钥**:', type="password") - if account_address and private_key: # 如果地址和私钥有内容 - if is_valid_eth_address(account_address) and is_valid_eth_private_key(private_key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(account_address) # 获取地址的 nonce - nonces[account_address] = current_nonce # 记录地址的 nonce - accounts.append((account_address.strip(), private_key.strip())) # 保存地址和私钥还有 nonce - else: - st.error("地址或私钥无效,请检查!") - st.stop() - - # 配置铭文文本 - ethscriptions_str = st.text_area(f'输入**多个域名铭文或其他**,可以用`空格`、`换行符`、`英文逗号(,)`分开,不要带 `data:,` 前缀,不要带`域名后缀`:') - - name_selected_option = st.radio("选择域名后缀:", ['🎨 自定义', '🆔.eths', '🆔.eth', '🌲.tree', '🦛.honk', '🔄.etch', '🌐.com'], index=1, horizontal=True) - if name_selected_option == '🎨 自定义': - name_selected_option = st.text_input('输入**域名后缀**:') - - # 以空格、换行符、英文逗号分隔文本并加上后缀 - ethscription_list = split_and_append(ethscriptions_str, name_selected_option) - - # 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 - if not validate_input(''.join(ethscription_list)): - st.warning("**请注意**:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - - token_check = st.toggle('题写前**检查是否被题写** `主网` `查重`') - # 题写铭文之前检查该铭文有没有被题写 - if token_check: - token_check = True - else: - token_check = False - sleep_3s = st.toggle('每次完成交易后暂停 3 秒') - # 每次交易成功后暂停 3 秒 - if sleep_3s: - sleep_3s = True - else: - sleep_3s = False - - # 点击发送交易开始 - if st.button(f'开始**发送交易**'): - if not accounts or not ethscriptions_str or not name_selected_option: # 检查是否留空 - st.error(f'请正确谨慎地填写内容,每一项都**不应留空**。') - st.stop() - else: - st.toast('看起来你输入的内容均无没有问题!', icon='🥳') - - st.toast(f'开始任务,需要题写的铭文总量为:{len(ethscription_list)}', icon='😎') - - # 对代币铭文 id 进行循环 - for name_str in ethscription_list: - # 使用当前账户发送交易,获取当前账户的 nonce - address, key = accounts[current_account_index] - # 获取 gas - gas_price = w3.eth.gas_price - # 得到完整的铭文文本 - if not name_str.startswith('data:,'): - input_data = f'data:,{name_str}' - - # 根据是否检查的开关进行 - if token_check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - st.toast(f'{input_data} 已经被题写!', icon='☹️') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 3 秒 - if sleep_3s: - time.sleep(3) # 暂停三秒 - st.toast(f'所有任务已经完成。', icon='🎉') - # 庆祝动画 - st.balloons() - # 显示所有交易的结果 - st.code('\n'.join(transaction_results)) -else: - st.error('# 阅读并打勾 ✅ 后方可使用。') diff --git a/data/huggingface_token_code.py b/data/huggingface_token_code.py deleted file mode 100644 index 50a2d8ddbf39009d17939376a9be1dd1a18e59da..0000000000000000000000000000000000000000 --- a/data/huggingface_token_code.py +++ /dev/null @@ -1,259 +0,0 @@ -# EthPen.com -# 最后更新日期:2023 年 9 月 5 日 - - -# 导入运行代码所需要的库 -import streamlit as st # streamlit app -from web3 import Web3 # 与以太坊交互的库 -import hashlib # 用于数据哈希 -import requests # 用于发送网络请求 -import re # 用于正则表达式 -import time # 用于时间相关 -import os # 用于操作系统文件 - - -# 许可使用开关 -approved_use = False - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(byte, '02x') for byte in text.encode('utf-8')) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - st.toast(f'{input_data}', icon='✅') - # 返回铭文还有交易哈希 - return input_data, tx_hash.hex() - - -# 网页前端显示 -st.set_page_config(page_title="EthPen - 批量题写代币铭文", page_icon="🪙", layout='centered', initial_sidebar_state='auto') - -# 网页标题 -st.subheader(r'🪙 :rainbow[EthPen - 代币铭文批量题写]', anchor=False, divider='rainbow') - -# 提醒 -st.markdown('### 在开始使用前,请仔细阅读相关说明,并在确认无误后打上 ✅。感谢您的理解与配合。') - -open_source = st.checkbox('我们已将网站代码完全开源。您可以访问并仔细阅读此页面的源码:[3_🪙_ 批量题写代币铭文.py](https://huggingface.co/spaces/Ethscriptions/eths/tree/main/pages)',) - -ask_ai = st.checkbox('如果你对此代码存有疑虑,建议你利用如 [OpenAI - ChetGPT](https://chat.openai.com/)、[Google - Bard](https://bard.google.com/)、[Anthropic - Claude](https://claude.ai/)、[抖音 - 豆包](https://www.doubao.com/)、[百度 - 文心一言](https://yiyan.baidu.com/)、[阿里 - 通义千问](https://qianwen.aliyun.com/) 等知名 AI 平台进行问询,这可以帮助你判断代码是否含有恶意内容。',) - -huggingface = st.checkbox('复制我们的代码,你同样可以在 [HuggingFace](https://HuggingFace.co) 上搭建专属于你的域名铭文批量题写工具。',) - -site = st.checkbox('请务必确保你正在访问的是 **[EthPen.com](https://ethpen.com)** 网站。我们保证站内代码不包含窃取私钥或其他恶意行为,你可以安心使用。',) - -use = st.checkbox('在使用过程中,请按照提示准确地填写信息,这样可以确保程序的顺畅运行。',) - -wallet = st.checkbox('为了安全起见,我们建议您使用备用账号(小号)并确保账号中不存放大额资金。',) - -test = st.checkbox('首次使用时,我们建议您先在测试网络中操作。确认一切无误后,再切换至主网络使用。',) - -feedback = st.checkbox('若您在使用过程中遇到问题,请及时向我们反馈。我们明白程序可能存在不完善之处,并且我们的能力也有限。真心希望得到各位程序员大佬的指导和交流。',) - -if open_source and ask_ai and huggingface and site and use and wallet and test and feedback: - approved_use = True -else: - approved_use = False - -if approved_use: - - st.markdown('## 批量题写代币铭文') - - # 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 - net_options = { - '1': 'Mainnet', - '5': 'Goerli', - '11155111': 'Sepolia' - } - selected_option = st.selectbox( - '**网络 ID**', - list(net_options.keys()), - format_func=lambda x: f"{x} ({net_options[x]})" - ) - chain_id = int(selected_option) - - # 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API - token_eth_prc_url = st.text_input( - f'**Ethereum PRC 链接**:选填,你可以去 [infura.io](https://app.infura.io/) 或者 [alchemy.com](https://alchemy.com/) 免费申请一个', - f'https://{net_options[str(chain_id)]}.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206') - w3 = Web3(Web3.HTTPProvider(f'{token_eth_prc_url}')) - - # 初始化当前账户索引为 0 - current_account_index = 0 - # 收集和显示所有交易的结果 - transaction_results = [] - # 创建账户列表 - accounts = [] - # 使用字典来跟踪每个地址的nonce - nonces = {} - - # 启用多账户操作 - multipl_accounts = st.toggle('启用**多账户**操作') - if multipl_accounts: - # 多账户的文本框 - account_list = st.text_area(f'输入多个 **ETH 地址及其对应的私钥**,用英文逗号分隔(,),如下:地址,私钥') - if account_list: # 如果账户列表有内容 - for line in account_list.split('\n'): # 根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - st.error(f"地址 {address} 或私钥 {key} 无效,请检查!") - st.stop() - else: - st.error(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - st.stop() - else: - account_address = st.text_input('填写你的 **ETH 地址**:') - private_key = st.text_input('填写你的 **ETH 地址对应的私钥**:', type="password") - if account_address and private_key: # 如果地址和私钥有内容 - if is_valid_eth_address(account_address) and is_valid_eth_private_key(private_key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(account_address) # 获取地址的 nonce - nonces[account_address] = current_nonce # 记录地址的 nonce - accounts.append((account_address.strip(), private_key.strip())) # 保存地址和私钥还有 nonce - else: - st.error("地址或私钥无效,请检查!") - st.stop() - - # 配置铭文文本 - token_protocol = st.text_input('填写需要题写代币铭文协议 **Protocol(p)**:', 'erc-20') - token_operation = st.text_input('填写需要题写代币铭文操作 **Operation(op)**:', 'mint') - token_ticker = st.text_input('填写需要题写代币铭文简称 **Ticker(tick)**:') - token_min_id = st.number_input('填写需要题写代币铭文范围的**最小 ID(id)**:', min_value=1, value=1, step=1) - token_max_id = st.number_input('填写需要题写代币铭文范围的**最大 ID(id)**:', value=21000, step=1) - token_amount = st.number_input('填写需要题写代币铭文数量 **Amount(amt)**:', min_value=1, value=1000, step=1) - st.markdown('###### 预览代币铭文:') - st.code( - f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{token_min_id}","amt":"{token_amount}"}}', - language="json", line_numbers=False) - # 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 - if not validate_input( - f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{token_min_id}","amt":"{token_amount}"}}'): - st.warning("**请注意**:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - - token_check = st.toggle('题写前**检查是否被题写** `主网` `查重`') - # 题写铭文之前检查该铭文有没有被题写 - if token_check: - token_check = True - else: - token_check = False - sleep_3s = st.toggle('每次完成交易后暂停 3 秒') - # 每次交易成功后暂停 3 秒 - if sleep_3s: - sleep_3s = True - else: - sleep_3s = False - - # 点击发送交易开始 - if st.button(f'开始**发送交易**'): - if not accounts or not token_protocol or not token_operation or not token_ticker: # 检查是否留空 - st.error(f'请正确谨慎地填写内容,每一项都**不应留空**。') - st.stop() - else: - st.toast('看起来你输入的内容均无没有问题!', icon='🥳') - - st.toast(f'开始任务,需要题写的铭文总量为:{token_max_id - token_min_id + 1}', icon='😎') - - # 对代币铭文 id 进行循环 - for the_id in range(token_min_id, token_max_id + 1): - # 使用当前账户发送交易,获取当前账户的 nonce - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - input_data = f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{the_id}","amt":"{token_amount}"}}' - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if token_check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - st.toast(f'{input_data} 已经被题写!', icon='☹️') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 3 秒 - if sleep_3s: - time.sleep(3) # 暂停三秒 - st.toast(f'所有任务已经完成。', icon='🎉') - # 庆祝动画 - st.balloons() - # 显示所有交易的结果 - st.code('\n'.join(transaction_results)) -else: - st.error('# 阅读并打勾 ✅ 后方可使用。') diff --git a/data/push_messages.db b/data/push_messages.db deleted file mode 100644 index 3ff6f15981c8a7808637c065ecf11641c25e2bcb..0000000000000000000000000000000000000000 Binary files a/data/push_messages.db and /dev/null differ diff --git a/data/python_name_code.py b/data/python_name_code.py deleted file mode 100644 index a28b10ae0f757a44d38aa63241a115ed28f8060a..0000000000000000000000000000000000000000 --- a/data/python_name_code.py +++ /dev/null @@ -1,201 +0,0 @@ -# EthPen.com -# 最后更新日期:2023 年 8 月 18 日 - -# 在开始使用前,请仔细阅读相关说明。感谢您的理解与配合。 -# 我们已将网站代码完全开源。您可以访问并仔细阅读此页面的源码:[2_🆔_批量题写域名铭文.py](https://huggingface.co/spaces/Ethscriptions/eths/tree/main/pages) -# 如果你对此代码存有疑虑,建议你利用如 [OpenAI - ChetGPT](https://chat.openai.com/)、[Google - Bard](https://bard.google.com/)、[Anthropic - Claude](https://claude.ai/)、[抖音 - 豆包](https://www.doubao.com/)、[百度 - 文心一言](https://yiyan.baidu.com/)、[阿里 - 通义千问](https://qianwen.aliyun.com/) 等知名 AI 平台进行问询,这可以帮助你判断代码是否含有恶意内容。 -# 复制我们的代码,你同样可以在 [HuggingFace](https://HuggingFace.co) 上搭建专属于你的域名铭文批量题写工具。 -# 请务必确保你正在访问的是 [EthPen.com](https://ethpen.com) 网站。我们保证站内代码不包含窃取私钥或其他恶意行为,你可以安心使用。 -# 在使用过程中,请按照提示准确地填写信息,这样可以确保程序的顺畅运行。 -# 为了安全起见,我们建议您使用备用账号(小号)并确保账号中不存放大额资金。 -# 首次使用时,我们建议您先在测试网络中操作。确认一切无误后,再切换至主网络使用。 -# 若您在使用过程中遇到问题,请及时向我们反馈。我们明白程序可能存在不完善之处,并且我们的能力也有限。真心希望得到各位程序员大佬的指导和交流。 - -# 导入运行代码所需要的库 -from web3 import Web3 # 与以太坊交互的库,安装的命令是 pip install web3 -import hashlib # 用于数据哈希,安装的命令是 pip install hashlib -import requests # 用于发送网络请求,安装的命令是 pip install requests -import re # 用于正则表达式 -import time # 用于时间相关 - -# ---------- 以下是基础配置 ---------- - -# 填写你的多个 ETH 地址及私钥,建议填写新建的钱包,用英文逗号分隔(,),如下:地址,私钥。 -accounts_str = ''' -账户1,私钥1 -账户2,私钥2 -账户3,私钥3 -''' - -# 需要题写的铭文内容,在三个单引号内输入多个域名铭文,可以用空格、换行符、英文逗号(,)分开,不要带 data:, 开头 -# 不要带 data:, 开头 -# 不要带 data:, 开头 -ethscription = ''' -123 -abcedfg -xyz 987 -哈哈哈 你好 -👋 😊 -ethpen.com -''' -# 你希望添加的后缀 -suffix = '.eths' -# 以空格、换行符、英文逗号分隔文本,并加上后缀 -ethscription_list = [item.strip() + suffix for item in re.split(r'[\s,]+', ethscription) if item] - -# 决定是否在题写铭文之前检查该铭文有没有被题写过,如果需要检查就填写 Ture 如果不需要就填 False -check = False - -# 每次交易成功后暂停 N 秒,0 为不暂停 -sleep_sec = 0 - -# 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API -w3 = Web3(Web3.HTTPProvider('https://sepolia.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206')) - -# 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 -chain_id = 11155111 - -# ---------- 以上是基础配置 ---------- - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已存在 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, # 账户的交易数 - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - print(f'{account_address} | {input_data} | Transaction Hash: {tx_hash.hex()}') - - -# 初始化当前账户索引为 0 -current_account_index = 0 -# 创建账户列表 -accounts = [] -# 使用字典来跟踪每个地址的nonce -nonces = {} - - -if accounts_str: # 如果账户列表有内容 - for line in accounts_str.strip().split('\n'): # 先去掉首尾的空白,然后根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - print(f"地址 {address} 或私钥 {key} 无效,请检查!") - exit() - else: - print(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - exit() - -# 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 -if not validate_input(ethscription): - print("请注意:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - -# 检查是否留空 -if not accounts or not ethscription: - print('请正确谨慎地填写内容,每一项都不应留空。') - exit() -else: - print('看起来你输入的内容均无没有问题!') - -# 认真检查铭文内容,如果发现错误,输入 1 结束 -for i in ethscription_list: - print(f'\033[44m{i}\033[m') -if input('请预览铭文,输入任意内容继续,输入 1 退出程序:') == '1': - exit() -print(f'开始任务,需要题写的铭文总量为:{len(ethscription_list)}') - -# 对代币铭文 id 进行循环 -for name_str in ethscription_list: - # 使用当前账户发送交易 - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - if not name_str.startswith('data:,'): - input_data = f'data:,{name_str}' - else: - input_data = name_str - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - print(f'{input_data} 已经被题写!') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 sleep_sec 秒 - time.sleep(sleep_sec) - -print(f'所有任务已经完成。') diff --git a/data/python_token_code.py b/data/python_token_code.py deleted file mode 100644 index 2e26830573974d27bf3ca761107dab8fb84181ce..0000000000000000000000000000000000000000 --- a/data/python_token_code.py +++ /dev/null @@ -1,189 +0,0 @@ -# EthPen.com -# 最后更新日期:2023 年 8 月 18 日 - -# 在开始使用前,请仔细阅读相关说明。感谢您的理解与配合。 -# 我们已将网站代码完全开源。您可以访问并仔细阅读此页面的源码:[3_🪙_ 批量题写代币铭文.py](https://huggingface.co/spaces/Ethscriptions/eths/tree/main/pages) -# 如果你对此代码存有疑虑,建议你利用如 [OpenAI - ChetGPT](https://chat.openai.com/)、[Google - Bard](https://bard.google.com/)、[Anthropic - Claude](https://claude.ai/)、[抖音 - 豆包](https://www.doubao.com/)、[百度 - 文心一言](https://yiyan.baidu.com/)、[阿里 - 通义千问](https://qianwen.aliyun.com/) 等知名 AI 平台进行问询,这可以帮助你判断代码是否含有恶意内容。 -# 复制我们的代码,你同样可以在 [HuggingFace](https://HuggingFace.co) 上搭建专属于你的域名铭文批量题写工具。 -# 请务必确保你正在访问的是 [EthPen.com](https://ethpen.com) 网站。我们保证站内代码不包含窃取私钥或其他恶意行为,你可以安心使用。 -# 在使用过程中,请按照提示准确地填写信息,这样可以确保程序的顺畅运行。 -# 为了安全起见,我们建议您使用备用账号(小号)并确保账号中不存放大额资金。 -# 首次使用时,我们建议您先在测试网络中操作。确认一切无误后,再切换至主网络使用。 -# 若您在使用过程中遇到问题,请及时向我们反馈。我们明白程序可能存在不完善之处,并且我们的能力也有限。真心希望得到各位程序员大佬的指导和交流。 - - -# 导入运行代码所需要的库 -from web3 import Web3 # 与以太坊交互的库,安装的命令是 pip install web3 -import hashlib # 用于数据哈希,安装的命令是 pip install hashlib -import requests # 用于发送网络请求,安装的命令是 pip install requests -import re # 用于正则表达式 -import time # 用于时间相关 - -# ---------- 以下是基础配置 ---------- - -# 填写你的多个 ETH 地址及私钥,建议填写新建的钱包,用英文逗号分隔(,),如下:地址,私钥。 -accounts_str = ''' -账户1,私钥1 -账户2,私钥2 -账户3,私钥3 -''' - -# 需要题写的代币铭文内容,变动的部分文本如 id 请用 "@#" 代替,例如:'data:,{"p":"erc-20","op":"mint","tick":"eths","id":"@#","amt":"1000"}' -ethscription = 'data:,{"p":"erc-20","op":"mint","tick":"eths","id":"@#","amt":"1000"}' - -# 设置代币铭文 id 的起始和结束范围 -min_id = 100 # 开始的整数 -max_id = 888 # 结束的整数 - -# 决定是否在题写铭文之前检查该铭文有没有被题写过,如果需要检查就填写 Ture 如果不需要就填 False -check = False - -# 每次交易成功后暂停 N 秒,0 为不暂停 -sleep_sec = 0 - -# 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API -w3 = Web3(Web3.HTTPProvider('https://sepolia.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206')) - -# 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 -chain_id = 11155111 - -# ---------- 以上是基础配置 ---------- - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(ord(char), '02x') for char in text) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, # 账户的交易数 - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - print(f'{account_address} | {input_data} | Transaction Hash: {tx_hash.hex()}') - - -# 初始化当前账户索引为 0 -current_account_index = 0 -# 创建账户列表 -accounts = [] -# 使用字典来跟踪每个地址的nonce -nonces = {} - - -if accounts_str: # 如果账户列表有内容 - for line in accounts_str.strip().split('\n'): # 先去掉首尾的空白,然后根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - print(f"地址 {address} 或私钥 {key} 无效,请检查!") - exit() - else: - print(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - exit() - -# 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 -if not validate_input(ethscription): - print("请注意:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - -# 检查是否留空 -if not accounts or not ethscription: - print('请正确谨慎地填写内容,每一项都不应留空。') - exit() -else: - print('看起来你输入的内容均无没有问题!') - -# 认真检查铭文内容,如果发现错误,输入 1 结束 -print(f'铭文文本:\033[44m{ethscription}\033[m,题写 id 范围为:{min_id} - {max_id}。') -if input('请预览铭文,输入任意内容继续,输入 1 退出程序:') == '1': - exit() -print(f'开始任务,需要题写的铭文总量为:{max_id - min_id + 1}') - -# 对代币铭文 id 进行循环 -for the_id in range(min_id, max_id + 1): - # 使用当前账户发送交易 - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - input_data = ethscription.replace('@#', str(the_id)) - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - print(f'{input_data} 已经被题写!') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 sleep_sec 秒 - time.sleep(sleep_sec) - -print(f'所有任务已经完成。') diff --git a/data/single_contract_abi.json b/data/single_contract_abi.json deleted file mode 100644 index f34b006741ae90f3b741ccf681fa83949d561aaa..0000000000000000000000000000000000000000 --- a/data/single_contract_abi.json +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[],"name":"CurrencyInvalid","type":"error"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[],"name":"EmptyOrderCancelList","type":"error"},{"inputs":[],"name":"EthscriptionInvalid","type":"error"},{"inputs":[],"name":"ExpiredSignature","type":"error"},{"inputs":[],"name":"InsufficientConfirmations","type":"error"},{"inputs":[],"name":"MsgValueInvalid","type":"error"},{"inputs":[],"name":"NoncesInvalid","type":"error"},{"inputs":[],"name":"OrderExpired","type":"error"},{"inputs":[],"name":"OrderNonceTooLow","type":"error"},{"inputs":[],"name":"SignatureInvalid","type":"error"},{"inputs":[],"name":"SignerInvalid","type":"error"},{"inputs":[],"name":"TrustedSignatureInvalid","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"newMinNonce","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"CancelAllOrders","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"orderNonces","type":"uint256[]"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"CancelMultipleOrders","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"EthscriptionDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"orderNonce","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"quantity","type":"uint256"},{"indexed":false,"internalType":"address","name":"seller","type":"address"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"endTime","type":"uint64"}],"name":"EthscriptionOrderExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"EthscriptionWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint96","name":"creatorFeeBps","type":"uint96"}],"name":"NewCreatorFeeBps","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"currencyManager","type":"address"}],"name":"NewCurrencyManager","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint96","name":"protocolFeeBps","type":"uint96"}],"name":"NewProtocolFeeBps","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"protocolFeeRecipient","type":"address"}],"name":"NewProtocolFeeRecipient","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"trustedVerifier","type":"address"}],"name":"NewTrustedVerifier","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"ethscriptions_protocol_TransferEthscriptionForPreviousOwner","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"cancelAllOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"orderNonces","type":"uint256[]"}],"name":"cancelMultipleMakerOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"creatorFeeBps","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currencyManager","outputs":[{"internalType":"contract ICurrencyManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint64","name":"startTime","type":"uint64"},{"internalType":"uint64","name":"endTime","type":"uint64"},{"internalType":"uint16","name":"protocolFeeDiscounted","type":"uint16"},{"internalType":"uint16","name":"creatorFee","type":"uint16"},{"internalType":"bytes","name":"params","type":"bytes"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct OrderTypes.EthscriptionOrder","name":"order","type":"tuple"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"executeEthscriptionOrder","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"orderNonce","type":"uint256"}],"name":"isUserOrderNonceExecutedOrCancelled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFeeBps","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_protocolFeeBps","type":"uint16"}],"name":"updateProtocolFeeBps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_trustedVerifier","type":"address"}],"name":"updateTrustedVerifier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userMinOrderNonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"bytes","name":"trustedSign","type":"bytes"}],"name":"withdrawEthscription","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawUnexpectedERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}] \ No newline at end of file diff --git a/data/single_contract_old_abi.json b/data/single_contract_old_abi.json deleted file mode 100644 index abd36cf7c8b08c798bce30047543b3f8e03c60a1..0000000000000000000000000000000000000000 --- a/data/single_contract_old_abi.json +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[],"name":"CurrencyInvalid","type":"error"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[],"name":"EmptyOrderCancelList","type":"error"},{"inputs":[],"name":"EthscriptionInvalid","type":"error"},{"inputs":[],"name":"ExpiredSignature","type":"error"},{"inputs":[],"name":"InsufficientConfirmations","type":"error"},{"inputs":[],"name":"MsgValueInvalid","type":"error"},{"inputs":[],"name":"NoncesInvalid","type":"error"},{"inputs":[],"name":"OrderExpired","type":"error"},{"inputs":[],"name":"OrderNonceTooLow","type":"error"},{"inputs":[],"name":"SignatureInvalid","type":"error"},{"inputs":[],"name":"SignerInvalid","type":"error"},{"inputs":[],"name":"TrustedSignatureInvalid","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"newMinNonce","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"CancelAllOrders","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"orderNonces","type":"uint256[]"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"CancelMultipleOrders","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"EthscriptionDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"orderNonce","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"quantity","type":"uint256"},{"indexed":false,"internalType":"address","name":"seller","type":"address"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"endTime","type":"uint64"}],"name":"EthscriptionOrderExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"indexed":false,"internalType":"uint64","name":"timestamp","type":"uint64"}],"name":"EthscriptionWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint96","name":"creatorFeeBps","type":"uint96"}],"name":"NewCreatorFeeBps","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"currencyManager","type":"address"}],"name":"NewCurrencyManager","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint96","name":"protocolFeeBps","type":"uint96"}],"name":"NewProtocolFeeBps","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"protocolFeeRecipient","type":"address"}],"name":"NewProtocolFeeRecipient","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"trustedVerifier","type":"address"}],"name":"NewTrustedVerifier","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"ethscriptions_protocol_TransferEthscriptionForPreviousOwner","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"cancelAllOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"orderNonces","type":"uint256[]"}],"name":"cancelMultipleMakerOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"creatorFeeBps","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currencyManager","outputs":[{"internalType":"contract ICurrencyManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint64","name":"startTime","type":"uint64"},{"internalType":"uint64","name":"endTime","type":"uint64"},{"internalType":"uint16","name":"protocolFeeDiscounted","type":"uint16"},{"internalType":"uint16","name":"creatorFee","type":"uint16"},{"internalType":"bytes","name":"params","type":"bytes"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct OrderTypes.EthscriptionOrder","name":"order","type":"tuple"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"executeEthscriptionOrder","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"orderNonce","type":"uint256"}],"name":"isUserOrderNonceExecutedOrCancelled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFeeBps","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_protocolFeeBps","type":"uint16"}],"name":"updateProtocolFeeBps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_trustedVerifier","type":"address"}],"name":"updateTrustedVerifier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userMinOrderNonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"ethscriptionId","type":"bytes32"},{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"bytes","name":"trustedSign","type":"bytes"}],"name":"withdrawEthscription","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawUnexpectedERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}] \ No newline at end of file diff --git a/img/.DS_Store b/img/.DS_Store deleted file mode 100644 index d1df972a0fc6b027729304bed872dd1c5a4b9a42..0000000000000000000000000000000000000000 Binary files a/img/.DS_Store and /dev/null differ diff --git a/img/0x.svg b/img/0x.svg deleted file mode 100644 index cc6de72e827a1db848d0e1bb6005cac458d6b927..0000000000000000000000000000000000000000 --- a/img/0x.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/img/Middlemarch.jpg b/img/Middlemarch.jpg deleted file mode 100644 index 82b9efb46bfc29e52e9ed6fc8a66733242db38b1..0000000000000000000000000000000000000000 Binary files a/img/Middlemarch.jpg and /dev/null differ diff --git a/img/ad.jpg b/img/ad.jpg deleted file mode 100644 index cbc998ca76cb1bb0480205fb65aa278833241a1f..0000000000000000000000000000000000000000 Binary files a/img/ad.jpg and /dev/null differ diff --git a/img/ad.png b/img/ad.png deleted file mode 100644 index ed47754a998c9b6c798eb93e8e4629fdb25dd58e..0000000000000000000000000000000000000000 Binary files a/img/ad.png and /dev/null differ diff --git a/img/address.svg b/img/address.svg deleted file mode 100644 index d5aa96703dbf6716911e7515b6a222a84f85263c..0000000000000000000000000000000000000000 --- a/img/address.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/img/alipay_qrcode.png b/img/alipay_qrcode.png deleted file mode 100644 index 24cb7ec8603b0fe048e3c030d01f33e8bd381089..0000000000000000000000000000000000000000 Binary files a/img/alipay_qrcode.png and /dev/null differ diff --git a/img/discord.svg b/img/discord.svg deleted file mode 100644 index 10dd82ac5a1770ff42d6074213853fff2acdcc58..0000000000000000000000000000000000000000 --- a/img/discord.svg +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/img/etch-market.png b/img/etch-market.png deleted file mode 100644 index 359bf10f510c85191507497d7d8646f8d02886f5..0000000000000000000000000000000000000000 Binary files a/img/etch-market.png and /dev/null differ diff --git a/img/etherscan-logo.svg b/img/etherscan-logo.svg deleted file mode 100644 index 3828303a94ac52be86e79af0936a5ce5583d59e5..0000000000000000000000000000000000000000 --- a/img/etherscan-logo.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - diff --git a/img/etherscan_input_data.png b/img/etherscan_input_data.png deleted file mode 100644 index 5125edfa77560d71ab618eccdee5e6489e407898..0000000000000000000000000000000000000000 Binary files a/img/etherscan_input_data.png and /dev/null differ diff --git a/img/ethpen_logo.svg b/img/ethpen_logo.svg deleted file mode 100644 index 75cd711ce91c4126aa0243c0a29cfcf556041745..0000000000000000000000000000000000000000 --- a/img/ethpen_logo.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - Layer 1 - - - - - - - - - - \ No newline at end of file diff --git a/img/eths_logo.jpeg b/img/eths_logo.jpeg deleted file mode 100644 index 367a1f859072949d79babf6b928e6c549e07247b..0000000000000000000000000000000000000000 Binary files a/img/eths_logo.jpeg and /dev/null differ diff --git a/img/eths_logo.jpg b/img/eths_logo.jpg deleted file mode 100644 index e8083d4a1a7aca9b675697d04f2a8c0c99cf3374..0000000000000000000000000000000000000000 Binary files a/img/eths_logo.jpg and /dev/null differ diff --git a/img/eths_logo.png b/img/eths_logo.png deleted file mode 100644 index ad62c98c2d365521e53670379fed060ddcde6b06..0000000000000000000000000000000000000000 Binary files a/img/eths_logo.png and /dev/null differ diff --git a/img/ethscriptions_logo_litto.png b/img/ethscriptions_logo_litto.png deleted file mode 100644 index ad266548ee3f92f4a8d3d3071c0f71c666f21f1c..0000000000000000000000000000000000000000 Binary files a/img/ethscriptions_logo_litto.png and /dev/null differ diff --git a/img/greater-than.svg b/img/greater-than.svg deleted file mode 100644 index 0afe93932be2b8d0f79c7b4889c575191524f1fb..0000000000000000000000000000000000000000 --- a/img/greater-than.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/img/huggingface_logo.svg b/img/huggingface_logo.svg deleted file mode 100644 index ef36d62b6ce1384f92d9d5476ff140aa4a21806e..0000000000000000000000000000000000000000 --- a/img/huggingface_logo.svg +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/img/input_data.png b/img/input_data.png deleted file mode 100644 index 784786ded235597cca5929d8a334596acf9f15c1..0000000000000000000000000000000000000000 Binary files a/img/input_data.png and /dev/null differ diff --git a/img/matamask-more.svg b/img/matamask-more.svg deleted file mode 100644 index b5437e8b499f43b9cf55aeafa5b06327eaaffd69..0000000000000000000000000000000000000000 --- a/img/matamask-more.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/img/metamask-gear.svg b/img/metamask-gear.svg deleted file mode 100644 index 253afa1acb5730a2c3b5fe83f82cc27f6af183e7..0000000000000000000000000000000000000000 --- a/img/metamask-gear.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/img/metamask-line.svg b/img/metamask-line.svg deleted file mode 100644 index c0b90dfbfb46c8a0c1fdf09b1e50c5096c9007f8..0000000000000000000000000000000000000000 --- a/img/metamask-line.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/img/metamask.svg b/img/metamask.svg deleted file mode 100644 index 2c7363d33cc7d144af7bcee84c358b7a0196be07..0000000000000000000000000000000000000000 --- a/img/metamask.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/img/news.jpeg b/img/news.jpeg deleted file mode 100644 index c1a14abaafb6b1490f6919015b87d91042f81278..0000000000000000000000000000000000000000 Binary files a/img/news.jpeg and /dev/null differ diff --git a/img/pushover_logo.jpg b/img/pushover_logo.jpg deleted file mode 100644 index ebe1499b38568ae8350ec9b7da35621726f57e14..0000000000000000000000000000000000000000 Binary files a/img/pushover_logo.jpg and /dev/null differ diff --git a/img/send.svg b/img/send.svg deleted file mode 100644 index 1b6bd0f25d115b25c7d7a985a5e2c5944e2d1ed9..0000000000000000000000000000000000000000 --- a/img/send.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/img/telegram.svg b/img/telegram.svg deleted file mode 100644 index 25c45e4cdec55c58698511ccbdf86d6e425af80e..0000000000000000000000000000000000000000 --- a/img/telegram.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/img/x.svg b/img/x.svg deleted file mode 100644 index c1f4737b5040594932478dd339119dc1a580772e..0000000000000000000000000000000000000000 --- a/img/x.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/logo/.DS_Store b/logo/.DS_Store deleted file mode 100644 index bc555451c6fffbdb2761ac7a01609dde7101e20e..0000000000000000000000000000000000000000 Binary files a/logo/.DS_Store and /dev/null differ diff --git a/logo/favicon.png b/logo/favicon.png deleted file mode 100644 index 23173db92e980ffd1c0a94e8546f9e8397c3f4f3..0000000000000000000000000000000000000000 Binary files a/logo/favicon.png and /dev/null differ diff --git a/logo/icon-512.png b/logo/icon-512.png deleted file mode 100644 index b7ff407e5ce110e665f13739e44447ddead52774..0000000000000000000000000000000000000000 Binary files a/logo/icon-512.png and /dev/null differ diff --git a/logo/icon-57.png b/logo/icon-57.png deleted file mode 100644 index c903ec652fbc95aaa681272280a3dbb3b668fb40..0000000000000000000000000000000000000000 Binary files a/logo/icon-57.png and /dev/null differ diff --git a/logo/icon-60.png b/logo/icon-60.png deleted file mode 100644 index 9dc076a6eb6331ee6d8d27eaa6a8d0bc49340653..0000000000000000000000000000000000000000 Binary files a/logo/icon-60.png and /dev/null differ diff --git a/logo/icon-60@3x.png b/logo/icon-60@3x.png deleted file mode 100644 index b79b07af4f326bd3a1f3508636a68b5b2d4e10da..0000000000000000000000000000000000000000 Binary files a/logo/icon-60@3x.png and /dev/null differ diff --git a/logo/icon-hdpi.png b/logo/icon-hdpi.png deleted file mode 100644 index c7cdad15bcb21d29fd04dbb16d1304addae26854..0000000000000000000000000000000000000000 Binary files a/logo/icon-hdpi.png and /dev/null differ diff --git a/logo/icon-ldpi.png b/logo/icon-ldpi.png deleted file mode 100644 index 3901a6fc2e384376745ed52096d4bd35a63cdd95..0000000000000000000000000000000000000000 Binary files a/logo/icon-ldpi.png and /dev/null differ diff --git a/logo/icon-mdpi.png b/logo/icon-mdpi.png deleted file mode 100644 index 8d6df768780820cd5cb580831770d85f4592fd76..0000000000000000000000000000000000000000 Binary files a/logo/icon-mdpi.png and /dev/null differ diff --git a/logo/icon-xhdpi.png b/logo/icon-xhdpi.png deleted file mode 100644 index 92c129e54bdc9784930105bebe5d80a108ffe0fe..0000000000000000000000000000000000000000 Binary files a/logo/icon-xhdpi.png and /dev/null differ diff --git a/logo/icon-xxhdpi.png b/logo/icon-xxhdpi.png deleted file mode 100644 index bb550aaba14d80a27ea2d5103e42ffb5916faba9..0000000000000000000000000000000000000000 Binary files a/logo/icon-xxhdpi.png and /dev/null differ diff --git a/logo/splash-1125x2436.png b/logo/splash-1125x2436.png deleted file mode 100644 index de93aa20e9f2698552981c635bdbb5ad1eeb59a1..0000000000000000000000000000000000000000 Binary files a/logo/splash-1125x2436.png and /dev/null differ diff --git a/logo/splash-1242x2208.png b/logo/splash-1242x2208.png deleted file mode 100644 index 058307b6ee55d2689c3dda2a20951be46d3f184f..0000000000000000000000000000000000000000 Binary files a/logo/splash-1242x2208.png and /dev/null differ diff --git a/logo/splash-640x1136.png b/logo/splash-640x1136.png deleted file mode 100644 index b4d98e4752ff673513c6001355c2ba1c6a3b9dec..0000000000000000000000000000000000000000 Binary files a/logo/splash-640x1136.png and /dev/null differ diff --git a/pages/.DS_Store b/pages/.DS_Store deleted file mode 100644 index fbd3a00df0c9429bdace2aec89a252a18d61251a..0000000000000000000000000000000000000000 Binary files a/pages/.DS_Store and /dev/null differ diff --git "a/pages/1_\360\237\224\215_\346\211\271\351\207\217\346\237\245\350\257\242\351\223\255\346\226\207\347\212\266\346\200\201.py" "b/pages/1_\360\237\224\215_\346\211\271\351\207\217\346\237\245\350\257\242\351\223\255\346\226\207\347\212\266\346\200\201.py" deleted file mode 100644 index b34d4e7d933d8c3148a7094397e4335419c79065..0000000000000000000000000000000000000000 --- "a/pages/1_\360\237\224\215_\346\211\271\351\207\217\346\237\245\350\257\242\351\223\255\346\226\207\347\212\266\346\200\201.py" +++ /dev/null @@ -1,408 +0,0 @@ -import base64 -import hashlib -import json -import requests -import streamlit as st -import re -import os -import sqlite3 -import pandas as pd -from concurrent.futures import ThreadPoolExecutor - - - -# 获取当前文件目录 -current_dir = os.path.dirname(__file__) -parent_dir = os.path.dirname(current_dir) -name_set_file = os.path.join(parent_dir, 'data', 'name_set.db') -name_set_conn = sqlite3.connect(name_set_file) -name_set_cursor = name_set_conn.cursor() - -content_set = '' -check_type = '' - -name_not_yet_total = 0 - -etherscan_api_key = os.environ.get('etherscan_api_key', '') - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return '0x' + ''.join(format(byte, '02x') for byte in text.encode('utf-8')) - - -# str SHA256 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 SHA256 值检查内容是否已被 ethscribed -def check_content_exists(sha): - endpoint = f"/ethscriptions/exists/{sha}" - try: - response = requests.get("https://mainnet-api.ethscriptions.com/api" + endpoint, timeout=5) - response.raise_for_status() # 如果响应状态码不是200,这会引发HTTPError - return response.json()['result'] - except requests.RequestException: # 捕获所有与requests相关的异常 - return "未知" - - -# 处理数据 -def orginize_data(index): - global name_not_yet_total - sha_value = sha256(names[index]) - response_data = check_content_exists(sha_value) - if hide_inscribed: - if not response_data: - result.append({"铭文": names[index], "状态": '未题写', "十六进制数据": all_items[index][2:]}) - name_not_yet_total += 1 - if response_data == '未知': - result.append({"铭文": names[index], "状态": '未知', "十六进制数据": all_items[index][2:]}) - name_not_yet_total += 1 - else: - if response_data: - result.append({"铭文": names[index], "状态": '已题写', "十六进制数据": all_items[index][2:]}) - elif response_data == '未知': - result.append({"铭文": names[index], "状态": '未知', "十六进制数据": all_items[index][2:]}) - name_not_yet_total += 1 - else: - result.append({"铭文": names[index], "状态": '未题写', "十六进制数据": all_items[index][2:]}) - name_not_yet_total += 1 - - -# 确定索引器是否落后 -def get_block_status(): - endpoint = "/block_status" - response = requests.get("https://mainnet-api.ethscriptions.com/api" + endpoint) - - try: - data = response.json() - return data.get('blocks_behind', None) - except json.JSONDecodeError: - print("Failed to decode JSON. Response content:") - print(response.text) - return None - - -# 获取题写铭文的矿工费 -def estimate_transaction_fee(text_length: int, speed: str = 'Propose') -> float: - """ - Estimate the transaction fee for an Ethereum transaction based on text length using Etherscan API. - - :param api_key: Etherscan API key. - :param text_length: Length of the input text. - :param speed: Desired confirmation speed. Can be 'Safe', 'Propose', or 'Fast'. - :param request_timeout: Timeout for the HTTP request in seconds. - :return: Estimated transaction fee in ETH or None in case of errors. - """ - try: - # Get current gas prices from Etherscan - base_url = "https://api.etherscan.io/api" - params = { - "module": "gastracker", - "action": "gasoracle", - "apikey": etherscan_api_key - } - response = requests.get(base_url, params=params, timeout=5) - response.raise_for_status() - - data = response.json() - if data['status'] != '1': - return None - - if speed not in ['Safe', 'Propose', 'Fast']: - return None - - selected_gas_price = int(data['result'][f"{speed}GasPrice"]) - - # Calculate gas for the input text - NON_ZERO_BYTE_GAS = 68 - ZERO_BYTE_GAS = 4 - - # Assuming every character is 1 byte (for simplification) - # In reality, certain UTF-8 characters may be more than 1 byte - data_gas = text_length * NON_ZERO_BYTE_GAS - - # Calculate total gas and fee - BASE_GAS = 21000 - total_gas = BASE_GAS + data_gas - total_fee_eth = total_gas * selected_gas_price * 1e-9 - - return total_fee_eth - - except (requests.Timeout, requests.RequestException): - return None - - -# 查询 ETH token 价格 -def get_eth_price(): - try: - # 使用Etherscan的API endpoint获取以太坊的价格 - url = f"https://api.etherscan.io/api?module=stats&action=ethprice&apikey=1I2ERGUVJZNJAFKY7MG4S317DUGRPXEQPF" - response = requests.get(url) - response.raise_for_status() # 将引发HTTPError,如果HTTP请求返回了不成功的状态码 - - data = response.json() - - if data["message"] == "OK": - eth_price = float(data["result"]["ethusd"]) - return eth_price - else: - print("Error fetching the ETH price") - return None - except requests.RequestException as e: - print(f"Error while accessing the API: {e}") - return None - - -st.set_page_config(page_title="EthPen - 批量查询铭文状态", page_icon="🔍", layout='centered', initial_sidebar_state='auto') -st.markdown(f'# Image :rainbow[批量查询铭文状态]', unsafe_allow_html=True) -st.subheader(r' ', anchor=False, divider='rainbow') - -st.write("", unsafe_allow_html=True) -st.markdown(f'### 💖 查找你心仪的铭文') -name_selected_option = st.radio("选择查询的类型:", - ['🔤纯文本', '🪙代币铭文', '🆔.eths', '🆔.eth', '🌲.tree', '🦛.honk', '🔄.etch', '🌐.com', '🥳.club'], index=0, - horizontal=True) - -if name_selected_option == '🔤纯文本': - check_type = '' -if name_selected_option == '🪙代币铭文': - token_check = True - token_str = st.text_input('填写代币铭文文本(变动的部分文本如 id 请用 "@#" 代替):', 'data:,{"p":"erc-20","op":"mint","tick":"eths","id":"@#","amt":"1000"}') - col1, col2 = st.columns(2) - with col1: - token_min_id = st.number_input('填写最小 ID:', min_value=1, value=1, step=1) - with col2: - token_max_id = st.number_input('填写最大 ID:', min_value=2, value=21000, step=1) - token_str_list = [] - if token_str != '' and '@#' in token_str: - for token_id in range(token_min_id, token_max_id + 1): - token_str_list.append(token_str.replace('@#', str(token_id))) - content_set = '\n'.join(token_str_list) - st.code(token_str_list[0], language="json", line_numbers=False) - content = st.text_area('铭文列表:', value=content_set) -else: - token_check = False -if name_selected_option == '🆔.eths': - check_type = '.eths' -if name_selected_option == '🆔.eth': - check_type = '.eth' -if name_selected_option == '🌲.tree': - check_type = '.tree' -if name_selected_option == '🦛.honk': - check_type = '.honk' -if name_selected_option == '🔄.etch': - check_type = '.etch' -if name_selected_option == '🌐.com': - check_type = '.com' -if name_selected_option == '🥳.club': - check_type = '.club' - -if not token_check: - # 执行SQL查询,获取所有表名 - name_set_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") - # 检索查询结果 - tables = name_set_cursor.fetchall() - name_srt_tables_options = [] - name_srt_tables_options.append('⌨️ 直接输入') - for table in tables: - name_srt_tables_options.append(table[0]) - name_srt_tables_options.append('📃 导入文件') - name_set_table = st.radio("选择系列:", name_srt_tables_options, index=0, disabled=token_check, horizontal=True) - if name_set_table and name_set_table != '⌨️ 直接输入' and name_set_table != '📃 导入文件': - name_set_tables_name_options = [] - # 执行SQL查询,获取指定表的所有 'name' 列的值 - name_set_cursor.execute(f"SELECT name FROM {name_set_table}") - # 检索查询结果 - names = name_set_cursor.fetchall() - # 打印所有 'name' 列的值 - for name in names: - name_set_tables_name_options.append(name[0]) - name_set_tables_name_options.sort() - name_set_table_name = st.radio("系列", name_set_tables_name_options, index=0, disabled=token_check, horizontal=True, - label_visibility="collapsed") - if name_set_table_name: - # 执行SQL查询,获取指定表的 'name' 和 'data' 列的值 - name_set_cursor.execute(f"SELECT data FROM {name_set_table} WHERE name='{name_set_table_name}'") - # 检索查询结果 - all_data = name_set_cursor.fetchall() - content_set = f'{all_data[0][0]}' - if name_set_table == "⌨️ 直接输入": - content_set = '' - if name_set_table == "📃 导入文件": - uploaded_file = st.file_uploader("上传文件", type=['txt', 'csv', 'xlsx']) - if uploaded_file is not None: - if uploaded_file.type not in ['text/plain', 'text/csv', 'application/vnd.ms-excel']: - st.error('文件类型不支持') - else: - # 读取上传的文件内容 - uploaded_file_contents = uploaded_file.read().decode('utf-8') - - # 将文件内容分割成列表,使用空格、换行符和逗号作为分隔符 - separators = [' ', '\n', ','] - uploaded_file_contents_list = re.split('|'.join(map(re.escape, separators)), uploaded_file_contents) - - # 在这里,file_contents_list 包含了分割后的文本元素 - # 去除重复元素,将列表转换为集合,然后再转回列表 - uploaded_unique_contents_list = list(set(uploaded_file_contents_list)) - content_set = ' '.join(uploaded_unique_contents_list) - -if not token_check: - custom_suffix = st.toggle('自定义前后缀') - if custom_suffix: - col1, col2 = st.columns(2) - with col1: - custom_prefix = st.text_input("自定义前缀") - with col2: - if check_type == '': - suffix_check = False - else: - suffix_check = True - custom_suffix = st.text_input("自定义后缀", disabled=suffix_check) - else: - custom_prefix, custom_suffix = '', '' - -if not token_check: - filter = st.toggle('过滤器') - if filter: - col1, col2, col3, col4, col5, col6 = st.columns(6) - with col1: - start_with = st.text_input("以*开头", key='过滤器(可选)1') - with col2: - end_with = st.text_input("以*结尾", key='过滤器(可选)2') - with col3: - contain = st.text_input("包含*", key='过滤器(可选)3') - with col4: - no_contain = st.text_input("不包含*", key='过滤器(可选)4') - with col5: - min_length = st.text_input("最少长度", key='过滤器(可选)5') - with col6: - max_length = st.text_input("最大长度", key='过滤器(可选)6') - - # 将过滤条件应用到原始 name_set 字符串列表 - filtered_list = content_set.split() # 使用空格、换行符和逗号分隔字符串,得到列表 - - if start_with: - filtered_list = [item for item in filtered_list if item.startswith(start_with)] - - if end_with: - filtered_list = [item for item in filtered_list if item.endswith(end_with)] - - if contain: - filtered_list = [item for item in filtered_list if contain in item] - - if no_contain: - filtered_list = [item for item in filtered_list if no_contain not in item] - - if min_length: - filtered_list = [item for item in filtered_list if len(item) >= int(min_length)] - - if max_length: - filtered_list = [item for item in filtered_list if len(item) <= int(max_length)] - - # 将处理后的列表重新合并成字符串 - content_set = ' '.join(filtered_list) - -if not token_check: - content = st.text_area('铭文列表:', value=content_set, key=1) - -hide_inscribed = st.toggle('隐藏已题写') - -enable_api = st.toggle('启用 Ethscriptions.com API (v1)') -if enable_api: - print(get_block_status()) - st.success(f"铭文数据来自 [Ethscriptions.com](https://ethscriptions.com/) 官方网站,当前索引器状态落后: {get_block_status()} 个区块。我们将以 100 个线程进行网络请求查询。尽管查询速度稍显缓慢,但所得数据确保了真实性与准确性。") -if st.button('🔎 查询', key='🔎 查询'): - st.markdown(f'### 📄 查询结果') - all_items = [] - names = [] - if token_check: - for i in token_str_list: - names.append(i) - all_items.append(text_to_hex(i)) - else: - if check_type == '': - names = re.split(r"\s+", content) - # names = list(set(names)) - names = [custom_prefix + name + custom_suffix for name in names] - names = ["data:," + name if not name.startswith("data:,") else name for name in names] - for i in names: - if names != 'data:,': - all_items.append(text_to_hex(i)) - else: - names = re.split(r"\s+", content) - # names = list(set(names)) - names = [custom_prefix + name + check_type for name in names] - names = ["data:," + name if not name.startswith("data:,") else name for name in names] - - for i in names: - if names != 'data:,': - all_items.append(text_to_hex(i)) - - ethscrptions_db_file = os.path.join(parent_dir, 'data', 'ethscriptions_data.db') - - ethscriptions_conn = sqlite3.connect(ethscrptions_db_file) - - ethscriptions_cursor = ethscriptions_conn.cursor() - names_total = len(names) - result = [] - if enable_api: - with ThreadPoolExecutor(max_workers=100) as executor: - for index in range(len(names)): - executor.submit(orginize_data, index) # Submit task to thread pool - else: - for index in range(len(names)): - ethscriptions_cursor.execute("SELECT * FROM data WHERE data=?", (all_items[index],)) - row = ethscriptions_cursor.fetchone() - if hide_inscribed: - if not row: - result.append({"铭文": names[index], "状态": "未题写", "十六进制数据": all_items[index][2:]}) - name_not_yet_total += 1 - else: - if row: - result.append({"铭文": names[index], "状态": "已题写", "十六进制数据": all_items[index][2:]}) - else: - result.append({"铭文": names[index], "状态": "未题写", "十六进制数据": all_items[index][2:]}) - name_not_yet_total += 1 - st.progress(1 - (name_not_yet_total / names_total), f'题写进度 {names_total - name_not_yet_total}/{names_total} ({(1 - (name_not_yet_total / names_total)) * 100:.0f}%):') - name_not_yet_total = 0 - - if result: - # 将结果转换为Pandas DataFrame - result_df = pd.DataFrame(result) - # print(result_df) - st.dataframe(result_df, use_container_width=True, hide_index=True) - # 使用列表解析获取所有"未题写"状态的"十六进制数据" - not_written_data = [item['十六进制数据'] for item in result if item['状态'] == '未题写'] - # 获取未题写数据的个数和总长度 - num_not_written = len(not_written_data) - total_length = sum(len(data) for data in not_written_data) - gas_spent = 0 if num_not_written == 0 else estimate_transaction_fee(total_length // num_not_written) - eth_price = get_eth_price() - st.success( - f'题写上面未题写的铭文平均每个最低花费 {gas_spent:.10f} ETH,约为 {gas_spent * eth_price:.2f}USD;题写全部未题写铭文最低需要花费 {gas_spent * num_not_written:.10f} ETH,约为 {gas_spent * num_not_written * eth_price:.2f}USD。') - # Convert DataFrame to CSV with proper encoding - csv_export = result_df.to_csv(index=False, encoding='utf-8') - # Add a download button for the DataFrame - st.download_button( - label="⏬ 下载查询结果", - data=csv_export, - file_name="ethpen_result_data.csv", - mime="text/csv" - ) - else: - st.markdown(f'### ☹️ 你来迟了~') - -# -# print(len(content_set)) -# gas_spent = 0 if len(content_set.split()) == 0 else estimate_transaction_fee(len(content_set) // len(content_set.split())) -# st.success(f'题写上面铭文平均每个最低花费 {gas_spent:.10f} ETH,约为 ${gas_spent * get_eth_price():.2f}。') \ No newline at end of file diff --git "a/pages/2_\360\237\206\224_ \346\211\271\351\207\217\351\242\230\345\206\231\345\237\237\345\220\215\351\223\255\346\226\207.py" "b/pages/2_\360\237\206\224_ \346\211\271\351\207\217\351\242\230\345\206\231\345\237\237\345\220\215\351\223\255\346\226\207.py" deleted file mode 100644 index a1e8bd33e1ddd2cf9448f72f85f40c4d5d9107ca..0000000000000000000000000000000000000000 --- "a/pages/2_\360\237\206\224_ \346\211\271\351\207\217\351\242\230\345\206\231\345\237\237\345\220\215\351\223\255\346\226\207.py" +++ /dev/null @@ -1,305 +0,0 @@ -# EthPen.com -# 最后更新日期:2023 年 9 月 5 日 - -# 导入运行代码所需要的库 -import streamlit as st # streamlit app -from web3 import Web3 # 与以太坊交互的库 -import hashlib # 用于数据哈希 -import requests # 用于发送网络请求 -import re # 用于正则表达式 -import time # 用于时间相关 -import os # 用于操作系统文件 -import base64 - - -# 许可使用开关 -approved_use = False - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 分隔文本函数 -def split_and_append(ethscriptions_str, name_selected_option): - separators = [' ', '\n', ','] - split_texts = [ethscriptions_str] # 初始时只有一个完整文本 - - for sep in separators: - pieces = [] - for text in split_texts: - pieces.extend(text.split(sep)) - split_texts = pieces - - # 移除空字符串 - split_texts = [text.strip() + name_selected_option for text in split_texts if text.strip() != ''] - - return split_texts - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(byte, '02x') for byte in text.encode('utf-8')) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - st.toast(f'{input_data}', icon='✅') - # 返回铭文还有交易哈希 - return input_data, tx_hash.hex() - - -# 网页前端显示 -st.set_page_config(page_title="EthPen - 批量题写域名铭文", page_icon="🆔", layout='centered', initial_sidebar_state='auto') - -# 网页标题 -st.markdown(f'# Image :rainbow[域名铭文批量题写]', unsafe_allow_html=True) -st.subheader(r'', anchor=False, divider='rainbow') - -# 提醒 -st.markdown('### 在开始使用前,请仔细阅读相关说明,并在确认无误后打上 ✅。感谢您的理解与配合。') - -open_source = st.checkbox('我们已将网站代码完全开源。您可以访问并仔细阅读此页面的源码:[2_🆔_批量题写域名铭文.py](https://huggingface.co/spaces/Ethscriptions/eths/tree/main/pages)',) - -ask_ai = st.checkbox('如果你对此代码存有疑虑,建议你利用如 [OpenAI - ChetGPT](https://chat.openai.com/)、[Google - Bard](https://bard.google.com/)、[Anthropic - Claude](https://claude.ai/)、[抖音 - 豆包](https://www.doubao.com/)、[百度 - 文心一言](https://yiyan.baidu.com/)、[阿里 - 通义千问](https://qianwen.aliyun.com/) 等知名 AI 平台进行问询,这可以帮助你判断代码是否含有恶意内容。',) - -huggingface = st.checkbox('复制我们的代码,你同样可以在 [HuggingFace](https://HuggingFace.co) 上搭建专属于你的域名铭文批量题写工具。',) - -site = st.checkbox('请务必确保你正在访问的是 **[EthPen.com](https://ethpen.com)** 网站。我们保证站内代码不包含窃取私钥或其他恶意行为,你可以安心使用。',) - -use = st.checkbox('在使用过程中,请按照提示准确地填写信息,这样可以确保程序的顺畅运行。',) - -wallet = st.checkbox('为了安全起见,我们建议您使用备用账号(小号)并确保账号中不存放大额资金。',) - -test = st.checkbox('首次使用时,我们建议您先在测试网络中操作。确认一切无误后,再切换至主网络使用。',) - -feedback = st.checkbox('若您在使用过程中遇到问题,请及时向我们反馈。我们明白程序可能存在不完善之处,并且我们的能力也有限。真心希望得到各位程序员大佬的指导和交流。',) - -# st.expander -huggingface_expander = st.expander("显示 HuggingFace 平台环境的代码", expanded=False) -python_expander = st.expander("显示 Python 本地环境的代码", expanded=False) - -current_dir = os.path.dirname(__file__) -parent_dir = os.path.dirname(current_dir) -python_file = os.path.join(parent_dir, 'data', 'python_name_code.py') -huggingface_file = os.path.join(parent_dir, 'data', 'huggingface_name_code.py') -with open(huggingface_file, "r", encoding="utf-8") as file: - huggingface_content = file.read() - huggingface_expander.markdown(f'Python 代码 `app.py`:') - huggingface_expander.code(huggingface_content, 'python', line_numbers=False) - huggingface_expander.markdown(f"依赖包清单 `requirements.txt`:") - huggingface_expander.code(f''' -Requests -streamlit -web3 -''') -with open(python_file, "r", encoding="utf-8") as file: - python_content = file.read() - python_expander.markdown(f'Python 代码:') - python_expander.code(python_content, 'python', line_numbers=False) - -if open_source and ask_ai and huggingface and site and use and wallet and test and feedback: - approved_use = True -else: - approved_use = False - -if approved_use: - - st.markdown('## 批量题写域名铭文') - - # 连接的网络 ID。比如说,1 代表主网络,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 - net_options = { - '1': 'Mainnet', - '5': 'Goerli', - '11155111': 'Sepolia' - } - selected_option = st.selectbox( - '**网络 ID**', - list(net_options.keys()), - format_func=lambda x: f"{x} ({net_options[x]})" - ) - chain_id = int(selected_option) - - # 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API - token_eth_prc_url = st.text_input( - f'**Ethereum PRC 链接**:选填,你可以去 [infura.io](https://app.infura.io/) 或者 [alchemy.com](https://alchemy.com/) 免费申请一个', - f'https://{net_options[str(chain_id)]}.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206') - w3 = Web3(Web3.HTTPProvider(f'{token_eth_prc_url}')) - # 初始化当前账户索引为 0 - current_account_index = 0 - # 收集和显示所有交易的结果 - transaction_results = [] - # 创建账户列表 - accounts = [] - # 使用字典来跟踪每个地址的nonce - nonces = {} - - # 启用多账户操作 - multipl_accounts = st.toggle('启用**多账户**操作') - if multipl_accounts: - # 多账户的文本框 - account_list = st.text_area(f'输入多个 **ETH 地址及其对应的私钥**,用英文逗号分隔(,),如下:地址,私钥') - if account_list: # 如果账户列表有内容 - for line in account_list.split('\n'): # 根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - st.error(f"地址 {address} 或私钥 {key} 无效,请检查!") - st.stop() - else: - st.error(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - st.stop() - else: - account_address = st.text_input('填写你的 **ETH 地址**:') - private_key = st.text_input('填写你的 **ETH 地址对应的私钥**:', type="password") - if account_address and private_key: # 如果地址和私钥有内容 - if is_valid_eth_address(account_address) and is_valid_eth_private_key(private_key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(account_address) # 获取地址的 nonce - nonces[account_address] = current_nonce # 记录地址的 nonce - accounts.append((account_address.strip(), private_key.strip())) # 保存地址和私钥还有 nonce - else: - st.error("地址或私钥无效,请检查!") - st.stop() - - # 配置铭文文本 - ethscriptions_str = st.text_area(f'输入**多个域名铭文或其他**,可以用`空格`、`换行符`、`英文逗号(,)`分开,不要带 `data:,` 前缀,不要带`域名后缀`:') - - name_selected_option = st.radio("选择域名后缀:", ['🎨 自定义', '🆔.eths', '🆔.eth', '🌲.tree', '🦛.honk', '🔄.etch', '🌐.com'], index=1, horizontal=True) - if name_selected_option == '🎨 自定义': - name_selected_option = st.text_input('输入**域名后缀**:') - - # 以空格、换行符、英文逗号分隔文本并加上后缀 - ethscription_list = split_and_append(ethscriptions_str, name_selected_option) - - # 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 - if not validate_input(''.join(ethscription_list)): - st.warning("**请注意**:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - - token_check = st.toggle('题写前**检查是否被题写** `主网` `查重`') - # 题写铭文之前检查该铭文有没有被题写 - if token_check: - token_check = True - else: - token_check = False - sleep_3s = st.toggle('每次完成交易后暂停 3 秒') - # 每次交易成功后暂停 3 秒 - if sleep_3s: - sleep_3s = True - else: - sleep_3s = False - - # 点击发送交易开始 - if st.button(f'开始**发送交易**'): - if not accounts or not ethscriptions_str or not name_selected_option: # 检查是否留空 - st.error(f'请正确谨慎地填写内容,每一项都**不应留空**。') - st.stop() - else: - st.toast('看起来你输入的内容均无没有问题!', icon='🥳') - - st.toast(f'开始任务,需要题写的铭文总量为:{len(ethscription_list)}', icon='😎') - - # 对代币铭文 id 进行循环 - for name_str in ethscription_list: - # 使用当前账户发送交易,获取当前账户的 nonce - address, key = accounts[current_account_index] - # 获取 gas - gas_price = w3.eth.gas_price - # 得到完整的铭文文本 - if not name_str.startswith('data:,'): - input_data = f'data:,{name_str}' - - # 根据是否检查的开关进行 - if token_check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - st.toast(f'{input_data} 已经被题写!', icon='☹️') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 3 秒 - if sleep_3s: - time.sleep(3) # 暂停三秒 - st.toast(f'所有任务已经完成。', icon='🎉') - # 庆祝动画 - st.balloons() - # 显示所有交易的结果 - st.code('\n'.join(transaction_results)) -else: - st.error('# 阅读并打勾 ✅ 后方可使用。') diff --git "a/pages/3_\360\237\252\231_ \346\211\271\351\207\217\351\242\230\345\206\231\344\273\243\345\270\201\351\223\255\346\226\207.py" "b/pages/3_\360\237\252\231_ \346\211\271\351\207\217\351\242\230\345\206\231\344\273\243\345\270\201\351\223\255\346\226\207.py" deleted file mode 100644 index faa17ddf600f368bb336e3384e35083d262db911..0000000000000000000000000000000000000000 --- "a/pages/3_\360\237\252\231_ \346\211\271\351\207\217\351\242\230\345\206\231\344\273\243\345\270\201\351\223\255\346\226\207.py" +++ /dev/null @@ -1,289 +0,0 @@ -# EthPen.com -# 最后更新日期:2023 年 9 月 5 日 - -# 导入运行代码所需要的库 -import streamlit as st # streamlit app -from web3 import Web3 # 与以太坊交互的库 -import hashlib # 用于数据哈希 -import requests # 用于发送网络请求 -import re # 用于正则表达式 -import time # 用于时间相关 -import os # 用于操作系统文件 -import base64 - - -# 许可使用开关 -approved_use = False - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 检查 ETH 地址是否有效 -def is_valid_eth_address(address): - if re.match("^0x[0-9a-fA-F]{40}$", address): - return True - return False - - -# 检查 Ethereum 私钥是否有效 -def is_valid_eth_private_key(private_key): - if re.match("^[0-9a-fA-F]{64}$", private_key): - return True - return False - - -# 验证输入的铭文文本是否含有空格和换行符,而且字母全部为小写 -def validate_input(data_str): - if re.search(r'[A-Z\s\n]', data_str): # 查找大写字母、空格或换行符 - return False - return True - - -# 把文字转换成 16 进制 -def text_to_hex(text): - return ''.join(format(byte, '02x') for byte in text.encode('utf-8')) - - -# 使用sha256算法计算哈希 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 使用 Ethscriptions API(主网)检查某个铭文是否已题写 -def check_content_exists(sha): - # 定义请求的网址 - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get('https://mainnet-api.ethscriptions.com/api' + endpoint) - # 如果返回状态码是200,说明请求成功,然后返回结果(Ture or False) - if response.status_code == 200: - return response.json()['result'] - - -# 发送自己到自己 0ETH 的交易 -def send_transaction(w3, account_address, private_key, chain_id, gas_price, input_data, current_nonce): - - # 设置交易的相关信息 - tx = { - 'chainId': chain_id, # 网络 ID - 'gas': 25000, # 如果交易 gas 过低,可适当调高 - 'gasPrice': gas_price, # gas 的价格 - 'nonce': current_nonce, - 'to': account_address, # 接收地址为自己 - 'value': 0, # 金额为 0ETH - 'data': text_to_hex(input_data), # 铭文内容 - } - - # 用私钥签名这个交易 - signed_tx = w3.eth.account.sign_transaction(tx, private_key) - # 发送签名后的交易并获取交易哈希 - tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) - # 打印结果信息 - st.toast(f'{input_data}', icon='✅') - # 返回铭文还有交易哈希 - return input_data, tx_hash.hex() - - -# 网页前端显示 -st.set_page_config(page_title="EthPen - 批量题写代币铭文", page_icon="🪙", layout='centered', initial_sidebar_state='auto') - -# 网页标题 -st.markdown(f'# Image :rainbow[代币铭文批量题写]', unsafe_allow_html=True) -st.subheader(r' ', anchor=False, divider='rainbow') - -# 提醒 -st.markdown('### 在开始使用前,请仔细阅读相关说明,并在确认无误后打上 ✅。感谢您的理解与配合。') - -open_source = st.checkbox('我们已将网站代码完全开源。您可以访问并仔细阅读此页面的源码:[3_🪙_ 批量题写代币铭文.py](https://huggingface.co/spaces/Ethscriptions/eths/tree/main/pages)',) - -ask_ai = st.checkbox('如果你对此代码存有疑虑,建议你利用如 [OpenAI - ChetGPT](https://chat.openai.com/)、[Google - Bard](https://bard.google.com/)、[Anthropic - Claude](https://claude.ai/)、[抖音 - 豆包](https://www.doubao.com/)、[百度 - 文心一言](https://yiyan.baidu.com/)、[阿里 - 通义千问](https://qianwen.aliyun.com/) 等知名 AI 平台进行问询,这可以帮助你判断代码是否含有恶意内容。',) - -huggingface = st.checkbox('复制我们的代码,你同样可以在 [HuggingFace](https://HuggingFace.co) 上搭建专属于你的域名铭文批量题写工具。',) - -site = st.checkbox('请务必确保你正在访问的是 **[EthPen.com](https://ethpen.com)** 网站。我们保证站内代码不包含窃取私钥或其他恶意行为,你可以安心使用。',) - -use = st.checkbox('在使用过程中,请按照提示准确地填写信息,这样可以确保程序的顺畅运行。',) - -wallet = st.checkbox('为了安全起见,我们建议您使用备用账号(小号)并确保账号中不存放大额资金。',) - -test = st.checkbox('首次使用时,我们建议您先在测试网络中操作。确认一切无误后,再切换至主网络使用。',) - -feedback = st.checkbox('若您在使用过程中遇到问题,请及时向我们反馈。我们明白程序可能存在不完善之处,并且我们的能力也有限。真心希望得到各位程序员大佬的指导和交流。',) - -# st.expander -huggingface_expander = st.expander("显示 HuggingFace 平台环境的代码", expanded=False) -python_expander = st.expander("显示 Python 本地环境的代码", expanded=False) - -current_dir = os.path.dirname(__file__) -parent_dir = os.path.dirname(current_dir) -python_file = os.path.join(parent_dir, 'data', 'python_token_code.py') -huggingface_file = os.path.join(parent_dir, 'data', 'huggingface_token_code.py') -with open(huggingface_file, "r", encoding="utf-8") as file: - huggingface_content = file.read() - huggingface_expander.markdown(f'Python 代码 `app.py`:') - huggingface_expander.code(huggingface_content, 'python', line_numbers=False) - huggingface_expander.markdown(f"依赖包清单 `requirements.txt`:") - huggingface_expander.code(f''' -Requests -streamlit -web3 -''') -with open(python_file, "r", encoding="utf-8") as file: - python_content = file.read() - python_expander.markdown(f'Python 代码:') - python_expander.code(python_content, 'python', line_numbers=False) - -if open_source and ask_ai and huggingface and site and use and wallet and test and feedback: - approved_use = True -else: - approved_use = False - -if approved_use: - - st.markdown('## 批量题写代币铭文') - - # 连接的网络 ID。比如说,1 代表 Mainnet,5 代表 Goerli 测试网络,11155111 代表 Sepolia 测试网络,如果你不放心,可以先用测试网试试。 - net_options = { - '1': 'Mainnet', - '5': 'Goerli', - '11155111': 'Sepolia' - } - selected_option = st.selectbox( - '**网络 ID**', - list(net_options.keys()), - format_func=lambda x: f"{x} ({net_options[x]})" - ) - chain_id = int(selected_option) - - # 这里配置 Ethereum PRC URL,如果你没有,请到 infura.io 或者 alchemy.com 申请一个免费的 API - token_eth_prc_url = st.text_input( - f'**Ethereum PRC 链接**:选填,你可以去 [infura.io](https://app.infura.io/) 或者 [alchemy.com](https://alchemy.com/) 免费申请一个', - f'https://{net_options[str(chain_id)]}.infura.io/v3/eab7f935b9af45e1a54f7d7ed06c5206') - w3 = Web3(Web3.HTTPProvider(f'{token_eth_prc_url}')) - - # 初始化当前账户索引为 0 - current_account_index = 0 - # 收集和显示所有交易的结果 - transaction_results = [] - # 创建账户列表 - accounts = [] - # 使用字典来跟踪每个地址的nonce - nonces = {} - - # 启用多账户操作 - multipl_accounts = st.toggle('启用**多账户**操作') - if multipl_accounts: - # 多账户的文本框 - account_list = st.text_area(f'输入多个 **ETH 地址及其对应的私钥**,用英文逗号分隔(,),如下:地址,私钥') - if account_list: # 如果账户列表有内容 - for line in account_list.split('\n'): # 根据换行符划分账户 - if ',' in line: # 检查是否包含逗号 - address, key = line.split(',') # 分开地址和私钥 - if is_valid_eth_address(address) and is_valid_eth_private_key(key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(address) # 获取地址的 nonce - nonces[address] = current_nonce # 记录地址的 nonce - accounts.append((address.strip(), key.strip())) # 保存地址和私钥还有 nonce - else: - st.error(f"地址 {address} 或私钥 {key} 无效,请检查!") - st.stop() - else: - st.error(f"输入格式错误,请确保每行包含一个地址和一个私钥,并使用英文逗号分隔(,)。错误行:**{line}**") - st.stop() - else: - account_address = st.text_input('填写你的 **ETH 地址**:') - private_key = st.text_input('填写你的 **ETH 地址对应的私钥**:', type="password") - if account_address and private_key: # 如果地址和私钥有内容 - if is_valid_eth_address(account_address) and is_valid_eth_private_key(private_key): # 验证地址和私钥 - current_nonce = w3.eth.get_transaction_count(account_address) # 获取地址的 nonce - nonces[account_address] = current_nonce # 记录地址的 nonce - accounts.append((account_address.strip(), private_key.strip())) # 保存地址和私钥还有 nonce - else: - st.error("地址或私钥无效,请检查!") - st.stop() - - # 配置铭文文本 - token_protocol = st.text_input('填写需要题写代币铭文协议 **Protocol(p)**:', 'erc-20') - token_operation = st.text_input('填写需要题写代币铭文操作 **Operation(op)**:', 'mint') - token_ticker = st.text_input('填写需要题写代币铭文简称 **Ticker(tick)**:') - token_min_id = st.number_input('填写需要题写代币铭文范围的**最小 ID(id)**:', min_value=1, value=1, step=1) - token_max_id = st.number_input('填写需要题写代币铭文范围的**最大 ID(id)**:', value=21000, step=1) - token_amount = st.number_input('填写需要题写代币铭文数量 **Amount(amt)**:', min_value=1, value=1000, step=1) - st.markdown('###### 预览代币铭文:') - st.code( - f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{token_min_id}","amt":"{token_amount}"}}', - language="json", line_numbers=False) - # 判断铭文文本里是否包含空格、换行符,而且所有的字母都必须为小写。 - if not validate_input( - f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{token_min_id}","amt":"{token_amount}"}}'): - st.warning("**请注意**:通常代币铭文文本里不能包含空格、换行符,而且所有的字母都必须为小写。") - - token_check = st.toggle('题写前**检查是否被题写** `主网` `查重`') - # 题写铭文之前检查该铭文有没有被题写 - if token_check: - token_check = True - else: - token_check = False - sleep_3s = st.toggle('每次完成交易后暂停 3 秒') - # 每次交易成功后暂停 3 秒 - if sleep_3s: - sleep_3s = True - else: - sleep_3s = False - - # 点击发送交易开始 - if st.button(f'开始**发送交易**'): - if not accounts or not token_protocol or not token_operation or not token_ticker: # 检查是否留空 - st.error(f'请正确谨慎地填写内容,每一项都**不应留空**。') - st.stop() - else: - st.toast('看起来你输入的内容均无没有问题!', icon='🥳') - - st.toast(f'开始任务,需要题写的铭文总量为:{token_max_id - token_min_id + 1}', icon='😎') - - # 对代币铭文 id 进行循环 - for the_id in range(token_min_id, token_max_id + 1): - # 使用当前账户发送交易,获取当前账户的 nonce - address, key = accounts[current_account_index] - # 得到完整的铭文文本 - input_data = f'data:,{{"p":"{token_protocol}","op":"{token_operation}","tick":"{token_ticker}","id":"{the_id}","amt":"{token_amount}"}}' - # 获取 gas - gas_price = w3.eth.gas_price - # 根据是否检查的开关进行 - if token_check: - # 这里是开了检查后请求 Ethscriptions API - if check_content_exists(sha256(input_data)): - # 返回数据为 Ture,说明该铭文已经被题写,打印信息 - st.toast(f'{input_data} 已经被题写!', icon='☹️') - else: - # 返回数据为 False,说明该铭文还没被题写,发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - else: - # 这里是未开检查后直接发送交易 - # 使用 current_nonce 发送交易 - data, tx_hash = send_transaction(w3, address, key, chain_id, gas_price, input_data, nonces[address]) - # 记录最后输出的结果 - transaction_results.append(f"{address} | {data} | Transaction Hash: {tx_hash}") - # 交易成功后,手动增加 nonce 值 - nonces[address] += 1 - # 更新当前账户索引,确保索引始终在账户列表的范围内 - current_account_index = (current_account_index + 1) % len(accounts) - # 暂停 3 秒 - if sleep_3s: - time.sleep(3) # 暂停三秒 - st.toast(f'所有任务已经完成。', icon='🎉') - # 庆祝动画 - st.balloons() - # 显示所有交易的结果 - st.code('\n'.join(transaction_results)) -else: - st.error('# 阅读并打勾 ✅ 后方可使用。') diff --git "a/pages/4_\360\237\222\271\357\270\217_\351\223\255\346\226\207\346\225\260\346\215\256\345\210\206\346\236\220.py" "b/pages/4_\360\237\222\271\357\270\217_\351\223\255\346\226\207\346\225\260\346\215\256\345\210\206\346\236\220.py" deleted file mode 100644 index 6510ecd32a6f62a16f94ffb05b5535a501147291..0000000000000000000000000000000000000000 --- "a/pages/4_\360\237\222\271\357\270\217_\351\223\255\346\226\207\346\225\260\346\215\256\345\210\206\346\236\220.py" +++ /dev/null @@ -1,1396 +0,0 @@ -import pickle -import streamlit as st -import requests -import os -from web3 import Web3 -import sqlite3 -import time -from datetime import datetime, timezone -import threading -import base64 -import configparser -import pandas as pd -import pytz -import json -from concurrent.futures import ThreadPoolExecutor -from collections import defaultdict - - -# 使用你的Ethereum节点的RPC地址 -infura_api_key_eths = os.environ.get('infura_api_key_eths', '') -etherscan_api_key = os.environ.get('etherscan_api_key', '') -w3 = Web3(Web3.HTTPProvider(infura_api_key_eths)) - -# Etherscan API -ETHERSCAN_API_URL = "https://api.etherscan.io/api" - -# 获取当前文件目录 -current_dir = os.path.dirname(__file__) -parent_dir = os.path.dirname(current_dir) - -# 构造数据库文件路径 -# eths 相关数据 文件路径 -eths_db_file = os.path.join(parent_dir, 'data', 'eths_data.db') # eths 相关 -# 所有已题写 ethscrptions 文件路径 -ethscrptions_db_file = os.path.join(parent_dir, 'data', 'ethscriptions_data.db') # 所有 ethscriptions,只检查有或没有 -# 配置文件 文件路径 -config_ini_file = os.path.join(parent_dir, 'data', 'config.ini') # 程序配置文件 -# ETCH 批量 文件路径 -etch_batch_orders_db_file = os.path.join(parent_dir, 'data', 'batch_orders.db') # ETCH 批量购买订单数据库 -# ETCH 单个 文件路径 -etch_single_orders_db_file = os.path.join(parent_dir, 'data', 'single_orders.db') # ETCH 单个购买订单数据库 -# 所有 ethscription 数据 文件路径 -all_ethscription_db_file = os.path.join(parent_dir, 'data', 'all_ethscription.db') # ID 对应铭文的数据库 -# Etch Market数据 pkl 文件路径 -etch_market_pkl_file = os.path.join(parent_dir, 'data', 'etch_market_data.pkl') -# ETCH eths 数据 pkl 文件路径 -etch_eths_pkl_file = os.path.join(parent_dir, 'data', 'etch_eths_data.pkl') -# ETCH eths 数据 pkl 文件路径 -etch_mfpurrs_pkl_file = os.path.join(parent_dir, 'data', 'etch_mfpurrs_data.pkl') -# ETCH eths 数据 pkl 文件路径 -etch_Hyppocritez_pkl_file = os.path.join(parent_dir, 'data', 'etch_Hyppocritez_data.pkl') - -all_pkl_file = [etch_market_pkl_file, etch_eths_pkl_file, etch_mfpurrs_pkl_file, etch_Hyppocritez_pkl_file] - -# 设置数据库 -ethscriptions_con = sqlite3.connect(ethscrptions_db_file) -ethscriptions_cur = ethscriptions_con.cursor() - -etch_batch_orders_show_con = sqlite3.connect(etch_batch_orders_db_file) -etch_batch_orders_show_cur = etch_batch_orders_show_con.cursor() - -etch_single_orders_show_con = sqlite3.connect(etch_single_orders_db_file) -etch_single_orders_show_cur = etch_single_orders_show_con.cursor() - -# all_ethscription_con = sqlite3.connect(all_ethscription_db_file) -# all_ethscription_cur = all_ethscription_con.cursor() - -# 配置合约 ABI 文件 -with open(os.path.join(parent_dir, 'data', 'batch_contract_abi.json'), "r") as batch: - contract_abi = json.load(batch) -batch_contract = w3.eth.contract(abi=contract_abi) - -with open(os.path.join(parent_dir, 'data', 'single_contract_abi.json'), "r") as single: - contract_abi = json.load(single) -single_contract = w3.eth.contract(abi=contract_abi) - -with open(os.path.join(parent_dir, 'data', 'single_contract_old_abi.json'), "r") as single_old: - contract_abi = json.load(single_old) -single_old_contract = w3.eth.contract(abi=contract_abi) - -my_style = ''' - -''' - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 查询 ETH token 价格 -def get_eth_price(): - try: - # 使用Etherscan的API endpoint获取以太坊的价格 - url = f"https://api.etherscan.io/api?module=stats&action=ethprice&apikey=1I2ERGUVJZNJAFKY7MG4S317DUGRPXEQPF" - response = requests.get(url) - response.raise_for_status() # 将引发HTTPError,如果HTTP请求返回了不成功的状态码 - - data = response.json() - - if data["message"] == "OK": - eth_price = float(data["result"]["ethusd"]) - return eth_price - else: - print("Error fetching the ETH price") - return None - except requests.RequestException as e: - print(f"Error while accessing the API: {e}") - return None - - -# 查询 ETCH 交易量和交易数 -def get_etch_volume_total(ethscription=None, days=None): - # 获取当前时间戳 - current_time = time.time() - - # 如果有days参数,则计算筛选的最小时间戳 - min_timestamp = None - if days: - min_timestamp = current_time - days * 24 * 60 * 60 - - # 查询数据库并获取结果的函数 - def query_db(db_file): - conn = sqlite3.connect(db_file) - cursor = conn.cursor() - - # 基本的查询 - query = "SELECT SUM(price), COUNT(DISTINCT transactionHash) FROM orders WHERE 1" - - # 添加条件 - if ethscription: - query += " AND ethscription = ?" - - if min_timestamp: - query += " AND startTime >= ?" - - # 执行查询 - params = [ethscription] if ethscription else [] - if min_timestamp: - params.append(min_timestamp) - - cursor.execute(query, tuple(params)) - result = cursor.fetchone() - conn.close() - - # 检查并替换None值为0 - result = tuple((0 if val is None else val) for val in result) - - return result - - # 从两个数据库中查询 - single_result = query_db(etch_single_orders_db_file) - batch_result = query_db(etch_batch_orders_db_file) - - # 计算总的交易量和交易数 - total_volume = single_result[0] + batch_result[0] - total_count = single_result[1] + batch_result[1] - - return total_volume, total_count - - -# 查询 ETCH 买家卖家数量 -def get_etch_address_total(ethscription=None, days=None): - - # 如果提供了天数限制,计算相应的UNIX时间戳 - min_timestamp = None - if days: - current_time = time.time() - days_in_seconds = days * 24 * 60 * 60 - min_timestamp = current_time - days_in_seconds - - def query_db(db_file, ethscription, min_timestamp): - conn = sqlite3.connect(db_file) - cursor = conn.cursor() - - where_clauses = [] - params = [] - - if ethscription: - where_clauses.append("o.ethscription = ?") - params.append(ethscription) - - if min_timestamp: - where_clauses.append("t.timeStamp >= ?") - params.append(min_timestamp) - - where_str = "" - if where_clauses: - where_str = "WHERE " + " AND ".join(where_clauses) - - # 查询addresses和signers - query = f""" - SELECT DISTINCT t.fromAddress, o.signer - FROM transactions t - JOIN orders o ON t.hash = o.transactionHash - {where_str} - """ - cursor.execute(query, tuple(params)) - - addresses = set() - signers = set() - for row in cursor.fetchall(): - addresses.add(row[0]) - signers.add(row[1]) - - conn.close() - - return addresses, signers - - single_addresses, single_signers = query_db(etch_single_orders_db_file, ethscription, min_timestamp) - batch_addresses, batch_signers = query_db(etch_batch_orders_db_file, ethscription, min_timestamp) - - # 合并两个集合 - total_addresses = single_addresses | batch_addresses - total_signers = single_signers | batch_signers - - # 计算结果 - num_buyers = len(total_addresses) - num_sellers = len(total_signers) - total_traders = len(total_addresses | total_signers) - - return num_buyers, num_sellers, total_traders - - -# 查询 ETCH 地址数 -def get_etch_address_total_list(ethscription=None, days=None): - # 获取当前时间戳(Unix时间格式) - current_timestamp = int(datetime.now().timestamp()) - - # 计算几天前的时间戳,如果提供了days参数 - days_ago_timestamp = current_timestamp - days * 24 * 60 * 60 if days else None - - # 定义一个查询数据库的内部函数 - def query_db(db_file): - conn = sqlite3.connect(db_file) - cursor = conn.cursor() - - # 构建SQL查询语句 - signer_query = "SELECT DISTINCT o.signer FROM orders o JOIN transactions t ON o.transactionHash = t.hash WHERE 1=1" - from_address_query = "SELECT DISTINCT t.fromAddress FROM transactions t WHERE 1=1" - - params = [] - if ethscription: - signer_query += " AND o.ethscription = ?" - params.append(ethscription) - - if days_ago_timestamp: - signer_query += " AND t.timeStamp >= ?" - from_address_query += " AND t.timeStamp >= ?" - params.append(days_ago_timestamp) - - cursor.execute(signer_query, tuple(params)) - signer_addresses = set([item[0] for item in cursor.fetchall()]) - - cursor.execute(from_address_query, tuple(params[:1] if days_ago_timestamp else [])) - from_address_addresses = set([item[0] for item in cursor.fetchall()]) - - conn.close() - - return signer_addresses, from_address_addresses - - # 查询两个数据库并取并集 - single_signer_addresses, single_from_address_addresses = query_db(etch_single_orders_db_file) - batch_signer_addresses, batch_from_address_addresses = query_db(etch_batch_orders_db_file) - - total_signer_addresses = single_signer_addresses.union(batch_signer_addresses) - total_from_address_addresses = single_from_address_addresses.union(batch_from_address_addresses) - - # 获取所有的signer和fromAddress地址,进行去重 - all_addresses = total_signer_addresses.union(total_from_address_addresses) - - return { - 'signer_count': len(total_signer_addresses), - 'from_address_count': len(total_from_address_addresses), - 'unique_addresses': all_addresses, - 'unique_address_count': len(all_addresses) - } - - -# 查询 ETCH 矿工费 -def get_etch_fee_total(ethscription=None): - # 定义用于统计的变量 - total_fee = 0 - - # 定义数据库路径 - dbs = [etch_single_orders_db_file, etch_batch_orders_db_file] - - # 对每个数据库执行查询操作 - for db in dbs: - # 创建数据库连接 - conn = sqlite3.connect(db) - cursor = conn.cursor() - - # 根据是否有ethscription参数来生成不同的查询语句 - if ethscription: - # 过滤特定ethscription并统计transactions中的transactionFee - query = """ - SELECT SUM(transactions.transactionFee) - FROM transactions - JOIN orders ON transactions.hash = orders.transactionHash - WHERE orders.ethscription = ? - """ - cursor.execute(query, (ethscription,)) - else: - # 不过滤ethscription,直接统计transactions中的transactionFee - query = "SELECT SUM(transactionFee) FROM transactions" - cursor.execute(query) - - # 获取查询结果 - result = cursor.fetchone() - if result[0]: # 防止结果为None - total_fee += result[0] - - # 关闭数据库连接 - conn.close() - - return total_fee - - -# etch 买入次数卖出次数买入金额卖出金额排行 -def get_etch_combined_rank(ethscription=None): - # 连接到两个数据库 - conn_single = sqlite3.connect(etch_single_orders_db_file) - conn_batch = sqlite3.connect(etch_batch_orders_db_file) - cur_single = conn_single.cursor() - cur_batch = conn_batch.cursor() - - # 设置过滤条件 - filter_condition = "" - if ethscription: - filter_condition = f" WHERE ethscription = '{ethscription}'" - - # 查询单订单数据库的卖出信息 - cur_single.execute(f""" - SELECT - signer, - SUM(price) as sell_amount, - COUNT(signer) as sell_count - FROM orders - {filter_condition} - GROUP BY signer - """) - single_sell_data = cur_single.fetchall() - - # 查询批量订单数据库的卖出信息 - cur_batch.execute(f""" - SELECT - signer, - SUM(price) as sell_amount, - COUNT(signer) as sell_count - FROM orders - {filter_condition} - GROUP BY signer - """) - batch_sell_data = cur_batch.fetchall() - - # 查询购买信息 - buy_query = f""" - SELECT - fromAddress, - SUM(value) as buy_amount, - COUNT(fromAddress) as buy_count - FROM transactions - JOIN orders ON transactions.hash = orders.transactionHash - {filter_condition} - GROUP BY fromAddress - """ - cur_single.execute(buy_query) - single_buy_data = cur_single.fetchall() - - cur_batch.execute(buy_query) - batch_buy_data = cur_batch.fetchall() - - # 数据处理,确保每个地址的所有交易都被汇总 - data = {} - - for signer, amount, count in single_sell_data + batch_sell_data: - signer = signer.lower() - if signer not in data: - data[signer] = {'sell_amount': 0, 'sell_count': 0, 'buy_amount': 0, 'buy_count': 0} - data[signer]['sell_amount'] += amount - data[signer]['sell_count'] += count - - for buyer, amount, count in single_buy_data + batch_buy_data: - buyer = buyer.lower() - if buyer not in data: - data[buyer] = {'sell_amount': 0, 'sell_count': 0, 'buy_amount': 0, 'buy_count': 0} - data[buyer]['buy_amount'] += amount - data[buyer]['buy_count'] += count - - # 结果整理 - result = [] - for address, values in data.items(): - net_buy = values['buy_amount'] - values['sell_amount'] - net_sell = values['sell_amount'] - values['buy_amount'] - volume = values['buy_amount'] + values['sell_amount'] - result.append({ - 'ETH 地址': address, - '买入次数': values['buy_count'], - '卖出次数': values['sell_count'], - '净买入 ETH': net_buy, - '净卖出 ETH': net_sell, - '交易总额 ETH': volume - }) - conn_batch.close() - conn_single.close() - return result - - -# 统计 price 排行 -def get_etch_top_price_rank(ethscription=None, limit=100): - # 连接到两个sqlite数据库 - conn_single = sqlite3.connect(etch_single_orders_db_file) - conn_batch = sqlite3.connect(etch_batch_orders_db_file) - - if ethscription: - filter_clause = f"AND ethscription = '{ethscription}'" - else: - filter_clause = "" - - # 使用SQL查询进行排序、计数和筛选 - query_template = f""" - SELECT - t.timeStamp, t.fromAddress, t.value, t.hash, COUNT(o.transactionHash) as order_count - FROM - transactions t - JOIN - orders o ON t.hash = o.transactionHash - WHERE - 1 = 1 {filter_clause} - GROUP BY - t.hash - ORDER BY - t.value DESC - LIMIT {limit} - """ - - data_single = conn_single.execute(query_template).fetchall() - data_batch = conn_batch.execute(query_template).fetchall() - - combined_data = data_single + data_batch - combined_data = sorted(combined_data, key=lambda x: x[2], reverse=True)[:limit] - - results = [] - for item in combined_data: - timeStamp, fromAddress, value, hash_val, order_count = item - formatted_time = datetime.utcfromtimestamp(timeStamp).strftime('%Y-%m-%d %H:%M:%S') - results.append({ - "时间": formatted_time, - "买家": fromAddress, - "金额": value, - "交易哈希": hash_val, - "订单数量": order_count - }) - conn_batch.close() - conn_single.close() - return results - - -# 统计 ethscriptionID 排行 -def get_etch_top_ethscriptionid_rank(ethscription=None): - # 定义数据库文件路径 - single_orders_db = etch_single_orders_db_file - batch_orders_db = etch_batch_orders_db_file - - # 定义从一个数据库中获取所有ethscriptionId的函数 - def get_ethscriptionids_from_db(db_path, ethscription): - conn = sqlite3.connect(db_path) - cursor = conn.cursor() - if ethscription: # 如果提供了ethscription参数,按该参数过滤数据 - cursor.execute("SELECT ethscriptionId, ethscription FROM orders WHERE ethscription = ?", (ethscription,)) - else: - cursor.execute("SELECT ethscriptionId, ethscription FROM orders") - ids = cursor.fetchall() - conn.close() - return ids - - # 从两个数据库中获取ethscriptionId数据 - single_ids = get_ethscriptionids_from_db(single_orders_db, ethscription) - batch_ids = get_ethscriptionids_from_db(batch_orders_db, ethscription) - - # 合并从两个数据库中获取的数据 - combined_ids = single_ids + batch_ids - - # 使用defaultdict统计ethscriptionId的出现次数 - counter = defaultdict(int) - id_to_ethscription = dict() - for eid, ethscription in combined_ids: - counter[eid] += 1 - id_to_ethscription[eid] = ethscription - - # 根据出现次数对ethscriptionId进行排序 - sorted_ids = sorted(counter.keys(), key=lambda x: counter[x], reverse=True) - - # 返回排序后的ethscriptionId列表及其对应的ethscription描述 - result = [ - { - 'EthscriptionID': eid, - '铭文类别': id_to_ethscription[eid], - '交易次数': counter[eid] - } - for eid in sorted_ids - ] - return result[:100] - - -# 列出最近 100 条交易 -def get_etch_last_100_orders(ethscription=None): - - query = """ - SELECT - t.blockNumber, t.timeStamp, t.hash, t.fromAddress, o.signer, o.price, o.ethscriptionId - FROM - orders o - JOIN - transactions t - ON - o.transactionHash = t.hash - {} - ORDER BY - t.timeStamp DESC - LIMIT 100 - """ - - if ethscription: - filter_query = "WHERE o.ethscription = ?" - query = query.format(filter_query) - params = (ethscription,) - else: - query = query.format("") - params = tuple() - - # Combine results from both databases - results = [] - for db_file in [etch_single_orders_db_file, etch_batch_orders_db_file]: - with sqlite3.connect(db_file) as conn: - cursor = conn.cursor() - cursor.execute(query, params) - results.extend(cursor.fetchall()) - - # Sort combined results by timestamp and pick the top 100 - results = sorted(results, key=lambda x: x[1], reverse=True)[:100] - - # Transform the results into a list of dictionaries and process timeStamp - keys = ["区块号", "时间", "交易哈希", "买家", "卖家", "金额", "EthscriptionId"] - processed_results = [] - for result in results: - processed_result = dict(zip(keys, result)) - processed_result["时间"] = datetime.utcfromtimestamp(processed_result["时间"]).strftime( - '%Y-%m-%d %H:%M:%S') - processed_results.append(processed_result) - - return processed_results - - -# 画出价格成交量成交额图 -def daily_transaction_volume_and_price_data(ethscription=None): - eth_price = get_eth_price() - # 连接到两个数据库 - conn_single = sqlite3.connect(etch_single_orders_db_file) - conn_batch = sqlite3.connect(etch_batch_orders_db_file) - - # 构造查询语句,获取orders和transactions的数据 - if ethscription: - query_single = f"SELECT o.*, t.timeStamp FROM orders o INNER JOIN transactions t ON o.transactionHash = t.hash WHERE o.ethscription = '{ethscription}'" - query_batch = f"SELECT o.*, t.timeStamp FROM orders o INNER JOIN transactions t ON o.transactionHash = t.hash WHERE o.ethscription = '{ethscription}'" - else: - query_single = "SELECT o.*, t.timeStamp FROM orders o INNER JOIN transactions t ON o.transactionHash = t.hash" - query_batch = "SELECT o.*, t.timeStamp FROM orders o INNER JOIN transactions t ON o.transactionHash = t.hash" - - df_single = pd.read_sql(query_single, conn_single) - df_batch = pd.read_sql(query_batch, conn_batch) - - # 合并两个数据集 - df = pd.concat([df_single, df_batch]) - - # 转换时间戳为日期 - df['date'] = pd.to_datetime(df['timeStamp'], unit='s').dt.date - - # 计算单价 - df['unit_price'] = df['price'] / df['quantity'] * eth_price - - # 按日期分组并聚合 - grouped = df.groupby('date').agg({ - 'unit_price': ['first', 'max', 'min', 'last'], - 'quantity': 'sum', - 'price': 'sum' - }) - - grouped.columns = ['开', '高', '低', '收', '交易量', '交易额'] - conn_single.close() - conn_batch.close() - return grouped - - -# 获取所有 ethscription 数据 -def get_all_ethscription_data(all_ethscription_conn, all_ethscription_cursor, ethscriptionId, db_lock): - endpoint = f"/ethscriptions/{ethscriptionId}" - try: - response = requests.get("https://mainnet-api.ethscriptions.com/api" + endpoint) - response.raise_for_status() # Raises stored HTTPError, if one occurred. - data = response.json() - - with db_lock: # Acquire DB lock to update the database - creator = data.get('creator', None) - creation_timestamp = data.get('creation_timestamp', None) - ethscription_number = data.get('ethscription_number', None) - mimetype = data.get('mimetype', None) - image_removed_by_request = data.get('image_removed_by_request_of_rights_holder', None) - content_uri = data.get('content_uri', None) - # 检查 name 是否存在于 collections 中 - if data['collections']: - name = data['collections'][0]['name'] - else: - name = None - # 5. 更新数据到相应的列 - update_query = ''' - UPDATE id_content - SET ethscription = ?, - creator = ?, - creation_timestamp = ?, - ethscription_number = ?, - mimetype = ?, - image_removed_by_request_of_rights_holder = ?, - content_uri = ?, - name = ? - WHERE ethscriptionId = ? - ''' - all_ethscription_cursor.execute(update_query, (data, creator, creation_timestamp, ethscription_number, mimetype, - image_removed_by_request, content_uri, name, ethscriptionId)) - - all_ethscription_conn.commit() - - except requests.RequestException as req_err: - print(f"Request error for identifier {ethscriptionId}: {req_err}") - except ValueError: - print(f"JSON decoding error for identifier {ethscriptionId}") - except Exception as e: - print(f"An unexpected error occurred for identifier {ethscriptionId}: {e}") - - -# 获取单个 ethscription 数据 -def get_specific_ethscription(ethscription_identifier): - endpoint = f"/ethscriptions/{ethscription_identifier}" - - try: - response = requests.get("https://mainnet-api.ethscriptions.com/api" + endpoint, timeout=3) - response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code - - if response.status_code == 200: - # Assuming the Content-Type is JSON - return response.json() - else: - print(f'Unexpected status code {response.status_code} for identifier: {ethscription_identifier}') - return None - - except requests.Timeout: - print(f"Request timed out for identifier: {ethscription_identifier}") - except requests.ConnectionError: - print(f"Connection error for identifier: {ethscription_identifier}") - except requests.TooManyRedirects: - print(f"Too many redirects for identifier: {ethscription_identifier}") - except requests.HTTPError as http_err: - print(f"HTTP error for identifier {ethscription_identifier}: {http_err}") - except requests.RequestException as req_err: - print(f"General error for identifier {ethscription_identifier}: {req_err}") - except Exception as e: - # Catch-all for any other unforeseen exceptions - print(f"An unexpected error occurred for identifier {ethscription_identifier}: {e}") - - return None # Ensure the function always returns a value even in the case of an error - - -# 通过 ID 从 all_ethscription 获取铭文内容 -def get_ethscription_by_id(ethscription_id, all_ethscription_cur): - # 执行查询语句 - all_ethscription_cur.execute("SELECT name FROM id_content WHERE ethscriptionId=?", (ethscription_id,)) - result = all_ethscription_cur.fetchone() - - # 返回结果 - if result: - return result[0] - else: - return None - - -# 更新 all_ethscription 铭文内容 -def update_all_ethscription_with_id(all_ethscription_conn, all_ethscription_cursor, db_lock): - all_ethscription_cursor.execute( - "SELECT ethscriptionId FROM id_content WHERE ethscription IS NULL OR ethscription = ''") - rows = all_ethscription_cursor.fetchall() - print(f'Not Processed EthscriptionID: {len(rows)}') - - # Use a thread pool with a fixed number of threads (e.g., 10 threads) - with ThreadPoolExecutor(max_workers=10) as executor: - for row in rows: - ethscriptionId = row[0] - executor.submit(get_all_ethscription_data, all_ethscription_conn, all_ethscription_cursor, ethscriptionId, db_lock) - - -# 根据 hash 查重 -def single_transaction_exists(tx_hash, single_orders_cursor): - single_orders_cursor.execute("SELECT hash FROM transactions WHERE hash = ?", (tx_hash,)) - return bool(single_orders_cursor.fetchone()) - - -# 批量购买合约 tx 检查 -def batch_transaction_exists(tx_hash, batch_orders_cursor): - batch_orders_cursor.execute("SELECT hash FROM transactions WHERE hash = ?", (tx_hash,)) - return bool(batch_orders_cursor.fetchone()) - - -# ABI 处理单笔购买合约交易 input data 数据 -def parse_single_input_data(input_data): - if input_data[:10] == '0xd2234424': - decoded_data = single_old_contract.decode_function_input(input_data) - return decoded_data # Returns the input data as a dictionary - if input_data[:10] == '0xd92a1740': - decoded_data = single_contract.decode_function_input(input_data) - return decoded_data # Returns the input data as a dictionary - - -# ABI 处理批量购买合约交易 input data 数据 -def parse_batch_input_data(input_data): - decoded_data = batch_contract.decode_function_input(input_data) - return decoded_data # Returns the input data as a dictionary - - -# 处理和储存单笔购买合约交易数据 -def process_and_store_single_transaction(tx, single_orders_cursor, single_orders_conn, all_ethscription_cur): - if tx['txreceipt_status'] == '1': - if tx['input'][:10] == '0xd2234424' or tx['input'][:10] == '0xd92a1740': - if not single_transaction_exists(tx['hash'], - single_orders_cursor): # Check if transaction already exists in DB - try: - data = parse_single_input_data(tx['input']) - # Calculate transaction fee (gasPrice * gasUsed) - transaction_fee = (float(tx['gasPrice']) * float(tx['gasUsed'])) / 1e18 - - function_name = data[0] - params = data[1] - # Handle bytes data - for key, value in params.items(): - if isinstance(value, bytes): - params[key] = value.hex() - # 获取并处理订单数据 - order = params.get('order', {}) - if order: # 确保order不为空 - for key in ['ethscriptionId', 'r', 's', 'params']: - if key in order: # 确保键在order中 - order[key] = order[key].hex() - - ethscription = get_ethscription_by_id(f'0x{order["ethscriptionId"]}', all_ethscription_cur) - if ethscription is None: - ethscription = get_specific_ethscription(f'0x{order["ethscriptionId"]}') - if ethscription is not None: - if ethscription['collections']: - ethscription = ethscription['collections'][0]['name'] - else: - ethscription = None - # Store transaction data first - single_orders_cursor.execute(''' - INSERT OR IGNORE INTO transactions (blockNumber, timeStamp, hash, fromAddress, value, txreceipt_status, transactionFee) - VALUES (?, ?, ?, ?, ?, ?, ?) - ''', ( - tx['blockNumber'], tx['timeStamp'], tx['hash'], tx['from'], float(tx['value']) / 1e18, - tx['txreceipt_status'], - transaction_fee)) - - single_orders_cursor.execute(''' - INSERT INTO orders (transactionHash, signer, creator, ethscriptionId, quantity, currency, price, - startTime, endTime, protocolFeeDiscounted, creatorFee, params, v, r, s, ethscription) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ''', ( - tx['hash'], order['signer'], order['creator'], '0x' + order['ethscriptionId'], order['quantity'], - order['currency'], float(order['price']) / 1e18, order['startTime'], order['endTime'], - order['protocolFeeDiscounted'], order['creatorFee'], json.dumps(order['params']), - order['v'], order['r'], order['s'], ethscription)) - single_orders_conn.commit() - - except Exception as e: - print(f"Error processing transaction {tx['hash']}: {e}") - pass - - -# 处理和储存批量购买合约交易数据 -def process_and_store_batch_transaction(tx, batch_orders_cursor, batch_orders_conn, all_ethscription_cur): - if not batch_transaction_exists(tx['hash'], batch_orders_cursor): # Check if transaction already exists in DB - try: - data = parse_batch_input_data(tx['input']) - - # Calculate transaction fee (gasPrice * gasUsed) - transaction_fee = (float(tx['gasPrice']) * float(tx['gasUsed'])) / 1e18 - - function_name = data[0] - params = data[1] - # Handle bytes data - for key, value in params.items(): - if isinstance(value, bytes): - params[key] = value.hex() - - # Insert order data - orders_data = params.get('orders', []) - - # Store transaction data first - batch_orders_cursor.execute(''' - INSERT OR IGNORE INTO transactions (blockNumber, timeStamp, hash, fromAddress, value, txreceipt_status, transactionFee) - VALUES (?, ?, ?, ?, ?, ?, ?) - ''', ( - tx['blockNumber'], tx['timeStamp'], tx['hash'], tx['from'], float(tx['value']) / 1e18, - tx['txreceipt_status'], - transaction_fee)) - - for order in orders_data: - for key in ['ethscriptionId', 'r', 's', 'params']: - order[key] = order[key].hex() - - ethscription = get_ethscription_by_id(f'0x{order["ethscriptionId"]}', all_ethscription_cur) - if ethscription is None: - ethscription = get_specific_ethscription(f'0x{order["ethscriptionId"]}') - if ethscription is not None: - if ethscription['collections']: - ethscription = ethscription['collections'][0]['name'] - else: - ethscription = None - - batch_orders_cursor.execute(''' - INSERT INTO orders (transactionHash, signer, creator, ethscriptionId, quantity, currency, price, - startTime, endTime, protocolFeeDiscounted, creatorFee, params, v, r, s, ethscription) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ''', (tx['hash'], order['signer'], order['creator'], '0x' + order['ethscriptionId'], order['quantity'], - order['currency'], float(order['price']) / 1e18, order['startTime'], order['endTime'], - order['protocolFeeDiscounted'], order['creatorFee'], json.dumps(order['params']), - order['v'], order['r'], order['s'], ethscription)) - - batch_orders_conn.commit() - - except Exception as e: - print(f"Error processing transaction {tx['hash']}: {e}") - pass - - -# 获取所有单笔购买合约交易 -def get_single_all_transactions(single_orders_cursor, single_orders_conn, all_ethscription_cur): - single_orders_cursor.execute('SELECT MAX(blockNumber) FROM transactions') - start_block_number = single_orders_cursor.fetchone()[0] - 100 - print(f'Get single all transactions: {start_block_number}') - - # 整理 ethscription 为空的内容 - single_orders_cursor.execute("SELECT ethscriptionId FROM orders WHERE ethscription IS NULL OR ethscription = ''") - ethscription_ids = [row[0] for row in single_orders_cursor.fetchall()] - for eid in ethscription_ids: - all_ethscription_cur.execute("SELECT name FROM id_content WHERE ethscriptionId = ?", (eid,)) - result = all_ethscription_cur.fetchone() - if result: - # If found, update the ethscription in orders table - single_orders_cursor.execute("UPDATE orders SET ethscription = ? WHERE ethscriptionId = ?", (result[0], eid)) - - # Commit changes and close connections - single_orders_conn.commit() - - page = 1 - - while True: - time.sleep(1) - params = { - "module": "account", - "action": "txlist", - "address": "0x57b8792c775D34Aa96092400983c3e112fCbC296", - "startblock": start_block_number, - "endblock": 99999999, - "page": page, - "offset": 100, - "sort": "asc", - "apikey": etherscan_api_key - } - try: - response = requests.get(ETHERSCAN_API_URL, params=params) - response.raise_for_status() # This will raise an HTTPError if the HTTP request returned an unsuccessful status code - txs = response.json().get('result', []) - except requests.ConnectionError: - print("Failed to connect to the server.") - txs = [] - except requests.Timeout: - print("The request timed out.") - txs = [] - except requests.RequestException as e: - print(f"An error occurred: {e}") - txs = [] - except ValueError: # This will catch JSON decoding errors - print("Failed to parse the response.") - txs = [] - - if not txs: - break - - for tx in txs: - process_and_store_single_transaction(tx, single_orders_cursor, single_orders_conn, all_ethscription_cur) - print(f'tx:{page}') - - page += 1 - - -# 获取所有批量购买合约交易 -def get_batch_all_transactions(batch_orders_cursor, batch_orders_conn, all_ethscription_cur): - batch_orders_cursor.execute('SELECT MAX(blockNumber) FROM transactions') - start_block_number = batch_orders_cursor.fetchone()[0] - 100 - print(f'Get batch all transactions: {start_block_number}') - - # 整理 ethscription 为空的内容 - batch_orders_cursor.execute("SELECT ethscriptionId FROM orders WHERE ethscription IS NULL OR ethscription = ''") - ethscription_ids = [row[0] for row in batch_orders_cursor.fetchall()] - for eid in ethscription_ids: - all_ethscription_cur.execute("SELECT name FROM id_content WHERE ethscriptionId = ?", (eid,)) - result = all_ethscription_cur.fetchone() - if result: - # If found, update the ethscription in orders table - batch_orders_cursor.execute("UPDATE orders SET ethscription = ? WHERE ethscriptionId = ?", - (result[0], eid)) - - # Commit changes and close connections - batch_orders_conn.commit() - - page = 1 - - while True: - params = { - "module": "account", - "action": "txlist", - "address": "0x941Bc2E04A776d436E183Fe4204Bb84FeBA564D3", - "startblock": start_block_number, - "endblock": 99999999, - "page": page, - "offset": 100, - "sort": "asc", - "apikey": etherscan_api_key - } - - try: - response = requests.get(ETHERSCAN_API_URL, params=params) - response.raise_for_status() # This will raise an HTTPError if the HTTP request returned an unsuccessful status code - txs = response.json().get('result', []) - except requests.ConnectionError: - print("Failed to connect to the server.") - txs = [] - except requests.Timeout: - print("The request timed out.") - txs = [] - except requests.RequestException as e: - print(f"An error occurred: {e}") - txs = [] - except ValueError: # This will catch JSON decoding errors - print("Failed to parse the response.") - txs = [] - - if not txs: - break - if page == 1: - for tx in txs[2:]: - process_and_store_batch_transaction(tx, batch_orders_cursor, batch_orders_conn, all_ethscription_cur) - else: - for tx in txs: - process_and_store_batch_transaction(tx, batch_orders_cursor, batch_orders_conn, all_ethscription_cur) - - # for tx in txs: - # process_and_store_transaction(tx) - - page += 1 - - -# 从 ETCH 获取 eths 数据(线程入口) -def get_eths_data(): - global eths_conn, eths_cur - # Initialize connection to SQLite database - eths_conn = sqlite3.connect(eths_db_file) - eths_cur = eths_conn.cursor() - # Create table to store ETHS data - eths_cur.execute(''' - CREATE TABLE IF NOT EXISTS eths_data - (date text, - eth_price real, - eths_price real, - eths_market_cap integer, - eths_owners integer, - eths_volume24h real, - eths_totalLocked integer, - eths_stakers integer, - eths_tvl real) - ''') - while True: - try: - # Get ETHS price data - price_url = 'https://www.etch.market/api/markets/collections/details' - price_params = {'category': 'token', 'collectionName': 'erc-20 eths'} - price_response = requests.get(price_url, params=price_params) - # Get ETHS staking data - staking_url = 'https://www.etch.market/api/staking/statistics/erc-20%20eths' - staking_response = requests.get(staking_url) - if price_response.status_code == 200 and staking_response.status_code == 200: - price_response = price_response.json() - staking_response = staking_response.json() - if price_response['message'] == 'success' and staking_response['message'] == 'success': - price_data = price_response['data']['collections'] - staking_data = staking_response['data'] - # Extract values from API responses - eth_price = float(price_data['unitPriceUsd']) / float(price_data['unitPrice']) - eths_price = float(price_data['unitPriceUsd']) - eths_market_cap = eths_price * 21000000 - eths_owners = int(price_data['owners']) - eths_volume24h = float(price_data['volume24h']) * eth_price - eths_totalLocked = int(staking_data['totalLocked']) - eths_stakers = int(staking_data['stakers']) - eths_tvl = float(staking_data['tvl']) * eth_price - # Current date/time - now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') - # Package data into tuple - data = (now, eth_price, eths_price, eths_market_cap, eths_owners, eths_volume24h, - eths_totalLocked, eths_stakers, eths_tvl) - eths_cur.execute('DELETE FROM eths_data') - eths_cur.execute('INSERT INTO eths_data VALUES (?,?,?,?,?,?,?,?,?)', data) - eths_conn.commit() - except Exception as e: - print(e) - etch_type_of_data = [None, 'erc-20 eths token', 'mfpurrs', 'Hyppocritez'] - - for index, i in enumerate(etch_type_of_data): - # ETCH 全网总成交量和成交订单数 - etch_total_volume_and_orders = get_etch_volume_total(ethscription=i) - # ETCH 全网 30 日成交量和成交订单数 - etch_30d_volume_and_orders = get_etch_volume_total(ethscription=i, days=30) - # ETCH 全网 7 日成交量和成交订单数 - etch_7d_volume_and_orders = get_etch_volume_total(ethscription=i, days=7) - # ETCH 全网 3 日成交量和成交订单数 - etch_3d_volume_and_orders = get_etch_volume_total(ethscription=i, days=3) - # ETCH 全网 1 日成交量和成交订单数 - etch_1d_volume_and_orders = get_etch_volume_total(ethscription=i, days=1) - # ETCH 全网总买家和卖家 - etch_total_buyers_sellers = get_etch_address_total(ethscription=i) - # ETCH 全网 1 日买家和卖家 - etch_1d_buyers_sellers = get_etch_address_total(ethscription=i, days=1) - # ETCH 全网总矿工费 - etch_total_fee = get_etch_fee_total(ethscription=i) - # ETCH 买入数卖出数买入金额卖出金额排行 - etch_combined_rank = get_etch_combined_rank(ethscription=i) - # ETCH 根据订单金额排行 - etch_top_price_rank = get_etch_top_price_rank(ethscription=i, limit=20) - # ETCH 根据 ethsctriptionID 交易次数排行 - etch_top_id_rank = get_etch_top_ethscriptionid_rank(ethscription=i) - # ETCH 列出最近 100 条交易 - etch_last_100_orders = get_etch_last_100_orders(ethscription=i) - # 画图 - daily_transaction_volume = daily_transaction_volume_and_price_data(ethscription=i) - etch_pkl_data_to_save = {'etch_total_volume_and_orders': etch_total_volume_and_orders, - 'etch_30d_volume_and_orders': etch_30d_volume_and_orders, - 'etch_7d_volume_and_orders': etch_7d_volume_and_orders, - 'etch_3d_volume_and_orders': etch_3d_volume_and_orders, - 'etch_1d_volume_and_orders': etch_1d_volume_and_orders, - 'etch_total_buyers_sellers': etch_total_buyers_sellers, - 'etch_1d_buyers_sellers': etch_1d_buyers_sellers, - 'etch_total_fee': etch_total_fee, - 'etch_combined_rank': etch_combined_rank, - 'etch_top_price_rank': etch_top_price_rank, - 'etch_top_id_rank': etch_top_id_rank, - 'etch_last_100_orders': etch_last_100_orders, - 'daily_transaction_volume': daily_transaction_volume - } - with open(all_pkl_file[index], 'wb') as file: - pickle.dump(etch_pkl_data_to_save, file) - time.sleep(180) - while True: - print('ETCH 获取数据错误退出') - time.sleep(15) - - -# 获取所有 ethscriptions 数据,只检查有或者没有(线程入口) -def get_ethscriptions_data(): - # 创建表 - ethscriptions_thread_con = sqlite3.connect(ethscrptions_db_file) - ethscriptions_thread_cur = ethscriptions_thread_con.cursor() - ethscriptions_thread_cur.execute('''CREATE TABLE IF NOT EXISTS data - (block_time text, block_number integer, data text, owner text, hash text)''') - - ethscriptions_thread_cur.execute('''CREATE TABLE IF NOT EXISTS process_blocks - (block_number integer)''') - # 获取最新的区块 - latest_block_number_thread = w3.eth.block_number - ethscriptions_thread_cur.execute("SELECT MAX(block_number) FROM process_blocks") - result_thread = ethscriptions_thread_cur.fetchone() - start_block_thread = result_thread[0] - 10 - while True: - - for block_number in range(start_block_thread, latest_block_number_thread): - - block = w3.eth.get_block(block_number, full_transactions=True) - - # 获取该区块中所有交易的列表 - transactions = block['transactions'] - for tx in transactions: - input_data = tx['input'] - if input_data.startswith(r"0x646174613a2c"): - - existing_data = ethscriptions_thread_cur.execute("SELECT * FROM data WHERE data=?", - (input_data,)).fetchone() - - if not existing_data: - timestamp = datetime.fromtimestamp(block['timestamp'], tz=timezone.utc) - - ethscriptions_thread_cur.execute('''INSERT INTO data (block_time, block_number, data, owner, hash) - VALUES (?, ?, ?, ?, ?)''', - ( - timestamp, tx['blockNumber'], input_data, tx['to'], - tx['hash'].hex())) - - ethscriptions_thread_con.commit() - # print(f'Get input data: {input_data}') - - # 更新process_blocks表 - ethscriptions_thread_cur.execute("INSERT INTO process_blocks (block_number) VALUES (?)", - (block_number,)) - # 只保留最新的一条记录 - ethscriptions_thread_cur.execute("DELETE FROM process_blocks WHERE block_number != ?", - (block_number,)) - ethscriptions_thread_con.commit() - print(f'Process current block: {block_number}') - - # 获取下次开始的区块号 - ethscriptions_thread_cur.execute("SELECT block_number FROM process_blocks") - result_thread = ethscriptions_thread_cur.fetchone() - start_block_thread = result_thread[0] - 1 - # 等待 - time.sleep(10) - # 获取最新的区块 - latest_block_number_thread = w3.eth.block_number - while True: - print('ETCH 获取已题写错误退出') - time.sleep(15) - -# 获取所有单笔购买订单(线程入口) -def get_etch_single_orders(): - # SQLite setup - single_orders_conn = sqlite3.connect(etch_single_orders_db_file) - single_orders_cursor = single_orders_conn.cursor() - - all_ethscription_con = sqlite3.connect(all_ethscription_db_file) - all_ethscription_cur = all_ethscription_con.cursor() - - while True: - get_single_all_transactions(single_orders_cursor, single_orders_conn, all_ethscription_cur) - time.sleep(15) - while True: - print('ETCH 单笔错误退出') - time.sleep(15) - - -# 获取所有批量购买订单(线程入口) -def get_etch_batch_orders(): - # SQLite setup - batch_orders_conn = sqlite3.connect(etch_batch_orders_db_file) - batch_orders_cursor = batch_orders_conn.cursor() - - all_ethscription_con = sqlite3.connect(all_ethscription_db_file) - all_ethscription_cur = all_ethscription_con.cursor() - - while True: - get_batch_all_transactions(batch_orders_cursor, batch_orders_conn, all_ethscription_cur) - time.sleep(15) - while True: - print('ETCH 多笔错误退出') - time.sleep(15) - - -# 获取所有 ethscriptions 数据,只检查有或者没有(线程入口) -def get_all_ethscription_by_id(): - # SQLite setup - all_ethscription_conn = sqlite3.connect(all_ethscription_db_file, check_same_thread=False) - all_ethscription_cursor = all_ethscription_conn.cursor() - - # Database lock - db_lock = threading.Lock() - - while True: - batch_conn = sqlite3.connect(etch_batch_orders_db_file) - batch_cursor = batch_conn.cursor() - - single_conn = sqlite3.connect(etch_single_orders_db_file) - single_cursor = single_conn.cursor() - - # 从 single_orders.db 中获取所有 ethscriptionId - single_cursor.execute("SELECT ethscriptionId FROM orders") - ethscriptions_single = single_cursor.fetchall() - - # 从 batch_orders.db 中获取所有 ethscriptionId - batch_cursor.execute("SELECT ethscriptionId FROM orders") - ethscriptions_batch = batch_cursor.fetchall() - - # 对于每一个 ethscriptionId,检查其是否在 all_ethscription.db 中 - for ethscription in ethscriptions_single: - all_ethscription_cursor.execute("SELECT COUNT(*) FROM id_content WHERE ethscriptionId=?", - (ethscription[0],)) - exists = all_ethscription_cursor.fetchone()[0] - - # 如果不存在,则插入 - if exists == 0: - all_ethscription_cursor.execute("INSERT INTO id_content (ethscriptionId, ethscription) VALUES (?, ?)", - (ethscription[0], None)) - all_ethscription_conn.commit() - # 对于每一个 ethscriptionId,检查其是否在 all_ethscription.db 中 - for ethscription in ethscriptions_batch: - all_ethscription_cursor.execute("SELECT COUNT(*) FROM id_content WHERE ethscriptionId=?", - (ethscription[0],)) - exists = all_ethscription_cursor.fetchone()[0] - - # 如果不存在,则插入 - if exists == 0: - all_ethscription_cursor.execute( - "INSERT INTO id_content (ethscriptionId, ethscription) VALUES (?, ?)", - (ethscription[0], None)) - all_ethscription_conn.commit() - batch_conn.close() - single_conn.close() - - update_all_ethscription_with_id(all_ethscription_conn, all_ethscription_cursor, db_lock) - - time.sleep(60) - while True: - print('ETCH get all 错误退出') - time.sleep(15) - - -# Streamlit app 布局设置 -st.set_page_config(page_title="EthPen - 铭文数据分析", page_icon="💹", layout='centered', initial_sidebar_state='auto') -st.write("", unsafe_allow_html=True) -st.markdown(f'# Image :rainbow[铭文数据分析]', unsafe_allow_html=True) -st.subheader(r'', anchor=False, divider='rainbow') -st.markdown(f'### $eths 数据盘点') -eths_conn = sqlite3.connect(eths_db_file) -eths_cur = eths_conn.cursor() -# 查询eths_data表中所有数据 -eths_cur.execute('SELECT * FROM eths_data') -# 获取所有结果 -eths_data = eths_cur.fetchall() -if eths_data: - col1, col2 = st.columns(2) - with col1: - eths_price = st.metric(label='ETHS 价格', value=f'${eths_data[0][2]:,.2f}') - - eths_price = st.metric(label='总量', value='21,000,000') - - eths_owners = st.metric(label='持有人数', value=f'{eths_data[0][4]:,.0f}') - - eths_stakers = st.metric(label='质押人数', value=f'{eths_data[0][7]:,.0f}') - with col2: - eths_tvl = st.metric(label='总市值', value=f'${eths_data[0][3]:,.0f}') - - eths_volume24h = st.metric(label='24小时成交量', value=f'${eths_data[0][5]:,.0f}') - - eths_totalLocked = st.metric(label='质押总量', value=f'{eths_data[0][6]:,.0f} $eths') - - eths_stakers = st.metric(label='ETHS TVL', value=f'${eths_data[0][8]:,.0f}') - -st.markdown(f'### 新铭文题写') -ethscriptions_cur.execute(''' - SELECT block_time, data - FROM data - ORDER BY block_time DESC - LIMIT 1000; - ''') -new_100_results_temp = ethscriptions_cur.fetchall() -new_100_results = [] - -for item in new_100_results_temp: - utc_dt = datetime.strptime(item[0], "%Y-%m-%d %H:%M:%S%z") - utc_dt = utc_dt.replace(tzinfo=pytz.UTC) - utc_plus_8_dt = utc_dt.astimezone(pytz.timezone("Asia/Shanghai")) - new_100_results.append({ - '时间 UTC +8': utc_plus_8_dt.strftime("%Y-%m-%d %H:%M:%S (UTC +8)")[:-8], - '铭文 data:,': bytes.fromhex(item[1][2:]).decode('utf-8', 'replace')[6:] - }) -result_df = pd.DataFrame(new_100_results) -st.dataframe(result_df, use_container_width=True, hide_index=True) - -st.markdown(f'### Etch Market 数据洞察') -eth_token_price = get_eth_price() - -data_selected_option = st.radio("选择查询的类型:", ['Etch Market', '$eths Token', 'mfpurrs NFT', 'Hyppocritez NFT'], index=0, horizontal=True, label_visibility = "collapsed") - -if data_selected_option == 'Etch Market': - ethscription = 0 -if data_selected_option == '$eths Token': - ethscription = 1 -if data_selected_option == 'mfpurrs NFT': - ethscription = 2 -if data_selected_option == 'Hyppocritez NFT': - ethscription = 3 - - -with open(all_pkl_file[ethscription], 'rb') as file: - etch_loaded_data = pickle.load(file) - -st.markdown(f'#### {data_selected_option} 数据概览') - -col1, col2 = st.columns(2) -with col1: - st.metric(label=f'总交易量 {etch_loaded_data["etch_total_volume_and_orders"][0]:.0f} ETH', value=f'${etch_loaded_data["etch_total_volume_and_orders"][0] * eth_token_price:,.0f}') - st.metric(label=f'30 日交易量 {etch_loaded_data["etch_30d_volume_and_orders"][0]:.0f} ETH', value=f'${etch_loaded_data["etch_30d_volume_and_orders"][0] * eth_token_price:,.0f}') - st.metric(label=f'7 日交易量 {etch_loaded_data["etch_7d_volume_and_orders"][0]:.0f} ETH', value=f'${etch_loaded_data["etch_7d_volume_and_orders"][0] * eth_token_price:,.0f}') - st.metric(label=f'3 日交易量 {etch_loaded_data["etch_3d_volume_and_orders"][0]:.0f} ETH', value=f'${etch_loaded_data["etch_3d_volume_and_orders"][0] * eth_token_price:,.0f}') - st.metric(label=f'1 日交易量 {etch_loaded_data["etch_1d_volume_and_orders"][0]:.0f} ETH', value=f'${etch_loaded_data["etch_1d_volume_and_orders"][0] * eth_token_price:,.0f}') - - st.metric(label=f'总交易人数 / 独立用户', value=f'{etch_loaded_data["etch_total_buyers_sellers"][2]:,.0f}') - st.metric(label=f'1 日交易人数', value=f'{etch_loaded_data["etch_1d_buyers_sellers"][2]:,.0f}') - st.metric(label=f'总消耗矿工费', value=f'{etch_loaded_data["etch_total_fee"]:,.2f}ETH') -with col2: - st.metric(label=f'总订单量', value=f'{etch_loaded_data["etch_total_volume_and_orders"][1]:,.0f}') - st.metric(label=f'30 日订单量', value=f'{etch_loaded_data["etch_30d_volume_and_orders"][1]:,.0f}') - st.metric(label=f'7 日订单量', value=f'{etch_loaded_data["etch_7d_volume_and_orders"][1]:,.0f}') - st.metric(label=f'3 日订单量', value=f'{etch_loaded_data["etch_3d_volume_and_orders"][1]:,.0f}') - st.metric(label=f'1 日订单量', value=f'{etch_loaded_data["etch_1d_volume_and_orders"][1]:,.0f}') - - st.metric(label=f'总买家 / 总卖家', value=f'{etch_loaded_data["etch_total_buyers_sellers"][0]:,.0f} / {etch_loaded_data["etch_total_buyers_sellers"][1]:,.0f}') - st.metric(label=f'1 日买家 / 卖家', value=f'{etch_loaded_data["etch_1d_buyers_sellers"][0]:,.0f} / {etch_loaded_data["etch_1d_buyers_sellers"][1]:,.0f}') - -st.markdown(f'#### {data_selected_option} 综合排行榜') -st.dataframe(etch_loaded_data["etch_combined_rank"], use_container_width=True, hide_index=True) - -st.markdown(f'#### {data_selected_option} 订单金额 TOP 20 排行榜') -st.dataframe(etch_loaded_data["etch_top_price_rank"], use_container_width=True, hide_index=True) - -st.markdown(f'#### {data_selected_option} EthscriptionID 换手次数 TOP 100 排行榜') -st.dataframe(etch_loaded_data["etch_top_id_rank"], use_container_width=True, hide_index=True) - -st.markdown(f'#### {data_selected_option} 最近 100 条交易') -st.dataframe(etch_loaded_data["etch_last_100_orders"], use_container_width=True, hide_index=True) -if ethscription != 0: - # daily_transaction_volume_and_price(etch_loaded_data["daily_transaction_volume"]) - # 显示蜡烛图 - st.markdown(f'#### {data_selected_option} 价格走势图') - st.line_chart(etch_loaded_data["daily_transaction_volume"][['开', '高', '低', '收']]) - # 显示成交量图 - st.markdown(f'#### {data_selected_option} 每日成交量图') - st.bar_chart(etch_loaded_data["daily_transaction_volume"]['交易量']) - -# 显示每日成交额图 -st.markdown(f'#### {data_selected_option} 每日成交额图') -st.bar_chart(etch_loaded_data["daily_transaction_volume"]['交易额']) - -# 线程入口 -config = configparser.ConfigParser() -config.read(config_ini_file) -thread_start_state_value = config['data_thread_start_state']['state'] -if thread_start_state_value == '0': - print('数据分析线程未启动。') - config['data_thread_start_state']['state'] = '1' - with open(config_ini_file, 'w') as configfile: - config.write(configfile) - - eths_thread = threading.Thread(target=get_eths_data) - ethscriptions_thread = threading.Thread(target=get_ethscriptions_data) - etch_single_orders_thread = threading.Thread(target=get_etch_single_orders) - etch_batch_orders_thread = threading.Thread(target=get_etch_batch_orders) - all_ethscription_by_id_thread = threading.Thread(target=get_all_ethscription_by_id) - - # 启动线程 - eths_thread.start() - ethscriptions_thread.start() - etch_single_orders_thread.start() - etch_batch_orders_thread.start() - all_ethscription_by_id_thread.start() - - # 等待线程结束 - eths_thread.join() - ethscriptions_thread.join() - etch_single_orders_thread.join() - etch_batch_orders_thread.join() - all_ethscription_by_id_thread.join() - -else: - print('数据分析线程已经启动。') diff --git "a/pages/5_\360\237\217\253_\346\225\231\347\250\213\344\270\255\345\277\203.py" "b/pages/5_\360\237\217\253_\346\225\231\347\250\213\344\270\255\345\277\203.py" deleted file mode 100644 index d99c4004b6ccfb02fb39e019cc0dec386cf74856..0000000000000000000000000000000000000000 --- "a/pages/5_\360\237\217\253_\346\225\231\347\250\213\344\270\255\345\277\203.py" +++ /dev/null @@ -1,18 +0,0 @@ -import base64 -import streamlit as st -import os - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# Streamlit app layout -st.set_page_config(page_title="EthPen - 教程中心", page_icon="🏫", layout='centered', initial_sidebar_state='auto') -st.markdown(f'# Image :rainbow[教程中心]', unsafe_allow_html=True) -st.subheader(r'', anchor=False, divider='rainbow') -st.error('开发中,仅供参考...') -st.error('若您有更好的建议或想法,请随时与我取得联系。') - diff --git "a/pages/6_\360\237\223\242_\346\216\250\351\200\201\351\200\232\347\237\245\346\234\215\345\212\241.py" "b/pages/6_\360\237\223\242_\346\216\250\351\200\201\351\200\232\347\237\245\346\234\215\345\212\241.py" deleted file mode 100644 index 0299ae082333787d421adf1d934fde8747d44f8f..0000000000000000000000000000000000000000 --- "a/pages/6_\360\237\223\242_\346\216\250\351\200\201\351\200\232\347\237\245\346\234\215\345\212\241.py" +++ /dev/null @@ -1,326 +0,0 @@ -import streamlit as st -import requests -import os -from web3 import Web3 -import sqlite3 -import time -import threading -import base64 -import configparser -import pandas as pd -import json -from concurrent.futures import ThreadPoolExecutor -from datetime import datetime - - -my_style = ''' - -''' - -# 获取 pushover api -pushover_api_token = os.environ.get('pushover_api_token', '') -pushover_user_token = os.environ.get('pushover_user_token', '') - -# 获取当前文件目录 -current_dir = os.path.dirname(__file__) -parent_dir = os.path.dirname(current_dir) -config_ini_file = os.path.join(parent_dir, 'data', 'config.ini') # 程序配置文件 -push_messages_db_file = os.path.join(parent_dir, 'data', 'push_messages.db') -all_ethscription_db_file = os.path.join(parent_dir, 'data', 'all_ethscription.db') - -# 设置数据库 -push_messages_conn = sqlite3.connect(push_messages_db_file) -push_messages_cur = push_messages_conn.cursor() - -# 使用你的Ethereum节点的RPC地址 -infura_api_key_eths = os.environ.get('infura_api_key_eths', '') -w3 = Web3(Web3.HTTPProvider(infura_api_key_eths)) - -# 设置 telegram api -telegram_bot_token = os.environ.get('telegram_bot_token', '') -telegram_channel_id = "@ethspush" -telegram_base_url = f"https://api.telegram.org/bot{telegram_bot_token}" - -thread_id = 0 -executor = ThreadPoolExecutor(max_workers=10) - -# 配置合约 ABI 文件 -with open(os.path.join(parent_dir, 'data', 'batch_contract_abi.json'), "r") as batch: - contract_abi = json.load(batch) -batch_contract = w3.eth.contract(abi=contract_abi) - -with open(os.path.join(parent_dir, 'data', 'single_contract_abi.json'), "r") as single: - contract_abi = json.load(single) -single_contract = w3.eth.contract(abi=contract_abi) - -with open(os.path.join(parent_dir, 'data', 'single_contract_old_abi.json'), "r") as single_old: - contract_abi = json.load(single_old) -single_old_contract = w3.eth.contract(abi=contract_abi) - - -# 图片 Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 通过 ID 从 all_ethscription 获取铭文内容 -def get_ethscription_by_id(ethscription_id, all_ethscription_cur): - # 执行查询语句 - all_ethscription_cur.execute("SELECT name FROM id_content WHERE ethscriptionId=?", (ethscription_id,)) - result = all_ethscription_cur.fetchone() - - # 返回结果 - if result: - return result[0] - else: - return None - - -# 获取单个 ethscription 数据 -def get_specific_ethscription(ethscription_identifier): - endpoint = f"/ethscriptions/{ethscription_identifier}" - - try: - response = requests.get("https://mainnet-api.ethscriptions.com/api" + endpoint, timeout=3) - response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code - - if response.status_code == 200: - # Assuming the Content-Type is JSON - return response.json() - else: - print(f'Unexpected status code {response.status_code} for identifier: {ethscription_identifier}') - return None - - except requests.Timeout: - print(f"Request timed out for identifier: {ethscription_identifier}") - except requests.ConnectionError: - print(f"Connection error for identifier: {ethscription_identifier}") - except requests.TooManyRedirects: - print(f"Too many redirects for identifier: {ethscription_identifier}") - except requests.HTTPError as http_err: - print(f"HTTP error for identifier {ethscription_identifier}: {http_err}") - except requests.RequestException as req_err: - print(f"General error for identifier {ethscription_identifier}: {req_err}") - except Exception as e: - # Catch-all for any other unforeseen exceptions - print(f"An unexpected error occurred for identifier {ethscription_identifier}: {e}") - - return None # Ensure the function always returns a value even in the case of an error - - -def send_message_to_channel(text): - url = f"{telegram_base_url}/sendMessage" - payload = { - "chat_id": telegram_channel_id, - "text": text - } - - response = requests.post(url, data=payload) - - if response.status_code == 200: - return response.json() - else: - return None - - -def send_pushover_notification(token, user_key, message, title): - - url = "https://api.pushover.net/1/messages.json" - - data = { - "token": token, - "user": user_key, - "message": message, - "title": title - } - - response = requests.post(url, data=data) - - if response.status_code == 200: - return response.json() - else: - return None - - -def send_message_to_channel_wrapper(text): - return send_message_to_channel(text) - - -def send_pushover_notification_wrapper(token, user_key, message, title): - return send_pushover_notification(token, user_key, message, title) - - -def get_push_data(): - push_messages_w_conn = sqlite3.connect(push_messages_db_file) - push_messages_w_cur = push_messages_w_conn.cursor() - all_ethscription_conn = sqlite3.connect(all_ethscription_db_file) - all_ethscription_cur = all_ethscription_conn.cursor() - - with ThreadPoolExecutor() as executor: - - while True: - block_number = w3.eth.block_number - # block_number = 18205797 - block = w3.eth.get_block(block_number, full_transactions=True) - transactions = block['transactions'] - for tx in transactions: - query = "SELECT EXISTS(SELECT 1 FROM messages WHERE hash=?)" - push_messages_w_cur.execute(query, (str(tx['hash'].hex()),)) - exists = push_messages_w_cur.fetchone()[0] - if not exists: - if tx['to'] == '0x57b8792c775D34Aa96092400983c3e112fCbC296': - if tx['value'] >= 1: - if tx['input'][:10] == '0xd2234424' or tx['input'][:10] == '0xd92a1740': - try: - if tx['input'][:10] == '0xd2234424': - data = single_old_contract.decode_function_input(tx['input']) - if tx['input'][:10] == '0xd92a1740': - data = single_contract.decode_function_input(tx['input']) - - params = data[1] - # Handle bytes data - for key, value in params.items(): - if isinstance(value, bytes): - params[key] = value.hex() - # 获取并处理订单数据 - order = params.get('order', {}) - if order: # 确保order不为空 - for key in ['ethscriptionId', 'r', 's', 'params']: - if key in order: # 确保键在order中 - order[key] = order[key].hex() - - ethscription = get_ethscription_by_id(f'0x{order["ethscriptionId"]}', all_ethscription_cur) - if ethscription: - ethscription = get_specific_ethscription() - if ethscription['collections']: - name = ethscription['collections'][0]['name'] - else: - name = ethscription['content_uri'] - if len(name) > 128: - name = ethscription['ethscription_number'] - msg_title = f"ETCH new order: {float(order['price']) / 1e18} ETH" - msg_text = f""" - Etch 新的单笔大额订单 - 时间:{datetime.fromtimestamp(block['timestamp'])} - 铭文:{name} - 数量:{order['quantity']} - 单价:{float(order['price']) / 1e18 / order['quantity']} - 金额:{float(order['price']) / 1e18} - 买家:{tx['from']} - 卖家:{order['signer']} - 链接:{'https://etherscan.io/tx/' + tx['hash'].hex()} - """ - # response = send_message_to_channel(msg_text) - telegram_future = executor.submit(send_message_to_channel_wrapper, msg_text) - pushover_future = executor.submit(send_pushover_notification_wrapper, pushover_api_token, pushover_user_token, msg_text, msg_title) - - telegram_response = telegram_future.result() - pushover_response = pushover_future.result() - - push_messages_w_cur.execute(''' - INSERT INTO messages (time, title, hash) VALUES (?, ?, ?) - ''', (str(datetime.fromtimestamp(block['timestamp'])), str(msg_title), str(tx['hash'].hex()))) - push_messages_w_conn.commit() - except Exception as e: - print(f"Error processing transaction {tx['hash'].hex()}: {e}") - - if tx['to'] == '0x941Bc2E04A776d436E183Fe4204Bb84FeBA564D3': - if tx['value'] >= 1: - if tx['input'][:10] == '0x3bb23351': - try: - data = batch_contract.decode_function_input(tx['input']) - params = data[1] - # Handle bytes data - for key, value in params.items(): - if isinstance(value, bytes): - params[key] = value.hex() - # 获取并处理订单数据 - orders_data = params.get('orders', []) - for order in orders_data: - for key in ['ethscriptionId', 'r', 's', 'params']: - order[key] = order[key].hex() - - msg_title = f"ETCH new order: {float(tx['value']) / 1e18} ETH" - msg_text = f""" - Etch 新的批量大额订单 - 时间:{datetime.fromtimestamp(block['timestamp'])} - 金额:{float(tx['value']) / 1e18} - 买家:{tx['from']} - 链接:{'https://etherscan.io/tx/' + tx['hash'].hex()} - """ - # response = send_message_to_channel(msg_text) - telegram_future = executor.submit(send_message_to_channel_wrapper, msg_text) - pushover_future = executor.submit(send_pushover_notification_wrapper, pushover_api_token, pushover_user_token, msg_text, msg_title) - - telegram_response = telegram_future.result() - pushover_response = pushover_future.result() - - push_messages_w_cur.execute(''' - INSERT INTO messages (time, title, hash) VALUES (?, ?, ?) - ''', ( - str(datetime.fromtimestamp(block['timestamp'])), str(msg_title), str(tx['hash'].hex()))) - push_messages_w_conn.commit() - except Exception as e: - print(f"Error processing transaction {tx['hash'].hex()}: {e}") - - time.sleep(10) - - -# Streamlit app layout -st.set_page_config(page_title="EthPen - 推送通知服务", page_icon="📢", layout='centered', initial_sidebar_state='auto') -st.markdown(f'# Image :rainbow[推送通知服务]', unsafe_allow_html=True) -st.subheader(r'', anchor=False, divider='rainbow') -st.error('开发中,仅供参考...') -st.error('若您有更好的建议或想法,请随时与我取得联系。') -st.markdown('### 订阅服务') -push_service_option = st.radio("选择通知的服务:", ['Telegram', 'Pushover', 'Bark', 'Server 酱', 'PushDeer', '钉钉', '企业微信', '飞书', 'Discord', '短信', '电话'], index=0, - horizontal=True, disabled=True) -col1, col2 = st.columns(2) -# 在第一个列中添加文本输入框 -text_input = col1.text_input("API Keys:", label_visibility='collapsed', disabled=True) -# 在第二个列中添加按钮 -button_clicked = col2.button("订阅", disabled=True) -st.markdown(f'''{my_style}Image Pushover - EthPen.com -Image @ethspush -''', unsafe_allow_html=True) -st.markdown('考虑到通知的时效性及操作的便捷性,暂不支持个人定制服务,且推送的触发条件为合约交易金额大于等于 1ETH。目前我们只开放了 Telegram 频道和 Pushover 作为通知方式。欢迎各位订阅并体验推送服务。') - -st.markdown('### 最近消息') -with sqlite3.connect(push_messages_db_file) as conn: - recent_messages = pd.read_sql_query("SELECT time, title, hash FROM messages ORDER BY time DESC LIMIT 10;", conn) -st.dataframe(recent_messages, use_container_width=True, hide_index=True) - -config = configparser.ConfigParser() -config.read(config_ini_file) -thread_start_state_value = config['push_thread_start_state']['state'] -if thread_start_state_value == '0': - print('消息推送线程未启动。') - config['push_thread_start_state']['state'] = '1' - with open(config_ini_file, 'w') as configfile: - config.write(configfile) - - # 创建线程对象 - push_thread = threading.Thread(target=get_push_data) - push_thread.start() - push_thread.join() - -else: - print('消息推送线程已经启动。') diff --git "a/pages/7_\342\204\271\357\270\217\357\270\217_EthPen.com \347\256\200\344\273\213.py" "b/pages/7_\342\204\271\357\270\217\357\270\217_EthPen.com \347\256\200\344\273\213.py" deleted file mode 100644 index 8fcc532059ca22a5852a74271338555c9b11ee54..0000000000000000000000000000000000000000 --- "a/pages/7_\342\204\271\357\270\217\357\270\217_EthPen.com \347\256\200\344\273\213.py" +++ /dev/null @@ -1,97 +0,0 @@ -import streamlit as st -import base64 -import os -import shutil - -my_style = ''' - -''' - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 压缩文件 -def zip_directory(directory_path, output_filename): - # 创建一个zip文件 - shutil.make_archive(output_filename, 'zip', directory_path) - return output_filename + ".zip" - - -# Streamlit app layout -st.set_page_config(page_title="EthPen - EthPen.com 简介", page_icon="ℹ️", layout='centered', - initial_sidebar_state='auto') -st.markdown(f'# Image :rainbow[EthPen.com 简介]', unsafe_allow_html=True) -st.subheader(r'', anchor=False, divider='rainbow') - -st.markdown( - f'欢迎踏足 EthPen - 以太之笔!这里汇聚了一系列关于 Ethscriptions 的精细工具集,无论是单一查询、铭文题写,还是批量检索、编码题写,乃至深入的教程导引、数据分析等,以太之笔都将助您铭文题写如飞。我们立志推广 Ethscriptions 的宏大理念,期望 $eths 翱翔于星空,与月相伴!若您携手建议或创意,我们热切期待您的声音。', - unsafe_allow_html=True) -st.markdown(r'## :rainbow[EthPen 题写铭文的好帮手!]') -st.markdown('') -st.markdown( - '顺便提一句,我是 pztuya。这个网站的所有内容都是我一手打造的。由于能力和时间所限,内容更新的速度可能较慢,甚至程序出错导致你的资金出现问题,我也是需要用户反馈后才去修改,希望您能理解。谢谢您的支持与耐心 😊~') - -st.markdown( - f'''{my_style}Image @pztuya -Image @NervosCKB -''', unsafe_allow_html=True) - -st.markdown( - f'''# Image @Ethscriptions -''', unsafe_allow_html=True) - -st.markdown('### 更新记录') -st.markdown('- 2023 年 8 月 28 日以前,项目上线,多种优化。') -st.markdown('- 2023 年 9 月 26 日,增加推送通知服务功能') -st.markdown('- 2023 年 9 月 26 日,增加更多的数据分析功能') -st.markdown('### 更新计划') -st.markdown('1. 添加链接 Metamask 钱包功能') -st.markdown('2. 添加 Metamask 钱包题写铭文功能') -st.markdown('3. 增加教程中心的多种教程') -st.markdown('4. 页面优化、代码优化') - - -# 下载所有文件 -st.markdown('### 下载数据库和配置文件') -database_download_password = os.environ.get('database_download_password', 'get_error') -col1, col2 = st.columns(2) -database_dl_pw_text_input = col1.text_input("输入密码:", label_visibility='collapsed') -database_dl_pw_button = col2.button("提交") -if database_dl_pw_button: - if database_dl_pw_text_input == database_download_password: - current_dir = os.path.dirname(__file__) - parent_dir = os.path.dirname(current_dir) - ethpen_data_file = os.path.join(parent_dir, 'data') - zipped_file = zip_directory(ethpen_data_file, "zipped_directory") - with open(zipped_file, "rb") as file: - bytes_data = file.read() - st.download_button( - label="下载文件", - data=bytes_data, - file_name="EthPen_data.zip", - mime="application/zip" - ) - os.remove(zipped_file) # 删除临时创建的zip文件 - else: - st.markdown('暂时未开放下载,密码输入错误,请重试。') diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index d6ba522ac4b33c79486b4eeaf3ff797ec8e2388f..0000000000000000000000000000000000000000 --- a/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -pandas==2.0.3 -pytz==2023.3 -Requests==2.31.0 -streamlit==1.26.0 -web3==6.6.1 diff --git a/video/.DS_Store b/video/.DS_Store deleted file mode 100644 index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..0000000000000000000000000000000000000000 Binary files a/video/.DS_Store and /dev/null differ diff --git "a/\360\237\226\212\357\270\217EthPen-\344\273\245\345\244\252\344\271\213\347\254\224.py" "b/\360\237\226\212\357\270\217EthPen-\344\273\245\345\244\252\344\271\213\347\254\224.py" deleted file mode 100644 index 4769f7cd9edc195ee7a9ed5d1ed9736843dda001..0000000000000000000000000000000000000000 --- "a/\360\237\226\212\357\270\217EthPen-\344\273\245\345\244\252\344\271\213\347\254\224.py" +++ /dev/null @@ -1,413 +0,0 @@ -import streamlit as st -import requests -import re -import json -import hashlib -import base64 -import sqlite3 -import os - - -infura_api_key_eths = os.environ.get('infura_api_key_eths', '') -# Ethscriptions Mainnet API 的基础 URL -BASE_URL = "https://mainnet-api.ethscriptions.com/api" - -# 获取当前文件目录 -current_dir = os.path.dirname(os.path.abspath(__file__)) - -# 构造数据库文件路径 -eths_db_file = os.path.join(current_dir, 'data', 'eths_data.db') - -# Initialize connection to SQLite database -conn = sqlite3.connect(eths_db_file) -c = conn.cursor() - -# Create table to store ETHS data -c.execute(''' - CREATE TABLE IF NOT EXISTS eths_data - (date text, - eth_price real, - eths_price real, - eths_market_cap integer, - eths_owners integer, - eths_volume24h real, - eths_totalLocked integer, - eths_stakers integer, - eths_tvl real) - ''') - -# 查询地址所属代币铭文的 token 列表 -token_list = [{'p': 'erc-20', 'tick': 'eths', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'gwei', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'ercs', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'etch', 'id': 21000, 'amt': '1000'}, - {'p': 'erc-20', 'tick': 'dumb', 'id': 21000, 'amt': '1000'}] - -my_style = ''' - -''' - - -# 图片Base64 -def image_to_base64(img_path): - with open(img_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode() - - -# 验证代币铭文函数 -def is_valid_eths(data, p, tick, id, amt): - # 构建匹配1到id-1的正则表达式 - pattern_range = "|".join([str(i) for i in range(1, id)]) - # 使用 f-string 插入参数到正则表达式 - pattern = rf'^data:,{{"p":"{p}","op":"mint","tick":"{tick}","id":"({pattern_range}|{id})","amt":"{amt}"}}$' - return bool(re.match(pattern, data)) - - -# 文本转换到十六进制 -def text_to_hex(text): - return '0x' + ''.join(format(byte, '02x') for byte in text.encode('utf-8')) - - -# str SHA256 -def sha256(input_string): - sha256 = hashlib.sha256() - sha256.update(input_string.encode('utf-8')) - return sha256.hexdigest() - - -# 根据 TX 获取 input data -def get_input_data(tx_hash): - endpoint = infura_api_key_eths - headers = { - "Content-Type": "application/json", - } - data = { - "jsonrpc": "2.0", - "id": 1, - "method": "eth_getTransactionByHash", - "params": [tx_hash] - } - eth_transaction = requests.post(endpoint, headers=headers, data=json.dumps(data)) - transaction_data = eth_transaction.json() - return transaction_data['result']['input'] - - -# 获取所有的 ethscriptions -def get_all_ethscriptions(page=None, per_page=None, sort_order=None): - endpoint = "/ethscriptions" - params = { - "page": page, # 页码 - "per_page": per_page, # 每页的数量 - "sort_order": sort_order # 排序顺序 - } - response = requests.get(BASE_URL + endpoint, params=params) - return response.json() - - -# 根据地址获取 ethscriptions -def get_ethscriptions_by_address(address): - all_ethscriptions = [] - page = 1 - per_page = 100 - while True: - endpoint = f"/ethscriptions/owned_by/{address}" - params = { - "page": page, - "per_page": per_page, - "sort_order": 'asc' - } - response = requests.get(BASE_URL + endpoint, params=params) - if response.status_code != 200: - print(f"Error fetching data: {response.text}") - break - ethscriptions = response.json() - all_ethscriptions.extend(ethscriptions) - if len(ethscriptions) < per_page: - break - page += 1 - return all_ethscriptions - - -# 使用ID或数字获取特定的 ethscription -def get_specific_ethscription(ethscription_identifier): - endpoint = f"/ethscriptions/{ethscription_identifier}" - response = requests.get(BASE_URL + endpoint) - return response.json() - - -# 获取特定 ethscription 的数据 -def get_ethscription_data(ethscription_identifier): - endpoint = f"/ethscriptions/{ethscription_identifier}/data" - response = requests.get(BASE_URL + endpoint) - return response.json() - - -# 使用 SHA256 值检查内容是否已被 ethscribed -def check_content_exists(sha): - endpoint = f"/ethscriptions/exists/{sha}" - response = requests.get(BASE_URL + endpoint) - if response.status_code == 200: - return response.json() - - -# 确定索引器是否落后 -def get_block_status(): - endpoint = "/block_status" - response = requests.get(BASE_URL + endpoint) - return response.json() - - -# 获取 $eths 价格 -def get_eths_price(): - params = { - 'category': 'token', - 'collectionName': 'erc-20 eths', - } - - response = requests.get( - 'https://www.etch.market/api/markets/collections/details', - params=params - ) - if response.status_code == 200: - response = response.json() - if response['message'] == 'success': - return response['data'] - return {} # 返回一个空字典作为默认值 - - -# 从 etch.market 那里获取用户地址代币余额 -def get_etch_token_amt(): - params = { - 'category': 'token', - 'tokenQuery': '', - } - - response = requests.get( - 'https://www.etch.market/api/markets/ethscriptions/collections/0x59724739940777947c56C4f2f2C9211cd5130FEf', - params=params - ) - if response.status_code == 200: - response = response.json() - if response['message'] == 'success': - return response['data'] - return {} # 返回一个空字典作为默认值 - - -# 获取 $eths 质押数据 -def get_eths_staking(): - response = requests.get('https://www.etch.market/api/staking/statistics/erc-20%20eths') - if response.status_code == 200: - response = response.json() - if response['message'] == 'success': - return response['data'] - return {} # 返回一个空字典作为默认值 - - -st.set_page_config(page_title="EthPen - 以太之笔", page_icon="🖊", layout='centered', initial_sidebar_state='auto') - -# 首页 -st.markdown( - f'# Image :rainbow[EthPen - 以太之笔]', - unsafe_allow_html=True) -st.subheader('', anchor=False, divider='rainbow') - -# 最近新闻 -st.markdown(f'### 最近新闻') - -st.markdown( - f'Image', - unsafe_allow_html=True) - - -st.markdown(f'> 3 周前,我们提出了 Ethscriptions 虚拟机的构想——一种通过将其解释为计算机指令来显著增强 Ethscriptions 功能的方法。今天,我们宣布了该虚拟机的首个实现。已在 Goerli 网络上线,并已在 GitHub 上完全开源!👆') - -# 广告位图片 -st.markdown(f'### 广告位') - - -# st.markdown( -# f'Image', -# unsafe_allow_html=True) -# -# st.markdown(f'> 拆分方案现在面向所有人推出!让我们一起加入权益挖矿的浪潮,并分享50%的月度服务费。') -st.markdown(f'😭 接不到广告,我太穷了。') - -st.markdown( - f'Image', - unsafe_allow_html=True) -st.markdown('') -st.markdown(f'复制 845076800。 打开支付宝搜索,赏我一个猪脚饭。🥺', unsafe_allow_html=True) - -st.markdown(f'### 什么是 Ethscriptions?', unsafe_allow_html=True) -st.markdown(f'{my_style}Image Ethscriptions 是一种新的在以太坊上创建和分享数字资产的方法,它通过使用交易 calldata 存储数据而不是智能合约来实现,这使其比 NFT 更为经济。它们是完全在链上、无需许可、抗审查的,并且其成本只是 NFT 的一小部分。', unsafe_allow_html=True) - -st.markdown(f'Image', unsafe_allow_html=True) -st.markdown('') -st.markdown('### 谁创造了 Ethscriptions?') -st.markdown(f'首个 [Ethscription](https://ethscriptions.com/ethscriptions/0) 是在 2016 年创建的,但正式的协议是由 Tom Lehman,又名 Image @Middlemarch 开发的。除了比特币的铭文,他还受到了来自 Poly Network 黑客的著名的 “原型 - Ethscription” 的启发,你可以在[这笔交易](https://etherscan.io/tx/0x0ae3d3ce3630b5162484db5f3bdfacdfba33724ffb195ea92a6056beaa169490)中看到它。', unsafe_allow_html=True) -st.markdown(f'- 快来加入 Image @ethscriptions,一起讨论 Ethscriptions 的未来!', unsafe_allow_html=True) -st.markdown(f'- 快来关注 Image @ethscriptions,掌握 Ethscriptions 的最新动态!', unsafe_allow_html=True) -st.markdown('### 如何题写 Ethscriptions?') -st.markdown(f'题写 Ethscriptions 是十分简单的,相当于在发送 ETH 交易时附带一些转账备注,我们就以使用人数最多的 MetaMask 钱包来举例,我们首先打开Image 显示十六进制数据。', unsafe_allow_html=True) -st.markdown(f'1. 打开 Image Metamask 钱包(如果已安装);', unsafe_allow_html=True) -st.markdown(f'2. 在右上角点击打开 Image 菜单栏;', unsafe_allow_html=True) -st.markdown(f'3. 点击打开 Image 设置项;', unsafe_allow_html=True) -st.markdown(f'4. 点击打开 Image 高级设置;', unsafe_allow_html=True) -st.markdown(f'5. 点击打开 Image 显示十六进制数据。', unsafe_allow_html=True) -st.markdown(f'然后让我们构思一下我们心仪的铭文,我们需要把铭文的文本转换成十六进制形式的数据,在下方文本框输入。', unsafe_allow_html=True) - -input_ethscriptions_str = st.text_input('默认以 `data:,` 开头,输入需要转换的文本:', key='输入需要转换的文本') -if st.button('转换', key='文本转换到十六进制形式'): - if not input_ethscriptions_str.startswith('data:,'): - input_ethscriptions_str = f'data:,{input_ethscriptions_str}' - input_ethscriptions_hex = text_to_hex(input_ethscriptions_str) - input_ethscriptions_sha = sha256(input_ethscriptions_str) - ethscriptions_data = check_content_exists(input_ethscriptions_sha) - if ethscriptions_data['result']: - st.markdown(f'☹️ :green[{input_ethscriptions_str}] 已经被题写!相关信息如下:') - selected_data = { - '当前拥有者': ethscriptions_data["ethscription"]["current_owner"], - '题写时间': ethscriptions_data["ethscription"]["creation_timestamp"], - '铭文编号': f'#{ethscriptions_data["ethscription"]["ethscription_number"]}', - '铭文完整内容': ethscriptions_data["ethscription"]["content_uri"], - } - st.json(selected_data) - else: - - st.markdown(f'😄 :green[{input_ethscriptions_str}] 还没被题写!快复制下方文本前去题写吧。') - st.code(input_ethscriptions_hex[2:], line_numbers=False) - -st.markdown(f'好,让我们发送一笔交易吧,这笔交易是自己给自己发送 0ETH 的交易。', unsafe_allow_html=True) -st.markdown(f'1. 点击发送 Image 发送交易;', unsafe_allow_html=True) -st.markdown(f'2. 接收地址填写 Image 自己的地址,这是铭文接收的地址,然后金额填写为 0ETH;', unsafe_allow_html=True) -st.markdown(f'3. 填写 Image 十六进制数据,也就是我们刚才复制的文本;', unsafe_allow_html=True) -st.markdown(f'4. 检查确认无误后发送交易。', unsafe_allow_html=True) -st.markdown(f'稍等片刻,我们就可以在 Image Etherscan 区块浏览器看到成功的交易。', unsafe_allow_html=True) -st.markdown(f'Image', unsafe_allow_html=True) -st.markdown('') - -st.markdown('我们可以输入铭文文本查询详细的信息,') -col1, col2 = st.columns(2) -ethscriptions_str = col1.text_input('输入完整的铭文文本:', '', label_visibility='collapsed') -search_information = col2.button('🔍 查询', key='查询信息') -if search_information: - if not ethscriptions_str.startswith('data:,'): - ethscriptions_str = f'data:,{ethscriptions_str}' - ethscriptions_all_str = sha256(ethscriptions_str) - ethscriptions_data = check_content_exists(ethscriptions_all_str) - if ethscriptions_data['result']: - st.markdown(f'###### :green[{ethscriptions_str}] 相关信息如下:') - selected_data = { - '当前拥有者': ethscriptions_data["ethscription"]["current_owner"], - '题写时间': ethscriptions_data["ethscription"]["creation_timestamp"], - '铭文编号': f'#{ethscriptions_data["ethscription"]["ethscription_number"]}', - '铭文完整内容': ethscriptions_data["ethscription"]["content_uri"], - } - st.json(selected_data) - else: - st.markdown(f'###### :green[{ethscriptions_str}] 铭文还没被题写!复制下方文本前去题写。') - st.code(f'{text_to_hex(ethscriptions_str)}', line_numbers=False) - -st.markdown(f'同时我们也可以前往 Image Ethscriptions 官方网站查看我们的铭文。', unsafe_allow_html=True) -st.markdown(f'如果你觉得上述的方法步骤繁琐,我们建议你使用 Ethscriptions 官方推荐的 [EthScriber](https://ethscriber.xyz/) 还有 [Etherscan IDM](https://etherscan.io/idm),其他题写工具须在你确保安全的情况下使用,因为你不能确定它要发送什么铭文的交易。', unsafe_allow_html=True) -st.markdown(f'EthPen.com 不仅为你提供优质的工具,还有详尽的教程供你参考。欢迎你前来探索!', unsafe_allow_html=True) -st.markdown(f'🎉 更多功能尽在左上角的 Image 菜单栏', unsafe_allow_html=True) - -st.markdown('### Ethscriptions 上的龙头代币是?') -st.markdown( - f'毫无疑问,当之无愧,它必须是 Ethscriptions 上第一个代币 Image $eths', - unsafe_allow_html=True) - -# 查询eths_data表中所有数据 -c.execute('SELECT * FROM eths_data') -# 获取所有结果 -eths_data = c.fetchall() - -# 定义卡片样式 -eths_card_style = """ - -""" -st.markdown(eths_card_style, unsafe_allow_html=True) -# 创建卡片的HTML内容 -eths_card_content = f""" -
- Image -

-
- Image -
-

Ethscriptions eths

-

${eths_data[0][2]:.2f}

-
-
-

市值:${eths_data[0][3]:,.0f}

-

总量:21,000,000

-

24h 交易量:${eths_data[0][5]:,.0f}

-

24h 交易所:Image Etch Market

-
INFO
-

官网:None

-

浏览器:Image Ethscriptions

-

Ethscription ID:Image 0x463654......bed2e4

-

部署时间:2023/06/18 05:46:11

-

公链:Ethereum Ethscriptions

-

持有人数:{eths_data[0][4]:,.0f}

-

社交:Image @ethscriptions Image @ethscriptions

-
Staking
-

质押总量:{eths_data[0][6]:,.0f} $eths

-

质押人数:{eths_data[0][7]:,.0f}

-

TVL:${eths_data[0][8]:,.0f}

-

立即买入 $eths

-
-""" -st.markdown(eths_card_content, unsafe_allow_html=True)