def DoTransfer(t_from, t_to, amount): if amount <= 0: Log("Cannot transfer negative amount") return False from_is_sender = CheckWitness(t_from) if not from_is_sender: Log("Not owner of funds to be transferred") return False if t_from == t_to: Log("Sending funds to self") return True context = GetContext() from_val = Get(context, t_from) if from_val < amount: Log("Insufficient funds to transfer") return False if from_val == amount: Delete(context, t_from) else: difference = from_val - amount Put(context, t_from, difference) to_value = Get(context, t_to) to_total = to_value + amount Put(context, t_to, to_total) DispatchTransferEvent(t_from, t_to, amount) return True
def Main(operation, args): """.""" # Am I who I say I am? user_hash = args[0] contender = args[1] if len(args) == 3: return False # authorized = CheckWitness(user_hash) # if not authorized: # Log("Not Authorized") # return False # Log("Authorized") ctx = GetContext() if operation == 'register': count = contender_register(ctx, contender) return count elif operation == 'vote': status = vote(ctx, contender) Log("voted") Log(status) return status elif operation == 'checkVote': Log("Check voted") status = check_vote(ctx, contender) Log("status is") Log(status) return status return False
def DoTransferFrom(t_from, t_to, amount): if amount <= 0: return False context = GetContext() allowance_key = concat(t_from, t_to) available_to_to_addr = Get(context, allowance_key) if available_to_to_addr < amount: Log("Insufficient funds approved") return False from_balance = Get(context, t_from) if from_balance < amount: Log("Insufficient tokens in from balance") return False to_balance = Get(context, t_to) # calculate the new balances new_from_balance = from_balance - amount new_to_balance = to_balance + amount new_allowance = available_to_to_addr - amount # persist the new balances Put(context, allowance_key, new_allowance) Put(context, t_to, new_to_balance) Put(context, t_from, new_from_balance) Log("transfer complete") # dispatch transfer event DispatchTransferEvent(t_from, t_to, amount) 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 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 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 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
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 Main(operation, args): """ Main definition for the smart contracts :param operation: the operation to be performed :type operation: str :param args: list of arguments. args[0] is always sender script hash args[1] is always product_id args[2] (optional) is always another script hash :param type: str :return: byterarray: The result of the operation """ # Am I who I say I am? user_hash = args[0] authorized = CheckWitness(user_hash) if not authorized: Log("Not Authorized") return False Log("Authorized") if operation is not None: if operation == 'add': Log('add invoked') return args[1] + args[2] Log('Inknown operation') return False
def Main(operation, items): j = 10 if operation == 'dostuff': j = 3 if len(items) == 2: bytes1 = items[0] bytes2 = items[1] len1 = len(bytes1) len2 = len(bytes2) total = concat(bytes1, bytes2) # j = len1 + len2 if total == 137707327489: Log("awesome!") else: Log("bad") else: j = 23 elif operation == 'dont': j = 4 return j
def Main(operation, args): """ Main definition for the smart contracts :param operation: the operation to be performed :type operation: str :param args: list of arguments. args[0] is always sender script hash args[1] is always domain args[2] (optional) is either target or other address args[3] (optional) is target (if args[2] is address) :param type: str :return: byterarray: The result of the operation """ # Common definitions user_hash = args[0] domain = args[1] domain_owner_key = concat(domain, ".owner") domain_target_key = concat(domain, ".target") owner = b'#\xba\'\x03\xc52c\xe8\xd6\xe5"\xdc2 39\xdc\xd8\xee\xe9' # This doesn't require authentication if operation == 'GetDomain': return Get(GetContext(), domain_target_key) # Everything after this requires authorization authorized = CheckWitness(user_hash) if not authorized: Log("Not Authorized") return False Log("Authorized") if operation == 'RegisterDomain': if (CheckWitness(owner)): address = args[2] Put(GetContext(), domain_owner_key, address) if len(args) == 4: target = args[3] Put(GetContext(), domain_target_key, target) return True if operation == 'SetDomainTarget': domain_owner = Get(GetContext(), domain_owner_key) if (CheckWitness(domain_owner)) or (CheckWitness(owner)): # License the product target = args[2] Put(GetContext(), domain_target_key, target) return True if operation == 'DeleteDomain': if (CheckWitness(owner)): Delete(GetContext(), domain_owner_key) Delete(GetContext(), domain_target_key) return True return False
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 DoTransfer(sender, receiver, amount): """ Method to transfer tokens from one account to another :param sender: the address to transfer from :type sender: bytearray :param receiver: the address to transfer to :type receiver: bytearray :param amount: the amount of tokens to transfer :type amount: int :return: whether the transfer was successful :rtype: bool """ if amount <= 0: Log("Cannot transfer negative amount") return False from_is_sender = CheckWitness(sender) if not from_is_sender: Log("Not owner of funds to be transferred") return False if sender == receiver: Log("Sending funds to self") return True context = GetContext() from_val = Get(context, sender) if from_val < amount: Log("Insufficient funds to transfer") return False if from_val == amount: Delete(context, sender) else: difference = from_val - amount Put(context, sender, difference) to_value = Get(context, receiver) to_total = to_value + amount Put(context, receiver, to_total) DispatchTransferEvent(sender, receiver, amount) return True
def close_challenge(ctx, owner, challenge_id): challenge_key = generate_challenge_key(owner, challenge_id) challenge = get_challenge(ctx, challenge_key) if challenge: if challenge['state'] != 'CLOSED': challenge['state'] = 'CLOSED' set_challenge(ctx, challenge_key, challenge) Log("Challenge closed.") return True Log("This challenge does not exist.") return False
def Main(operation, args): """ :param operation: str The name of the operation to perform :param args: list A list of arguments along with the operation """ if operation == 'GetVersion': # very simple method to test the contract Log("Invoked GetVersion") return BZSVERSION # Am I who I say I am? args[0] musth be the wallet hash code authorized = CheckWitness(args[0]) if not authorized: Log("Not Authorized") return 'Not Authorized' Log(args[0]) # storage operations if operation == 'Store': if len(args) < 4: return 'Invalid arguments' category = args[1] id = args[2] put(category, id, args[3]) # args[3] = arbitrary payload Notify(['Store:', category, id]) return 'OK' if operation == 'Retrieve': if len(args) < 3: return 'Invalid arguments' category = args[1] id = args[2] data = get(category, id) Notify(['Retrieve:', category, id]) return data if operation == 'Delete': if len(args) < 3: return 'Invalid arguments' category = args[1] id = args[2] skey = concat(category, id) Delete(GetContext(), skey) Notify(['Delete:', category, id]) return 'OK' # if operation in pawnOps: # print("SmartPawn operation") # sp = SmartPawn(store) # return sp.execute(operation, args) return 'Invalid operation'
def ResultNotice(order_key, funds_transfered, oracle_cost): """ Method to signal results by oracle :param order_key: the key of the exchange :type order_key: bytearray :param funds_transfered: funds on external blockchain transfered :type weather_param: int :param oracle_cost: costs made by the oracle to do this assignment :type oracle_cost: int :return: whether a pay out to the customer is done :rtype: bool """ # Check if the method is triggered by the oracle for this exchange context = GetContext() order_data = Get(context, order_key) oracle = order_data[8] if not CheckWitness(oracle): Log("Must be oracle to notice results") return False timestamp = order_data[3] utc_offset = order_data[4] status = order_data[12] if not status == 'initialized': Log("Contract has incorrect status to do a result notice") return False order_data[12] = 'funds-transfered' # order status order_data[13] = funds_transfered order_data[14] = oracle_cost # Get timestamp of current block currentHeight = GetHeight() currentBlock = GetHeader(currentHeight) current_time = currentBlock.Timestamp Put(context, order_key, order_data) timezone_timestamp = timestamp + (3600 * utc_offset) timezone_current_time = current_time + (3600 * utc_offset) if timezone_current_time < timezone_timestamp: Log("Datetime of result notice is lower than agreed datetime") return False else: DispatchResultNoticeEvent(order_key, funds_transfered, oracle_cost) return True
def Main(operation, args): if operation == 'StartPlay': game_id = start_play(args[0], args[1], args[2]) if game_id: Log(concat('Successful start play invoke. Game id = ', game_id)) else: Log('Start play failed.') return game_id elif operation == 'Answer': return answer(args[0], args[1], args[2], args[3]) else: Log('Method not implemented')
def DoTransferFrom(t_from, t_to, amount): """ Method to transfer NEP5 tokens of a specified amount from one account to another :param t_from: the address to transfer from :type t_from: bytearray :param t_to: the address to transfer to :type t_to: bytearray :param amount: the amount of NEP5 tokens to transfer :type amount: int :return: whether the transfer was successful :rtype: bool """ if amount <= 0: return False context = GetContext() allowance_key = concat(t_from, t_to) available_to_to_addr = Get(context, allowance_key) if available_to_to_addr < amount: Log("Insufficient funds approved") return False from_balance = Get(context, t_from) if from_balance < amount: Log("Insufficient tokens in from balance") return False to_balance = Get(context, t_to) # calculate the new balances new_from_balance = from_balance - amount new_to_balance = to_balance + amount new_allowance = available_to_to_addr - amount # persist the new balances Put(context, allowance_key, new_allowance) Put(context, t_to, new_to_balance) Put(context, t_from, new_from_balance) Log("transfer complete") # dispatch transfer event DispatchTransferEvent(t_from, t_to, amount) return True
def do_transfer(t_from, t_to, amount): context = GetContext() if amount < 0: # raise Exception('Amount MUST be greater than or equal to 0') notifyErrorAndReturnFalse("Amount MUST be greater than or equal to 0") if len(t_from) != 20: return notifyErrorAndReturnFalse("From should be 20-byte addresses") if len(t_to) != 20: return notifyErrorAndReturnFalse("From should be 20-byte addresses") if CheckWitness(t_from): if t_from == POOL: return notifyErrorAndReturnFalse( "Nobody can withdraw from the pool") if t_from == t_to: Log("Transfer to self") return True from_val = Get(context, t_from) if from_val < amount: return notifyErrorAndReturnFalse("insufficient funds") if from_val == amount: Put(context, t_from, 0) else: difference = from_val - amount Put(context, t_from, difference) to_value = Get(context, t_to) to_total = to_value + amount Put(context, t_to, to_total) DispatchTransferEvent(t_from, t_to, amount) return True else: Log("from address is not the tx sender") return False
def Deploy(dapp_name, oracle, time_margin, min_time, max_time): """ Method for the dApp owner initiate settings in storage :param dapp_name: name of the dapp :type dapp_name: str :param oracle: oracle that is used :type oracle: bytearray :param time_margin: time margin in seconds :type time_margin: int :param min_time: minimum time until the datetime of the event in seconds :type min_time: int :param max_time: max_time until the datetime of the event in seconds :type max_time: int :return: whether the update succeeded :rtype: bool """ # if not CheckWitness(OWNER): # Log("Must be owner to deploy dApp") # return False context = GetContext() Put(context, 'dapp_name', dapp_name) Put(context, 'oracle', oracle) if time_margin < 0: Log("time_margin must be positive") return False Put(context, 'time_margin', time_margin) if min_time < 3600 + time_margin: Log("min_time must be greater than 3600 + time_margin") return False Put(context, 'min_time', min_time) if max_time <= (min_time + time_margin): Log("max_time must be greather than min_time + time_margin") return False Put(context, 'max_time', max_time) 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 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
def Main(): # print działa jak Log() print('Hello Arek - print') # Log() służy do logowania/wyświetlenia komunikatu w event hub Log('Hello Arek - log') # Notify() wypisuje informacje w event hub, jest w stanie wypisać stan obiektów Notify('Hello Arek - notify')
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 deploy(): """ :return: bool: Whether the operation was successful """ if not Get(ctx, 'initialized'): owner_initial_address = b'\xee\xee\xf8\xe5_\xde\x1aI\xed\xef\xca\xa5>\x17\x83?x\xf4\xff3' set_owner_address(ctx, owner_initial_address) if not CheckWitness(get_owner_address(ctx)): print("Must be owner to deploy") return False # do deploy logic Put(ctx, 'initialized', 1) # Allocate owner balance of 41 m Put(ctx, get_owner_address(ctx), TOKEN_OWNER_AMOUNT) # Allocate Challenge Reserve balance Put(ctx, CHALLENGE_SYSTEM_RESERVE, CHALLENGE_SYSTEM_INITIAL_AMOUNT) circulation = TOKEN_OWNER_AMOUNT + CHALLENGE_SYSTEM_INITIAL_AMOUNT Log("Deployed successfully!") # Add owner balance and challenge reserve balance to circulation return add_to_circulation(ctx, circulation) return False
def get_challenge(ctx, challenge_key): Log("Retrieving challenge.") to_retrieve = Get(ctx, challenge_key) if to_retrieve: challenge = Deserialize(to_retrieve) return challenge return False
def challenge_expiry_date(ctx, owner, challenge_id): challenge_key = generate_challenge_key(owner, challenge_id) challenge = get_challenge(ctx, challenge_key) if challenge: return challenge['timestamp'] + 1209600 Log("This challenge does not exist.") return False
def submission_number(ctx, owner, challenge_id): challenge_key = generate_challenge_key(owner, challenge_id) challenge = get_challenge(ctx, challenge_key) if challenge: return len(challenge['submissions']) Log("This challenge does not exist.") return False
def is_challenge_open(ctx, owner, challenge_id): challenge_key = generate_challenge_key(owner, challenge_id) challenge = get_challenge(ctx, challenge_key) if challenge: return challenge['state'] == 'OPEN' Log("This challenge does not exist.") return False
def DoMatch(src_order_key, dst_order_key, course): """ Method for the dApp owner to match exchange requests Input data: all not matched requests. Output data: matched pairs """ # Check if the method is triggered by the oracle for this exchange context = GetContext() src_order_data = Get(context, src_order_key) oracle = src_order_data[12] src_deposit_amount = src_order_data[10] dst_order_data = Get(context, dst_order_key) dst_deposit_amount = dst_order_data[10] if not CheckWitness(oracle): Log("Must be oracle to notice results") return False # refund deposit of the source wallet t1 = DoTransfer(DEPOSIT_WALLET, QUARK_WALLET, src_deposit_amount) # refund deposit of the source wallet t2 = DoTransfer(DEPOSIT_WALLET, QUARK_WALLET, dst_deposit_amount) if t1 and t2: DispatchExchangeEvent(src_order_key) DispatchExchangeEvent(dst_order_key) return True return False