【Mquant】9:python批量铭刻erc-20铭文

文章目录

  • 1. ETHS铭文
  • 2.批量查询是否被mint
  • 3. 批量mint


1. ETHS铭文

ETHS铭文是以太坊铭文协议Ethscriptions的代币名称。Ethscriptions是一个基于以太坊的铭文协议,允许用户在以太坊主网上刻入不同类型的文件,并将其记录到区块中。ETHS作为Ethscriptions的第一个"概念币",引起了人们的关注和热议。

以太坊铭文协议Ethscriptions的特点包括:

  1. 使用交易调用数据在以太坊上创建和共享数字藏品的新协议[1]。
  2. 利用以太坊calldata进行铭文创作,相比使用合约储存更便宜、去中心化,并且能够保证所有有效内容的全球唯一性。
  3. 铭文的大小不能超过96KB。

ETHS铭文的铸造方式相对简单,以下是一个示例的铸造步骤:

  1. 复制代码:data:,{“p”:“erc-20”,“op”:“mint”,“tick”:“eths”,“id”:“21000以内的任意数字”,“amt”:“1000”}。
  2. 将这串代码进行转码,转为16进制。
  3. 打开钱包,向自己的地址转入0ETH,并将转码获得的16进制填写。
  4. 确认付款,完成代币的铸造。

需要注意的是,ETHS铭文的共识承认只限于编号在21000以内的铭文,而且对于重复被打的编号,只有最先被打的那张ETHS铭文会被承认。

2.批量查询是否被mint

首先安装包:

pip install requests
import hashlib
import json

import requests
import threading


def query_content(content):
    content1 = "data:," + content
    sha256_hash = hashlib.sha256(content1.encode()).hexdigest()

    url = f"https://eth-script-indexer-eca25c4cf43b.herokuapp.com/api/ethscriptions/exists/{sha256_hash}"

    try:
        response = requests.get(url)

        if response.status_code == 200:
            result = response.json()
            if result['result']:
                # owner = result['ethscription']['current_owner']
                # creator = result['ethscription']['creator']
                # creation_timestamp = result['ethscription']['creation_timestamp']
                #
                # # 转换时间格式为易读形式
                # creation_timestamp = datetime.datetime.strptime(
                #     creation_timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
                #
                return -1
            else:
                # hex_content = binascii.hexlify(content.encode()).decode()
                # print(f"\n'{content}'的铭文内容尚未被铭刻。")
                # print(f"该铭文文本(含data:,)的16进制输出为:{hex_content}")
                return json.loads(content)["id"]
        else:
            print(f"\n获取'{content}'的数据失败,请检查你的输入是否正确。")
    except requests.exceptions.RequestException as e:
        print(f"\n发送请求时遇到错误: {e}")


def main(name, id_min, id_max):
    ids = []
    lock = threading.Lock()

    def process_content(name, id):
        content = '{"p":"erc-20","op":"mint","tick":"' + name + '","id":"' + str(number) + '","amt":"1000"}'
        id = query_content(content)
        with lock:
            ids.append(id)

    # 创建线程列表
    threads = []
    for number in range(id_min, id_max):
        thread = threading.Thread(target=process_content, args=(name, number,))
        threads.append(thread)
        thread.start()

        # 限制线程数量为20
        if len(threads) >= 20:
            # 等待前面的线程完成
            for t in threads:
                t.join()
            threads = []

    # 等待剩余线程完成
    for thread in threads:
        thread.join()

    # 过滤掉值为-1的元素
    ids = list(filter(lambda x: x != -1, ids))
    print("未打铭文列表:",ids)


if __name__ == '__main__':
    id_min = int(input("请输入查询id范围下限:"))
    id_max = int(input("请输入查询id范围上限:"))
    name = input("输入铭文名称:")
    main(name, id_min, id_max)

【Mquant】9:python批量铭刻erc-20铭文_第1张图片

3. 批量mint

安装web3包

pip install web3 eth_account
import hashlib
import threading
import time

from web3 import Web3, HTTPProvider
from eth_account import Account
import concurrent.futures
import requests
from eth_account.signers.local import LocalAccount
import binascii


def string_to_hex(string):
    return '0x' + binascii.hexlify(string.encode()).decode()


def query_domain(content):
    content_ = "data:," + content
    sha256_hash = hashlib.sha256(content_.encode()).hexdigest()

    url = f"https://eth-script-indexer-eca25c4cf43b.herokuapp.com/api/ethscriptions/exists/{sha256_hash}"

    try:
        response = requests.get(url)
        if response.status_code == 200:
            result = response.json()
            if result['result']:
                print(content, "不能被mint")
                return False
            else:
                print(content, "可以mint")
                return True
        else:
            print(f"\n获取'{content}'的数据失败,请检查你的输入是否正确。")
    except requests.exceptions.RequestException as e:
        print(f"\n发送请求时遇到错误: {e}")


def mint_ethscriptions(w3, wallet, to_address, private_key, content):
    nonce = w3.eth.get_transaction_count(wallet.address)
    # 获取当前燃气价格
    gas_price = w3.eth.gas_price
    hex_data_URI = string_to_hex("data:," + content)
    tx = {
        'to': to_address,
        'value': w3.to_wei(0, 'ether'),  # 发送的以太币数量
        'data': hex_data_URI,
        'nonce': nonce,
        'gas': 30000,  # 估算的燃气量
        'gasPrice': gas_price,
        'chainId': 1,  # 主网的链ID
    }
    # 使用私钥进行交易签名
    # signed_transaction = w3.eth.account.sign_transaction(tx, private_key)
    # tx_hash = w3.eth.send_raw_transaction(signed_transaction.rawTransaction)
    # print(f'Transaction hash: {tx_hash.hex()}')
    #
    # tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    # print(f'Transaction was confirmed in block {tx_receipt["blockNumber"]}')
    print('Done')


def main(private_key, name, id_min, id_max):
    w3 = Web3(HTTPProvider("https://rpc.ankr.com/eth"))
    wallet: LocalAccount = Account.from_key(private_key)
    count = 0  # 计数器
    count_lock = threading.Lock()  # 创建锁对象

    def process_id(name, number):
        global count
        content = '{"p":"erc-20","op":"mint","tick":"' + name + '","id":"' + str(number) + '","amt":"1000"}'
        flag = query_domain(content)
        if flag:
            with count_lock:
                if count < 100:
                    mint_ethscriptions(w3, wallet, wallet.address, private_key, content)
                    count += 1

    with concurrent.futures.ThreadPoolExecutor() as executor:
        ids = range(id_min, id_max)
        names = [name] * len(ids)
        for i in range(0, len(ids), 20):
            batch_ids = ids[i:i + 20]
            batch_names = names[i:i + 20]
            executor.map(process_id, batch_names, batch_ids)
            time.sleep(10)  # 休息60秒


if __name__ == '__main__':
    private_key = input("请输入钱包私钥:")
    name = input("请输入要mint的铭文名字:")
    id_min = int(input("请输入铭文编号下限:"))
    id_max = int(input("请输入铭文编号上限:"))
    main(private_key, name, id_min, id_max)

【Mquant】9:python批量铭刻erc-20铭文_第2张图片

有问题欢迎私聊,可+量化交易~裙,领取量化交易资料

你可能感兴趣的:(量化,python,区块链,开发语言)