Beispiel #1
0
def check_allPostIds():
    all_posts = Get(GetContext(), get_all_ids)
    if not all_posts:
        Notify("[!] Creating all_posts object")
        all_posts = {}
        serialized = Serialize(all_posts)
        Put(GetContext(), get_all_ids, serialized)
Beispiel #2
0
def kyc_register(ctx, args):
    """

    :param args:list a list of addresses to register
    :param token:Token A token object with your ICO settings
    :return:
        int: The number of addresses to register for KYC
    """
    ok_count = 0

    if CheckWitness(TOKEN_OWNER):

        print("Is owner")

        for address in args:

            if len(address) == 20:

                print("Saving address to kyc")

                kyc_storage_key = concat(KYC_KEY, address)
                Put(ctx, kyc_storage_key, True)

                OnKYCRegister(address)
                ok_count += 1

    return ok_count
Beispiel #3
0
def register_smart_lock(address, smart_lock_ip, owner_name, room_name, price):
    if not CheckWitness(address):
        return False
    Log('Registering Smart LOCK')
    Put(context, smart_lock_ip, address)

    key = concat(smart_lock_ip, '/price')
    Put(context, key, price)

    key = concat(smart_lock_ip, '/owner')
    Put(context, key, owner_name)

    key = concat(smart_lock_ip, '/room')
    Put(context, key, room_name)

    return True
Beispiel #4
0
def add_to_board_list(board_id):
    serialized_list = Get(ctx, AD_LIST_KEY)
    board_list = Deserialize(serialized_list)
    board_list.append(board_id)
    serizlized_list = Serialize(board_list)
    Put(ctx, AD_LIST_KEY, serizlized_list)
    return True
Beispiel #5
0
def add_to_circulation(context, amount):

    TOKEN_CIRC_KEY = b'in_circulation'
    current_supply = Get(context, TOKEN_CIRC_KEY)
    current_supply += amount
    Put(context, TOKEN_CIRC_KEY, current_supply)
    return True
Beispiel #6
0
def get_new_game_id():
    context = GetContext()
    game_id = Get(context, 'new_game_id')
    if not game_id:
        game_id = 1
    Put(context, 'new_game_id', game_id + 1)
    return int_to_str(game_id)
Beispiel #7
0
def calculate_crowdsale_bonus_round_amount(ctx, address, neo_amount,
                                           current_in_circulation,
                                           verify_only):
    """
    Calculate the amount of tokens that can be exchanged in bonus round of crowdsale

    :param ctx:GetContext() used to access contract storage
    :param address: address to calculate amount for
    :param neo_amount:int amount of neo attached for exchange
    :param current_in_circulation:int amount tokens in circulation
    :param verify_only:bool if this is the actual exchange, or just a verification

    :return:int Amount of tokens to be exchanged
    """

    print('bonus round of crowd sale')
    crowdsale_round_key = concat(CROWDSALE_ROUND, address)
    amount_exchanged = Get(ctx, crowdsale_round_key)

    exchange_amount = neo_amount * CROWDSALE_BONUS_ROUND_TOKENS_PER_NEO
    max_circulation = TOKEN_TOTAL_SUPPLY - TOKEN_TEAM_AMOUNT
    new_circulation = current_in_circulation + exchange_amount
    isBelowMaxCirculation = new_circulation <= max_circulation

    new_exchanged_neo_amount = neo_amount + amount_exchanged
    isAboveMinExchange = CROWDSALE_NEO_MIN <= new_exchanged_neo_amount
    isBelowMaxExchange = new_exchanged_neo_amount <= CROWDSALE_NEO_MAX

    if isBelowMaxCirculation and isAboveMinExchange and isBelowMaxExchange:
        if not verify_only:
            Put(ctx, crowdsale_round_key, new_exchanged_neo_amount)
        return exchange_amount

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

    if len(args) != 1:
        Log("ERROR: Incorrect number of arguments")
        return False

    salt = args[0]

    # Act based on requested operation
    if operation == "GenerateRandom":
        height = GetHeight()
        header = GetHeader(height)
        consensus = header.ConsensusData >> 32
        random = (consensus * salt) >> 32
        if random < 100 and random > 10:
            random = random * random
        elif random < 10:
            random = random * random * consensus

        Put(GetContext(), "random", random)
            
    else:
        Log("[!] Operation not found!")

    return False
def DeleteOrder(order_id):
    order = GetOrder(order_id)
    if not order:
        Log("Order doesn't exist")
        return False

    usr_adr = order[0]
    if not check_permission(usr_adr):
        Log("Must be owner to delete an order")
        return False

    orders_id = GetOrderIdList()
    found = False
    i = 0
    while i < len(orders_id):
        if orders_id[i] == order_id:
            found = True
            orders_id.remove(i)  # pop by index
            i = len(orders_id) + 1  # break
        i += 1
    if found:

        orders_serialized = serialize_array(orders_id)
        context = GetContext()
        Put(context, ORDER_ID_LIST_PREFIX, orders_serialized)

        order_key = concat(ORDER_ID_PREFIX, order_id)
        Delete(context, order_key)
        return True
    else:
        Log("Order doesn't exist")
        return False
Beispiel #10
0
def register_provider(context, args):
    if not CheckWitness(OWNER):
        Notify(ILLEGAL_CALL)
        return False

    name = args[0]
    provider = args[1]

    if not name:
        Notify(MISSING_PROVIDER_NAME)
        return False

    if len(provider) != 20:
        Notify(INVALID_ADDRESS)
        return False

    if Get(context, name):
        Notify(ALREADY_EXISTING_PROVIDER)
        return False

    Notify(['[REGISTER-PROVIDER] name:', name, 'provider:', provider])

    Put(context, name, provider)

    return True
Beispiel #11
0
def Main():

    # pobieramy kontekst storage'u dla danego kontraktu
    # każdy kontrakt ma własny obszar storage
    context = GetContext()

    # klucz
    item_key = 'moj-klucz'

    # pobieramy wartość za pomocą klucza
    item_value = Get(context, item_key)

    msg = ['Wartosc odczytana ze storage:', item_value]
    Notify(msg)

    # w przypadku gdy para klucz-wartość nie są zapisane
    # próba pobrania wartości za pomocą nie istniejącego w storage klucza
    # zwróci wartość pustego ciągu bajtów b''
    if len(item_value) == 0:
        Notify('Klucz nie istnieje w storage, ustawiam wartosc na 1')
        item_value = 1

    else:
        Notify("Klucz juz jest w storage, zwiększam wartosc o 1.")
        item_value += 1

    # zapisanie wartości pod kluczem
    Put(context, item_key, item_value)

    msg = ["Nowa wartosc zapisana do storage:", item_value]
    Notify(msg)

    return item_value
def DeleteRecord(record_id):
    record = GetRecord(record_id)
    if not record:
        Log("Record doesn't exist")
        return False

    usr_adr = record[0]
    if not check_permission(usr_adr):
        Log("Must be owner to delete a record")
        return False

    records_id = GetRecordIdList(usr_adr)
    found = False
    i = 0
    while i < len(records_id):
        if records_id[i] == record_id:
            found = True
            records_id.remove(i)  # pop by index
            i = len(records_id) + 1  # break
        i += 1
    if found:
        records_serialized = serialize_array(records_id)
        record_id_list_key = concat(RECORD_ID_LIST_PREFIX, usr_adr)
        context = GetContext()
        Put(context, record_id_list_key, records_serialized)

        record_key = concat(RECORD_ID_META_PREFIX, record_id)
        Delete(context, record_key)
        return True
    else:
        Log("Record doesn't exist")
        return False
def del_serialized(ctx, key, value):
    list_bytes = Get(ctx, key)
    new_list = []
    deleted = False
    if len(list_bytes) != 0:
        deserialized_list = Deserialize(list_bytes)

        for item in deserialized_list:
            if item == value:
                deleted = True
            else:
                new_list.append(item)

        if (deleted):
            if len(new_list) != 0:
                serialized_list = Serialize(new_list)
                Put(ctx, key, serialized_list)
            else:
                Delete(ctx, key)
            print("Target element has been removed.")
            return True

    print("Target element has not been removed.")

    return False
Beispiel #14
0
def edit_period(ctx, args):
    """
    args[0] := user_hash
    args[1] := board ID
    args[2] := new_period
    """
    if len(args) == 3:
        user_hash = args[0]
        board_id = args[1]
        new_period = args[2]
        if not check_board_exist(board_id):
            return False
        # Check Expired
        if check_expired(board_id):
            if not update_board_round(board_id):
                return False

        if user_hash != Get(ctx, get_owner_key(board_id)):
            print('User is not authenticated to edit content of this board')
            return False
        else:
            '''
            Some Other checks on new bidding round period
            '''
            if new_period > 1200:
                Put(ctx, get_period_key(board_id), new_period)
                return True

        return False
Beispiel #15
0
def edit_content(ctx, args):
    """
    args[0] := user_hash
    args[1] := board ID
    args[2] := new content
    """
    if len(args) == 3:
        user_hash = args[0]
        board_id = args[1]
        new_content = args[2]
        if not check_board_exist(board_id):
            return False
        # Check Expired
        if check_expired(board_id):
            if not update_board_round(board_id):
                return False

        if user_hash != Get(ctx, get_owner_key(board_id)):
            print('User is not authenticated to edit content of this board')
            return False
        else:
            '''
            Some Other checks on the incoming content
            '''
            Put(ctx, get_content_key(board_id), new_content)
            return True
def create_verification_request(source_address, target_address):
    """
    The target user is doing this!
    :param target_address:
    :param source_address:
    :return:
    """

    msg = concat("Target users requests verification from ", source_address)
    Notify(msg)

    # if not CheckWitness(target_address):
    #     Notify("target_address argument is not the same as the tx sender")
    #     return False

    context = GetContext()
    key = _build_verification_request_key(source_address, target_address)
    result = Get(context, key)

    if not result:
        msg = concat("Verification request has been created for source ",
                     source_address)
        Notify(msg)
        Put(context, key, PENDING_STATUS)
        return True

    Notify(
        "Verification has already been started or completed for this source target combination"
    )
    return False
Beispiel #17
0
def calculate_limitsale_amount(ctx, address, neo_amount,
                               current_in_circulation, verify_only):
    """
    Calculate the amount of tokens that can be exchanged in limit round

    :param ctx:GetContext() used to access contract storage
    :param address: address to calculate amount for
    :param neo_amount:int amount of neo attached for exchange
    :param current_in_circulation:int amount tokens in circulation
    :param verify_only:bool if this is the actual exchange, or just a verification

    :return:int Amount of tokens to be exchanged
    """

    print('in limited round of token sale')
    limit_round_key = concat(LIMITSALE_ROUND, address)
    amount_exchanged = Get(ctx, limit_round_key)

    exchange_amount = neo_amount * LIMITSALE_TOKENS_PER_NEO
    max_circulation_limit_round = TOKEN_INITIAL_AMOUNT + TOKEN_LIMITSALE_MAX
    new_circulation = current_in_circulation + exchange_amount
    isBelowMaxCirculation = new_circulation < max_circulation_limit_round

    new_exchanged_neo_amount = neo_amount + amount_exchanged
    isAboveMinExchange = LIMITSALE_NEO_MIN <= new_exchanged_neo_amount
    isBelowMaxExchange = new_exchanged_neo_amount <= LIMITSALE_NEO_MAX

    if isBelowMaxCirculation and isAboveMinExchange and isBelowMaxExchange:
        if not verify_only:
            Put(ctx, limit_round_key, new_exchanged_neo_amount)
        return exchange_amount

    return 0
def Main():
    context = GetContext()

    # This is the storage key we use in this example
    item_key = 'test-storage-key'

    # Try to get a value for this key from storage
    item_value = Get(context, item_key)
    msg = ["Value read from storage:", item_value]
    Notify(msg)

    if len(item_value) == 0:
        Notify("Storage key not yet set. Setting to 1")
        item_value = 1

    else:
        Notify("Storage key already set. Incrementing by 1")
        item_value += 1

    # Store the new value
    Put(context, item_key, item_value)
    msg = ["New value written into storage:", item_value]
    Notify(msg)

    return item_value
Beispiel #19
0
def check_winner(game_id):
    context = GetContext()
    game_key_prefix = concat('game.', game_id)
    winner_key = concat(game_key_prefix, '.winner')
    winner = Get(context, winner_key)
    if winner:
        return winner

    answer1_key = concat(game_key_prefix, '.answer1')
    answer1 = Get(context, answer1_key)
    if not answer1:
        return -1
    answer2_key = concat(game_key_prefix, '.answer2')
    answer2 = Get(context, answer2_key)
    if not answer2:
        return -1

    player_index = get_winner_index(answer1, answer2)
    if player_index == 0:
        winner = 'draw'
    else:
        player_key = concat('.player', int_to_str(player_index))
        winner = Get(context, concat(game_key_prefix, player_key))
    Put(context, winner_key, winner)
    delete_game(game_id)
    return winner
Beispiel #20
0
def Main(operation):

    # create an array
    stuff = ['a', 3, ['j', 3, 5], 'jk', 'lmnopqr']

    # serialize it
    to_save = Serialize(stuff)
    Put(ctx, 'serialized', to_save)

    if operation == 1:
        return to_save

    elif operation == 2:

        to_retrieve = Get(ctx, 'serialized')
        return to_retrieve

    elif operation == 3:

        to_retrieve = Get(ctx, 'serialized')
        deserialized = Deserialize(to_retrieve)
        return deserialized

    elif operation == 4:

        to_retrieve = Get(ctx, 'serialized')
        deserialized = Deserialize(to_retrieve)
        return deserialized[2]

    return False
def remove_token_from_owners_list(ctx, t_owner, t_id):
    """Removes a token from owner's list of tokens

    :param StorageContext ctx: current store context
    :param byte[] t_owner: token owner
    :param bytes t_id: token id
    :return: token removal success
    :rtype: bool
    """
    length = Get(ctx, t_owner)  # get how many tokens this owner owns
    # this should be impossible, but just in case, leaving it here
    if len(length) == b'\x00':
        Notify('owner has no tokens')
        return False

    # if Delete returns True, that means the token was
    # successfully deleted and we should decrement the owner's balance.
    # otherwise, the token didn't exist/didn't belong to the owner,
    # so Delete returns False in that case.
    if Delete(ctx, concat(t_owner, t_id)):
        new_balance = length - 1
        if new_balance > 0:
            Put(ctx, t_owner, new_balance)
        else:
            Delete(ctx, t_owner)

        Log("removed token from owner's list and decremented owner's balance")
        return True

    Notify("token not found in owner's list")
    return False
Beispiel #22
0
def give_user_gas(ad_id, reciever_id, reciever_ad_count):

    reciever_info = list(length=5)
    ad_data = list(length=8)

    ad_id = args[0]
    reciever_id = args[1]
    reciever_ad_count = args[2]
    if reciever_ad_count < 1:
        return 'User did not view any ads'

        ad_data = deserialize_bytearray(Get(ctx, ad_id))
        ad_gas_amount = ad_data[7]
        reciever_info = Get(ctx, reciever_id)
        ad_gas_amount = ad_gas_amount / 2
        reciever_info[3] = ad_gas_amount
        reciever_info[4] = reciever_info[4] + 1
        Delete(ctx, reciever_id)
        data_serialized = serialize_array(reciever_info)

        Put(ctx, reciever_id, data_serialized)
        if transfer:
            Notify(' Transaction approved')
            update_gas = update_gas(ad_id, ad_gas_amount)
            if update_gas:
                Notify("Gas amount on acc updated ")
                return True
    return False
def add_token_to_owners_list(ctx, t_owner, t_id):
    """Adds a token to the owner's list of tokens

    :param StorageContext ctx: current store context
    :param byte[] t_owner: token owner (could be either a smart
        contract or a wallet address)
    :param bytes t_id: token ID
    :return: successfully added token to owner's list
    :rtype: bool
    """
    length = Get(ctx, t_owner)  # number of tokens the owner has
    Put(ctx, concat(t_owner, t_id), t_id)  # store owner's new token
    length += 1  # increment the owner's balance
    Put(ctx, t_owner, length)  # store owner's new balance
    Log("added token to owner's list and incremented owner's balance")
    return True
Beispiel #24
0
def Main(operation, data):

    if operation == 'store_data':

        Put(ctx, 'i1', 1)
        Put(ctx, 'i2', 2)
        Put(ctx, 'i3', -3)
        Put(ctx, 'i4', 400000000000)

        Put(ctx, 's1', 'abc')
        Put(ctx, 's2', 'hello world')
        Put(ctx, 's3', 'ok')

        Put(ctx, 'b1', b'\x01\x02\x03')
        Put(ctx, 'b2', bytearray(b'\x1a\xff\x0a'))

        return True

    elif operation == 'get_data':

        items = []

        items.append(Get(ctx, 'i1'))
        items.append(Get(ctx, 's1'))
        items.append(Get(ctx, 'b1'))

        return items

    elif operation == 'do_migrate':

        print("migrating")

        param_list = bytearray(b'\x07')
        return_type = bytearray(b'\x05')
        properties = 1
        name = 'migrated contract 3'
        version = '0.3'
        author = 'localhuman3'
        email = '*****@*****.**'
        description = 'test migrate3'

        new_contract = Migrate(data, param_list, return_type, properties, name, version, author, email, description)

        return new_contract

    elif operation == 'do_destroy':

        Destroy()

        return True

    return False
Beispiel #25
0
def do_mint_token(ctx, args):
    """Mints a new NFT token; stores it's properties, URI info, and
    owner on the blockchain; updates the totalSupply

    :param StorageContext ctx: current store context
    :param list args:
        0: byte[] t_owner: token owner
        1: byte[] t_claims: token's claims
    :return: mint success
    :rtype: bool
    """
    t_id = Get(ctx, TOKEN_CIRC_KEY)
    # the int 0 is represented as b'' in neo-boa, this caused bugs
    # throughout my code
    # This is the reason why token id's start at 1 instead
    t_id += 1

    # this should never already exist
    if len(Get(ctx, t_id)) == 20:
        Notify('token already exists')
        return False

    t_owner = args[0]
    if len(t_owner) != 20:
        Notify(INVALID_ADDRESS_ERROR)
        return False

    t_claims = args[1]
    if len(t_claims) == b'\x00':
        Notify('missing claims data string')
        return False

    token_amount = Get(ctx, t_owner)
    Notify(token_amount)
    if token_amount > 0:
        Notify('address already has an identity token')
        return False

    Put(ctx, t_id, t_owner)  # update token's owner
    Put(ctx, concat('claims/', t_id), t_claims)
    add_token_to_owners_list(ctx, t_owner, t_id)
    Put(ctx, TOKEN_CIRC_KEY, t_id)  # update total supply

    # Log this minting event
    OnMint(t_owner)
    OnIDKMint(t_owner)
    return True
Beispiel #26
0
def Main(operation, addr, group="", value=0):

	groups = {
	"elderly": [],
	"disabled": []
	}

	# Get trigger to determine interaction
	trigger = GetTrigger()

	# address of node that calls contract
	caller = addr

	# Used to spend assets on behalf of contract's address
	if trigger == Verification():
	
		if CheckWitness(OWNER):
			return True
	
		return False
	
	# Main body of Smart Contract
	elif trigger == Application():
		

		if operation == 'balance':
			return Get(ctx, addr)

		elif operation == 'register':

			groups[group] = groups[group].append(addr)

		elif operation == 'add':
			assert security_check()==True
	        balance = Get(ctx, addr)
	        new_balance = balance + value
	        Put(ctx, addr, new_balance)
	        return new_balance

    	elif operation == 'subtract':
			assert security_check()==True
	        balance = Get(ctx, addr)
	        Put(ctx, addr, balance - value)
	        return balance - value

		elif operation == 'totalSupply':
			return totalSupply()
Beispiel #27
0
def add_private_placement(ctx, address):
    print("Adding private placement address")
    if CheckWitness(TOKEN_OWNER):
        if len(address) == 20:
            storage_key = concat(PP_KEY, address)
            Put(ctx, storage_key, True)
            return True
    return False
Beispiel #28
0
def removeQuestionId(questionId):
    Notify("[!] Remove QuestionID to all_question_ids object")
    serial = Get(GetContext(), get_all_ids)
    all_question_ids = Deserialize(serial)
    all_question_ids.remove(questionId)
    new_serial = Serialize(all_question_ids)
    Put(GetContext(), get_all_ids, new_serial)
    Notify("[!] Removed QuestionID from all_question_ids object")
Beispiel #29
0
def Register(domain, owner):
    context = GetContext()
    occupy = Get(context, domain)
    if occupy != None:
        return False
    Put(context, domain, owner)
    Push('Register', domain, owner)
    return True
Beispiel #30
0
def addQuestionId(questionId, question):
    Notify("[!] Add QuestionID to all_question_ids object")
    serial = Get(GetContext(), get_all_ids)
    all_question_ids = Deserialize(serial)
    all_question_ids[questionId] = question
    new_serial = Serialize(all_question_ids)
    Put(GetContext(), get_all_ids, new_serial)
    Notify("[!] Added QuestionID to all_question_ids object")