Ejemplo n.º 1
0
def buyCat(from_acc, animal, amount):
    if not CheckWitness(from_acc):
        Notify("Not the owner, can't buy")
        return False

    tmplist = Get(ctx, from_acc + "CAT")
    if len(tmplist) != 0:
        delist = Deserialize(tmplist)
        Notify(delist)
        delist.append(animal)
        Notify(delist)
        Put(ctx, from_acc + "CAT", Serialize(delist))
    else:
        Put(ctx, from_acc + "CAT", Serialize([animal]))
        Notify(Serialize([animal]))

    current_balance = Get(ctx, from_acc)
    if current_balance <= amount:
        Notify("Insufficient funds")
        return False
    to_balance = Get(ctx, TOKEN_OWNER)
    to_balance += amount
    Put(ctx, TOKEN_OWNER, to_balance)
    current_balance -= amount
    if current_balance != 0:
        Put(ctx, from_acc, current_balance)
    else:
        Delete(ctx, from_acc)
    OnTransfer(from_acc, TOKEN_OWNER, amount)
    return True
Ejemplo n.º 2
0
def _save_space_ids(new_id):
    ids = Get(ctx, KEY_SPACE_IDS)

    if ids:
        deserialized = Deserialize(ids)
        deserialized.append(new_id)

        Put(ctx, KEY_SPACE_IDS, Serialize(deserialized))
    else:
        Put(ctx, KEY_SPACE_IDS, Serialize([new_id]))
Ejemplo n.º 3
0
def do_approve(ctx, Caller, args):
    """Approve a token to be transferred to a third party by an approved spender

    :param StorageContext ctx: current store context
    :param bytearray t_owner: current owner of the token
    :param bytearray t_spender: spender to approve
    :param int t_id: int: token id
    :param bool revoke: set to True to revoke previous approval
    :return: approval success
    :rtype: bool
    """
    t_owner = args[0]
    t_spender = args[1]
    t_id = args[2]
    revoke = False

    if len(args) > 3:
        revoke = args[3]

    if Caller != GetEntryScriptHash() and not is_whitelisted_dex(ctx, Caller):
        # non-whitelisted contracts can only approve their own funds for transfer,
        # even if they have the signature of the owner on the invocation
        t_owner = Caller

    assert len(t_owner) == 20, INVALID_ADDRESS_ERROR
    assert len(t_spender) == 20, INVALID_ADDRESS_ERROR
    assert t_id, TOKEN_DNE_ERROR

    ownership_key = concat('ownership/', t_id)
    ownership = safe_deserialize(Get(ctx, ownership_key))

    assert ownership, TOKEN_DNE_ERROR
    assert has_key(ownership, 'owner'), TOKEN_DNE_ERROR
    assert t_owner == ownership['owner'], PERMISSION_ERROR
    assert t_owner != t_spender, 'same owner and spender'
    assert authenticate(t_owner, Caller), PERMISSION_ERROR

    # revoke previous approval if revoke is True
    if revoke:
        if has_key(ownership, 'approved'):
            ownership.remove('approved')
            Put(ctx, ownership_key, Serialize(ownership))

        # log the revoking of previous approvals
        OnApprove(t_owner, t_spender, 0)
        OnNFTApprove(t_owner, '', t_id)
        return True

    ownership['approved'] = concat(t_owner, t_spender)
    # approve this transfer
    Put(ctx, ownership_key, Serialize(ownership))
    # Log this approval event
    OnApprove(t_owner, t_spender, 1)
    OnNFTApprove(t_owner, t_spender, t_id)
    return True
Ejemplo n.º 4
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: bytearray t_owner: token owner
        1: int t_id: token id (must not already exist)
        2: str t_properties: token's read only data
        3: str t_uri: token's uri
        4: str t_rw_properties: token's read/write data (optional)
    :return: mint success
    :rtype: bool
    """

    t_circ = Get(ctx, TOKEN_CIRC_KEY)
    t_circ += 1

    assert len(args[0]) == 20, INVALID_ADDRESS_ERROR
    assert args[1], 'missing token id'
    assert args[2], 'missing properties'
    assert args[3], 'missing uri'

    t_id = args[1]
    token = safe_deserialize(Get(ctx, concat('token/', t_id)))
    assert not token, 'token already exists'

    # basically a token 'object' containing the token's
    # id, uri, and properties
    token = {}
    ownership = {}  # information about the token's owner

    token['id'] = t_id
    token['uri'] = args[3]
    token['properties'] = args[2]  # this can never change

    if len(args) > 4:
        token['rwproperties'] = args[4]
    else:
        token['rwproperties'] = ''

    ownership['owner'] = args[0]

    Put(ctx, concat('token/', t_id), Serialize(token))
    # update token's owner
    Put(ctx, concat('ownership/', t_id), Serialize(ownership))
    res = add_token_to_owners_list(ctx, ownership['owner'], t_id)
    Put(ctx, TOKEN_CIRC_KEY, t_circ)  # update total supply
    # Log this minting event
    OnTransfer('', ownership['owner'], 1)
    OnNFTTransfer('', ownership['owner'], t_id)
    OnMint(ownership['owner'], 1)
    OnNFTMint(ownership['owner'], t_id)
    return True
Ejemplo n.º 5
0
def follow(ctx, uid, fAddr):
    """
    Follow another user

    Args:
        uid -> unique user id
        fAddr -> to-follow script hash
    """
    #how to prevent multiple following?
    fUid = isRegistered(ctx, fAddr)
    if not fUid == False:
        if fUid == uid:
            Notify("User cannot follow himself")
            return False
        if not isFollowing(ctx, uid, fUid):
            # Count following += 1 for uid
            ##a_save = Get(ctx, uid)
            ##a_save_d = Deserialize(a_save)
            ##a_count = a_save_d[6]
            ##aa_count = a_count + 1
            ##a_save_d[6] = aa_count
            ##a_save_s = Serialize(a_save_d)
            ##Put(ctx, uid, a_save_s)
            aa_count = updateAccCount(ctx, uid, 6, False)

            # Count follower += 1 for fUid
            ##b_save = Get(ctx, fUid)
            ##b_save_d = Deserialize(b_save)
            ##b_count = b_save_d[5]
            ##bb_count = b_count + 1
            ##b_save_d[5] = bb_count
            ##b_save_s = Serialize(b_save_d)
            ##Put(ctx, fUid, b_save_s)
            bb_count = updateAccCount(ctx, fUid, 5, False)

            # Add follow to iterated storage for uid
            t1 = [fUid, bb_count]
            t1_s = Serialize(t1)
            PutThree(ctx, uid, ".following.", aa_count, t1_s)

            # Add follow to iterated storage for fUid
            t2 = [uid, aa_count]
            t2_s = Serialize(t2)
            PutThree(ctx, fUid, ".followers.", bb_count, t2_s)

            #Set follow indicator = true
            PutThree(ctx, uid, ".followcheck.", fUid, True)

            OnFollow(uid, fUid)
            return True
        Notify("User already following")
        return False
    Notify("User to follow not registered")
    return False
Ejemplo n.º 6
0
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
Ejemplo n.º 7
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
Ejemplo n.º 8
0
def sendMessage(args):

    # Args
    sender = args[0]
    message = args[1]
    time = GetTime()

    context = GetContext()
    count = 'count'
    lastCount = Get(context, count)

    if lastCount == '':
        newCount = 1
    else:
        newCount = lastCount + 1
    
    Put(context, count, newCount)

    key = concat('message.',newCount)

    rawData = [message, time, sender]
    value = Serialize(rawData)
    
    Put(context, key, value)
    Notify(concat('Put message: ', value))

    return True
Ejemplo n.º 9
0
def serialize_length_item(item):
    '''
    This function serialize's a single offer to be put in storage
    :param item:
    :return: data: hash of offer
    '''
    return Serialize(item)
Ejemplo n.º 10
0
def serialize_array(items):
    '''
    This function serialize's and array of offers to be put in storage
    :param items:
    :return: data: hash of array of offers
    '''
    return Serialize(items)
Ejemplo n.º 11
0
def vote(args):
    """
    Vote for a proposal
    :param args: list of arguments [PROPOSAL_ID, VOTE]
    :return: bool, result of the execution
    """
    if len(args) != 2:
        return False

    # get proposal from storage
    proposal_id = args[0]
    proposal_storage = Get(ctx, proposal_id)

    # check proposal existence
    if not proposal_storage:
        print("Proposal not found")
        return False

    # get caller address
    references = GetScriptContainer().References
    if len(references) < 1:
        return False
    caller_addr = references[0].ScriptHash

    # check if address already voted
    if Get(ctx, concat(proposal_id, caller_addr)):
        print('Already voted')
        return False

    # Deserialize proposal array
    proposal = Deserialize(proposal_storage)

    # iterate authorized address
    index = 0
    while index < len(proposal[3]):
        if proposal[3][index] == caller_addr:
            authorized = True
            break
        index += 1

    if not authorized:
        print('Not allowed to vote')
        return False

    # increment vote counter
    if args[1] == 1:
        print('Yes!')
        proposal[1] = proposal[1] + 1
    else:
        print('No!')
        proposal[2] = proposal[2] + 1

    # serialize proposal and write to storage
    proposal_storage = Serialize(proposal)
    Put(ctx, proposal_id, proposal_storage)

    # mark address as voted
    Put(ctx, concat(proposal_id, caller_addr), True)

    return True
Ejemplo n.º 12
0
def InsertCharacter(attrList):

    ID_TIP_KEY = "id-tip-key"

    Notify("Calling InsertCharacterByAttrList")
    context = GetContext()

    # Make sure that it can be converted correctly
    character = ConvertFromList(attrList)

    nextId = Get(context, ID_TIP_KEY)
    if not nextId:
        Notify("id-tip-key is not set")
        nextId = 0
    else:
        Notify("id-tip-key is set")

    nextId = nextId + 1

    serialized = Serialize(attrList)
    Notify(serialized)

    Put(context, nextId, serialized)
    Put(context, ID_TIP_KEY, nextId)

    return nextId
Ejemplo n.º 13
0
def addMessage(ctx, party, direction, message, partySecond, time, ipfs,
               encrypted):
    newLastIndex = IncrementThree(ctx, party, direction, "latest")
    messageData = [message, time, partySecond, ipfs, encrypted]
    messageTemp = Serialize(messageData)
    PutThree(ctx, party, direction, newLastIndex, messageTemp)
    return True
Ejemplo n.º 14
0
def DeletePublication(args):
    sender = args[0]
    name = args[1]

    if not CheckWitness(sender):
        print('Account owner must be sender')
        return [False, 'Account owner must be sender']

    context = GetContext()

    publications_key = concat('publications', sender)
    publication_key = concat(publications_key, sha1(name))

    publication = Get(context, publication_key)
    if not publication:
        print('Publication does not exist')
        return [False, 'Publication does not exist']

    publication = Deserialize(publication)
    if not publication[5]:
        print('Publication has already been deleted')
        return [False, 'Publication has already been deleted']
    """
    Check for active bids etc here - revisit if time (OOS)
    """

    publication[5] = False

    Put(context, publication_key, Serialize(publication))

    return [True, '']
Ejemplo n.º 15
0
def check_allQuestionIds():
    all_questions = Get(GetContext(), get_all_ids)
    if not all_questions:
        Notify("[!] Creating all_question_ids object")
        all_question_ids = {}
        serialized = Serialize(all_question_ids)
        Put(GetContext(), get_all_ids, serialized)
Ejemplo n.º 16
0
def addMessage(party, direction, message, partySecond, time):
    context = GetContext()
    partyHelper = concat(direction, 'latest')
    partyLast = concat(party, partyHelper)
    lastIndex = Get(context, partyLast)
    if lastIndex == '':
        # No last Index, set first (1)
        newLastIndex = 1
    else:
        # Increment last index
        newLastIndex = lastIndex + 1
    Notify(concat('lastindex +1: ', newLastIndex))
    # Set new last index
    Put(context, partyLast, newLastIndex)
    Notify(concat('put partyLast: ', partyLast))
    # Set message for index
    partyHelper2 = concat(direction, newLastIndex)
    partyMessageId = concat(party, partyHelper2)
    # Create message with header and body
    # header contains partySecond (sender / receiver) and time
    # body contains message
    # messageData = [partySecond,time,message]
    messageData = [message, time, partySecond]
    messageTemp = Serialize(messageData)
    Put(context, partyMessageId, messageTemp)
    Notify(concat('pt msg: ', messageTemp))
    return True
Ejemplo n.º 17
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)
Ejemplo n.º 18
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
Ejemplo n.º 19
0
def cancel_bookinng(ctx, space_id, guest_address, date):
    if not CheckWitness(guest_address):
        return False

    booking_id = _build_booking_id(space_id, date)
    serialized_booking = Get(ctx, booking_id)
    if not serialized_booking:
        return False
    
    booking = Deserialize(serialized_booking)

    # guest_address, start_at, approved, canceled
    start_at = booking[1]
    canceled = booking[3]

    height = GetHeight()

    if height > start_at:
        return False

    if canceled:
        return False

    booking[3] = True
    Put(ctx, booking_id, Serialize(booking))

    return_percent = _caluclate_return_percent(start_at, height)
    OnBookingCancel(space_id, date, return_percent)

    return return_percent
Ejemplo n.º 20
0
def removePostId(postId):
    Notify("[!] Remove PostID to all_posts object")
    serial = Get(GetContext(), get_all_ids)
    all_posts = Deserialize(serial)
    all_posts.remove(postId)
    new_serial = Serialize(all_posts)
    Put(GetContext(), get_all_ids, new_serial)
    Notify("[!] Removed PostID from all_posts object")
Ejemplo n.º 21
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        is_owner = CheckWitness(CONTRACT_OWNER)
        if is_owner:
            return True
        else:
            return False
    elif trigger == Application():
        if operation == "array":
            Notify("array")
            #31
            bigdata = 'In ac dui quis mi consectetuer '
            i = 0
            while i < 2200:
                bigdata = concat(bigdata, 'In ac dui quis mi consectetuer ')
                i = i + 1
            time = GetTime()
            data = [bigdata, time]
            result = Serialize(data)
            return result
        if operation == "dict":
            Notify("dict")
            j = 10
            d = {
                'a': 1,
                'b': 4,
                4: 'blah',
                'm': j,
                'z': [1, 3, 4, 5, 'abcd', j]
            }
            result = Serialize(d)
            return result
        if operation == "bool":
            Notify("array")
            #31
            bigdata = 'In ac dui quis mi consectetuer '
            time = GetTime()
            data = [False, True, False, True]
            result = Serialize(data)
            return result
        else:
            return False
    return False
Ejemplo n.º 22
0
def Main(operation, args):
    ctx = GetContext()

    if operation == 'createAsset':
        if len(args) > 3:
            assetId = strVal(args[0])
            senderKey = strVal(args[1])
            receiverKey = strVal(args[2])
            middleManKey = strVal(args[3])
            asset = {
                'senderKey': senderKey,
                'receiverKey': receiverKey,
                'middleManKey': middleManKey,
                'snapshots': []
            }
            serializedAsset = Serialize(asset)
            Put(ctx, assetId, serializedAsset)
            return "Asset created successfully"
        return "Invalid number of args to create an asset"

    elif operation == 'updateAsset':
        if len(args) > 1:
            assetId = strVal(args[0])
            snapshotHash = strVal(args[1])
            asset = Get(ctx, assetId)
            if asset != None and hasUpdatePermissions(asset):
                asset['snapshots'].append(snapshotHash)
                serializedAsset = Serialize(asset)
                Put(ctx, assetId, serializedAsset)
                return "Asset updated"
            else:
                return "Asset not found"
        return "Invalid number of args to create an asset"

    elif operation == 'getAsset':
        if len(args) > 0:
            assetId = strVal(args[0])
            asset = Get(ctx, assetId)
            if asset != None:
                deserializedAsset = Deserialize(asset)
                return deserializedAsset
            else:
                "Asset not found"
        return "Invalid number of args to get an asset"

    return "No valid operation specified"
Ejemplo n.º 23
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")
Ejemplo n.º 24
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")
Ejemplo n.º 25
0
def addPostId(postId, title):
    Notify("[!] Add PostID to all_posts object")
    serial = Get(GetContext(), get_all_ids)
    all_posts = Deserialize(serial)
    all_posts[postId] = title
    new_serial = Serialize(all_posts)
    Put(GetContext(), get_all_ids, new_serial)
    Notify("[!] Added PostID to all_posts object")
Ejemplo n.º 26
0
def do_transfer(ctx, Caller, args):
    """Transfers a token at the specified id from the t_owner address
    to the t_to address

    :param StorageContext ctx: current store context
    :param list args:
        0: bytearray t_to: transfer to address
        1: int t_id: token id
    :return: transfer success
    :rtype: bool
    """
    # we don't need the t_from because the token data stores the owner
    t_from = ""
    t_to = args[0]
    t_id = args[1]

    if len(
            args
    ) == 3:  # use traditional from, to, id format if they want to send it
        t_from = args[0]
        t_to = args[1]
        t_id = args[2]

    if Caller != GetEntryScriptHash() and not is_whitelisted_dex(ctx, Caller):
        # non-whitelisted contracts can only approve their own funds for transfer,
        # even if they have the signature of the owner on the invocation
        t_from = Caller

    assert len(t_to) == 20, INVALID_ADDRESS_ERROR
    ownership = safe_deserialize(Get(ctx, concat('ownership/', t_id)))

    assert ownership, TOKEN_DNE_ERROR
    assert has_key(ownership, 'owner'), TOKEN_DNE_ERROR
    assert len(ownership['owner']) == 20, TOKEN_DNE_ERROR

    t_owner = ownership['owner']

    if t_owner == t_to:
        print('transfer to self')
        return True

    assert authenticate(t_owner, Caller), PERMISSION_ERROR

    res = remove_token_from_owners_list(ctx, t_owner, t_id)
    assert res, 'unable to remove token from owner list'

    ownership['owner'] = t_to  # update token's owner
    # remove any existing approvals for this token
    if has_key(ownership, 'approved'):
        ownership.remove('approved')

    Put(ctx, concat('ownership/', t_id), Serialize(ownership))
    res = add_token_to_owners_list(ctx, t_to, t_id)

    # log this transfer event
    OnTransfer(t_owner, t_to, 1)
    OnNFTTransfer(t_owner, t_to, t_id)
    return True
Ejemplo n.º 27
0
def remove_userInvite(wallet_id, invite_id):
    invites = get_userInvites(wallet_id)
    for i in range(0, len(invites)):
        if invite_id == invites[i]:
            invites.remove(i)
            serial = Serialize(invites)
            Put(GetContext(), wallet_id, serial)
            return True
    return False
Ejemplo n.º 28
0
def addPostId(postId):
    check_allPostIds()
    Notify("[!] Add PostID to all_posts object")
    serial = Get(GetContext(), get_all_ids)
    all_posts = Deserialize(serial)
    all_posts.append(postId)
    new_serial = Serialize(all_posts)
    Put(GetContext(), get_all_ids, new_serial)
    Notify("[!] Added PostID to all_posts object")
Ejemplo n.º 29
0
def update_rate(_type, rate):

    if CheckWitness(token_owner):
        rates = get_rates(_type)
        rates.append(rate)
        Put(context, _type, Serialize(rates))
        return True

    return False
Ejemplo n.º 30
0
def set_rw_properties(ctx, id, data):
    token_key = concat('token/', id)
    token = safe_deserialize(Get(ctx, token_key))

    if not token:
        print(TOKEN_DNE_ERROR)
        return False
    token['rwproperties'] = data
    Put(ctx, token_key, Serialize(token))
    return True