def DepositNeo(): # get reference to the tx the invocation is in tx = GetScriptContainer() references = tx.References if len(references) < 1: print("no neo attached") return False # we need to determine who sent the tx reference = references[0] sender = GetScriptHash(reference) # this will keep track of how much neo was deposited value = 0 output_asset_id = GetAssetId(reference) if output_asset_id != NEO_ASSET_ID: print("Must deposit NEO") return False # this is the contract's address receiver = GetExecutingScriptHash() # go through all the outputs # and check if the receiver is the contract # if that is true, we add the value of the output to the # total sum that was deposited for output in tx.Outputs: shash = GetScriptHash(output) if shash == receiver: output_val = GetValue(output) value = value + output_val if value > 0: print("neo was deposited") Notify(value) timestamp = GetHeight() # now we know value was deposited from the sender context = GetContext() print("timestamp: ", timestamp) Put(context, "timestamp", timestamp) print("deposited") return True return False
def DepositNeo(): # get reference to the tx the invocation is in tx = GetScriptContainer() references = tx.References if len(references) < 1: print("no neo attached") return False # we need to determine who sent the tx reference = references[0] sender = GetScriptHash(reference) # this will keep track of how much neo was deposited value = 0 # this is the contract's address receiver = GetExecutingScriptHash() # go through all the outputs # and check if the receiver is the contract # if that is true, we add the value of the output to the # total sum that was deposited for output in tx.Outputs: shash = GetScriptHash(output) if shash == receiver: output_asset_id = GetAssetId(output) if output_asset_id == NEO_ASSET_ID: output_val = GetValue(output) value = value + output_val if value > 0: # now we know value was deposited from the sender # check the current balance of the sender # add it to the deposit amount, and save context = GetContext() current_balance = Get(context, sender) new_balance = current_balance + value Put(context, sender, new_balance) # send deposit event onDeposit(sender, value) return True return False
def SubmitPrediction(oracle, game_type, instance_ts, prediction): if not isGameInstanceLive(game_type, instance_ts): return "Game Instance not yet commissioned" if isGameInstanceJudged(game_type, instance_ts): return "Game Instance already judged" if CheckTimestamp(instance_ts): return JudgeInstance(game_type, instance_ts) # Too late to submit, but can judge else: # Check if Oracle already registered if isOracleRegisteredForInstance(oracle, game_type, instance_ts): return "Already registered" current_oracle_balance = GetOracleBalance(oracle) n_oracles_for_instance = GetOracleCountForInstance(game_type, instance_ts) # See if the agent has sent any NEO-GAS assets tx = GetScriptContainer() refs = tx.References if len(refs) < 1: if current_oracle_balance >= collateral_requirement: new_count = n_oracles_for_instance + 1 RegisterOracle(game_type, instance_ts, oracle, new_count) else: # No assets sent and existing balance too low return "Not enough balance to register" else: ref = refs[0] sentAsset = GetAssetId(ref) #sender_hash = GetScriptHash(ref) if sentAsset == GAS_ASSET_ID: receiver = GetExecutingScriptHash() totalGasSent = 0 cOutputs = len(tx.Outputs) for output in tx.Outputs: Log(output.Value) shash = GetScriptHash(output) if shash == receiver: totalGasSent = totalGasSent + output.Value if totalGasSent == b'\x00e\xcd\x1d': current_oracle_balance = current_oracle_balance + totalGasSent key = concat(key_prefix_agent_available_balance, oracle) # Updates Balance of Oracle context = GetContext() Put(context, key, current_oracle_balance) new_count = n_oracles_for_instance + 1 RegisterOracle(game_type, instance_ts, oracle, new_count) else: return "Wrong amount of NEO GAS Sent" # Now to submit prediction if no errors RegisterPrediction(game_type, instance_ts, oracle, prediction) p_count = IncrementCountForPrediction(game_type, instance_ts, prediction) max_so_far = GetCurrentMax(game_type, instance_ts) if p_count > max_so_far: # New Current Winner UpdateMaxVotes(game_type, instance_ts, p_count) UpdatePrediction(game_type, instance_ts, prediction) if CheckTimestamp(instance_ts): return JudgeInstance(game_type, instance_ts) return True
def CanWithdrawNeo(): print("[can withdraw Neo]") tx = GetScriptContainer() context = GetContext() for output in tx.Outputs: shash = GetScriptHash(output) output_asset_id = GetAssetId(output) if output_asset_id == NEO_ASSET_ID: print("Asset is Neo") else: return False return True saved_timestamp = Get(context, "timestamp") Notify("saved_timestamp: ", saved_timestamp) current_timestamp = GetHeight() Notify("current_timestamp: ", current_timestamp) return current_timestamp > (saved_timestamp + 4)
def Register(prediction_name, context): if CheckPredictionGameLive(prediction_name, context): tx = GetScriptContainer() refs = tx.References if len(refs) < 1: Log("No payment sent in transaction") return False ref = refs[0] sentAsset = GetAssetId(ref) sender_hash = GetScriptHash(ref) k1 = concat("balance", sender_hash) key = concat(k1, prediction_name) balance = Get(context, key) if balance >= 5: Log("Already registered") return False else: if sentAsset == GAS_ASSET_ID: 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("Correct GAS Received") Put(context, key, 5) return True else: Log("Wrong amount of GAS") return False else: Log("Not GAS") return False else: Log("Prediction Game not live") return False
def Main(num): receiver = GetExecutingScriptHash() tx = GetScriptContainer() references = tx.References reference = references[0] sender = GetScriptHash(reference) output_asset_id = GetAssetId(reference) if output_asset_id == GAS_ASSET_ID: print("good") for output in tx.Outputs: shash = GetScriptHash(output) value = GetValue(output) / 100000000 remainder = value % 1 value = value - remainder OnSpend(b'AFxLPTwPoxowEHvvYYd5RKfJ3VqMTwh4pm', value, receiver) return num return 0
def getValue(): tx = GetScriptContainer() references = tx.References reference = references[0] output_asset_id = GetAssetId(reference) if output_asset_id == GAS_ASSET_ID: for output in tx.Outputs: shash = GetScriptHash(output) value = GetValue(output) / 100000000 remainder = value % 1 value = value - remainder return value print("gas not found rip") return 0
def CanClaimGas(): print("Withdrawing Donations") tx = GetScriptContainer() tpe = GetType(tx) print("Type: ", tpe) for output in tx.Outputs: shash = GetScriptHash(output) output_asset_id = GetAssetId(output) if output_asset_id == GAS_ASSET_ID: print("Asset is Gas") else: return False return True
def add_url(url): """ Generates a new code and stores the <code, url> pair into the blockchain. """ # Retrieves the current "height" of the blockchain, as of the related block and timestamp. current_height = GetHeight() header = GetHeader(current_height) # Retrieves the hash of the considered sender. tx = GetScriptContainer() references = tx.References ref = references[0] sender = GetScriptHash(ref) # Generates a random number from the consensus data of the block (the pseudo-random number # generated by the consensus node). We also generate a number from the considered URL. random_number = header.ConsensusData >> 32 url_seed = url[:16] >> 96 # Generates a unique code. s1 = b58encode(current_height, 6) s2 = b58encode(random_number, 2) s3 = b58encode(url_seed, 4) code_p1 = concat(s1, s2) code = concat(code_p1, s3) # Puts the URL and the related information into the ledger. context = GetContext() contextkey_for_url = get_contextkey_for_url(code) contextkey_for_sender = get_contextkey_for_sender(code) # NOTE: dictionaries are not yet supported by the neo-boa compiler so we have to derive multiple # context keys from the code value for each item associated with the considered code. Put(context, contextkey_for_url, url) Put(context, contextkey_for_sender, sender) # Fires an event indicating which <code, url> pair has been persisted into the ledger. DispatchNewURLEvent(code, url) return True
def Main(operation, args): trigger = GetTrigger() if trigger == Verification(): return CheckWitness(OWNER) elif trigger == Application(): context = GetContext() l = len(args) if l == 1: key = args[0] elif l == 2: key = args[0] value = args[1] else: Log("Bad invocation argument count") Log(l) return False if operation == 'getvalue': return Get(context, key) elif operation == 'putvalue': prefix = take(key, 6) if BADPREFIX == prefix: Log("Hacking attempt!") return False if CheckWitness(OWNER): Log("Owner found, bypassing payment") Put(context, key, value) return True else: # check if we got paid tx = GetScriptContainer() refs = tx.References if len(refs) < 1: Log("No payment sent in transaction") return False ref = refs[0] sentAsset = GetAssetId(ref) if sentAsset == GAS_ASSET_ID: sender = GetScriptHash(ref) receiver = GetExecutingScriptHash(); totalGasSent = 0 for output in tx.Outputs: shash = GetScriptHash(output) if shash == receiver: totalGasSent = totalGasSent + output.Value Log ("Total GAS sent:") Log (totalGasSent) pkey = concat('price/', key) keyprice = Get(context, pkey) if totalGasSent == keyprice: Log("Price met, setting value and sending notification") notification=[sender,key,value] Notify(notification) Put(context, key, value) return True Log("Price not met!") return False return False elif operation == 'getprice': key = concat('price/', key) return Get(context, key) elif operation == 'putprice': if CheckWitness(OWNER): key = concat('price/', key) Put(context, key, value) return True else: Log("Access denied") return False else: Log("Invalid operation") return False return False
def Deposit(escrow_script_hash, note): """ Put money into the contract and set the transactions vins to be owned by escrow_script_hash :param escrow_script_hash: the script hash who will be able to move these funds out :type escrow_script_hash: bytearray :param note: a note for the recipient (escrow_script_hash) :type note: strung :return: True if the deposit was successful, otherwise, false. :rtype: bool """ # Get the transaction info. tx = GetScriptContainer() # Check if the transactions has currency attached references = tx.References if len(references) < 1: return False # Sender's script hash. We'll also grant them ownership of the funds if they need to retrieve their money # before it's claimed or if it will never be claimed. reference = references[0] sender = GetScriptHash(reference) # This is the contract's address contract_script_hash = GetExecutingScriptHash() context = GetContext() deposited = False # Go through all the outputs and handle deposits for output in tx.Outputs: shash = GetScriptHash(output) output_asset_id = GetAssetId(output) # We only care about NEO/GAS coming to the contract. if shash == contract_script_hash: output_val = GetValue(output) deposited = True # Update our total counter for this asset. This is just for fun display purposes total_all_time_key = concat("totalAllTime", output_asset_id) total_all_time = Get(context, total_all_time_key) new_total_all_time = total_all_time + output_val Put(context, total_all_time_key, new_total_all_time) # Here we keep a record of all the tx hashes belonging to the sender and recipient. # The idea is that they can view a list of these transactions. # # Also, the sender can rescind any that was still idle after a week (Mom didn't care enough to pick up # her GAS) if deposited: tx_hash = GetHash(tx) time = GetCurrentTimestamp() tx_info = [escrow_script_hash, sender, time, note] tx_info_serialized = serialize_array(tx_info) Put(context, tx_hash, tx_info_serialized) AddTransactionToScriptHash('recipient_history', escrow_script_hash, tx_hash) AddTransactionToScriptHash('sender_history', sender, tx_hash) return True return False
def Main(operation, args): trigger = GetTrigger() if trigger == Verification(): # Verification is done when sending money out of the contract. # # We need to check the sender's balance to make sure they have enough to allow them # to send what they're trying to send # # Note: Contract owner has no special privileges here. tx = GetScriptContainer() valid = False # Go through all the outputs and make sure there's only one output destination. # This will be used if we're auto-rescinding the assets (ie sending back to the original # sender after a week goes by without the recipient picking up). We'll make sure there's only # one output script hash and it matches the stored script hash of the original sender # # Also we make sure not outputs are going to the contract script hash because we don't support # change. output_script_hash = None contract_script_hash = GetExecutingScriptHash() for output in tx.Outputs: shash = GetScriptHash(output) if shash == contract_script_hash: return False if output_script_hash == None: output_script_hash = shash elif shash != output_script_hash: return False for input in tx.Inputs: hash = InputGetHash(input) context = GetContext() tx_info_serialized = Get(context, hash) tx_info = deserialize_bytearray(tx_info_serialized) escrow = tx_info[0] sender = tx_info[1] time = tx_info[2] is_escrow = CheckWitness(escrow) if is_escrow != True: if sender != output_script_hash: return False current_time = GetCurrentTimestamp() seven_days = 604800 minimum_time = time + seven_days if current_time < minimum_time: return False # We have at least one. We'll keep checking if there are more. print('That input was valid') valid = True print('All good') return valid elif trigger == Application(): if operation == 'name': n = "Sendeo" return n elif operation == 'deposit': if len(args) != 2: return False recipient = args[0] note = args[1] deposit = Deposit(recipient, note) return deposit return False
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
def Main(operation, args): """ :param operation: new, submit, judge, getvalue :param args: optional arguments :return: Bool """ trigger = GetTrigger() if trigger == Application: Log("trigger: Application") context = GetContext() if operation == 'getvalue': Log("op: getvalue") key = args[0] return Get(context, key) if operation == 'new': id = args[0] Put(context, "current_game", id) Log("Created a new game") elif operation == 'submit': id = args[0] price = args[1] Log(id) Log(price) # Only allow submissions for the current game current_game = Get(context, "current_game") if current_game != id: Log("Not the correct game") return False tx = GetScriptContainer() refs = tx.References nRef = len(refs) Log(nRef) ref = refs[0] sender = GetScriptHash(ref) Log(sender) key = concat(sender, id) Log(key) oldprice = Get(context, key) if oldprice == 0: Append(context, sender, id) Put(context, key, price) # Update if already exists elif operation == 'judge': id = args[0] playerkey = concat("players::", id) curr_list = Get(context, playerkey) nplayers = len(curr_list) // 20 max = 0 best_price = -1 for i in range(0, nplayers): start = 20 * i player = substr(curr_list, start, 20) Log(player) key = concat(player, id) price = Get(context, key) price_key = concat(id, price) count = Increment(context, price_key) if count > max: max = count best_price = price if max == 0: Log("No entries") return False else: Log(max) Log(best_price) Put(context, id, best_price) return True return True return False
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
def getSource(): tx = GetScriptContainer() references = tx.References reference = references[0] sender = GetScriptHash(reference) return sender
def ReconcileBalances(): print("[Reconcile balances]") # this is the contract's address sender_addr = GetExecutingScriptHash() tx = GetScriptContainer() withdrawal_amount = 0 receiver_addr = bytearray(0) # go through the outputs of the tx # and find ones that are neo # and also the receiver cannot be the contract ( sender_addr ) for output in tx.Outputs: shash = GetScriptHash(output) output_asset_id = GetAssetId(output) if output_asset_id == NEO_ASSET_ID: if shash != sender_addr: print("[reconcile] output is to receiver") receiver_addr = shash output_val = GetValue(output) withdrawal_amount = withdrawal_amount + output_val Notify(withdrawal_amount) Notify(output) else: print( "[Reconcile balances] output is to contract sender addr, ignore" ) Notify(output) else: print("[Reconcile balances] output is not neo") Notify(output) # we check recevier addr and amount if len(receiver_addr) > 0: print("[Reconcile balances] receiver addr is valid") Notify(receiver_addr) context = GetContext() current_balance = Get(context, receiver_addr) print("[Reconcile balances] current balance") Notify(current_balance) Notify(withdrawal_amount) if withdrawal_amount <= current_balance: new_balance = current_balance - withdrawal_amount print("[Reconcile balances] new balance is...") Notify(current_balance) Notify(new_balance) Put(context, receiver_addr, new_balance) onWithdrawReconciled(receiver_addr, new_balance) print("[Reconcile balances] withdrawl amount il less than balance") return True else: print("[Reconcile balances] not enough to witdraw") else: print("[Reconcile balances] receiver addr not set") return False
def CanWithdrawNeo(): print("[can withdraw]") is_invocation = IsInvocationTx() if is_invocation: # this is the contract's address sender_addr = GetExecutingScriptHash() tx = GetScriptContainer() withdrawal_amount = 0 receiver_addr = bytearray(0) # go through the outputs of the tx # and find ones that are neo # and also the receiver cannot be the contract ( sender_addr ) for output in tx.Outputs: shash = GetScriptHash(output) output_asset_id = GetAssetId(output) if output_asset_id == NEO_ASSET_ID: if shash != sender_addr: print("[can withdraw] output is to receiver") receiver_addr = shash output_val = GetValue(output) withdrawal_amount = withdrawal_amount + output_val Notify(withdrawal_amount) Notify(output) else: print( "[can withdraw] output is to contract sender addr, ignore" ) Notify(output) else: print("[can withdraw] output is not neo") Notify(output) # we check recevier addr and amount if len(receiver_addr) > 0: print("[can withdraw] receiver addr is valid") Notify(receiver_addr) context = GetContext() current_balance = Get(context, receiver_addr) print("[can withdraw] current balance") Notify(current_balance) Notify(withdrawal_amount) if withdrawal_amount <= current_balance: print("[can withdraw] withdrawl amount il less than balance") onWithdraw(receiver_addr, withdrawal_amount) return True else: print("[can withdraw] not enough to witdraw") else: print("[can withdraw] receiver addr not set") return False
def CanWithdrawNeo(): print("[can withdraw]") tx = GetScriptContainer() type = GetType(tx) invoke_type = b'\xd1' print("[can withdraw] got tx type...") if type == invoke_type: print("[can withdraw] Is invocation!!") # this is the contract's address sender_addr = GetExecutingScriptHash() withdrawal_amount = 0 receiver_addr = bytearray(0) # go through the outputs of the tx # and find ones that are neo # and also the receiver cannot be the contract ( sender_addr ) for output in tx.Outputs: shash = GetScriptHash(output) output_asset_id = GetAssetId(output) if output_asset_id == NEO_ASSET_ID: output_val = GetValue(output) if shash != sender_addr: print("[can withdraw] output is to receiver") receiver_addr = shash withdrawal_amount = withdrawal_amount + output_val Notify(withdrawal_amount) Notify(output) else: print( "[can withdraw] output is to contract sender addr, subtract from withdraw total" ) withdrawal_amount = withdrawal_amount - output_val Notify(output) else: print("[can withdraw] output is not neo") Notify(output) # we check recevier addr and amount if len(receiver_addr) > 0: print("[can withdraw] receiver addr is valid") Notify(receiver_addr) context = GetContext() current_balance = Get(context, receiver_addr) print("[can withdraw] current balance") Notify(current_balance) Notify(withdrawal_amount) if withdrawal_amount <= current_balance: print("[can withdraw] withdrawl amount il less than balance") onWithdraw(receiver_addr, withdrawal_amount) return True else: print("[can withdraw] not enough to witdraw") else: print("[can withdraw] receiver addr not set") else: print("[can withdraw] tx is not invocation tx. return false") return False
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