Exemple #1
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
Exemple #2
0
def CanWithdrawNeo():

    print("[can withdraw Neo]")

    tx = GetScriptContainer()
    context = GetContext()

    for output in tx.Outputs:
        shash = GetScriptHash(output)
        output_asset_id = GetAssetId(output)

        if output_asset_id == NEO_ASSET_ID:
            print("Asset is Neo")

        else:

            return False

    return True

    saved_timestamp = Get(context, "timestamp")

    Notify("saved_timestamp: ", saved_timestamp)

    current_timestamp = GetHeight()

    Notify("current_timestamp: ", current_timestamp)

    return current_timestamp > (saved_timestamp + 4)
def getAttachedAssets(receiver) -> Attachments:

    attachment = Attachments()
    tx = GetScriptContainer()
    references = tx.References
    attachment.receiver_addr = receiver

    if len(references) > 0:
        reference = references[0]
        attachment.sender_addr = reference.ScriptHash

        sent_amount_gas = 0

        for output in tx.Outputs:
            if output.AssetId != attachment.gas_asset_id:
                Notify('error: only gas please')
                return False

            if output.ScriptHash == receiver:
                sent_amount_gas += output.Value

            else:
                n = 0

        Notify(sent_amount_gas)
        attachment.gas_attached = sent_amount_gas

    return attachment
Exemple #4
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
Exemple #5
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
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
Exemple #7
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
Exemple #8
0
def GetTransactionHash() -> str:
    """Fetches the hash of the current transaction.

    Return:
        (str): hash of current transaction.
    """

    transaction = GetScriptContainer()
    hash = GetHash(transaction)
    return hash
Exemple #9
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
Exemple #10
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
Exemple #11
0
def getValue():
    tx = GetScriptContainer()
    references = tx.References
    reference = references[0]
    output_asset_id = GetAssetId(reference)
    if output_asset_id == GAS_ASSET_ID:
        for output in tx.Outputs:
            shash = GetScriptHash(output)
            value = GetValue(output) / 100000000
            remainder = value % 1
            value = value - remainder
            return value
    print("gas not found rip")
    return 0
Exemple #12
0
def IsInvocationTx():

    tx = GetScriptContainer()

    type = tx.Type

    Notify(type)

    if type == InvocationTransaction():

        print("Is invocation!!")

        return True

    print("not invocation")
    return False
def getOutputScriptHashes():
    attachment = Attachments()
    tx = GetScriptContainer()
    references = tx.References
    script_hashes = []

    if len(references) > 0:
        for output in tx.Outputs:
            if output.AssetId != attachment.gas_asset_id:
                Notify('error: only gas, please')
                return False

            script_hash = output.ScriptHash
            script_hashes.append(script_hash)

    return script_hashes
Exemple #14
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!")
Exemple #15
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
Exemple #16
0
def CanClaimGas():
    print("Withdrawing Donations")

    tx = GetScriptContainer()
    tpe = GetType(tx)
    print("Type: ", tpe)

    for output in tx.Outputs:
        shash = GetScriptHash(output)
        output_asset_id = GetAssetId(output)

        if output_asset_id == GAS_ASSET_ID:
            print("Asset is Gas")

        else:

            return False

    return True
Exemple #17
0
def GetTXInputs():

    tx = GetScriptContainer()

    inputs = tx.Inputs
    inputlen = len(inputs)

    results = list(length=inputlen)

    count = 0

    for input in tx.Inputs:

        txid = GetHash(input)
        index = GetIndex(input)
        item = [txid, index]
        results[count] = item
        count += 1

    return results
Exemple #18
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
Exemple #19
0
def add_url(url):
    """ Generates a new code and stores the <code, url> pair into the blockchain. """
    # Retrieves the current "height" of the blockchain, as of the related block and timestamp.
    current_height = GetHeight()
    header = GetHeader(current_height)

    # Retrieves the hash of the considered sender.
    tx = GetScriptContainer()
    references = tx.References
    ref = references[0]
    sender = GetScriptHash(ref)

    # Generates a random number from the consensus data of the block (the pseudo-random number
    # generated by the consensus node). We also generate a number from the considered URL.
    random_number = header.ConsensusData >> 32
    url_seed = url[:16] >> 96

    # Generates a unique code.
    s1 = b58encode(current_height, 6)
    s2 = b58encode(random_number, 2)
    s3 = b58encode(url_seed, 4)
    code_p1 = concat(s1, s2)
    code = concat(code_p1, s3)

    # Puts the URL and the related information into the ledger.
    context = GetContext()
    contextkey_for_url = get_contextkey_for_url(code)
    contextkey_for_sender = get_contextkey_for_sender(code)
    # NOTE: dictionaries are not yet supported by the neo-boa compiler so we have to derive multiple
    # context keys from the code value for each item associated with the considered code.
    Put(context, contextkey_for_url, url)
    Put(context, contextkey_for_sender, sender)

    # Fires an event indicating which <code, url> pair has been persisted into the ledger.
    DispatchNewURLEvent(code, url)

    return True
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
Exemple #21
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
Exemple #22
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
Exemple #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
Exemple #24
0
def GetTransactionHash() -> str:
    transaction = GetScriptContainer()
    hash = GetHash(transaction)
    return hash
Exemple #25
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
Exemple #26
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
Exemple #27
0
def Main(operation, args):
    """
    :param operation: new, submit, judge, getvalue
    :param args: optional arguments
    :return: Bool
    """

    trigger = GetTrigger()
    if trigger == Application:
        Log("trigger: Application")
        context = GetContext()

        if operation == 'getvalue':
            Log("op: getvalue")
            key = args[0]
            return Get(context, key)

        if operation == 'new':
            id = args[0]
            Put(context, "current_game", id)
            Log("Created a new game")

        elif operation == 'submit':
            id = args[0]
            price = args[1]
            Log(id)
            Log(price)

            # Only allow submissions for the current game
            current_game = Get(context, "current_game")
            if current_game != id:
                Log("Not the correct game")
                return False

            tx = GetScriptContainer()
            refs = tx.References
            nRef = len(refs)
            Log(nRef)
            ref = refs[0]
            sender = GetScriptHash(ref)
            Log(sender)
            key = concat(sender, id)
            Log(key)
            oldprice = Get(context, key)
            if oldprice == 0:
                Append(context, sender, id)
            Put(context, key, price)  # Update if already exists

        elif operation == 'judge':
            id = args[0]
            playerkey = concat("players::", id)
            curr_list = Get(context, playerkey)
            nplayers = len(curr_list) // 20
            max = 0
            best_price = -1
            for i in range(0, nplayers):
                start = 20 * i
                player = substr(curr_list, start, 20)
                Log(player)
                key = concat(player, id)
                price = Get(context, key)
                price_key = concat(id, price)
                count = Increment(context, price_key)
                if count > max:
                    max = count
                    best_price = price
            if max == 0:
                Log("No entries")
                return False
            else:
                Log(max)
                Log(best_price)
                Put(context, id, best_price)
                return True
        return True
    return False
Exemple #28
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
Exemple #29
0
def getSource():
    tx = GetScriptContainer()
    references = tx.References
    reference = references[0]
    sender = GetScriptHash(reference)
    return sender
Exemple #30
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