def add_voucher(user: User, institution: Institution, description, expires):
    """
    Creates a new voucher for the given user.
    :parameter user the user instance who will retrieve an voucher
    :parameter institution the institution instance which offer the voucher
    :parameter description a description for the voucher
    :parameter expires the period of validity in days
    :return: the index of the created voucher
    """
    description = WEB3.toBytes(text=description)
    contract = WEB3.eth.contract(address=institution.scAddress, abi=INSTITUTION_JSON["abi"])
    tx_hash = contract.functions.addVoucher(user.publickeyUser, description, expires).buildTransaction({
        'nonce': WEB3.eth.getTransactionCount(WEB3.eth.defaultAccount),
        'from': WEB3.eth.defaultAccount
    })
    # signed_tx = WEB3.eth.account.sign_transaction(tx_hash, private_key=master_key)
    # tx_raw = WEB3.eth.sendRawTransaction(signed_tx.rawTransaction)
    tx_raw = WEB3.eth.sendTransaction(tx_hash)
    tx_receipt = WEB3.eth.waitForTransactionReceipt(tx_raw)
    if tx_receipt.status != 1:
        raise RuntimeError("SC Call failed!")

    processed_receipt = contract.events.newVoucher().processReceipt(tx_receipt)
    index = processed_receipt[0].args._index  # pylint:disable=protected-access
    print(index)
    return index
def project_constructor(owner: User, description: str, goal: int):
    projects_sc = WEB3.eth.contract(abi=PROJECT_JSON["abi"], bytecode=PROJECT_JSON["bytecode"])

    description_bytes = WEB3.toBytes(text=str(description))

    # constructor(_owner, _admin, _partial_payment, _projectTargetName, _projectTargetAmount, _minDonation)
    ctor = projects_sc.constructor(owner.publickeyUser, WEB3.eth.defaultAccount,
                                   80,
                                   description_bytes,
                                   goal,
                                   int(WEB3.toWei(0.01, 'ether')))
    tx_hash = ctor.buildTransaction({'nonce': WEB3.eth.getTransactionCount(owner.publickeyUser),
                                     'from': owner.publickeyUser})
    signed_tx = WEB3.eth.account.sign_transaction(tx_hash, private_key=owner.privatekeyUser)
    tx_hash = WEB3.eth.sendRawTransaction(signed_tx.rawTransaction)
    tx_receipt = WEB3.eth.waitForTransactionReceipt(tx_hash)
    if tx_receipt.status != 1:
        raise RuntimeError("SC Call failed!")

    return tx_receipt.contractAddress
def project_add_milestone(project: Project, owner: User, name: str, goal: int, until: int):
    projects_sc = WEB3.eth.contract(address=project.scAddress, abi=PROJECT_JSON["abi"])

    tx_hash = projects_sc.functions.addMilestone(WEB3.toBytes(text=name),
                                                 int(goal),
                                                 int(until)). \
        buildTransaction({'nonce': WEB3.eth.getTransactionCount(owner.publickeyUser),
                          'from': owner.publickeyUser})
    signed_tx = WEB3.eth.account.sign_transaction(tx_hash, private_key=owner.privatekeyUser)
    tx_hash = WEB3.eth.sendRawTransaction(signed_tx.rawTransaction)

    tx_receipt = WEB3.eth.waitForTransactionReceipt(tx_hash)
    if tx_receipt.status != 1:
        raise RuntimeError("SC addMilestone Call failed!")

    processed_receipt = projects_sc.events.AddMilestone().processReceipt(tx_receipt)
    if len(processed_receipt) < 1:
        raise RuntimeError("SC addMilestone no Events")
    if WEB3.toText(processed_receipt[0].args._name) != name:  # pylint:disable=protected-access
        raise RuntimeError("SC addMilestone Event name wrong!")
    if processed_receipt[0].args._amount != goal:  # pylint:disable=protected-access
        raise RuntimeError("SC addMilestone Event goal wrong!")

    return processed_receipt[0].args.milestone_id
Beispiel #4
0
def voucher_post(user):
    """
    Handles POST for resource <base>/api/voucher/user .
    :return: json data of projects
    """
    id_voucher = request.headers.get('idVoucher')
    if not id_voucher:
        return jsonify({'error': 'missing id'}), 400
    try:
        check_params_int([id_voucher])
    except ValueError:
        return jsonify({"error": "bad argument"}), 400

    session = DB_SESSION()

    try:
        voucher = session.query(Voucher).filter(
            Voucher.idVoucher == id_voucher).one()
        balance = WEB3.eth.getBalance(user.publickeyUser)

        if balance < voucher.priceVoucher:  # ToDo: gas-cost?
            return jsonify({'error': 'not enough balance'}), 406
        if not voucher.available:
            return jsonify({'error': 'voucher not available'}), 406

        association = VoucherUser(
            usedVoucher=False,
            expires_unixtime=(datetime.now() + timedelta(0, 2 * 31536000)),
            voucher=voucher,
            user=user)

        inst: Institution = session.query(Institution).filter(
            Institution.idInstitution == voucher.institution_id).one()

        transaction = {
            'nonce': WEB3.eth.getTransactionCount(user.publickeyUser),
            'to': inst.publickeyInstitution,
            'value': voucher.priceVoucher,
            'gas': 200000,
            'gasPrice': WEB3.toWei('50', 'gwei')
        }
        signed_transaction = WEB3.eth.account.sign_transaction(
            transaction, user.privatekeyUser)
        WEB3.eth.sendRawTransaction(signed_transaction.rawTransaction)

        cfg_parser: configparser.ConfigParser = configparser.ConfigParser()
        cfg_parser.read("backend_config.ini")

        voucher_sc = WEB3.eth.contract(
            address=WEB3.toChecksumAddress(cfg_parser["Voucher"]["ADDRESS"]),
            abi=json.loads(cfg_parser["Voucher"]["ABI"]))

        transaction = voucher_sc.functions.addVoucher(user.publickeyUser,
                                                      WEB3.toBytes(text=voucher.titleVoucher),
                                                      666) \
            .buildTransaction({'nonce': WEB3.eth.getTransactionCount(user.publickeyUser)})
        signed_transaction = WEB3.eth.account.sign_transaction(
            transaction, user.privatekeyUser)

        WEB3.eth.sendRawTransaction(signed_transaction.rawTransaction)

        session.add(voucher)
        session.add(association)
        session.commit()
    except InvalidAddress:
        return jsonify({'error': 'given publickey is not valid'}), 400
    except NoResultFound:
        return jsonify({'error': 'Voucher doesnt exist'}), 404

    return jsonify({'status': 'voucher bought'}), 200