def QueryFarmContract(FarmContract_name): msg = concat("QueryFarmContract: ", FarmContract_name) Notify(msg) context = GetContext() owner = Get(context, FarmContract_name) if not owner: Notify("This farm Contract is not yet registered") return False Notify(owner) return owner
def QueryBuyer(Buyer_name): msg = concat("QueryBuyer: ", Buyer_name) Notify(msg) context = GetContext() owner = Get(context, Buyer_name) if not owner: Notify("This Buyer is not yet registered") return False Notify(owner) return owner
def Main(operation, addr, value): print("Running Sample v4") trigger = GetTrigger() print(trigger) # This determines that the SC is runnning in Verification mode # This determines whether the TX will be relayed to the rest of the network # The `Verification` portion of SC is *read-only*, so calls to `Storage.Put` will fail. # You can, however, use `Storage.Get` if trigger == Verification(): print("Running Verification!") # This routine is: if the invoker ( or the Address that signed the contract ) is not OWNER, # Then we return False, and the TX will not be relayed to the network # Otherwise, we know the owner address signed the TX and return True is_owner = CheckWitness(OWNER) if is_owner: print("Is Owner!") return True print("Not Owner") return False elif trigger == Application(): print("Running Application!") if not is_valid_addr(addr): print("Not Valid Address") return False ctx = GetContext() if operation == 'add': balance = Get(ctx, addr) new_balance = balance + value Put(ctx, addr, new_balance) return new_balance elif operation == 'remove': balance = Get(ctx, addr) Put(ctx, addr, balance - value) return balance - value elif operation == 'balance': return Get(ctx, addr) return False
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 query_asset(asset_id): msg = concat("QueryAsset: ", asset_id) Notify(msg) context = GetContext() owner = Get(context, asset_id) info = Get(context, asset_id+'info') if not owner: Notify("Asset is not yet registered") return False Notify(owner) return info
def get_last_ticket_no(): ctx = GetContext() no = Get(ctx, LAST_TICKET_NO) if not no: return notifyErrorAndReturnZero("Can not find the last ticket") else: return no
def get_current_game_no(): ctx = GetContext() current_game_no = Get(ctx, CURRENT_GAME_NO) if not current_game_no: return 1 else: return current_game_no
def AddHash(id, hash): msg = concat("RegisterHash: ", id) msg = concat(msg, hash) Notify(msg) context = GetContext() exists = Get(context, id) if exists: Notify("ID is already registered") return False Put(context, id, hash) return True
def VerifyRecord(record_id): context = GetContext() record_meta_key = concat(RECORD_ID_META_PREFIX, record_id) record_meta_serialized = Get(context, record_meta_key) if not record_meta_serialized: Log("Record doesn't exist") return False record_meta = deserialize_bytearray(record_meta_serialized) usr_adr = record_meta[0] pub_key = record_meta[1] creator_adr = record_meta[2] if not check_permission(usr_adr): Log("Must be owner to verify a record") return False context = GetContext() record_meta_upd = [usr_adr, pub_key, creator_adr, True] record_meta_upd_serialized = serialize_array(record_meta_upd) record_meta_key = concat(RECORD_ID_META_PREFIX, record_id) Put(context, record_meta_key, record_meta_upd_serialized) return True
def BalanceOf(account): """ Method to return the current balance of an address :param account: the account address to retrieve the balance for :type account: bytearray :return: the current balance of an address :rtype: int """ context = GetContext() balance = Get(context, account) return balance
def get_last_verified_ticket_no(): context = GetContext() no = Get(context, LAST_VERIFIED_TICKET_NO) if not no: return notifyErrorAndReturnZero("No verified tickets yet") else: return no
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 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': if CheckWitness(domain_owner_key) 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 DoTransfer(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: 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 SetAddress(domain_name, to_address): msg = concat("SetAddress: ", domain_name) Notify(msg) context = GetContext() owner = Get(context, domain_name) if not CheckWitness(owner): Notify("Owner argument is not the same as the sender") return False if not len(to_address) != 34: Notify("Invalid new owner address. Must be exactly 34 characters") return False Put(context, "{domain_name}.neo", to_address) return True
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 addSubaccountAsMaster(executionerPublicKey, domainName, subDomainName, walletHash): if not CheckWitness(executionerPublicKey): return False #check if owner and domain exists if not existDomainAndOwnerWithHash(executionerPublicKey, domainName): return False ctx = GetContext() # "simpli/sub/ SubaccountKey = createSubMainKey(domainName, walletHash) subKey = createSubNameKey(SubaccountKey, subDomainName) #if exist subdomain name, return false if existSubDomain(subKey): return False if existSubaccount(SubaccountKey): masterApproved = Get(ctx, createMasterApprovedKey(SubaccountKey)) masterApproved = masterApproved + 0x30 if masterApproved is None: return False if not masterApproved: return False subsKeyValue = concat(subDomainName, ":") subsKeyValue = concat(subsKeyValue, walletHash) #save to all subs keyHashes = createSubsKey(domainName) addHashToHashes(keyHashes, subsKeyValue, ";") #save to all scripthash domains tr = concat("s:", subDomainName) addDomainToStorage(walletHash, tr) else: #save sub scripthash Put(ctx, SubaccountKey, walletHash) #save sub approved false Put(ctx, createSubApprovedKey(SubaccountKey), 0x30) #save master approved Put(ctx, createMasterApprovedKey(SubaccountKey), 0x01) Put(ctx, subKey, subDomainName) Put(ctx, createSubRootNameKey(SubaccountKey), subDomainName) return True
def PurchaseData(order_id, pub_key): order = GetOrder(order_id) if not order: Log("Order doesn't exist") return False if order[3] != '': Log("Already purchased") return False if pub_key == '': Log("Empty public key") return False tx = GetScriptContainer() references = tx.References if len(references) < 1: Log("No NEO attached") return False receiver_addr = GetExecutingScriptHash() received_NEO = 0 for output in tx.Outputs: if output.ScriptHash == receiver_addr: if output.AssetId == NEO_ASSET_ID: received_NEO += output.Value received_NEO /= 100000000 Log("Received total NEO:") Log(received_NEO) price = order[2] if received_NEO < price: Log("Not enough NEO") return False Log("Rewriting order to new public key") context = GetContext() order[3] = pub_key order_data_serialized = serialize_array(order) order_key = concat(ORDER_ID_PREFIX, order_id) Put(context, order_key, order_data_serialized) Log("Payment to user") reference = references[0] sender = GetScriptHash(reference) usr_adr = order[0] DispatchTransferEvent(sender, usr_adr, price) return True
def SetSubdomain(domain_name, subdomain): msg = concat("SetSubdomain: ", domain_name) Notify(msg) context = GetContext() owner = Get(context, domain_name) if not owner: Notify("Domain is not yet registered") return False if not CheckWitness(owner): Notify("Sender is not the owner, cannot transfer") return False Put(context, "{subdomain}.{domain_name}", owner) return True
def AddIPFSHash(domain_name, IPFS): msg = concat("AddIPFS: ", domain_name) Notify(msg) context = GetContext() owner = Get(context, domain_name) if not owner: Notify("Domain is not yet registered") return False if not CheckWitness(owner): Notify("Sender is not the owner, cannot transfer") return False Put(context, "{domain_name}.ipfs", IPFS) return True
def QueryFarmContract(FarmContract_name, OwnerNeoAddress): msg = concat("QueryFarmContract: ", FarmContract_name) msg2 = concat(msg, OwnerNeoAddress) Notify(msg2) storage_key = concat(FarmContract_name, OwnerNeoAddress) context = GetContext() Owner = getRegistry(context, storage_key) if not Owner: Notify("This Farm Contract is not yet registered") return False farm_contract_info = deserialize_bytearray(Owner) Notify(farm_contract_info) return farm_contract_info
def get_certs(address): """Fetches all certifications for a given address returns: a list of certifying user and content """ ctx = GetContext() current_data = Get(ctx, address) if current_data: entries = deserialize_bytearray(current_data) final = add_delimiter(entries) Notify('Found items, returning them') else: Notify('No certifications found for this address') final = 'Error: No certifications found for this address' return final
def Main(op, args): context = GetContext() key = 'key' if op == 'get': value = Get(context, key) Notify(["read from storage", value]) return value if op == 'put': if len(args) == 0: Notify("i have no value to put") return False Put(context, key, args[0]) return True
def Main(voter, operation, poll, selection): if not CheckWitness(voter): print(concat("CheckWitness failed for: ", voter)) return False ctx = GetContext() if operation == "select": return vote_for_selection(ctx, voter, poll, selection) elif operation == "result": return get_selection_result(ctx, poll, selection) return False
def get_winning_numbers(game_no): context = GetContext() key = concat(WINNING_NUMBERS, game_no) result = Get(context, key) if not result: return notifyErrorAndReturnFalse("No drawing result") else: return result
def get_ticket_info(ticket_no): context = GetContext() key = concat(TICKET, ticket_no) ticket = Get(context, key) if not ticket: return notifyErrorAndReturnFalse('Can not find the ticket') else: return ticket
def InsertRecord(creator_adr, usr_adr, data_pub_key, data_encr): if not check_permission(creator_adr): Log("Wrong creator_adr") return False users = GetUserList() found = False for user in users: if user == usr_adr: found = True if not found: users.append(usr_adr) users_serialized = serialize_array(users) context = GetContext() Put(context, USR_ADR_LIST_KEY, users_serialized) msg = concat("New user: "******"New record: ", record_id) Notify(msg) return record_id
def RegisterBuyer(Buyer_name, owner): msg = concat("RegisterBuyer: ", Buyer_name) Notify(msg) if not CheckWitness(owner): Notify("Owner argument is not the same as the person who registered") return False context = GetContext() exists = Get(context, Buyer_name) if exists: Notify("Buyer is already registered") return False Put(context, Buyer_name, owner) return True
def TimeMachine(args): added_days = args[0] if not CheckWitness(OWNER): print('Only the contract owner may use the time machine') return [False, 'Witness must be owner'] context = GetContext() time_warp = Get(context, 'time_machine') new_time_warp = time_warp + added_days * SECONDS_IN_DAY Put(context, 'time_machine', new_time_warp) return [True, '']
def RegisterDomain(domain_name, owner): msg = concat("RegisterDomain: ", domain_name) Notify(msg) if not CheckWitness(owner): Notify("Owner argument is not the same as the sender") return False context = GetContext() exists = Get(context, domain_name) if exists: Notify("Domain is already registered") return False Put(context, domain_name, owner) return True