def Main(operation, arguments): print("Running DNS contract v1") trigger = GetTrigger() if len(arguments) < 1 or (operation == 'put' and len(arguments) < 2): return False if not is_valid_addr(arguments[0]): return False # This determines that the SC is running 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!") if operation == 'put' or operation == 'delete': return CheckWitness(arguments[0]) elif operation == 'get': return True return False elif trigger == Application(): print("Running Application!") ctx = GetContext() if operation == 'put': Put(ctx, arguments[0], arguments[1]) return True elif operation == 'get': return Get(ctx, arguments[0]) elif operation == 'delete': Delete(ctx, arguments[0]) return True return False return False
def CurrentSwapRate(): """ Method to calculate the current 'going rate' or exchange ratio of NEO to NEP5 tokens :return: the current rate :rtype: int """ basic = 1000 * FACTOR duration = ICO_END_TIME - ICO_START_TIME print("getting swap rate") context = GetContext() print("got context") total_supply = Get(context, 'totalSupply') print("got total supply") if total_supply >= TOTAL_AMOUNT: return False print("getting current height...") currentHeight = GetHeight() print("got current height") currentBlock = GetHeader(currentHeight) print("got current block...") time = currentBlock.Timestamp - ICO_START_TIME if time < 0: return 0 elif time < 86400: return basic * 130 / 100 elif time < 259200: return basic * 120 / 100 elif time < 604800: return basic * 110 / 100 elif time < duration: return basic return 0
def register_proposal(args): """ Register a New prosal :param args: list of arguments [PROPOSA ID, PROPOSAL DESCRIPTION, AUTHORIZED ADDR 1, AUTHORIZED ADDR N, ...] :return: bool, result of the execution """ if len(args) < 4: return False # check proposal existence proposal_id = args[0] if Get(ctx, proposal_id): print("Already a Proposal") return False # proposal arguments proposal = [] proposal.append(args[1]) # proposal description proposal.append(0) # yes counter proposal.append(0) # no counter # iterate from the third parameter to extract authorized addresses proposal_address = [] index = 2 while index < len(args): address = args[index] # check address format if len(address) != 20: print('bad address format') return False proposal_address.append(address) index += 1 proposal.append(proposal_address) # authorized addresses # serialize proposal and write to storage proposal_storage = Serialize(proposal) Put(ctx, proposal_id, proposal_storage) return True
def deploy(): """ Deploy the contract: initialize all settings. """ if not CheckWitness(CONTRACT_OWNER): return "Must be owner to deploy" if not Get(ctx, 'initialized'): # do deploy logic Put(ctx, 'initialized', 1) Put(ctx, AD_LIST_KEY, Serialize([])) Put(ctx, CONTRACT_OWNER, TOKEN_INITIAL_AMOUNT) # Set ICO Start and end date height = GetHeight() Put(ctx, BLOCK_SALE_START_KEY, height) Put(ctx, BLOCK_SALE_LIMIT_END_KEY, height + ICO_LIMITED_DURATION) return add_to_circulation(ctx, TOKEN_INITIAL_AMOUNT) return 'Deploy Failed'
def allowance(context, arguments): address = arguments[0] to = arguments[1] # Address has to be 20 bytes if len(address) != 20: print('Address is incorrect') return False # To address has to be 20 bytes if len(to) != 20: print('Address is incorrect') return False key = concat(address, to) # Return the allowance allowance = Get(context, key) return allowance
def register_wallet(context, args): if not CheckWitness(OWNER): Notify(ILLEGAL_CALL) return False wallet = args[0] if len(wallet) != 20: Notify(INVALID_ADDRESS) return False if Get(context, wallet): Notify(ALREADY_EXISTING_WALLET) return False Notify(['[REGISTER-WALLET] wallet:', wallet]) Put(context, wallet, True) return True
def exchange_token(): tx = GetScriptContainer() references = tx.References sender_addr = None receiver_addr = GetExecutingScriptHash() sent_amount_neo = 0 sender_addr = 1 neo_amount = 0 if len(references) > 0: reference = references[0] sender_addr = reference.ScriptHash for output in tx.Outputs: if output.ScriptHash == receiver_addr: neo_amount += output.Value if neo_amount == 0: return false exchanged_amount = neo_amount * 10 current_balance = Get(ctx, sender_addr) Put(ctx, sender_addr, current_balance + exchanged_amount) return True
def TransferRegistry(Registry_name, to_address): msg = concat("TransferRegistry: ", Registry_name) Notify(msg) context = GetContext() owner = Get(context, Registry_name) if not owner: Notify("Registry is not yet registered") return False if not CheckWitness(owner): Notify("This person is not the owner, Registry ownership cannot be transfered") return False if not len(to_address) != 34: Notify("Invalid new owner neo address. Must be exactly 34 characters") return False putRegistry(context, Registry_name, to_address) return True
def deploy(): """ :param token: Token The token to deploy :return: bool: Whether the operation was successful """ if not CheckWitness(TOKEN_OWNER): print("Must be owner to deploy") return False if not Get(ctx, 'initialized'): # do deploy logic Put(ctx, 'initialized', 1) Put(ctx, TOKEN_OWNER, TOKEN_INITIAL_AMOUNT) # dispatch transfer event for minting OnTransfer(None, TOKEN_OWNER, TOKEN_INITIAL_AMOUNT) return add_to_circulation(ctx, TOKEN_INITIAL_AMOUNT) return False
def TransferFarm(Farm_name, to_address): msg = concat("TransferFarm: ", Farm_name) Notify(msg) context = GetContext() owner = Get(context, Farm_name) if not owner: Notify("Farm is not yet registered") return False if not CheckWitness(owner): Notify("This person is not the owner, farm ownership cannot transfer") return False if not len(to_address) != 34: Notify("Invalid new owner neo address. Must be exactly 34 characters") return False Put(context, Farm_name, to_address) return True
def do_modify_uri(ctx, args): """Modifies token URI :param StorageContext ctx: current store context :param int t_id: token id :param str t_uri: token uri :return: URI modification success :rtype: bool """ t_id = args[0] t_uri = args[1] token_key = concat('token/', t_id) token = safe_deserialize(Get(ctx, token_key)) assert token, TOKEN_DNE_ERROR token['uri'] = t_uri Put(ctx, token_key, Serialize(token)) return True
def Transfer(domain, to): if to == None: return False context = GetContext() owner = Get(context, domain) if owner == None: return False if owner == to: return True is_owner = CheckWitness(owner) if not is_owner: return False Put(context, domain, to) Push('Transfer', domain) return True
def transfer_asset(asset_id, to_address): msg = concat("TransferAsset: ", asset_id) Notify(msg) context = GetContext() owner = Get(context, asset_id) if not owner: Notify("Asset is not yet registered") return False if not CheckWitness(owner): Notify("Sender is not the owner, cannot transfer") return False if not len(to_address) != 34: Notify("Invalid new owner address. Must be exactly 34 characters") return False Put(context, asset_id, to_address) return True
def bid_for_board(board_id, bidder, bid, content): if bid <= 0: ''' and other value checking''' return False highest_bid_key = get_highest_bid_key(board_id) highest_bid = Get(ctx, highest_bid_key) if bid > highest_bid: highest_bidder_key = get_highest_bidder_key(board_id) Put(ctx, highest_bidder_key, bidder) Put(ctx, highest_bid_key, bid) next_content_key = get_next_content_key(board_id) Put(ctx, next_content_key, content) return True else: print('Bid Smaller than Current Bid') 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 TransferDomain(domain_name, to_address): msg = concat("TransferDomain: ", 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 if not len(to_address) != 34: Notify("Invalid new owner address. Must be exactly 34 characters") return False Put(context, domain_name, to_address) return True
def min_tokens(ctx, from_address, to_address, tokens): """ Mint tokens for an address :param from_address: the address from which the tokens are being minted (should always be the contract address) :param to_address: the address to transfer the minted tokens to :param tokens: the number of tokens to mint """ # lookup the current balance of the address current_balance = Get(ctx, to_address) new_total = current_balance + tokens #save new balance on the address Put(ctx, to_address, new_total) # update the in circulation amount result = add_to_circulation(ctx, tokens) # dispatch transfer event OnTransfer(from_address, to_address, tokens)
def mint_tokens(ctx, address, amount): """ Mint tokens for an address :param ctx:GetContext() used to access contract storage :param to_address: the address to add the tokens to :param amount:int the number of tokens to mint :return:bool Whether the operation was successful """ # lookup the current balance of the address current_balance = Get(ctx, address) # add it to the the exchanged tokens and persist in storage new_total = amount + current_balance Put(ctx, address, new_total) # update the in circulation amount return add_to_circulation(ctx, amount)
def do_approve(ctx, t_owner, t_spender, t_id, revoke): if len(t_owner) != 20: return False if len(t_spender) != 20: return False if len(t_id) == 0: t_id = 0 if len(revoke) == 0: revoke = 0 t_owner = Get(ctx, t_id) if len(t_owner) != 20: print("token does not exist") return False if CheckWitness(t_owner): approval_key = concat("approved/", t_id) if revoke != 0: Delete(ctx, approval_key) OnApprove(t_owner, t_spender, 0) OnNFTApprove(t_owner, '', t_id) return True # only one third-party spender can be approved # at any given time for a specific token approved_spend = concat(t_owner, t_spender) Put(ctx, approval_key, approved_spend) OnApprove(t_owner, t_spender, 1) OnNFTApprove(t_owner, t_spender, t_id) return True print("Incorrect permission") 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 a key for a value (likely a key to ipfs) args[2] is the value to be stored (likely ipfs hash) :param type: str :return: byterarray: The result of the operation """ print("checking if authorized") # Am I who I say I am? user_hash = args[0] authorized = CheckWitness(user_hash) if not authorized: print("Not Authorized") return False print("Authorized") #blockchain key, is the key stored for the data stored (probably ipfs) blockchain_key = args[1] if operation == 'Save': print("operation = Save()") blockchain_value = args[2] Put(GetContext(), blockchain_key, blockchain_value) return True if operation == 'Get': print("operation = Get()") stored_value = Get(GetContext(), blockchain_key) if stored_value: return stored_value return False
def register(ctx, args): """ Register new account Args: 0 -> script hash of invoker 1 -> unique user id 2 -> display name 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 """ 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] 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 transfer_to_smart_contract(ctx, t_from, args, is_mint): """Transfers a token to a smart contract and triggers the receiving contract's onNFTTransfer event. :param StorageContext ctx: current store context :param byte[] t_from: transfer from address (who is sending the NFT) :param list args: 0: byte[] t_to: transfer to address (who is receiving the NFT) 1: bytes t_id: token id 2: extra_arg (optional) :param bool is_mint: whether or not the token is being minted :return: transfer success :rtype: bool """ t_to = args[0] t_id = args[1] if len(t_from) != 20 or len(t_to) != 20: Notify(INVALID_ADDRESS_ERROR) return False # invoke the onNFTTransfer operation of the recipient contract, # if it returns False, then reject the transfer success = DynamicAppCall(t_to, 'onNFTTransfer', args) if success is False: Notify('transfer rejected by recipient contract') return False # need to check funds again in case a transfer or approval # change happened inside the onTokenTransfer call # the `is_mint` check is needed because you can't get the token # owner for a token that hasn't finished being minted yet if is_mint is False: t_owner = Get(ctx, t_id) if t_owner != t_from: Notify('insufficient funds') return False Log('transfer accepted by recipient contract') return True
def create(data): """ Parameters ---------- data : boa.builtins.list The input data containing an address and a hash, both in bytes Returns ------- bool Returns False if the entry does exist already, otherwise True """ if Get(ctx, data[IDX_KEY]): print('Error: Entry already exists!') return False data_serialized = serialize_data(data) Put(ctx, data[IDX_KEY], data_serialized) return True
def has_user_participated(account): if len(account) != 20: return notifyErrorAndReturnFalse("Account should be 20-byte addresses") context = GetContext() current_game_no = get_current_game_no() flag = concat(PLAYER, account) flag = concat(flag, current_game_no) flag = concat(flag, "first") check_user_participation = Get(context, flag) if check_user_participation: return True return False
def perform_exchange(ctx): """ :param token:Token The token object with NEP5/sale settings :return: bool: Whether the exchange was successful """ attachments = get_asset_attachments() # [receiver, sender, gas] current_balance = Get(ctx, attachments[1]) exchanged_tokens += attachments[2] * TOKENS_PER_GAS # add it to the the exchanged tokens and persist in storage new_total = exchanged_tokens + current_balance Put(ctx, attachments[1], new_total) # update the in circulation amount result = add_to_circulation(ctx, exchanged_tokens) return True
def UnregisterFarmContract(FarmContract_name, OwnerNeoAddress): msg = concat("UnregisterFarmContract: ", FarmContract_name) msg2 = concat(msg, OwnerNeoAddress) Notify(msg2) storage_key = concat(FarmContract_name, OwnerNeoAddress) context = GetContext() owner = Get(context, storage_key) if not owner: Notify("FarmContract is not yet registered") return False if not CheckWitness(owner): Notify( "This person is not the owner of the FarmContract, the FarmContract cannot be deleted" ) return False removeRegistry(context, storage_key) return True
def generateAlien(xna, alienName, blockHeight): context = GetContext() counter = Get(context, 'counter') if not counter: Put(context, 'counter', 1) else: Put(context, 'counter', counter + 1) counter += 1 temp_alien = { 'xna': xna, 'alienName': alienName, 'blockHeight': blockHeight, 'id': counter } Put(context, temp_alien['id'], Serialize(temp_alien)) Notify(concat("Alien created, ID: ", temp_alien['id'])) return temp_alien
def register_ad(senderhash, ad_id, ad_description, lat_lng, ad_exp, ad_views, ad_sell, ad_price): ad_exists = Get(ctx, ad_id) Notify("Ad exists works ") ad_data = list(length=8) #senderhash ad_data[0] = senderhash ad_data[1] = ad_id #ad description ad_data[2] = ad_description #lat and long ad_data[3] = lat_lng # ad expiration ad_data[4] = ad_exp # total views ad_data[5] = ad_views #auto sell ad_data[6] = ad_sell #price in gas ad_data[7] = ad_price if not ad_exists: Notify("Ad does not exist") serialized_ad_data = serialize_array(ad_data) Notify("Data Serialized ") Put(ctx, ad_id, serialized_ad_data) Notify("ad registered") Notify(serialized_ad_data) else: Notify("Ad Exists") return False
def GetAllowance(t_owner, t_spender): """ Gets the amount of tokens that a spender is allowed to spend from the owners' account. :param t_owner: Owner of tokens :type t_owner: bytearray :param t_spender: Requestor of tokens :type t_spender: bytearray :return: Amount allowed to be spent by Requestor on behalf of owner :rtype: int """ context = GetContext() allowance_key = concat(t_owner, t_spender) amount = Get(context, allowance_key) return amount
def print_info(adr): """ Prints the information stored in the blockchain for the given address :return: indication success execution of the command :rtype: bool """ termsba = Get(ctx, adr) if not termsba: Notify("Partnership for address is not yet created") return False serterms = deserialize_bytearray(termsba) currency = serterms[0] flatfees_struc = serterms[1] partnership_struc = serterms[2] webpage = serterms[3] msg = concat("Partnership Information:", " ") a = concat("Address : ", adr) msg = concat(msg, a) c = concat(", Currency : ", currency) msg = concat(msg, c) d = concat(", Flatfee Structure : ", flatfees_struc) msg = concat(msg, d) e = concat(", Partnership Structure: ", partnership_struc) msg = concat(msg, e) f = concat(", Webpage: ", webpage) msg = concat(msg, f) Notify(msg) json_like_string = concat('["', currency) json_like_string = concat(json_like_string, '","') json_like_string = concat(json_like_string, flatfees_struc) json_like_string = concat(json_like_string, '","') json_like_string = concat(json_like_string, partnership_struc) json_like_string = concat(json_like_string, '", "') json_like_string = concat(json_like_string, webpage) json_like_string = concat(json_like_string, '"]') return json_like_string