10 python使用Web3.py库验证BSC智能合约代码,返回码200,但并未验证成功

如题,我写了个python脚本想自动化创建代币和验证代币智能合约代码,在脚本post合约代码数据验证bsc智能合约代码时,返回状态码200,但是浏览器查看该合约,并未进行验证。请大佬们帮忙看下怎么回事?

# 发布智能合约到链上并验证合约代码
def DeployContract():
    # 1.读取智能合约代码,从智能合约代码中提取solidity版本
    # 2.替换合约名称,代币名称,代币数量
    # 3.编译智能合约
    # 4.部署智能合约到链上
    # 5.验证合约代码
    # 6.获取部署成功的合约地址

    PRIVATE_KEY = 'eewqrewqrewq'

    # 1.读取智能合约代码,从智能合约代码中提取solidity版本
    with open(f"../AAA_Contract/314_contract.sol", 'r') as f:
        src = f.readlines()
        print(src, type(src))
    Version = '0.8.19'
    print(Version)

    # 2.替换合约名称,代币名称,代币数量
    with open("../AAA_Contract/314_contract.sol", 'r') as f:
        contract_code = f.read()
        print(contract_code, type(contract_code))

    TokenName = "sss314"
    TokenSymbol = "sss314"
    TokenTotalSupply = "38880000000"

    contract_name = "sss_314"

    # 正则表达式匹配合约名称
    contract_name_pattern = r'(?<=contract )\w+(?= is Context, IERC20, IERC20Metadata, Ownable, IEERC314)'
    # 替换合约名称
    contract_code = re.sub(contract_name_pattern, contract_name, contract_code)

    # 正则表达式匹配 _name, _symbol 和 totalSupply_ 变量的赋值
    name_pattern = r'(_name\s*=\s*")[^"]*(";)'
    symbol_pattern = r'(_symbol\s*=\s*")[^"]*(";)'
    total_supply_pattern = r'(uint256\s+totalSupply_\s*=\s*)\d+'

    # 替换变量值
    contract_code = re.sub(name_pattern, r'\g<1>' + TokenName + r'\2', contract_code)
    contract_code = re.sub(symbol_pattern, r'\g<1>' + TokenSymbol + r'\2', contract_code)
    contract_code = re.sub(total_supply_pattern, r'\g<1>' + TokenTotalSupply, contract_code)
    print(contract_code, type(contract_code))

    # 将修改后的合约代码存储为新文件
    with open(f"../AAA_Contract/{TokenName}.sol", 'w', encoding='utf-8') as f:
        f.write(contract_code)

    # 3.编译智能合约获取bytecode
    install_solc(Version)  # 选择编译器版本
    compiled_sol = compile_standard(
        {
            "language": "Solidity",
            "sources": {f"{TokenName}.sol": {"content": contract_code}},
            "settings": {
                "outputSelection": {
                    "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]}
                }
            },
        },
        solc_version=Version,
    )
    bytecode = compiled_sol["contracts"][f"{TokenName}.sol"][contract_name]["evm"]["bytecode"]["object"]
    print(bytecode)

    # 获取合约ABI
    abi = compiled_sol["contracts"][f"{TokenName}.sol"][contract_name]["abi"]

    # 4.部署智能合约
    web3.eth.default_account = web3.eth.account.privateKeyToAccount(PRIVATE_KEY).address
    DeployContractNow = web3.eth.contract(abi=abi, bytecode=bytecode)

    # 构建交易
    transaction = DeployContractNow.constructor().build_transaction({
        'chainId': 97,
        'gas': 5000000,
        'gasPrice': web3.to_wei('5', 'gwei'),
        'nonce': web3.eth.get_transaction_count(web3.eth.default_account),
    })

    # 签署交易
    signed_txn = web3.eth.account.sign_transaction(transaction, private_key=PRIVATE_KEY)

    # 发送交易
    tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
    tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

    # 获取已发布合约的地址
    contract_address = tx_receipt.contractAddress
    print(contract_address)

    # 5.验证合约代码
    BSCScanApi = 'sdfds'
    BSCScanURL = 'https://api-testnet.bscscan.com/api'

    data = {
        'apikey': BSCScanApi,
        'module': 'contract',
        'action': 'verifysourcecode',
        'contractaddress': contract_address,
        'sourceCode': contract_code,
        'codeformat': 'solidity-single-file',
        'contractname': f"{TokenName}",
        'compilerversion': "0.8.19+commit.7dd6d404",
        'optimizationUsed': 0,
        'runs': 200,
        'licenseType': '0',
        'evmversion': '',
    }

    result = requests.post(BSCScanURL, data=data)
    print(result.status_code)

贴上bsc官方API的文档和截图

26ff6ae17d8cc52775a06e9d6cbc76b.png

API文档链接:https://docs.bscscan.com/api-endpoints/contracts

/////////////////////////////////////分割线/////////////////////////////////////

尝试部署后,合约可以部署成功,但是验证代码时总是验证不了,返回状态码200: https://testnet.bscscan.com/address/0x80A6F648E3B240F682c67C9904062C544f6B38B1

请先 登录 后评论

最佳答案 2024-05-16 21:20

改下 然后再打印一下 result 的数据看下有没有具体的提示

    BSCScanApi = 'sdfds'
    BSCScanURL = 'https://api-testnet.bscscan.com/api'
    data = {

        'contractname': contract_name,
        'compilerversion': "v0.8.19+commit.7dd6d404",
        'optimizationUsed': '0',
        'runs': '200',
    }

    response = requests.post(BSCScanURL, data=data)
    if response.status_code == 200:
        result = response.json()
        if result['status'] == '1':
            print("Verification request successful:", result['result'])
            return result['result']
        else:
            print("Verification request failed:", result['message'], result['result'])
    else:
        print("HTTP request failed with status code:", response.status_code)

# Deploy and verify the contract
deploy_contract()
请先 登录 后评论

其它 1 个回答

Wade - Footprint Analytics CTO
  擅长:数据分析,GameFi,NFT
请先 登录 后评论
  • 1 关注
  • 0 收藏,666 浏览
  • 用户_20014 提出于 2024-05-14 21:33

相似问题