Пример #1
0
    def call(self, inputparams):
        if len(inputparams) == 0:
            sols = list_files(contracts_dir + "/*.sol")
            for sol in sols:
                print(sol + ".sol")
            return
        common.check_param_num(inputparams, 3)
        paramsname = ["contractname", "address", "func"]
        params = fill_params(inputparams, paramsname)
        contractname = params["contractname"]
        address = params["address"]
        if address == "last" or address == "latest":
            address = ContractNote.get_last(contractname)
            if address is None:
                sys.exit("can not get last address for [{}],break;".format(
                    contractname))

        tx_client = transaction_common.TransactionCommon(
            address, contracts_dir, contractname)
        fn_name = params["func"]
        fn_args = inputparams[3:]
        print("INFO>> client info: {}".format(tx_client.getinfo()))
        print("INFO >> call {} , address: {}, func: {}, args:{}".format(
            contractname, address, fn_name, fn_args))
        try:
            result = tx_client.call_and_decode(fn_name, fn_args)
            common.print_tx_result(result)

        except Exception as e:
            common.print_error_msg("call", e)
Пример #2
0
    def completion(self, prefix, parsed_args, **kwargs):
        """
        complete the shell
        """
        if parsed_args.cmd is None:
            return self.supported_cmds
        # deploy contract
        if parsed_args.cmd[0] == "deploy":
            return CommandParser.get_contracts()

        # call and sendtx
        # warn(parsed_args)
        if parsed_args.cmd[0] == "call" or parsed_args.cmd[0] == "sendtx":
            # only list the contract name
            if len(parsed_args.cmd) == 1:
                return CommandParser.get_contracts()
            # list the contract address
            if len(parsed_args.cmd) == 2:
                return ContractNote.get_contract_addresses(parsed_args.cmd[1])
            # list functions
            if len(parsed_args.cmd) == 3:
                return CommandParser.get_functions_by_contract(parsed_args.cmd[1])

        # call showaccount
        if parsed_args.cmd[0] == "showaccount":
            return CommandParser.get_accounts()
        # registerCNS [contract_name] [contract_address] [contract_version]
        if parsed_args.cmd[0] == "registerCNS":
            # list contract name
            if len(parsed_args.cmd) == 1:
                return CommandParser.get_contracts()
            # list contract address
            if len(parsed_args.cmd) == 2:
                return ContractNote.get_contract_addresses(parsed_args.cmd[1])
        # queryCNSByName [contract_name]
        if parsed_args.cmd[0] == "queryCNSByName":
            # list contract name
            if len(parsed_args.cmd) == 1:
                return CommandParser.get_contracts()
        # queryCNSByNameAndVersion [contract_name] [contract_version]
        if parsed_args.cmd[0] == "queryCNSByNameAndVersion":
            if len(parsed_args.cmd) == 1:
                return CommandParser.get_contracts()
        # sysconfig
        if parsed_args.cmd[0] == "setSystemConfigByKey" or parsed_args.cmd[0] == "getSystemConfigByKey":
            return ["tx_count_limit", "tx_gas_limit"]
        return []
Пример #3
0
 def checkContractExit(self, contract_name):
     #address = ContractNote.get_contract_addresses(contract_name)
     address = ContractNote.get_last(contract_name)
     if address is None:
         return False, None
     else:
         # 暂时返回低一个就可以了
         return True, address
def get_arbitration_list(request):
    max_item_count = request.POST.get("page_max_items")
    page_id = request.POST.get("page_id")
    if max_item_count is None or page_id is None:
        max_item_count = page_id = None
    else:
        max_item_count = int(max_item_count)
        page_id = int(page_id)
        if max_item_count < 1 or page_id < 0:
            max_item_count = page_id = None

    contract_name = "User"
    contract_address = ContractNote.get_last(contract_name)

    abi_file = f"contracts/{contract_name}.abi"
    data_parser = DatatypeParser()
    data_parser.load_abi_file(abi_file)
    contract_abi = data_parser.contract_abi

    client = BcosClient()
    res = client.call(contract_address, contract_abi, "get_arbitration_list",
                      [])

    transaction_id_list, _ = res
    transaction_list = []
    transaction_count = 0
    for transaction_id in transaction_id_list:
        res = client.call(contract_address, contract_abi,
                          "get_transaction_info", [transaction_id])
        transaction_info = {
            "user_id_sell": res[1],
            "user_id_buy": res[2],
            "desc": res[3],
            "commodity_id": res[4],
            "price": res[5],
            "state": res[6],
            "id": transaction_id,
        }
        ret_code = 0 if transaction_info["state"] != -999 else -1
        if ret_code == 0:
            transaction_list.append(transaction_info)
            transaction_count += 1

    client.finish()

    if max_item_count is None:
        page_num = 1 if len(transaction_list) > 0 else 0
    else:
        page_num = (len(transaction_list) + max_item_count -
                    1) // max_item_count
        transaction_list = transaction_list[page_id *
                                            max_item_count:(page_id + 1) *
                                            max_item_count]

    return JsonResponse({
        "transaction_list": transaction_list,
        "page_num": page_num,
    })
def user_commodity_list(request):
    user_id = request.POST.get('user_id')

    max_item_count = request.POST.get("page_max_items")
    page_id = request.POST.get("page_id")
    if max_item_count is None or page_id is None:
        max_item_count = page_id = None
    else:
        max_item_count = int(max_item_count)
        page_id = int(page_id)
        if max_item_count < 1 or page_id < 0:
            max_item_count = page_id = None

    contract_name = "User"
    contract_address = ContractNote.get_last(contract_name)

    abi_file = f"contracts/{contract_name}.abi"
    data_parser = DatatypeParser()
    data_parser.load_abi_file(abi_file)
    contract_abi = data_parser.contract_abi

    client = BcosClient()
    res = client.call(contract_address, contract_abi, "get_commodity_list",
                      [user_id])

    commodity_id_list, commodity_count = res
    commodity_list = []
    for commodity_id in commodity_id_list:
        commodity_info = client.call(contract_address, contract_abi,
                                     "get_commodity_info", [commodity_id])
        commodity_info = {
            "owner": commodity_info[0],
            "name": commodity_info[1],
            "image": commodity_info[2],
            "desc": commodity_info[3],
            "price": commodity_info[4],
            "state": commodity_info[5],
            "id": commodity_info[6],
            "type": commodity_info[7],
        }
        if commodity_info["state"] != -999:
            commodity_list.append(commodity_info)

    client.finish()

    if max_item_count is None:
        page_num = 1 if len(commodity_list) > 0 else 0
    else:
        page_num = (len(commodity_list) + max_item_count - 1) // max_item_count
        commodity_list = commodity_list[page_id *
                                        max_item_count:(page_id + 1) *
                                        max_item_count]

    return JsonResponse({
        "commodity_list": commodity_list,
        "page_num": page_num,
    })
Пример #6
0
    def deploy(self, inputparams):
        print(inputparams)
        if len(inputparams) == 0:
            sols = list_files(contracts_dir + "/*.sol")
            for sol in sols:
                print(sol + ".sol")
            return
        """deploy abi bin file"""
        # must be at least 2 params
        common.check_param_num(inputparams, 1)
        contractname = inputparams[0].strip()
        # need save address whether or not
        needSaveAddress = True
        args_len = len(inputparams)
        # need save address whether or not
        needSaveAddress = False
        args_len = len(inputparams)
        if inputparams[-1] == "save":
            needSaveAddress = True
            args_len = len(inputparams) - 1
        # get the args
        fn_args = inputparams[1:args_len]

        tx_client = transaction_common.TransactionCommon(
            "", contracts_dir, contractname)

        try:
            receipt = tx_client.send_transaction_getReceipt(None,
                                                            fn_args,
                                                            deploy=True)[0]
            print("INFO >> client info: {}".format(tx_client.getinfo()))
            print("deploy result  for [{}] is:\n {}".format(
                contractname, json.dumps(receipt, indent=4)))
            name = contractname
            address = receipt["contractAddress"]
            blocknum = int(receipt["blockNumber"], 16)
            txhash = receipt["transactionHash"]
            ContractNote.save_contract_address(name, address)
            print("on block : {},address: {} ".format(blocknum, address))
            if needSaveAddress is True:
                ContractNote.save_address_to_contract_note(name, address)
                print("address save to file: ",
                      client_config.contract_info_file)
            else:
                print("""\nNOTE : if want to save new address as last
                    address for (call/sendtx)\nadd 'save' to cmdline and run again"""
                      )
            ContractNote.save_history(name, address, blocknum, txhash)
            data_parser = DatatypeParser(default_abi_file(contractname))
            # 解析receipt里的log 和 相关的tx ,output
            print_receipt_logs_and_txoutput(tx_client, receipt, "",
                                            data_parser)
        except Exception as e:
            print("deploy exception! ", e)
            traceback.print_exc()
            tx_client.finish()
 def parse_tx_and_receipt(self, result, cmd, params):
     if result is None:
         return
     # decode output
     contractname = None
     if len(params) == 3:
         contractname = params[2]
     else:
         hisdetail = ContractNote.get_address_history(result["to"])
         if hisdetail is not None:
             contractname = hisdetail["name"]
             print("transaction to contract : {} (deploy time: {})".format(
                 contractname, hisdetail["timestr"]))
     if contractname is None:
         return
     self.parse_output(cmd, contractname, result)
Пример #8
0
    def parse_tx_and_receipt(self, result, cmd, params):
        if result is None:
            return
        # decode output
        contractname = None
        # print(params)
        to_addr = None
        if "to" in result:
            to_addr = result["to"]
        deploy_addr = None
        is_deploy = False
        if to_addr is None or to_addr == "0x0000000000000000000000000000000000000000":
            is_deploy = True
            if "contractAddress" in result:
                # transaction 结构体并没有contractAddress字段
                deploy_addr = result["contractAddress"]

        if len(params) >= 2:
            contractname = params[-1]
            # 試一下是否存在這個合約
            abi_path = os.path.join(self.contract_path, contractname + ".abi")
            if not os.path.exists(abi_path):
                contractname = None

        # 从参数获取不到,则从地址去检索历史记录,尝试获取

        if contractname is None:
            # 如果是部署合约,则to是空的,要获取address
            to_addr = result["to"]
            if is_deploy and deploy_addr is not None:
                abi_contract_addr = deploy_addr
            else:
                abi_contract_addr = to_addr
            hisdetail = ContractNote.get_address_history(abi_contract_addr)
            if hisdetail is not None:
                contractname = hisdetail["name"]
                print(
                    "histroy transaction to contract : {} [{}] (deploy time: {})"
                    .format(contractname, abi_contract_addr,
                            hisdetail["timestr"]))

        if is_deploy and deploy_addr is not None:
            print("\nis [DEPLOY] transaction,result address : {}\n".format(
                deploy_addr))
        if contractname is None:
            return
        self.parse_output(cmd, contractname, result)
def create_commodity(request):
    user_id = request.POST.get('user_id')
    commodity_name = request.POST.get('commodity_name')
    commodity_desc = request.POST.get('commodity_desc')
    commodity_image = request.FILES.get('commodity_image')

    static_dir = settings.STATICFILES_DIRS[0]
    image_id = get_random_id(length=18)
    ext = os.path.splitext(commodity_image.name)[-1]
    image_name = image_id + ext
    image_save_path = os.path.join(static_dir, image_name)
    with open(image_save_path, 'wb') as f:
        for content in commodity_image.chunks():
            f.write(content)
    scale_image_too_big(image_save_path)
    commodity_image = "/static/" + image_name

    contract_name = "User"
    contract_address = ContractNote.get_last(contract_name)

    abi_file = f"contracts/{contract_name}.abi"
    data_parser = DatatypeParser()
    data_parser.load_abi_file(abi_file)
    contract_abi = data_parser.contract_abi

    client = BcosClient()
    receipt = client.sendRawTransactionGetReceipt(
        contract_address, contract_abi, "create_commodity",
        [user_id, commodity_name, commodity_image, commodity_desc])
    txhash = receipt['transactionHash']
    txresponse = client.getTransactionByHash(txhash)
    inputresult = data_parser.parse_transaction_input(txresponse['input'])
    res = data_parser.parse_receipt_output(inputresult['name'],
                                           receipt['output'])
    client.finish()

    code_map = {
        1: 0,  # success 
        -1: -1,  # user state error
        -2: -2,  # unknown error
    }

    ret_code = code_map[res[0]]

    return JsonResponse({"code": ret_code})
Пример #10
0
    def sendtx(self, inputparams):
        if len(inputparams) == 0:
            sols = list_files(contracts_dir + "/*.sol")
            for sol in sols:
                print(sol + ".sol")
            return
        common.check_param_num(inputparams, 3)
        paramsname = ["contractname", "address", "func"]
        params = fill_params(inputparams, paramsname)
        contractname = params["contractname"]
        address = params["address"]
        if address == "last" or address == "latest":
            address = ContractNote.get_last(contractname)
            if address is None:
                sys.exit("can not get last address for [{}],break;".format(
                    contractname))

        tx_client = transaction_common.TransactionCommon(
            address, contracts_dir, contractname)
        fn_name = params["func"]
        fn_args = inputparams[3:]
        print("INFO>> client info: {}".format(tx_client.getinfo()))
        print("INFO >> sendtx {} , address: {}, func: {}, args:{}".format(
            contractname, address, fn_name, fn_args))
        try:
            from_account_signer = None
            # from_account_signer = Signer_ECDSA.from_key_file(
            #    "bin/accounts/tester.keystore", "123456")
            # print(keypair.address)
            # 不指定from账户,如需指定,参考上面的加载,或者创建一个新的account,
            # 参见国密(client.GM_Account)和非国密的account管理类LocalAccount
            (receipt, output) = tx_client.send_transaction_getReceipt(
                fn_name, fn_args, from_account_signer=from_account_signer)
            data_parser = DatatypeParser(tx_client.contract_abi_path)
            # 解析receipt里的log 和 相关的tx ,output
            print_receipt_logs_and_txoutput(tx_client, receipt, "",
                                            data_parser)
        except Exception as e:
            common.print_error_msg("sendtx", e)
Пример #11
0
def getContractAddr(contractName):
    return ContractNote.get_contract_addresses(contractName)[0]
Пример #12
0
 def deploylog(self):
     historys = ContractNote.get_history_list()
     for address in historys:
         print("{} -> {} ".format(address, historys[address]))
Пример #13
0
 def deploylast(self):
     contracts = ContractNote.get_last_contracts()
     for name in contracts:
         print("{} -> {}".format(name, contracts[name]))
Пример #14
0
    client = BcosClient()
    print(client.getinfo())
    # 部署合约
    print(
        "\n>>Deploy:----------------------------------------------------------"
    )
    with open("contracts/SimpleInfo.bin", 'r') as load_f:
        contract_bin = load_f.read()
        load_f.close()
    result = client.deploy(contract_bin)
    print("deploy", result)
    print("new address : ", result["contractAddress"])
    contract_name = os.path.splitext(os.path.basename(abi_file))[0]
    memo = "tx:" + result["transactionHash"]
    # 把部署结果存入文件备查
    ContractNote.save_address_to_contract_note(contract_name,
                                               result["contractAddress"])
    # 发送交易,调用一个改写数据的接口
    print(
        "\n>>sendRawTransaction:----------------------------------------------------"
    )
    to_address = result['contractAddress']  # use new deploy address
    args = [
        'simplename', 2024,
        to_checksum_address('0x7029c502b4F824d19Bd7921E9cb74Ef92392FB1c')
    ]

    receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi,
                                                  "set", args)
    print("receipt:", receipt)

    # 解析receipt里的log
    # with open("contracts/v1_2.bin", 'r') as load_f:
    #     contract_bin = load_f.read()
    #     load_f.close()
    # result = client.deploy(contract_bin)
    # print("deploy", result)
    # print("new address : ", result["contractAddress"])
    contract_name = os.path.splitext(os.path.basename(abi_file))[0]
    # memo = "tx:" + result["transactionHash"]
    # 把部署结果存入文件备查
    # ContractNote.save_address(contract_name,
    #                           result["contractAddress"],
    #                           int(result["blockNumber"], 16), memo)
    # 发送交易,调用一个改写数据的接口
    print("\n>>sendRawTransaction:----------------------------------------------------")
    # 获取智能合约的地址
    to_address = ContractNote.get_last(contract_name)
    args = None

    receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "Task1", args)
    print("receipt:", receipt)

    # 解析receipt里的log
    print("\n>>parse receipt and transaction:--------------------------------------")
    txhash = receipt['transactionHash']
    print("transaction hash: ", txhash)
    logresult = data_parser.parse_event_logs(receipt["logs"])
    i = 0
    for log in logresult:
        if 'eventname' in log:
            i = i + 1
            print("{}): log name: {} , data: {}".format(i, log['eventname'], log['eventdata']))
Пример #16
0
    if 'save' in args, so save addres to file''')
    if cmd == "deploy":
        '''deploy abi bin file'''
        abibinfile = inputparams[0]
        with open(abibinfile, "r") as f:
            contractbin = f.read()
        result = client.deploy(contractbin)
        print("deploy result  for [{}] is:\n {}".format(
            abibinfile, json.dumps(result, indent=4)))
        name = contractname = os.path.splitext(os.path.basename(abibinfile))[0]
        address = result['contractAddress']
        blocknum = int(result["blockNumber"], 16)
        print("on block : {},address: {} ".format(blocknum, address))
        if len(inputparams) == 2:
            if inputparams[1] == "save":
                ContractNote.save_address(name, address, blocknum)
                print("address save to file: ",
                      client_config.contract_info_file)
        else:
            print(
                "\nNOTE : if want to save new address as last addres for (call/sendtx)\nadd 'save' to cmdline and run again"
            )
        sys.exit(0)

    #--------------------------------------------------------------------------------------------
    # console cmd entity
    #--------------------------------------------------------------------------------------------
    validcmds.append("call")
    usagemsg.append('''call [contractname] [address] [func]  [args...]
    call合约的一个只读接口,解析返回值
    call a constant funciton of contract and get the returns
Пример #17
0
def list_address(contract_name):
    """
    get address according to contract_name
    """
    return ContractNote.get_contract_addresses(contract_name)
Пример #18
0
    def on_push(self, packmsg: ChannelPack):
        print("EventPushHandler", packmsg.detail())
        strmsg = packmsg.data.decode("utf-8")
        response = json.loads(strmsg)
        print("response filterID:", response['filterID'])
        #print("response:", json.dumps(response,indent=4))
        loglist = parser.parse_event_logs(response["logs"])
        print(json.dumps(loglist, indent=4))


# 从文件加载abi定义
abi_file = "contracts/HelloEvent.abi"
parser = data_parser = DatatypeParser(abi_file)
contract_abi = data_parser.contract_abi
contractnode = ContractNote()
address = contractnode.get_last("HelloEvent")
print("event contract address is ", address)
client = None
client = BcosClient()
info = client.getinfo()
print("client info:", info)
params_set = ["aaabbb"]
params_setnum_5 = ["setnum_ab", 5]
params_setnum_10 = ["setnum_ab", 10]
params_settwo_1 = ["settwo_aabb", 10, 'key1']
params_settwo_2 = ["settwo_aabb", 10, 'key2']


'''
    CHANNEL_RPC_REQUEST = 0x12,        // type for rpc request
Пример #19
0
def main(argv):
    try:
        usagemsg = usage(client_config)
        cmd, inputparams = parse_commands(argv)
        precompile = Precompile(cmd, inputparams,
                                contracts_dir + "/precompile")
        # check cmd
        valid = check_cmd(cmd, validcmds)
        if valid is False:
            printusage(usagemsg, precompile)
            return
        # try to callback cns precompile
        precompile.call_cns()
        # try to callback consensus precompile
        precompile.call_consensus()
        # try to callback config precompile
        precompile.call_sysconfig_precompile()
        # try to callback permission precompile
        precompile.call_permission_precompile()
        # try to callback crud precompile
        precompile.call_crud_precompile()
        # try to callback rpc functions
        rpcConsole = RPCConsole(cmd, inputparams, contracts_dir)
        rpcConsole.executeRpcCommand()
        if cmd == 'showaccount':
            # must be 2 params
            common.check_param_num(inputparams, 2, True)
            name = inputparams[0]
            password = inputparams[1]
            keyfile = "{}/{}.keystore".format(
                client_config.account_keyfile_path, name)
            # the account doesn't exists
            if os.path.exists(keyfile) is False:
                raise BcosException("account {} doesn't exists".format(name))
            print("show account : {}, keyfile:{} ,password {}  ".format(
                name, keyfile, password))
            try:
                with open(keyfile, "r") as dump_f:
                    keytext = json.load(dump_f)
                    stat = StatTool.begin()
                    privkey = Account.decrypt(keytext, password)
                    stat.done()
                    print("decrypt use time : %.3f s" % (stat.time_used))
                    ac2 = Account.from_key(privkey)
                    print("address:\t", ac2.address)
                    print("privkey:\t", encode_hex(ac2.key))
                    print("pubkey :\t", ac2.publickey)
                    print("\naccount store in file: [{}]".format(keyfile))
                    print("\n**** please remember your password !!! *****")
            except Exception as e:
                raise BcosException(("load account info for [{}] failed,"
                                     " error info: {}!").format(name, e))

        if cmd == 'newaccount':
            common.check_param_num(inputparams, 2, True)
            name = inputparams[0]
            max_account_len = 240
            if len(name) > max_account_len:
                common.print_info(
                    "WARNING", "account name should no more than {}".format(
                        max_account_len))
                sys.exit(1)
            password = inputparams[1]
            print("starting : {} {} ".format(name, password))
            ac = Account.create(password)
            print("new address :\t", ac.address)
            print("new privkey :\t", encode_hex(ac.key))
            print("new pubkey :\t", ac.publickey)

            stat = StatTool.begin()
            kf = Account.encrypt(ac.privateKey, password)
            stat.done()
            print("encrypt use time : %.3f s" % (stat.time_used))
            keyfile = "{}/{}.keystore".format(
                client_config.account_keyfile_path, name)
            print("save to file : [{}]".format(keyfile))
            forcewrite = False
            if not os.access(keyfile, os.F_OK):
                forcewrite = True
            else:
                # old file exist,move to backup file first
                if (len(inputparams) == 3 and inputparams[2] == "save"):
                    forcewrite = True
                else:
                    forcewrite = common.backup_file(keyfile)
            if forcewrite:
                with open(keyfile, "w") as dump_f:
                    json.dump(kf, dump_f)
                    dump_f.close()
            print(">>-------------------------------------------------------")
            print(
                "INFO >> read [{}] again after new account,address & keys in file:"
                .format(keyfile))
            with open(keyfile, "r") as dump_f:
                keytext = json.load(dump_f)
                stat = StatTool.begin()
                privkey = Account.decrypt(keytext, password)
                stat.done()
                print("decrypt use time : %.3f s" % (stat.time_used))
                ac2 = Account.from_key(privkey)
                print("address:\t", ac2.address)
                print("privkey:\t", encode_hex(ac2.key))
                print("pubkey :\t", ac2.publickey)
                print("\naccount store in file: [{}]".format(keyfile))
                print("\n**** please remember your password !!! *****")
                dump_f.close()

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "deploy":
            '''deploy abi bin file'''
            # must be at least 2 params
            common.check_param_num(inputparams, 1)
            contractname = inputparams[0].strip()
            gasPrice = 30000000
            # need save address whether or not
            needSaveAddress = False
            args_len = len(inputparams)
            if inputparams[-1] == "save":
                needSaveAddress = True
                args_len = len(inputparams) - 1
            # get the args
            fn_args = inputparams[1:args_len]
            trans_client = transaction_common.TransactionCommon(
                "", contracts_dir, contractname)
            result = trans_client.send_transaction_getReceipt(
                None, fn_args, gasPrice, True)[0]

            print("deploy result  for [{}] is:\n {}".format(
                contractname, json.dumps(result, indent=4)))
            name = contractname
            address = result['contractAddress']
            blocknum = int(result["blockNumber"], 16)
            ContractNote.save_contract_address(name, address)
            print("on block : {},address: {} ".format(blocknum, address))
            if needSaveAddress is True:
                ContractNote.save_address(name, address, blocknum)
                print("address save to file: ",
                      client_config.contract_info_file)
            else:
                print('''\nNOTE : if want to save new address as last
                    address for (call/sendtx)\nadd 'save' to cmdline and run again'''
                      )

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "call" or cmd == "sendtx":
            common.check_param_num(inputparams, 3)
            paramsname = ["contractname", "address", "func"]
            params = fill_params(inputparams, paramsname)
            contractname = params["contractname"]
            address = params["address"]
            if address == "last":
                address = ContractNote.get_last(contractname)
                if address is None:
                    sys.exit("can not get last address for [{}],break;".format(
                        contractname))

            tx_client = transaction_common.TransactionCommon(
                address, contracts_dir, contractname)
            fn_name = params["func"]
            fn_args = inputparams[3:]
            print("INFO >> {} {} , address: {}, func: {}, args:{}".format(
                cmd, contractname, address, fn_name, fn_args))
            if cmd == "call":
                result = tx_client.call_and_decode(fn_name, fn_args)
                print("INFO >> {} result: {}".format(cmd, result))
            if cmd == "sendtx":
                receipt = tx_client.send_transaction_getReceipt(
                    fn_name, fn_args)[0]
                data_parser = DatatypeParser(default_abi_file(contractname))
                # 解析receipt里的log 和 相关的tx ,output
                print_receipt_logs_and_txoutput(tx_client, receipt, "",
                                                data_parser)
        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "list":
            RPCConsole.print_rpc_usage()
            print(
                "--------------------------------------------------------------------"
            )

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "txinput":
            contractname = inputparams[0]
            inputdata = inputparams[1]
            abi_path = default_abi_file(contractname)
            if os.path.isfile(abi_path) is False:
                raise BcosException(
                    "execute {} failed for {} doesn't exist".format(
                        cmd, abi_path))
            try:
                dataParser = DatatypeParser(abi_path)
                # print(dataParser.func_abi_map_by_selector)
                result = dataParser.parse_transaction_input(inputdata)
                print("\nabifile : ", default_abi_file(contractname))
                print("parse result: {}".format(result))
            except Exception as e:
                raise BcosException("execute {} failed for reason: {}".format(
                    cmd, e))

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "checkaddr":
            address = inputparams[0]
            result = to_checksum_address(address)
            print("{} -->\n{}".format(address, result))

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "usage":
            printusage(usagemsg, precompile)
    except TransactionException as e:
        common.print_error_msg(cmd, e)
    except PrecompileError as e:
        common.print_error_msg(cmd, e)
    except BcosError as e:
        common.print_error_msg(cmd, e)
    except CompileError as e:
        common.print_error_msg(cmd, e)
    except ArgumentsError as e:
        common.print_error_msg(cmd, e)
    except BcosException as e:
        common.print_error_msg(cmd, e)
def search_commodity(request):
    keywords = request.POST.get("keywords")
    keywords = [keyword for keyword in keywords.split(' ') if len(keyword) > 0]
    commodity_type = request.POST.get("commodity_type")

    reverse = bool(int(request.POST.get("reverse", '0')))

    max_item_count = request.POST.get("page_max_items")
    page_id = request.POST.get("page_id")
    if max_item_count is None or page_id is None:
        max_item_count = page_id = None
    else:
        max_item_count = int(max_item_count)
        page_id = int(page_id)
        if max_item_count < 1 or page_id < 0:
            max_item_count = page_id = None

    if commodity_type is None:
        query_method = "get_onsale_list"
        query_args = []
    else:
        commodity_type = int(commodity_type)
        query_method = "get_onsale_type_list"
        query_args = [commodity_type]

    contract_name = "User"
    contract_address = ContractNote.get_last(contract_name)

    abi_file = f"contracts/{contract_name}.abi"
    data_parser = DatatypeParser()
    data_parser.load_abi_file(abi_file)
    contract_abi = data_parser.contract_abi

    client = BcosClient()
    res = client.call(contract_address, contract_abi, query_method, query_args)

    commodity_id_list, commodity_count = res
    commodity_list = []
    for commodity_id in commodity_id_list:
        commodity_info = client.call(contract_address, contract_abi,
                                     "get_commodity_info", [commodity_id])
        commodity_info = {
            "owner": commodity_info[0],
            "name": commodity_info[1],
            "image": commodity_info[2],
            "desc": commodity_info[3],
            "price": commodity_info[4],
            "state": commodity_info[5],
            "id": commodity_info[6],
            "type": commodity_info[7],
        }
        if commodity_info["state"] != -999:
            commodity_list.append(commodity_info)

    client.finish()

    commodity_match_score_list = []
    for commodity_info in commodity_list:
        score = 0
        for keyword in keywords:
            score += int(keyword.lower() in commodity_info["name"].lower())
            score += int(keyword.lower() in commodity_info["desc"].lower())
        commodity_match_score_list.append(score)

    commodity_list = [
        item[0] for item in sorted(iter(
            i for i in zip(commodity_list, commodity_match_score_list)
            if i[1] > 0),
                                   key=lambda x: x[1],
                                   reverse=True)
    ]

    if reverse:
        commodity_list.reverse()

    if max_item_count is None:
        page_num = 1 if len(commodity_list) > 0 else 0
    else:
        page_num = (len(commodity_list) + max_item_count - 1) // max_item_count
        commodity_list = commodity_list[page_id *
                                        max_item_count:(page_id + 1) *
                                        max_item_count]

    return JsonResponse({
        "commodity_list": commodity_list,
        "page_num": page_num,
    })
Пример #21
0
data_parser.load_abi_file(abi_file)
contract_abi = data_parser.contract_abi

#部署合约
print("\n>>Deploy:---------------------------------------------------------------------")
with open("contracts/SimpleInfo.bin", 'r') as load_f:
    contract_bin = load_f.read()
    load_f.close()
result = client.deploy(contract_bin)
print("deploy",result)
print("new address : ",result["contractAddress"])
contract_name =  os.path.splitext(os.path.basename(abi_file))[0]
memo = "tx:"+result["transactionHash"]
#把部署结果存入文件备查
from client.contractnote import ContractNote
ContractNote.save_address(contract_name, result["contractAddress"], int(result["blockNumber"], 16), memo)


#发送交易,调用一个改写数据的接口
print("\n>>sendRawTransaction:----------------------------------------------------------")
to_address = result['contractAddress'] #use new deploy address
args = ['simplename', 2024, to_checksum_address('0x7029c502b4F824d19Bd7921E9cb74Ef92392FB1c')]

receipt = client.sendRawTransactionGetReceipt(to_address,contract_abi,"set",args)
print("receipt:",receipt)

#解析receipt里的log
print("\n>>parse receipt and transaction:----------------------------------------------------------")
txhash = receipt['transactionHash']
print("transaction hash: " ,txhash)
logresult = data_parser.parse_event_logs(receipt["logs"])
def market_commodity_list_order_by_price(request):
    commodity_type = request.POST.get("commodity_type")
    reverse = bool(int(request.POST.get("reverse", '0')))

    max_item_count = request.POST.get("page_max_items")
    page_id = request.POST.get("page_id")
    if max_item_count is None or page_id is None:
        max_item_count = page_id = None
    else:
        max_item_count = int(max_item_count)
        page_id = int(page_id)
        if max_item_count < 1 or page_id < 0:
            max_item_count = page_id = None

    if commodity_type is None:
        query_method = "get_onsale_list"
        query_args = []
    else:
        commodity_type = int(commodity_type)
        query_method = "get_onsale_type_list"
        query_args = [commodity_type]

    contract_name = "User"
    contract_address = ContractNote.get_last(contract_name)

    abi_file = f"contracts/{contract_name}.abi"
    data_parser = DatatypeParser()
    data_parser.load_abi_file(abi_file)
    contract_abi = data_parser.contract_abi

    client = BcosClient()
    res = client.call(contract_address, contract_abi, query_method, query_args)

    commodity_id_list, commodity_count = res
    commodity_list = []
    for commodity_id in commodity_id_list:
        commodity_info = client.call(contract_address, contract_abi,
                                     "get_commodity_info", [commodity_id])
        commodity_info = {
            "owner": commodity_info[0],
            "name": commodity_info[1],
            "image": commodity_info[2],
            "desc": commodity_info[3],
            "price": commodity_info[4],
            "state": commodity_info[5],
            "id": commodity_info[6],
            "type": commodity_info[7],
        }
        if commodity_info["state"] != -999:
            commodity_list.append(commodity_info)

    client.finish()

    commodity_list.sort(key=lambda commodity_info: commodity_info["price"],
                        reverse=reverse)

    if max_item_count is None:
        page_num = 1 if len(commodity_list) > 0 else 0
    else:
        page_num = (len(commodity_list) + max_item_count - 1) // max_item_count
        commodity_list = commodity_list[page_id *
                                        max_item_count:(page_id + 1) *
                                        max_item_count]

    return JsonResponse({
        "commodity_list": commodity_list,
        "page_num": page_num,
    })