Beispiel #1
0
 def put(self, key, value):
     Put(self.ctx, key, value)
Beispiel #2
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 #3
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 #4
0
def Main(value):

    Put("key", value)
Beispiel #5
0
    def voteForOutcome(self, ID: bytes, outcome: int, amount: int,
                       voter: bytes, contractAddress: bytes):
        ctx = GetContext()

        #check if witness
        isvoter = CheckWitness(voter)
        if not isvoter:
            #print('Must be voter to vote for outcome')
            return False

        #check if Oracle is challenged
        isChallenged = self.isChallenged(ID)
        if not isChallenged:
            #print('Oracle is not be challenged yet')
            return False

        #check if front runner period is not over yet
        isFrontRunnerPeriodOver = self.isFrontRunnerPeriodOver(ID)
        if isFrontRunnerPeriodOver:
            #print('Front runner period is over, oracle is done')
            return False

        #read param from storage
        keySpreadMultiplier = concat(b'SpreadMultiplier', ID)
        spreadMultiplier = Get(ctx, keySpreadMultiplier)
        keyTotalAmount = concat(b'TotalAmount', ID)
        totalAmount = Get(ctx, keyTotalAmount)
        keyTotalOutcomeAmounts = concat(outcome, ID)
        totalOutcomeAmounts = Get(ctx, keyTotalOutcomeAmounts)

        maxAmount = (totalAmount - totalOutcomeAmounts) * spreadMultiplier
        if maxAmount > totalOutcomeAmounts:
            maxAmount = maxAmount - totalOutcomeAmounts
        else:
            maxAmount = 0
        if amount > maxAmount:
            amount = maxAmount

        #deposit
        isok = self.deposit(voter, contractAddress, amount)

        if not isok:
            #print('Deposit Failed')
            return False

        keyOutcomeAmountT = concat(voter, ID)
        keyOutcomeAmount = concat(outcome, keyOutcomeAmountT)
        outcomeAmount = Get(ctx, keyOutcomeAmount)
        outcomeAmount = outcomeAmount + amount
        Put(ctx, keyOutcomeAmount, outcomeAmount)

        keyTotalOutcomeAmounts = concat(outcome, ID)
        totalOutcomeAmounts = Get(ctx, keyTotalOutcomeAmounts)
        totalOutcomeAmounts = totalOutcomeAmounts + amount
        Put(ctx, keyTotalOutcomeAmounts, totalOutcomeAmounts)

        keyTotalAmount = concat(b'TotalAmount', ID)
        totalAmount = Get(ctx, keyTotalAmount)
        totalAmount = totalAmount + amount
        Put(ctx, keyTotalAmount, totalAmount)

        #check if front runner changes
        keyFrontRunner = concat(b'FrontRunner', ID)
        frontRunner = Get(ctx, keyFrontRunner)
        keyTotalOutcomeAmountsF = concat(frontRunner, ID)
        totalOutcomeAmountsF = Get(ctx, keyTotalOutcomeAmountsF)

        isfrontrunnerChanges1 = (outcome != frontRunner)
        isfrontrunnerChanges2 = (totalOutcomeAmounts > totalOutcomeAmountsF)
        if not isfrontrunnerChanges1:
            return False
        if not isfrontrunnerChanges2:
            return False
        else:
            Put(ctx, keyFrontRunner, outcome)
            now = self.now()
            keyFrontRunnerSetTimestamp = concat(b'FrontRunnerSetTimestamp', ID)
            Put(ctx, keyFrontRunnerSetTimestamp, now)
            return True
Beispiel #6
0
def relic_price_write(context, owner, relic, price):
    price_key = relic_price_key(owner, relic)
    Put(context, price_key, price)
    OnRelicPrice(owner, relic, price)
def Main(operation, args):
    """
    Calling the Main function of this NEO smart contract enables registering
    a last will or inheritage datum. It also allows to set heirs and transfers
    of inheritage, which works exactly like the NEO licensing contracts.
    """

    caller = args[0] # used with CheckWitness below to conform authorization
    caller_is_authorized = CheckWitness(caller) # Boolean

    if not caller_is_authorized:
        print('Action denied.')
        return False

    print('Action granted.')
    
    input_inheritage_datum = args[1]
    caller_with_input_will_or_inheritage_datum = concat(caller, input_inheritage_datum)

    # Set testator_or_heir to the optional third argument or use the caller
    if len(args) == 3:
        testator_or_heir = args[2]
        legal_entity_with_inheritage_datum = concat(testator_or_heir, input_inheritage_datum)
    else:
        testator_or_heir = caller
        legal_entity_with_inheritage_datum = caller_with_input_will_or_inheritage_datum


    if operation != None:


        if operation == 'RegisterWillOrInheritage':        
            """
            Register will or equity specification 
            document to the contract caller.
            """
            storage_occupying_name = Get(GetContext, input_inheritage_datum)

            if storage_occupying_name:
                print(storage_occupying_name)
              
            else:
                Put(GetContext, input_inheritage_datum, caller)
                
                print("Your will was successfully registered.")
                
            return True


        if operation == 'SetInheritage':        
            """
            Set a testator_or_heir for a registered equity.
            """
            if authorization_check(input_inheritage_datum):
                Put(GetContext, legal_entity_with_inheritage_datum, testator_or_heir)
                
                print("The inheritage was successfully set to legal entity.")

                return True


        if operation == 'QueryInheritage':
            """
            Quiery the legal testator_or_heir of an inheritage.
            """
            legal_testator_or_heir = Get(GetContext, legal_entity_with_inheritage_datum)
            
            print(legal_testator_or_heir)

            if legal_testator_or_heir:
                return True


        if operation == 'CancelInheritage':
            if authorization_check(input_inheritage_datum):
                testator_or_heir_to_del = args[2]

                inheritage_to_be_removed = concat(testator_or_heir_to_del, input_inheritage_datum)
                Delete(GetContext, inheritage_to_be_removed)

                print("The inheritance was successfully removed from the will.")

                return True


        if operation == 'ChangeInheritage':
            legal_entity = Get(GetContext, caller_with_input_will_or_inheritage_datum)

            if legal_entity:
                is_authorized_legal_entity = CheckWitness(legal_entity)

                if is_authorized_legal_entity:
                    changed_testator_or_heir = args[2]
                    changed_testator_with_input_inheritage_datum = concat(changed_testator_or_heir, input_inheritage_datum)
                    Delete(GetContext, caller_with_input_will_or_inheritage_datum)
                    Put(GetContext, changed_testator_with_input_inheritage_datum, changed_testator_or_heir)

                    print("Your will has changed.")

                    return True


        return False
Beispiel #8
0
def put(category, id, value):
    skey = concat(category, id)
    Put(GetContext(), skey, value)
Beispiel #9
0
def AddOracle(prediction_name, normalised_timestamp, oracle, context):
    k0 = concat("oracles", prediction_name)
    key = concat(k0, normalised_timestamp)
    oracles = Get(context, key)
    new_oracles = concat(oracles, oracle)
    Put(context, key, new_oracles)
Beispiel #10
0
def AddBalance(prediction_name, sender_hash, winnings, context):
    k0 = concat("balance", sender_hash)
    key = concat(k0, prediction_name)
    balance = Get(context, key)
    balance = balance + winnings
    Put(context, key, balance)
Beispiel #11
0
def UpdateTimestamp(prediction_name, timestamp, context):
    key = concat("timestamp", prediction_name)
    Put(context, key, timestamp)
Beispiel #12
0
def UpdateMaxVotes(prediction_name, normalised_timestamp, count, context):
    k0 = concat("max_votes", prediction_name)
    key = concat(k0, normalised_timestamp)
    Put(context, key, count)
Beispiel #13
0
def ZeroBalance(prediction_name, sender_hash, context):
    k0 = concat("balance", sender_hash)
    key = concat(k0, prediction_name)
    Put(context, key, 0)
Beispiel #14
0
def put_offer(marketplace, address, item_id, price):
    """
    Put a new offer up on a marketplace.

    :return:
        bool: Whether the offer was put.
    """
    context = GetContext()

    # The price of the offer must be greater than 0.
    if price <= 0:
        return False

    # Check marketplace permissions.
    owner = marketplace_owner(marketplace)
    if not CheckWitness(owner):
        print("Operation Forbidden: Only the owner of this marketplace may invoke the operation - put_offer")
        return False

    # If the removal of the item from the address was successful, put the offer up.
    if remove_item(marketplace, address, item_id):

        # Concatenate the key to get the current index of the marketplace, then get the current offer index.
        marketplace_index_key = concat(current_offer_index_key, marketplace)
        index = Get(context, marketplace_index_key)

        # Concatenate the key to get all the offers on the marketplace.
        marketplace_offers_key = concat(offers_key,marketplace)

        # If the index has not been set yet we create it, else we create a new offer id with the current index.
        if not index:
            index = 1
            marketplace_offer_id = concat(marketplace, "offer\x01")
        else:
            # Create the offer id to put into storage.
            offer_id = concat("offer", index)
            # Concatenate the name of the marketplace and offer so we can access these offers on individual markets.
            marketplace_offer_id = concat(marketplace, offer_id)

        # Get the list of all offers that are currently up in the marketplace.
        all_offers_s = get_all_offers(marketplace)

        # If there are no offers in the storage, put the first element in a new list
        # else, append the offer id to the pre-existing list of offer ids.
        if not all_offers_s:
            all_offers = [marketplace_offer_id]
        else:
            all_offers = deserialize_bytearray(all_offers_s)
            all_offers.append(marketplace_offer_id)

        # Serialize the list of offers we have modified.
        all_offers_s = serialize_array(all_offers)
        # Create a new serialized offer ready to put into storage.
        offer = new_offer(address, marketplace_offer_id, item_id, price)

        # Put the list of all offers and the offer id into storage.
        Delete(context, marketplace_offers_key)
        Put(context, marketplace_offers_key, all_offers_s)
        Put(context, marketplace_offer_id, offer)

        # Can now increment the offer index for the marketplace and save it into storage.
        index += 1
        Delete(context, marketplace_index_key)
        Put(context, marketplace_index_key, index)

        return True

    return False
Beispiel #15
0
def relic_balance_write(context, owner, relic, amount):
    owner_key = relic_balance_key(owner, relic)
    Put(context, owner_key, amount)
    OnRelicBalance(owner, relic, amount)
Beispiel #16
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
Beispiel #17
0
def relic_sell_write(context, owner, relic, amount):
    sale_key = relic_sale_key(owner, relic)
    Put(context, sale_key, amount)
    OnRelicSell(owner, relic, amount)
Beispiel #18
0
def Milestone(milestone_key, agreement, customer, assignee, platform,
              timestamp, utc_offset, oracle, pay_out, asset, threshold):
    """
    Method to create a milestone

    :param milestone_key: unique identifier for the milestone
    :type milestone_key: str

    :param agreement: key of the parent agreement this milestone belongs to
    :type agreement: str

    :param customer: customer party of the milestone
    :type customer: bytearray

    :param assignee: assignee party of the milestone
    :type assignee: bytearray

    :platform: id of platform on which the project repository is (e.g. GitHub)
    :type platform: str

    :param timestamp: timezone naive datetime of the day of the event
    :type timestamp: int

    :param utc_offset: positive or negative utc_offset for timestamp
    :type utc_offset: int

    :param oracle: oracle (reviewer of the task)
    :type oracle: bytearray

    :param pay_out: the amount to pay out to the assignee on success
    :type pay_out: int

    :param asset: the NEO asset used in the milestone instance
    type asset: bytearray

    :param threshold: the minimum score for the milestone (out of 100)
    :type threshold: int

    :return: whether the milestone was successfully added
    :rtype: bool
    """

    context = GetContext()
    m = Get(context, milestone_key)

    if len(m) > 0:
        Notify("milestone_key not unique, please use another")
        return False

    # Get timestamp of current block
    currentHeight = GetHeight()
    currentBlock = GetHeader(currentHeight)
    current_time = currentBlock.Timestamp

    # Compute timezone adjusted time
    timezone_timestamp = timestamp + (utc_offset * 3600)
    timezone_current_time = current_time + (utc_offset * 3600)

    # Check if timestamp is not out of boundaries
    if timezone_timestamp < (timezone_current_time + MIN_TIME - TIME_MARGIN):
        Notify("Datetime must be $MIN_TIME seconds ahead")
        return False

    elif timezone_timestamp > (timezone_current_time + MAX_TIME + TIME_MARGIN):
        Notify("Datetime must be $MAX_TIME seconds ahead")
        return False

    fee = Get(context, 'fee')

    if len(fee) == 0:
        fee = INITIAL_FEE

    # Check if pay_out and fee are not zero or below
    if pay_out <= 0:
        Notify("Pay_out is zero or negative")
        return False

    if fee <= 0:
        Notify("Fee is zero or negative")
        return False

    # check if payment is received if milestone is not created by OWNER
    if not CheckWitness(OWNER):
        attachments = get_asset_attachments()
        total_cost = pay_out + fee

        if asset == attachments.neo_asset_id:
            if attachments.neo_attached > 0:
                if not attachments.neo_attached == total_cost:
                    Notify("Incorrect payment received, returning funds")
                    DoTransfer(OWNER, customer, attachments.neo_attached)
                    return False
            else:
                Notify("No payment received")
                return False

        elif asset == attachments.gas_asset_id:
            if attachments.gas_attached > 0:
                if not attachments.gas_attached == total_cost:
                    Notify("Incorrect payment received, returning funds")
                    DoTransfer(OWNER, customer, attachments.gas_attached)
                    return False
            else:
                Notify("No payment received")
                return False

    status = 'initialized'

    # Set place holder value
    review_score = 0

    milestone_data = [agreement, customer, assignee, platform, timestamp, utc_offset, oracle, pay_out, asset, fee, threshold, status, review_score]
    milestone_data_serialized = serialize_array(milestone_data)
    Put(context, milestone_key, milestone_data_serialized)

    DispatchMilestoneEvent(milestone_key)

    return True
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