def approver_fund_claim(ctx, voter, challenger, owner, challenge_id): submission_key = generate_submission_key(challenger, owner, challenge_id) Log("Generating submission key.") submission = get_submission(ctx, submission_key) if submission: if GetTime() >= submission['timestamp'] + 87000: Log("Submission is closed.") approvers = submission['approvers'] approver = contains(approvers, voter) if approver: Log("Voter approved the submission.") if submission['status'] == 'APPROVED': Log("Submission was approved. Voter is eligible for claim." ) approvers.remove(approver[voter]) submission['approvers'] = approvers set_submission(ctx, submission_key, submission) Log("Voter has been removed from the approver list. Claim can proceed." ) return submission['approver_count'] else: Log("Submission was not approved.") return False else: Log("Voter is not in the approver list.") return False else: Log("Submission is still open.") return False else: Log("This submission does not exist.") return False
def sendMessage(args): # Args sender = args[0] receiver = args[1] # messageA: for "encrypt-to-self". encrypted with public key from A (sender). messageA = args[2] # messageB: encrypted with public key from B (receiver). messageB = args[3] time = GetTime() Log('time') Notify(concat('time', time)) """ Sender A = scripthash of sender storage A.send.{index} stores the sent message from A for respective index storage A.send.latest stores the index of the last message sent from A Receiver B = scripthash of receiver storage B.receive.{index} stores the received message for the recipient B for the respective index storage B.receive.latest stores the index of the last message received for B """ # Add message "envrypt-to-self" addMessage(sender, '.send.', messageA, receiver, time) # Add message for recipient addMessage(receiver, '.receive.', messageB, sender, time) return True
def submit(ctx, challenge_key, submission_key): challenge = get_challenge(ctx, challenge_key) if challenge: if challenge['state'] == 'OPEN': submissions = challenge['submissions'] if contains(submissions, submission_key): Log("Submission already exists.") return False elif len(submissions) < 100: Log("Adding new submission.") submissions.append(submission_key) challenge['submissions'] = submissions set_challenge(ctx, challenge_key, challenge) return True elif GetTime() > challenge['timestamp'] + 1209600: Log("This challenge has expired.") challenge['state'] = 'CLOSED' set_challenge(ctx, challenge_key, challenge) return False else: Log("The maximum number of submissions for this challenge has been reached." ) challenge['state'] = 'CLOSED' set_challenge(ctx, challenge_key, challenge) return False else: return False Log("This challenge does not exist.") return False
def create_submission(ctx, challenger, owner, challenge_id): challenge_key = generate_challenge_key(owner, challenge_id) Log("Generating challenge key.") submission_key = generate_submission_key(challenger, owner, challenge_id) Log("Generating submission key.") Log("Initiating a new submission.") submission = { 'challenger': challenger, 'challenge_key': challenge_key, 'voters': [], 'difference': 0, 'approvers': [], 'approver_count': 0, 'rejecters': [], 'rejecter_count': 0, 'status': 'APPROVED', 'state': 'CLOSED', 'timestamp': GetTime(), 'claimed': 'NO' } status = submit(ctx, challenge_key, submission_key) if status: Log("Storing submission.") set_submission(ctx, submission_key, submission) return submission_key else: Log("Submission was not stored.") return False
def update_board_round(board_id): # update ruond end date highest_bid = Get(ctx, get_highest_bid_key(board_id)) unpaid_payment = Get(ctx, get_unpaid_key(board_id)) board_admin = Get(ctx, get_board_admin_key(board_id)) # Store unpaid tokens (revenue) to storage if not pay_in_token(ctx, CONTRACT_OWNER, board_admin, unpaid_payment): print('Payment error.') return False # Update Payment to be received after next period Put(ctx, get_unpaid_key(board_id), highest_bid) period = Get(ctx, get_period_key(board_id)) round_end = GetTime() + period Put(ctx, get_endtime_key(board_id), round_end) # update owner to highest bidder new_owner = Get(ctx, get_highest_bidder_key(board_id)) Put(ctx, get_owner_key(board_id), new_owner) # update content to new owner's content new_content = Get(ctx, get_next_content_key(board_id)) Put(ctx, get_content_key(board_id), new_content) # Set highest bid to 0 Put(ctx, get_highest_bid_key(board_id), 0) print('Update Round Completed') return True
def promoter_fund_claim(ctx, challenger, owner, challenge_id): submission_key = generate_submission_key(challenger, owner, challenge_id) Log("Generating submission key.") submission = get_submission(ctx, submission_key) if submission: if GetTime() >= submission['timestamp'] + 87000: Log("Submission is closed.") submission['state'] = 'CLOSED' if submission['status'] == 'APPROVED': Log("Submission has been approved. Eligible for claim.") if submission['claimed'] == 'NO': Log("Reward has not been claimed. Mining...") submission['claimed'] = 'YES' set_submission(ctx, submission_key, submission) return True else: Log("Reward has already been claimed.") return False else: Log("Submission has been rejected. Not eligible for claim.") return False else: Log("Submission is still open.") return False else: Log("This submission does not exist.") return False
def reallocate(): """ Once the token sale is over, the owner can take back the remaining tokens. :return: bool: Whether the operation was successful """ if not CheckWitness(get_owner_address(ctx)): print("Must be owner to reallocate") return False time = GetTime() if time < SERIES_A_END: print("Must wait until the end of Series A before re-allocating.") return False current_balance = Get(ctx, get_owner_address(ctx)) crowdsale_available = crowdsale_available_amount(ctx) new_balance = current_balance + crowdsale_available Put(ctx, get_owner_address(ctx), new_balance) Log("Reallocated successfully!") return add_to_circulation(ctx, crowdsale_available)
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
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
def buy(player, numbers): context = GetContext() current_game_no = Get(context, CURRENT_GAME_NO) # Check if the lottery is launched. # A method called launch() needs to be triggered by this contract owner in order to begin the lottery. if not current_game_no: return notifyErrorAndReturnFalse("The game has not been launched yet") # Ticket price will be transferred to the POOL is_transferred = do_transfer(player, POOL, TICKET_PRICE) if is_transferred: last_ticket_no = Get(context, LAST_TICKET_NO) new_ticket_no = last_ticket_no + 1 new_ticket_key = concat(TICKET, new_ticket_no) new_ticket = [ current_game_no, player, serialize_array(numbers), GetTime() ] Put(context, new_ticket_key, serialize_array(new_ticket)) Put(context, LAST_TICKET_NO, new_ticket_no) player_key = concat(PLAYER, player) player_key = concat(player_key, current_game_no) # It needs flags to fetch all tickets by addresses and in order to check if a user is qualified for drawing. if not has_user_participated(player): player_key = concat(player_key, "first") else: player_key = concat(player_key, new_ticket_no) Put(context, player_key, new_ticket_no) DispatchBuyEvent(player, new_ticket_no, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]) return True return False
def set_locked(ctx): """ This function is for prevent Op Not Converted: EXTENDED_ARG """ now = GetTime() set_locked_until(ctx, ECOSYSTEM_RESERVE_ADDRESS, now + 3 * 30 * 86400) set_locked_until(ctx, ADVISOR_FUNDS_ADDRESS, now + 3 * 30 * 86400) set_locked_until(ctx, EMPLOYEE_FUNDS_ADDRESS1, now + 365 * 86400) set_locked_until(ctx, EMPLOYEE_FUNDS_ADDRESS2, now + 2 * 365 * 86400) set_locked_until(ctx, RESERVE_FUNDS_ADDRESS, now + 365 * 86400)
def create_challenge(ctx, owner, challenge_id): challenge_key = generate_challenge_key(owner, challenge_id) Log("Generating challenge key.") last_challenge_date = last_challenge_timestamp(ctx, owner) challenge_package = check_challenge_package(ctx, owner) using_package = False can_create_challenge = False if GetTime() > last_challenge_date + 2592000: can_create_challenge = True Log("The business can create a challenge.") elif challenge_package > 0: can_create_challenge = True using_package = True Log("The business has created a challenge in the past 30 days. Using challenge package." ) else: Log("The last challenge created by the business was less than 30 days ago." ) Log("The business challenge package is empty.") if can_create_challenge: if not get_challenge(ctx, challenge_key): Log("Challenge does not already exist. Initiating a new challenge." ) challenge = { 'owner': owner, 'cid': challenge_id, 'state': 'OPEN', 'submissions': [], 'timestamp': GetTime() } set_challenge(ctx, challenge_key, challenge) update_last_challenge_date(ctx, owner, challenge['timestamp']) if using_package: decrement_challenge_package(ctx, owner) return True else: Log("Challenge key already exists.") return False else: Log("The business cannot create a challenge at the moment.") return False
def do_transfer_from(ctx, t_from, t_to, amount): if amount <= 0: return False available_key = concat(t_from, t_to) if len(available_key) != 40: return False now = GetTime() locked_until_from = get_locked_until(ctx, t_from) locked_until_to = get_locked_until(ctx, t_to) if now < locked_until_from or now < locked_until_to: log = debug_log("from or to is locked!") return False available_to_to_addr = Get(ctx, available_key) if available_to_to_addr < amount: log = debug_log("Insufficient funds approved") return False from_balance = Get(ctx, t_from) if from_balance < amount: log = debug_log("Insufficient tokens in from balance") return False to_balance = Get(ctx, t_to) new_from_balance = from_balance - amount new_to_balance = to_balance + amount Put(ctx, t_to, new_to_balance) Put(ctx, t_from, new_from_balance) log = debug_log("transfer complete") new_allowance = available_to_to_addr - amount if new_allowance == 0: log = debug_log("removing all balance") Delete(ctx, available_key) else: log = debug_log("updating allowance to new allowance") Put(ctx, available_key, new_allowance) OnTransfer(t_from, t_to, amount) return True
def calculate_can_exchange(ctx, amount, address, verify_only): """ Perform custom token exchange calculations here. :param amount:int Number of tokens to convert from asset to tokens :param address:bytearray The address to mint the tokens to :return: bool: Whether or not an address can exchange a specified amount """ timestap = GetTime() current_in_circulation = Get(ctx, TOKEN_CIRC_KEY) new_amount = current_in_circulation + amount if new_amount > TOKEN_TOTAL_SUPPLY: return False if timestap >= ROUND1_START and timestap <= ROUND1_END: print("Minting Round 1") r1key = concat(address, MINTED_ROUND1_KEY) # the following looks up whether an address has been # registered with the contract for KYC regulations # check if they have already exchanged in round 1 # if not, then save the exchange for limited round if amount <= MAX_EXCHANGE_ROUND1 and kyc_status( ctx, 'round1', address) and not Get(ctx, r1key): if not verify_only: Put(ctx, r1key, True) return True if timestap >= ROUND2_START and timestap <= ROUND2_END: print("Minting round 2") r2key = concat(address, MINTED_ROUND2_KEY) if amount <= MAX_EXCHANGE_ROUND2 and kyc_status( ctx, 'round2', address) and not Get(ctx, r2key): if not verify_only: Put(ctx, r2key, True) return True print("Not eligible") return False
def perform_exchange(ctx): """ :param token:Token The token object with NEP5/sale settings :return: bool: Whether the exchange was successful """ now = GetTime() attachments = get_asset_attachments() # [receiver, sender, neo, gas] exchangeables = get_exchangeable(ctx, attachments[1], attachments[2], now) exchanged_tokens = exchangeables[0] state = exchangeables[2] exchange_ok = exchanged_tokens > 0 if not exchange_ok: # This should only happen in the case that there are a lot of TX on the final # block before the total amount is reached. An amount of TX will get through # the verification phase because the total amount cannot be updated during that phase # because of this, there should be a process in place to manually refund tokens if attachments[2] > 0: OnRefund(attachments[1], attachments[2]) # if you want to exchange gas instead of neo, use this # if attachments.gas_attached > 0: # OnRefund(attachments.sender_addr, attachments.gas_attached) return False add_balance(ctx, attachments[1], exchanged_tokens) sub_balance(ctx, SALE_FUNDS_ADDRESS, exchanged_tokens) sale_prefix = None if state == IS_WHITELIST_SALE: sale_prefix = STORAGE_PREFIX_PURCHASED_WHITELIST if state == IS_PRESALE: sale_prefix = STORAGE_PREFIX_PURCHASED_PRESALE if state == IS_CROWDSALE: sale_prefix = STORAGE_PREFIX_PURCHASED_CROWDSALE add_minted_tokens(ctx, sale_prefix, exchanged_tokens) add_contributed_neo(ctx, sale_prefix, attachments[1], attachments[2]) # update the in circulation amount # result = add_to_circulation(ctx, exchanged_tokens) # dispatch transfer event OnTransfer(SALE_FUNDS_ADDRESS, attachments[1], exchanged_tokens) affiliate = do_affiliate(ctx, attachments[1], exchanged_tokens) return True
def completeStake(args): """ Complete the stake specified by `stakeID` If the staking period is complete, this returns the staked tokens to the user, and dispatches a `complete` event Note that since this method can return tokens ONLY back to the address that originally staked the tokens, it can be called by anyone. :param args (list): a list with the first item being the address in question and the second being the stakeID :return: (bool): success """ stakes = getStakesForAddr(args[0]) stakeID = args[1] stake = stakes[stakeID] if not stake: raise Exception("Could not find stake") addr = stake['addr'] amount = stake['amount'] now = GetTime() if stake['endTime'] > now: raise Exception("Not eligible to unstake yet") if stake['complete']: raise Exception("Stake already completed") # transfer back to user args = [GetExecutingScriptHash(), addr, amount] transferOfTokens = DynamicAppCall(getStakingContract(), 'transfer', args) if transferOfTokens: stake['completed'] = True stakes[stakeID] = stake addrStakeKey = concat(STAKE_ADDR_KEY, addr) Put(ctx, addrStakeKey, Serialize(stakes)) OnStakeComplete(stakeID, addr) return True return False
def tweet(ctx, addr, uid, content, retweet): """ Post tweet Args: addr -> script hash of invoker uid -> unique user id content -> Tweet content retweet -> If '' then normal tweet. If key is given (from retweet operation) then this is a retweet Return: storage key for new tweet Tweet storage uid.tweet.{id (incremented per user)} => array[]: 0 -> script hash of invoker 1 -> uid 2 -> display name 3 -> tweet text 4 -> time of tweet 5 -> count comments 6 -> count retweets 7 -> count likes 8 -> count unlikes 9 -> storage key retweeted tweet """ #get user account data and count+1 for tweet accData = updateAccCount(ctx, uid, 4, True) newIndex = accData[4] name = accData[2] # save new tweet time = GetTime() save = [addr, uid, name, content, time, 0, 0, 0, 0, retweet] save_s = Serialize(save) PutThree(ctx, uid, ".tweet.", newIndex, save_s) # increment total tweet count tweetIndex = IncrementOne(ctx, "tweets") # set the storage key for latest tweet tmp1 = concat(uid, ".tweet.") tmp2 = concat(tmp1, newIndex) PutTwo(ctx, "tweet.", tweetIndex, tmp2) OnTweet(tweetIndex, uid, tmp2) return tmp2
def do_transfer(ctx, t_from, t_to, amount): if amount <= 0: return False if len(t_to) != 20: return False if CheckWitness(t_from): now = GetTime() locked_until_from = get_locked_until(ctx, t_from) locked_until_to = get_locked_until(ctx, t_to) if now < locked_until_from or now < locked_until_to: log = debug_log("from or to is locked!") return False if t_from == t_to: log = debug_log("transfer to self!") return True from_val = Get(ctx, t_from) if from_val < amount: log = debug_log("insufficient funds") return False if from_val == amount: Delete(ctx, t_from) else: difference = from_val - amount Put(ctx, t_from, difference) to_value = Get(ctx, t_to) to_total = to_value + amount Put(ctx, t_to, to_total) OnTransfer(t_from, t_to, amount) return True else: log = debug_log("from address is not the tx sender") return False
def get_time_left(): context = GetContext() current_game_no = get_current_game_no() if current_game_no == 1: key = LAST_DRAWING_AT else: key = concat(LAST_DRAWING_AT, current_game_no - 1) last_drawing_at = Get(context, key) now = GetTime() time_left = now - (last_drawing_at + DRAWING_SCHEDULE) return time_left
def register(ctx, args): """ Register new account Args: 0 -> script hash of invoker 1 -> unique user id 2 -> display name 3 -> public key Account storage uid => array[]: 0 -> script hash of invoker 1 -> uid 2 -> display name 3 -> time of registration 4 -> count tweets 5 -> count followers 6 -> count following 7 -> count unfollowed 8 -> count unfollowing 9 -> public key """ addr = args[0] uid = args[1] # check if uid is free if not Get(ctx, uid): # check if user already registered if not isRegistered(ctx,addr): # register the script hash with the uid Put(ctx, addr, uid) name = args[2] time = GetTime() save = [addr, uid, name, time, 0, 0, 0, 0, 0, args[3]] save_s = Serialize(save) # register the uid with user data Put(ctx, args[1], save_s) # Increment total account count + 1 IncrementOne(ctx, "accounts") OnRegister(addr,uid) return True Notify("User is already registered") return False Notify("UserId already taken") return False
def comment(ctx, uid, tweet, comment): """ Comment a tweet Args: uid -> unique user id tweet -> key of to-comment comment -> comment text """ count = updateTweetCount(ctx, tweet, "comment") if count > 0: # save comment for tweet time = GetTime() save = [uid, time, comment] save_s = Serialize(save) PutThree(ctx, tweet, ".comment.", count, save_s) OnComment(uid, tweet) return True Notify("To-comment tweet does not exist") return False
def deploy(): context = GetContext() if not CheckWitness(OWNER): return notifyErrorAndReturnFalse("Must be owner to deploy") if not Get(context, DEPLOYED_AT): current_time = GetTime() Put(context, DEPLOYED_AT, current_time) Put(context, OWNER, TOTAL_SUPPLY) DispatchTransferEvent(None, OWNER, TOTAL_SUPPLY) else: return notifyErrorAndReturnFalse("Already deployed!")
def add_volume(asset_id, native_amount, foreign_amount): time = GetTime() bucket_number = time / bucket_duration volume_key = concat("tradeVolume", bucket_number) volume_key = concat(volume_key, asset_id) volume_data = get(volume_key) if len(volume_data) == 0: volume = set_volume() volume["Native"] = native_amount volume["Foreign"] = foreign_amount else: volume = deserialize(volume_data) volume["Native"] = volume["Native"] + native_amount volume["Foreign"] = volume["Foreign"] + foreign_amount put(volume_key, serialize_array(volume))
def autopick(player): samples = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ] numbers = [] # Use current time in blockchain to in order to generate the numbers. randomNumber = GetTime() for i in range(1, 6): percentage = (randomNumber * i) % (39 - i) numbers.append(samples[percentage]) samples.remove(percentage) return buy(player, numbers)
def add_volume(asset_id, native_amount, foreign_amount): time = GetTime() storage = MCTManager() bucket_number = time / bucket_duration volume_key = concat("tradeVolume", bucket_number) volume_key = concat(volume_key, asset_id) volume_data = storage.get(volume_key) if len(volume_data) == 0: volume = Volume() volume.Native = native_amount volume.Foreign = foreign_amount else: volume = storage.deserialize(volume_data) volume.Native = volume.Native + native_amount volume.Foreign = volume.Foreign + foreign_amount storage.put(volume_key, storage.serialize_array(volume))
def reject(ctx, voter, challenger, owner, challenge_id): submission_key = generate_submission_key(challenger, owner, challenge_id) Log("Generating submission key.") submission = get_submission(ctx, submission_key) if submission: if GetTime() < submission['timestamp'] + 87000: voters = submission['voters'] voted = contains(voters, voter) Log("Checking that the user has not already voted for this submission." ) Log(voted) if voted == False: Log("Rejecting submission.") rejecters = submission['rejecters'] voters.append(voter) rejecters.append(voter) submission['voters'] = voters submission['rejecters'] = rejecters submission['rejecter_count'] = len(submission['rejecters']) submission['difference'] = submission[ 'approver_count'] - submission['rejecter_count'] if submission['difference'] >= 0: submission['status'] = 'APPROVED' elif submission['difference'] < 0: submission['status'] = 'REJECTED' set_submission(ctx, submission_key, submission) return True else: Log("The user already voted.") return False else: Log("This submission has expired.") submission['state'] = 'CLOSED' set_submission(ctx, submission_key, submission) return False else: Log("This submission does not exist.") return False
def getLucky(): numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ] winning_numbers = [] currentHeight = GetHeight() currentHeader = GetHeader(currentHeight) randomNumber = GetConsensusData(currentHeader) randomNumber = randomNumber * GetTime() for i in range(1, 6): percentage = (randomNumber * i) % (39 - i) winning_numbers.append(numbers[percentage]) numbers.remove(percentage) return serialize_array(winning_numbers)
def sendMessage(ctx, sender, receiver, message, ipfs, encrypted): """ Send message Args: sender -> sender address receiver -> receiver address message -> Contains the message or the ipfs hash ipfs -> Boolean if ipfs is used encrypted -> Boolean if message is encrypted A = scripthash of sender storage A.send.{index} stores the sent message from A for respective index storage A.send.latest stores the index of the last message sent from A Receiver B = scripthash of receiver storage B.receive.{index} stores the received message for the recipient B for the respective index storage B.receive.latest stores the index of the last message received for B """ time = GetTime() Log('time') Notify(concat('time', time)) if not ValidateIPFS(ipfs): return False # Add message header for sender addMessage(ctx, sender, '.send.', message, receiver, time, ipfs, encrypted) # Add message header for recipient addMessage(ctx, receiver, '.receive.', message, sender, time, ipfs, encrypted) return True
def launch(): context = GetContext() if not CheckWitness(OWNER): return notifyErrorAndReturnFalse("Must be owner to launch") if not Get(context, LAUNCHED_AT): current_time = GetTime() Put(context, LAUNCHED_AT, current_time) Put(context, CURRENT_GAME_NO, 1) key = concat(LAST_DRAWING_AT, 0) Put(context, key, current_time) return do_transfer(OWNER, POOL, INITIAL_POOL) else: return notifyErrorAndReturnFalse("Already launched!")
def getWarpedTime(context): time = GetTime() time_warp = Get(context, 'time_machine') return time + time_warp