Beispiel #1
0
def SubmitPrediction(oracle, game_type, instance_ts, prediction):
    if not isGameInstanceLive(game_type, instance_ts):
        return "Game Instance not yet commissioned"
    if isGameInstanceJudged(game_type, instance_ts):
        return "Game Instance already judged"
    if CheckTimestamp(instance_ts):
        return JudgeInstance(game_type, instance_ts) # Too late to submit, but can judge
    else:
        # Check if Oracle already registered
        if isOracleRegisteredForInstance(oracle, game_type, instance_ts):
            return "Already registered"
        current_oracle_balance = GetOracleBalance(oracle)
        n_oracles_for_instance = GetOracleCountForInstance(game_type, instance_ts)

        # See if the agent has sent any NEO-GAS assets
        tx = GetScriptContainer()
        refs = tx.References

        if len(refs) < 1:
            if current_oracle_balance >= collateral_requirement:
                new_count = n_oracles_for_instance + 1
                RegisterOracle(game_type, instance_ts, oracle, new_count)
            else:
                # No assets sent and existing balance too low
                return "Not enough balance to register"
        else:
            ref = refs[0]
            sentAsset = GetAssetId(ref)
            #sender_hash = GetScriptHash(ref)
            if sentAsset == GAS_ASSET_ID:
                receiver = GetExecutingScriptHash()
                totalGasSent = 0
                cOutputs = len(tx.Outputs)
                for output in tx.Outputs:
                    Log(output.Value)
                    shash = GetScriptHash(output)
                    if shash == receiver:
                        totalGasSent = totalGasSent + output.Value
                if totalGasSent == b'\x00e\xcd\x1d':
                    current_oracle_balance = current_oracle_balance + totalGasSent
                    key = concat(key_prefix_agent_available_balance, oracle)
                    # Updates Balance of Oracle
                    context = GetContext()
                    Put(context, key, current_oracle_balance)
                    new_count = n_oracles_for_instance + 1
                    RegisterOracle(game_type, instance_ts, oracle, new_count)
                else:
                    return "Wrong amount of NEO GAS Sent"

        # Now to submit prediction if no errors
        RegisterPrediction(game_type, instance_ts, oracle, prediction)
        p_count = IncrementCountForPrediction(game_type, instance_ts, prediction)
        max_so_far = GetCurrentMax(game_type, instance_ts)
        if p_count > max_so_far:
            # New Current Winner
            UpdateMaxVotes(game_type, instance_ts, p_count)
            UpdatePrediction(game_type, instance_ts, prediction)
        if CheckTimestamp(instance_ts):
            return JudgeInstance(game_type, instance_ts)
        return True
Beispiel #2
0
def get_asset_attachments_for_prev() -> Attachments:
    attachment = Attachments()

    tx = GetScriptContainer()  # type:Transaction

    sent_amount_neo = 0
    sent_amount_gas = 0

    attachment.receiver_addr = GetExecutingScriptHash()

    for input in tx.Inputs:

        prev_tx = GetTransaction(input.Hash)
        references = prev_tx.References

        if len(references) > 0:

            reference = references[0]
            sender_addr = reference.ScriptHash

            prev_output = prev_tx.Outputs[input.Index]

            if prev_output.ScriptHash == attachment.receiver_addr and prev_output.AssetId == attachment.neo_asset_id:
                sent_amount_neo += prev_output.Value

            if prev_output.ScriptHash == attachment.receiver_addr and prev_output.AssetId == attachment.gas_asset_id:
                sent_amount_gas += prev_output.Value

    attachment.neo_attached = sent_amount_neo
    attachment.gas_attached = sent_amount_gas

    return attachment
Beispiel #3
0
def get_asset_attachments() -> Attachments:

    attachment = Attachments()

    tx = GetScriptContainer()  # type:Transaction
    references = GetReferences(tx)
    attachment.receiver_addr = GetExecutingScriptHash()

    m = len(references)
    Notify(m)
    if len(references) > 0:

        reference = references[0]
        attachment.sender_addr = reference.ScriptHash

        sent_amount_neo = 0
        sent_amount_gas = 0
        for output in tx.Outputs:
            if output.ScriptHash == attachment.receiver_addr and output.AssetId == attachment.neo_asset_id:
                sent_amount_neo += output.Value

            if output.ScriptHash == attachment.receiver_addr and output.AssetId == attachment.gas_asset_id:
                sent_amount_gas += output.Value

        print("hello!")
        attachment.neo_attached = sent_amount_neo
        attachment.gas_attached = sent_amount_gas

    return attachment
Beispiel #4
0
def Main(operation):
    """

    :param operation:
    :return:
    """
    hash = GetExecutingScriptHash()

    Notify(hash)

    account = GetAccount(hash)

    print("account!")

    Notify(account)

    print("will get asset")
    asset = GetAsset(GAS)

    Notify(asset)

    print("will get balance")
    balance = GetBalance(account, GAS)

    Notify(balance)

    return operation
Beispiel #5
0
def get_asset_attachments() -> Attachments:
    """
    Bekommen Sie Informationen über NEO oder Gas das an eine Invocation TX angehängt ist

    :return:
        Attachments: Ein Objekt mit Informationen über angehängte NEO und GAS
    """
    attachment = Attachments()

    tx = GetScriptContainer()  # type:Transaction
    references = tx.References
    attachment.receiver_addr = GetExecutingScriptHash()

    if len(references) > 0:

        reference = references[0]
        attachment.sender_addr = reference.ScriptHash

        sent_amount_neo = 0
        sent_amount_gas = 0

        for output in tx.Outputs:
            if output.ScriptHash == attachment.receiver_addr and output.AssetId == attachment.neo_asset_id:
                sent_amount_neo += output.Value

            if output.ScriptHash == attachment.receiver_addr and output.AssetId == attachment.gas_asset_id:
                sent_amount_gas += output.Value

        attachment.neo_attached = sent_amount_neo
        attachment.gas_attached = sent_amount_gas

    return attachment
Beispiel #6
0
def get_asset_attachments() -> Attachments:
    """
    Gets information about NEO and Gas attached to an invocation TX
    :return:
        Attachments: An object with information about attached neo and gas
    """
    attachment = Attachments()

    tx = GetScriptContainer()
    references = tx.References
    attachment.receiver_addr = GetExecutingScriptHash()

    if len(references) > 0:

        reference = references[0]
        attachment.sender_addr = reference.ScriptHash

        sent_amount_neo = 0
        sent_amount_gas = 0

        for output in tx.Outputs:
            if output.ScriptHash == attachment.receiver_addr and output.AssetId == attachment.neo_asset_id:
                sent_amount_neo += output.Value

            if output.ScriptHash == attachment.receiver_addr and output.AssetId == attachment.gas_asset_id:
                sent_amount_gas += output.Value

        attachment.neo_attached = sent_amount_neo
        attachment.gas_attached = sent_amount_gas

    return attachment
Beispiel #7
0
def DepositNeo():
    # get reference to the tx the invocation is in
    tx = GetScriptContainer()

    references = tx.References

    if len(references) < 1:
        print("no neo attached")
        return False

    # we need to determine who sent the tx
    reference = references[0]
    sender = GetScriptHash(reference)

    # this will keep track of how much neo was deposited
    value = 0

    output_asset_id = GetAssetId(reference)

    if output_asset_id != NEO_ASSET_ID:
        print("Must deposit NEO")
        return False

    # this is the contract's address
    receiver = GetExecutingScriptHash()

    # go through all the outputs
    # and check if the receiver is the contract
    # if that is true, we add the value of the output to the
    # total sum that was deposited

    for output in tx.Outputs:
        shash = GetScriptHash(output)
        if shash == receiver:
            output_val = GetValue(output)
            value = value + output_val

    if value > 0:

        print("neo was deposited")
        Notify(value)

        timestamp = GetHeight()
        # now we know value was deposited from the sender

        context = GetContext()

        print("timestamp: ", timestamp)
        Put(context, "timestamp", timestamp)

        print("deposited")

        return True

    return False
Beispiel #8
0
def DepositNeo():

    # get reference to the tx the invocation is in
    tx = GetScriptContainer()

    references = tx.References

    if len(references) < 1:
        print("no neo attached")
        return False

    # we need to determine who sent the tx
    reference = references[0]
    sender = GetScriptHash(reference)

    # this will keep track of how much neo was deposited
    value = 0

    # this is the contract's address
    receiver = GetExecutingScriptHash()

    # go through all the outputs
    # and check if the receiver is the contract
    # if that is true, we add the value of the output to the
    # total sum that was deposited

    for output in tx.Outputs:
        shash = GetScriptHash(output)
        if shash == receiver:

            output_asset_id = GetAssetId(output)

            if output_asset_id == NEO_ASSET_ID:

                output_val = GetValue(output)
                value = value + output_val

    if value > 0:

        # now we know value was deposited from the sender

        # check the current balance of the sender
        # add it to the deposit amount, and save
        context = GetContext()
        current_balance = Get(context, sender)
        new_balance = current_balance + value
        Put(context, sender, new_balance)

        # send deposit event
        onDeposit(sender, value)

        return True

    return False
Beispiel #9
0
def spend(context, amount, src, dest, tag):
    context = GetContext()
    org_tag = concat(src, tag)
    total = Get(context, org_tag)
    if not total:
        return False
    if amount > total:
        return False
    Delete(context, org_tag)
    new_total = total - amount
    Put(context, org_tag, new_total)
    receiver = GetExecutingScriptHash()
    OnSpend(dest, amount, receiver)
    return True
Beispiel #10
0
def PickWinner():

    tx = GetScriptContainer()
    context = GetContext()
    references = tx.References
    if _TimeHasExpired():
        winningEntry = _getWinner()
        schash = GetExecutingScriptHash()
        entries = GetEntries()
        numEntries = len(entries)
        luckycut = numEntries - 30
        OnWinner(winningEntry, luckycut, schash)
        SetTime()
        Put(context, "entries", 0)
    else:
        print("contest isn't over yet!")
Beispiel #11
0
def Register(prediction_name, context):
    if CheckPredictionGameLive(prediction_name, context):
        tx = GetScriptContainer()
        refs = tx.References
        if len(refs) < 1:
            Log("No payment sent in transaction")
            return False
        ref = refs[0]
        sentAsset = GetAssetId(ref)
        sender_hash = GetScriptHash(ref)

        k1 = concat("balance", sender_hash)
        key = concat(k1, prediction_name)

        balance = Get(context, key)
        if balance >= 5:
            Log("Already registered")
            return False
        else:
            if sentAsset == GAS_ASSET_ID:
                receiver = GetExecutingScriptHash()
                totalGasSent = 0
                cOutputs = len(tx.Outputs)
                Log(cOutputs)
                for output in tx.Outputs:
                    Log(output.Value)
                    shash = GetScriptHash(output)
                    if shash == receiver:
                        totalGasSent = totalGasSent + output.Value
                Log("Total GAS sent:")
                Log(totalGasSent)
                if totalGasSent == b'\x00e\xcd\x1d':
                    Log("Correct GAS Received")
                    Put(context, key, 5)
                    return True
                else:
                    Log("Wrong amount of GAS")
                    return False
            else:
                Log("Not GAS")
                return False
    else:
        Log("Prediction Game not live")
    return False
Beispiel #12
0
def Main(num):
	receiver = GetExecutingScriptHash()

	tx = GetScriptContainer()
	references = tx.References
	reference = references[0]
	sender = GetScriptHash(reference)

	output_asset_id = GetAssetId(reference)
	if output_asset_id == GAS_ASSET_ID:
		print("good")

	for output in tx.Outputs:
		shash = GetScriptHash(output)
		value = GetValue(output) / 100000000
		remainder = value % 1
		value = value - remainder
		OnSpend(b'AFxLPTwPoxowEHvvYYd5RKfJ3VqMTwh4pm', value, receiver)
		return num

	return 0
Beispiel #13
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        return CheckWitness(OWNER)

    elif trigger == Application():
        context = GetContext()
        l = len(args)
        if l == 1:
            key = args[0]
        elif l == 2:
            key = args[0]
            value = args[1]
        else:
            Log("Bad invocation argument count")
            Log(l)
            return False

        if operation == 'getvalue':
            return Get(context, key)
  
        elif operation == 'putvalue':
            prefix = take(key, 6)
            if BADPREFIX == prefix:
                Log("Hacking attempt!")
                return False

            if CheckWitness(OWNER):
                Log("Owner found, bypassing payment")
                Put(context, key, value)
                return True
            else:
                # check if we got paid
                tx = GetScriptContainer()
                refs = tx.References
                if len(refs) < 1:
                    Log("No payment sent in transaction")
                    return False
                ref = refs[0]
                sentAsset = GetAssetId(ref)
                if sentAsset == GAS_ASSET_ID:
                    sender = GetScriptHash(ref)
                    receiver = GetExecutingScriptHash();
                    totalGasSent = 0
            
                    for output in tx.Outputs:
                        shash = GetScriptHash(output)
                        if shash == receiver:
                            totalGasSent = totalGasSent + output.Value

                    Log ("Total GAS sent:")
                    Log (totalGasSent)
                    pkey = concat('price/', key)
                    keyprice = Get(context, pkey)

                    if totalGasSent == keyprice:
                        Log("Price met, setting value and sending notification")
                        notification=[sender,key,value]
                        Notify(notification)
                        Put(context, key, value)
                        return True
                   
                    Log("Price not met!")
                    return False
            
            return False
        elif operation == 'getprice':
            key = concat('price/', key)
            return Get(context, key)

        elif operation == 'putprice':
            if CheckWitness(OWNER):
                key = concat('price/', key)
                Put(context, key, value)
                return True
            else:
                Log("Access denied")
                return False
        else:
            Log("Invalid operation")
            return False
    return False
Beispiel #14
0
def Main(operation_string_para, args):
    trigger = GetTrigger()

    if trigger == Verification:
        # all the hashes, which were found in the transaction outputs
        script_hashes = getOutputScriptHashes()

        if not script_hashes:
            return False

        withdrawal_controller = WithdrawalController()

        for script_hash in script_hashes:
            # these are all the assets, which were created by requesting withdrawals
            released_assets = withdrawal_controller.getReleasedAssets(
                script_hash)

            if released_assets:
                attachment = getAttachedAssets(script_hash)
                # if the requestes asset value is not higher than the stored asset value, allow withdrawal
                if attachment.gas_attached <= released_assets:
                    SpentReleasedAssets(script_hash, attachment.gas_attached)
                    return True
            else:
                n = 0

        return False

    elif trigger == Application:

        if operation_string_para != None:

            args_count = len(args)

            if args_count < 1:
                return 'error: please provide operation arguments'

            # the operation controller check for arguments count and operation string matches
            operations_controller = OperationsController()
            # the withdrawal controller is reponsible for handling the withdrawal requests from the contracts receiver
            withdrawal_controller = WithdrawalController()

            init_operation_strings = operations_controller.validInitOperationStrings(
            )

            # after the receiver has transferred assets from the smart contract, the amount of his released assets has to be reduced.
            if operations_controller.isSpentAssets(operation_string_para):
                if not operations_controller.operationArgsAreValid(
                        operation_string_para, args):
                    return 'error: operation arguments count invalid'

                address = args[0]
                spent_assets = args[1]
                return withdrawal_controller.spentAssets(address, spent_assets)

            # the uid is the identifier for every payment contract between two partys
            uid = args[0]
            payment = Payment()
            payment_in_use = payment.isInUse(uid)

            # only handle init operations at this point
            for init_operation_string in init_operation_strings:
                if operation_string_para == init_operation_string:

                    if not operations_controller.operationArgsAreValid(
                            operation_string_para, args):
                        return 'error: operation arguments count invalid'

                    if payment_in_use:
                        return 'error: cant initialize payment contract. uid is in use'

                    principal = args[1]
                    receiver = args[2]
                    withdrawal_controller.initialize(uid, receiver)

                    if operations_controller.isInitTimeContract(
                            operation_string_para):
                        return payment.initializeTimeContract(args)

                    if operations_controller.isInitUnitsContract(
                            operation_string_para):
                        return payment.initializeUnitsContract(args)

            # all remaining operations need an initialized payment contract
            if not payment_in_use:
                return 'error: operation invalid. payment contract not in use'

            if not operations_controller.operationArgsAreValid(
                    operation_string_para, args):
                return 'error: operation arguments count invalid'

            payment_has_started = payment.hasStarted(uid)

            if not payment_has_started:
                return 'error: operation invalid. payment contract not in use yet'

            # the balance is the available amount, minus spent units and those, which are currently
            if operations_controller.isGetBalance(operation_string_para):
                return payment.getBalance(uid)

            principal = payment.getPrincipalAddress(uid)
            receiver = payment.getReceiverAddress(uid)

            is_principal = CheckWitness(principal)
            is_receiver = CheckWitness(receiver)

            # only the receiver can claim units, which he worked for in a UnitsContract
            if operations_controller.isClaimUnits(operation_string_para):
                if not is_receiver:
                    return 'error: not authorized'

                units_to_claim = args[1]
                units_to_claim = payment.claimUnits(uid, units_to_claim)

                if units_to_claim:
                    OnClaimUnits(uid, units_to_claim)

                return units_to_claim

            # only the owner can authorized units, which the receiver claimed
            if operations_controller.isAuthorizeUnits(operation_string_para):
                if not is_principal:
                    return "error: not authorized"

                units_to_authorize = args[1]
                return payment.authorizeOpenUnits(uid, units_to_authorize)

            # this will return the total amount of available assets transferred by withdrawal requests
            # the receiver can use this, to get the amount of assets he can spent from the smart-contract
            if operations_controller.isGetAvailableAssets(
                    operation_string_para):
                if is_receiver:
                    return withdrawal_controller.getReleasedAssets(receiver)

                return False

            # this will return the amount of assets, which the receiver has requested
            #  the owner can use this, to deposit assets for the receiver
            if operations_controller.isGetOpenWithdrawalValue(
                    operation_string_para):
                if not is_principal:
                    return "error: not authorized"

                return withdrawal_controller.getOpenWithdrawalValue(uid)

            payment_type = payment.getType(uid)

            # only the receiver can request withdrawals from the smart-contract
            if operations_controller.isRequestWithdrawal(
                    operation_string_para):
                if not is_receiver:
                    return "error: not authorized"

                existing_withdrawal_request = withdrawal_controller.getWithdrawalRequest(
                    uid)

                if existing_withdrawal_request:
                    return 'error: withdrawal request in progress. please wait until it finishes'

                units_balance = payment.getUnitsBalance(uid)

                if units_balance == 0:
                    return 'error: withdrawal request invalid. nothing to withdraw'

                current_value = payment.getBalance(uid)

                # if this payment contract was created with all assets deposited up front, there is no need to trigger an event.
                # The withdrawal amount is released immediately
                if payment_type == payment.PAYMENT_TYPE_UP_FRONT:
                    payment.spentUnitsAfterWithdrawalAuthorize(
                        uid, current_value, False)
                    withdrawal_controller.releaseAttachedAssets(
                        receiver, current_value)

                    return current_value
                # all the assets for a withdrawal requests within a just-in-time contract need to deposited manually by the owner
                elif payment_type == payment.PAYMENT_TYPE_JUST_IN_TIME:
                    withdrawal_controller.createNewWithdrawalRequest(
                        uid, units_balance, current_value)
                    payment.reserveUnitsForWithdrawal(uid, units_balance)
                    OnWithdrawalRequest(uid, current_value)

                    return current_value

                return False
            # this operation is used by the owner to deposit assets for the requested amount
            if operations_controller.isDepositWithdrawalsRequest(
                    operation_string_para):
                if not is_principal:
                    return "error: not authorized"

                if payment_type == payment.PAYMENT_TYPE_UP_FRONT:
                    Notify(
                        'error: you cant deposit assets for an up-front contract'
                    )
                    return False

                existing_withdrawal_request = withdrawal_controller.getWithdrawalRequest(
                    uid)

                if not existing_withdrawal_request:
                    return 'error: there is no pending withdrawal request'

                # we get all the assets, which are attached and are ment for the smart-contracts script hash
                contract_script_hash = GetExecutingScriptHash()
                attached_assets = getAttachedAssets(contract_script_hash)
                attached_gas = attached_assets.gas_attached

                if attached_gas == 0:
                    return 'error: no gas attached'

                open_withdrawal_value = withdrawal_controller.getOpenWithdrawalValue(
                    uid)

                # One can never deposit more assets than the requested amount
                if attached_gas != open_withdrawal_value:
                    return 'error: attached gas amount has to match withdrawal requests value'

                payment.spentUnitsAfterWithdrawalAuthorize(
                    uid, attached_gas, True)
                withdrawal_controller.releaseAttachedAssets(
                    receiver, attached_gas)
                withdrawal_controller.clearWithdrawalRequest(uid)

                return attached_gas

        return 'error: no operation string provided'

    return 'error: unknown triger'
Beispiel #15
0
    def initialize(self, args, consume_type):

        if not consume_type:
            return "error: no consume type defined"

        uid = args[0]
        principal_address = args[1]
        receiver_address = args[2]
        overall_value = args[3]
        from_timestamp = args[4]
        to_timestamp = args[5]
        payment_type = args[6]

        storage_api = StorageApi()

        overall_value = overall_value * FACTOR

        # when initializing an up-front contract, the total asset amount has to be attached
        if payment_type == self.PAYMENT_TYPE_UP_FRONT:
            contract_script_hash = GetExecutingScriptHash()
            attached_assets = getAttachedAssets(contract_script_hash)

            if attached_assets.gas_attached == 0:
                return 'error: no gas attached'

            if attached_assets.gas_attached != overall_value:
                return 'error: attached gas is not matching overall value'

            storage_api.putValue(self.STORAGE_KEY_UP_FRONT_HOLDINGS, uid,
                                 attached_assets.gas_attached)

        storage_api.putValue(self.STORAGE_KEY_PRINCIPAL_ADDRESS, uid,
                             principal_address)
        storage_api.putValue(self.STORAGE_KEY_RECEIVER_ADDRESS, uid,
                             receiver_address)
        storage_api.putValue(self.STORAGE_KEY_OVERALL_VALUE, uid,
                             overall_value)
        storage_api.putValue(self.STORAGE_KEY_FROM_TIMESTAMP, uid,
                             from_timestamp)
        storage_api.putValue(self.STORAGE_KEY_TO_TIMESTAMP, uid, to_timestamp)
        storage_api.putValue(self.STORAGE_KEY_PAYMENT_TYPE, uid, payment_type)

        storage_api.putValue(self.STORAGE_KEY_SPENT_UNITS, uid, 0)
        storage_api.putValue(self.STORAGE_KEY_OPEN_UNITS, uid, 0)
        storage_api.putValue(self.STORAGE_KEY_RESERVED_UNITS, uid, 0)
        storage_api.putValue(self.STORAGE_KEY_CURRENT_UNITS, uid, 0)

        storage_api.putValue(self.STORAGE_KEY_CONSUME_TYPE, uid, consume_type)

        # for TimeContracts the total unit count is defined by the timestamps
        if consume_type == self.CONSUME_TYPE_TIME:
            total_units = to_timestamp - from_timestamp
            storage_api.putValue(self.STORAGE_KEY_TOTAL_UNITS, uid,
                                 total_units)
            return True

        # for UnitContracts the total unit count is set by the invoker
        elif consume_type == self.CONSUME_TYPE_UNITS:
            total_units = args[7]
            storage_api.putValue(self.STORAGE_KEY_TOTAL_UNITS, uid,
                                 total_units)
            return True
        else:
            return False

        return True
Beispiel #16
0
def Deposit(escrow_script_hash, note):
    """
    Put money into the contract and set the transactions vins to be owned by escrow_script_hash

    :param escrow_script_hash: the script hash who will be able to move these funds out
    :type escrow_script_hash: bytearray

    :param note: a note for the recipient (escrow_script_hash)
    :type note: strung

    :return: True if the deposit was successful, otherwise, false.
    :rtype: bool

    """

    # Get the transaction info.
    tx = GetScriptContainer()

    # Check if the transactions has currency attached
    references = tx.References
    if len(references) < 1:
        return False

    # Sender's script hash. We'll also grant them ownership of the funds if they need to retrieve their money
    # before it's claimed or if it will never be claimed.
    reference = references[0]
    sender = GetScriptHash(reference)

    # This is the contract's address
    contract_script_hash = GetExecutingScriptHash()

    context = GetContext()

    deposited = False

    # Go through all the outputs and handle deposits
    for output in tx.Outputs:
        shash = GetScriptHash(output)
        output_asset_id = GetAssetId(output)

        # We only care about NEO/GAS coming to the contract.
        if shash == contract_script_hash:
            output_val = GetValue(output)

            deposited = True

            # Update our total counter for this asset. This is just for fun display purposes
            total_all_time_key = concat("totalAllTime", output_asset_id)
            total_all_time = Get(context, total_all_time_key)
            new_total_all_time = total_all_time + output_val
            Put(context, total_all_time_key, new_total_all_time)

    # Here we keep a record of all the tx hashes belonging to the sender and recipient.
    # The idea is that they can view a list of these transactions.
    #
    # Also, the sender can rescind any that was still idle after a week (Mom didn't care enough to pick up
    # her GAS)
    if deposited:
        tx_hash = GetHash(tx)
        time = GetCurrentTimestamp()
        tx_info = [escrow_script_hash, sender, time, note]
        tx_info_serialized = serialize_array(tx_info)
        Put(context, tx_hash, tx_info_serialized)

        AddTransactionToScriptHash('recipient_history', escrow_script_hash,
                                   tx_hash)
        AddTransactionToScriptHash('sender_history', sender, tx_hash)

        return True

    return False
Beispiel #17
0
def CanWithdrawNeo():

    print("[can withdraw]")

    tx = GetScriptContainer()

    type = GetType(tx)

    invoke_type = b'\xd1'

    print("[can withdraw] got tx type...")

    if type == invoke_type:
        print("[can withdraw] Is invocation!!")

        # this is the contract's address
        sender_addr = GetExecutingScriptHash()

        withdrawal_amount = 0

        receiver_addr = bytearray(0)

        # go through the outputs of the tx
        # and find ones that are neo
        # and also the receiver cannot be the contract ( sender_addr )
        for output in tx.Outputs:
            shash = GetScriptHash(output)

            output_asset_id = GetAssetId(output)

            if output_asset_id == NEO_ASSET_ID:

                output_val = GetValue(output)

                if shash != sender_addr:

                    print("[can withdraw] output is to receiver")
                    receiver_addr = shash

                    withdrawal_amount = withdrawal_amount + output_val

                    Notify(withdrawal_amount)
                    Notify(output)

                else:

                    print(
                        "[can withdraw] output is to contract sender addr, subtract from withdraw total"
                    )

                    withdrawal_amount = withdrawal_amount - output_val

                    Notify(output)
            else:

                print("[can withdraw] output is not neo")
                Notify(output)

        # we check recevier addr and amount

        if len(receiver_addr) > 0:

            print("[can withdraw] receiver addr is valid")
            Notify(receiver_addr)

            context = GetContext()

            current_balance = Get(context, receiver_addr)

            print("[can withdraw] current balance")
            Notify(current_balance)
            Notify(withdrawal_amount)

            if withdrawal_amount <= current_balance:

                print("[can withdraw] withdrawl amount il less than balance")

                onWithdraw(receiver_addr, withdrawal_amount)

                return True

            else:

                print("[can withdraw] not enough to witdraw")
        else:

            print("[can withdraw] receiver addr not set")
    else:

        print("[can withdraw] tx is not invocation tx. return false")

    return False
Beispiel #18
0
def Main(operation, args):
    """
    :param operation: get or put
    :param args: optional arguments
    :return: Bool
    """

    Log("Running Main Loop")
    trigger = GetTrigger()
    if trigger == Verification:
        Log("trigger: Verification")
        is_owner = CheckWitness(owner)
        if is_owner:
            return True
    elif trigger == Application:
        Log("trigger: Application")
        context = GetContext()
        if operation == 'getvalue':
            Log("op: getvalue")
            key = args[0]
            return Get(context, key)
        if operation == 'register-oracle':
            Log("op: register-oracle")
            nArgs = len(args)
            Log(nArgs)
            if len(args) != 1:
                return False
            tx = GetScriptContainer()
            refs = tx.References
            if len(refs) < 1:
                Log("No payment sent in transaction")
                return False
            ref = refs[0]
            sentAsset = GetAssetId(ref)
            sender = GetScriptHash(ref)
            oracle_app = args[0]
            k = concat(sender, oracle_app)
            amount = Get(context, k)
            if amount == 5:
                Log("Already registered")
                return False
            if sentAsset == GAS_ASSET_ID:
                Log("Ok it is GAS")
                receiver = GetExecutingScriptHash()
                totalGasSent = 0
                cOutputs = len(tx.Outputs)
                Log(cOutputs)
                for output in tx.Outputs:
                    Log(output.Value)
                    shash = GetScriptHash(output)
                    if shash == receiver:
                        totalGasSent = totalGasSent + output.Value

                Log("Total GAS sent:")
                Log(totalGasSent)
                if totalGasSent == b'\x00e\xcd\x1d':
                    Log("That's what we wanted")
                    Notify("We received the GAS")

                    Put(context, k, 5)
                    return True
                else:
                    Log("We didn't want this.")
                    return False
            else:
                Log("Not Gas")
                return False
    return False
Beispiel #19
0
def AddEntry():
    tx = GetScriptContainer()
    context = GetContext()
    references = tx.References
    if _TimeHasExpired():
        # refund gas and neo and pick winner
        PickWinner()
        return 0
    print("adding entry")
    if len(references) < 1:
        print("no gas attached")
        return False

    print("reading reference")
    reference = references[0]
    print("reference read")

    sender = GetScriptHash(reference)
    print("sender hash is")
    print(sender)
    print("reading script hash")

    print("getting asset ID. ID is here:")
    output_asset_id = GetAssetId(reference)
    print(output_asset_id)
    print('asset id printed above')
    if output_asset_id == GAS_ASSET_ID:
        print("executing script hash")
        receiver = GetExecutingScriptHash()
        for output in tx.Outputs:
            shash = GetScriptHash(output)
            print("getting shash..")
            if shash == receiver:
                print("adding value?")
                value = GetValue(output) / 100000000
                print("value storing in entries")
                print(value)
                print('string we will save to the entries array')
                entries = Get(context, 'entries')
                print('current entries')
                print(entries)
                remainder = value % 1
                print('remainder is')
                Notify(remainder)
                value = value - remainder
                print('remainder and value set')
                Notify(value)
                if value > 0:
                    if entries != bytearray(b''):
                        print('deserializing the byte array')
                        entries = deserialize_bytearray(entries)
                        end = len(entries) + value
                        if end > 1024:
                            print('contest capped at 1024')
                            return 0
                        new_entries = range(0, end)
                        i = 0
                        for item in new_entries:
                            if i < len(entries):
                                new_entries[i] = entries[i]
                            else:
                                new_entries[i] = sender
                            i += 1
                        # last_entry = entries[len(entries) - 1]
                        # colon_index = [pos for pos, char in enumerate(
                        #     last_entry) if char == ':']
                        # previous_total = substr(
                        #     last_entry, 0, colon_index)
                    else:
                        print('setting an empty array')
                        # list isn't working below
                        new_entries = range(0, value)
                        j = 0
                        for item in new_entries:
                            new_entries[j] = sender
                            j += 1
                else:
                    print("no gas added")
                Notify(new_entries)
                new_entries = serialize_array(new_entries)
                Put(context, "entries", new_entries)
    return entries
Beispiel #20
0
def MintTokens():
    """
    Method for an address to call in order to deposit NEO into the NEP5 token owner's address in exchange for a calculated amount of NEP5 tokens

    :return: whether the token minting was successful
    :rtype: bool

    """
    print("minting tokens!")

    tx = GetScriptContainer()

    references = tx.References

    print("helol1")
    if len(references) < 1:
        print("no neo attached")
        return False

    print("hello2")
    reference = references[0]
    print("hello2")
    #    sender = reference.ScriptHash

    sender = GetScriptHash(reference)
    print("hello4")

    value = 0
    print("hello5")
    output_asset_id = GetAssetId(reference)
    if output_asset_id == NEO_ASSET_ID:

        print("hello6")
        receiver = GetExecutingScriptHash()
        print("hello7")
        for output in tx.Outputs:
            shash = GetScriptHash(output)
            print("getting shash..")
            if shash == receiver:
                print("adding value?")
                output_val = GetValue(output)
                value = value + output_val

        print("getting rate")
        rate = CurrentSwapRate()
        print("got rate")
        if rate == 0:
            OnRefund(sender, value)
            return False

        num_tokens = value * rate / 100000000

        context = GetContext()

        balance = Get(context, sender)

        new_total = num_tokens + balance

        Put(context, sender, new_total)

        total_supply = Get(context, 'totalSupply')

        new_total_supply = total_supply + num_tokens

        Put(context, 'totalSupply', new_total_supply)

        OnTransfer(0, sender, num_tokens)

        return True

    return False
Beispiel #21
0
def ReconcileBalances():

    print("[Reconcile balances]")
    # this is the contract's address
    sender_addr = GetExecutingScriptHash()

    tx = GetScriptContainer()

    withdrawal_amount = 0

    receiver_addr = bytearray(0)

    # go through the outputs of the tx
    # and find ones that are neo
    # and also the receiver cannot be the contract ( sender_addr )
    for output in tx.Outputs:
        shash = GetScriptHash(output)

        output_asset_id = GetAssetId(output)

        if output_asset_id == NEO_ASSET_ID:

            if shash != sender_addr:

                print("[reconcile] output is to receiver")
                receiver_addr = shash

                output_val = GetValue(output)

                withdrawal_amount = withdrawal_amount + output_val

                Notify(withdrawal_amount)
                Notify(output)

            else:

                print(
                    "[Reconcile balances] output is to contract sender addr, ignore"
                )
                Notify(output)
        else:

            print("[Reconcile balances] output is not neo")
            Notify(output)

    # we check recevier addr and amount

    if len(receiver_addr) > 0:

        print("[Reconcile balances] receiver addr is valid")
        Notify(receiver_addr)

        context = GetContext()

        current_balance = Get(context, receiver_addr)

        print("[Reconcile balances] current balance")
        Notify(current_balance)
        Notify(withdrawal_amount)

        if withdrawal_amount <= current_balance:

            new_balance = current_balance - withdrawal_amount

            print("[Reconcile balances] new balance is...")
            Notify(current_balance)
            Notify(new_balance)

            Put(context, receiver_addr, new_balance)

            onWithdrawReconciled(receiver_addr, new_balance)
            print("[Reconcile balances] withdrawl amount il less than balance")
            return True

        else:

            print("[Reconcile balances] not enough to witdraw")
    else:

        print("[Reconcile balances] receiver addr not set")

    return False
Beispiel #22
0
def CanWithdrawNeo():

    print("[can withdraw]")
    is_invocation = IsInvocationTx()

    if is_invocation:
        # this is the contract's address
        sender_addr = GetExecutingScriptHash()

        tx = GetScriptContainer()

        withdrawal_amount = 0

        receiver_addr = bytearray(0)

        # go through the outputs of the tx
        # and find ones that are neo
        # and also the receiver cannot be the contract ( sender_addr )
        for output in tx.Outputs:
            shash = GetScriptHash(output)

            output_asset_id = GetAssetId(output)

            if output_asset_id == NEO_ASSET_ID:

                if shash != sender_addr:

                    print("[can withdraw] output is to receiver")
                    receiver_addr = shash

                    output_val = GetValue(output)

                    withdrawal_amount = withdrawal_amount + output_val

                    Notify(withdrawal_amount)
                    Notify(output)

                else:

                    print(
                        "[can withdraw] output is to contract sender addr, ignore"
                    )
                    Notify(output)
            else:

                print("[can withdraw] output is not neo")
                Notify(output)

        # we check recevier addr and amount

        if len(receiver_addr) > 0:

            print("[can withdraw] receiver addr is valid")
            Notify(receiver_addr)

            context = GetContext()

            current_balance = Get(context, receiver_addr)

            print("[can withdraw] current balance")
            Notify(current_balance)
            Notify(withdrawal_amount)

            if withdrawal_amount <= current_balance:

                print("[can withdraw] withdrawl amount il less than balance")

                onWithdraw(receiver_addr, withdrawal_amount)

                return True

            else:

                print("[can withdraw] not enough to witdraw")
        else:

            print("[can withdraw] receiver addr not set")

    return False
Beispiel #23
0
def Main(operation, args):
    trigger = GetTrigger()

    if trigger == Verification():
        # Verification is done when sending money out of the contract.
        #
        # We need to check the sender's balance to make sure they have enough to allow them
        # to send what they're trying to send
        #
        # Note: Contract owner has no special privileges here.

        tx = GetScriptContainer()

        valid = False

        # Go through all the outputs and make sure there's only one output destination.
        # This will be used if we're auto-rescinding the assets (ie sending back to the original
        # sender after a week goes by without the recipient picking up). We'll make sure there's only
        # one output script hash and it matches the stored script hash of the original sender
        #
        # Also we make sure not outputs are going to the contract script hash because we don't support
        # change.
        output_script_hash = None
        contract_script_hash = GetExecutingScriptHash()
        for output in tx.Outputs:
            shash = GetScriptHash(output)
            if shash == contract_script_hash:
                return False

            if output_script_hash == None:
                output_script_hash = shash
            elif shash != output_script_hash:
                return False

        for input in tx.Inputs:
            hash = InputGetHash(input)
            context = GetContext()
            tx_info_serialized = Get(context, hash)
            tx_info = deserialize_bytearray(tx_info_serialized)

            escrow = tx_info[0]
            sender = tx_info[1]
            time = tx_info[2]

            is_escrow = CheckWitness(escrow)

            if is_escrow != True:
                if sender != output_script_hash:
                    return False

                current_time = GetCurrentTimestamp()
                seven_days = 604800
                minimum_time = time + seven_days
                if current_time < minimum_time:
                    return False

            # We have at least one. We'll keep checking if there are more.
            print('That input was valid')
            valid = True

        print('All good')
        return valid

    elif trigger == Application():
        if operation == 'name':
            n = "Sendeo"
            return n

        elif operation == 'deposit':
            if len(args) != 2:
                return False

            recipient = args[0]
            note = args[1]

            deposit = Deposit(recipient, note)

            return deposit

    return False
Beispiel #24
0
def mint_tokens():
    """
    Mint tokens during a crowdsale period.

    :return:
        bool: Whether tokens were successfully minted.
    """

    attachments = Attachments()
    context = GetContext()

    # If the token is not deployed yet, return.
    if not Get(context, token_deployed):
        print("Call deploy_token before minting..")
        return False

    tx = GetScriptContainer()  # type:Transaction
    references = tx.References
    attachments.receiver_addr = GetExecutingScriptHash()

    if len(references) > 0:

        reference = references[0]
        attachments.sender_addr = reference.ScriptHash

        sent_amount_neo = 0
        sent_amount_gas = 0

        for output in tx.Outputs:
            if output.ScriptHash == attachments.receiver_addr and output.AssetId == attachments.neo_asset_id:
                sent_amount_neo += output.Value

            if output.ScriptHash == attachments.receiver_addr and output.AssetId == attachments.gas_asset_id:
                sent_amount_gas += output.Value

        attachments.neo_attached = sent_amount_neo
        #attachments.gas_attached = sent_amount_gas

    # Accepting NEO for the sale.
    if attachments.neo_attached == 0:
        return False

    # The following looks up whether an address has been
    # registered with the contract for KYC regulations
    # this is not required for operation of the contract.
    if not kyc_status(attachments.sender_addr):
        return False

    # Calculate the amount requested.
    amount_requested = attachments.neo_attached * tokens_per_neo / 100000000

    # Check if we can exchange.
    can_exchange = calculate_can_exchange(amount_requested, attachments.sender_addr)

    if not can_exchange:
        return False

    # Lookup the current balance of the address.
    current_balance = Get(context, attachments.sender_addr)

    # Calculate the amount of tokens the attached neo will earn.
    exchanged_tokens = attachments.neo_attached * tokens_per_neo / 100000000

    # If using GAS instead of NEO use this.
    # exchanged_tokens += attachments.gas_attached * tokens_per_gas / 100000000

    # Add it to the exchanged tokens and put it into storage.
    new_total = exchanged_tokens + current_balance
    Put(context, attachments.sender_addr, new_total)

    # Update the circulation amount.
    add_to_circulation(exchanged_tokens)

    # Dispatch the transfer event.
    OnTransfer(attachments.receiver_addr, attachments.sender_addr, exchanged_tokens)

    return True