def guessForOEP4(player, number, amount, inviter): constracthash = GetExecutingScriptHash() #bla = balanceOf(constracthash, TNT) #OEP_MAX = bla / 100 if amount < OPE4_MIN: #or amount > OEP_MAX: ErrorNotify(ERROR_AMONT) return False if CheckRange(number) == False: ErrorNotify(ERROR_NUMBER) return False playbla = balanceOf(player, TNT) if playbla < amount: ErrorNotify(ERROR_BANLANCE) return False id = Get(ctx, BET_ID_PREFIX) Put(ctx, BET_ID_PREFIX, id + 1) # 游戏次数 sysnumber = GeneratorRandom() if number > sysnumber: winreward = GetBetReward(number, amount) #win = winreward - amount transferOEP4(constracthash, player, win) else: transferOEP4(player, constracthash, amount) Notify(['guess', TNT, player,amount, id + 1, number, sysnumber]) # rewardInviterFEE(inviter,constracthash,amount,TNT) return True
def get_asset_attachments(): """ Gets information about Gas attached to an invocation TX :return: list: A list with information about attached gas """ tx = GetScriptContainer() references = tx.References receiver_addr = GetExecutingScriptHash() sender_addr = None sent_amount_gas = 0 if len(references) > 0: reference = references[0] sender_addr = reference.ScriptHash for output in tx.Outputs: if output.ScriptHash == receiver_addr: #Only stick with GAS in this Hackathon #if output.AssetId == neo_asset_id: #sent_amount_neo += output.Value if output.AssetId == gas_asset_id: sent_amount_gas += output.Value return [receiver_addr, sender_addr, sent_amount_gas]
def get_asset_attachments_for_prev(): attachment = create_attachment() tx = GetScriptContainer() # type:Transaction sent_amount_neo = 0 sent_amount_gas = 0 attachment["receiver_addr"] = GetExecutingScriptHash() for ins in tx.Inputs: prev_tx = GetTransaction(ins.Hash) references = prev_tx.References if len(references) > 0: reference = references[0] attachment["sender_addr"] = reference.ScriptHash prev_output = prev_tx.Outputs[ins.Index] if prev_output.ScriptHash == attachment["receiver_addr"] and prev_output.AssetId == attachment["neo_asset_id"]: sent_amount_neo += prev_output.Value if prev_output.ScriptHash == attachment["receiver_addr"] and prev_output.AssetId == attachment["gas_asset_id"]: sent_amount_gas += prev_output.Value attachment.neo_attached = sent_amount_neo attachment.gas_attached = sent_amount_gas return attachment
def process_withdrawal(): my_container = GetScriptContainer() my_hash = GetExecutingScriptHash() withdrawl_stage = WithdrawStage(my_container) if withdrawl_stage is None: return False withdrawingaddr = getWithdrawAddress(mycontainer, withdrawlstage) assetID = getWithdrawlAsset(mycontainer) if len(assetID) == 20: iswithdrawingNEP5 = True else: iswithdrawingNEP5 = False # inputs = mycontainer.getInputs() # outputs = mycontainer.getOutputs() if withdrawlstage == 'Mark': amount = getbalance(withdrawingaddr, assetID) # Here you can add withdraw fees and things like that markwithdrawal(withdrawingaddr, assetID, amount) byteArray = ['0'] if iswithdrawingNEP5: put(myhash + byteArray, withdrawingaddr) # else: # value = 0 # for output in outputs: # value += outputs[output]['Value'] withdrawing(withdrawingaddr, assetID, amount) return True
def Main(operation, args): trigger = GetTrigger() if trigger == Verification(): if CheckWitness(OWNER): return True return False elif trigger == Application(): if operation == 'currentKing': return Get(ctx, KOTH_KEY) if operation == 'currentBounty': myhash = GetExecutingScriptHash() currentBalance = TUT_Contract('balanceOf', [myhash]) current_bounty = currentBalance + INCREMENT return current_bounty chash = GetCallingScriptHash() if chash != TUT_Scripthash: print('Token type not accepted by this contract') return False elif operation == 'onTokenTransfer': print('onTokenTransfer() called') return handle_token_received(ctx, args) return False
def Withdraw(address, amount): if len(address) != 20: return False if CheckWitness(address) != True: return False if amount % FACTOR != 0: ErrorNotify(ERROR_TONT_WITHDRAW) return False blakey = concat(BALANCE_PREFIX, address) fromBalance = Get(ctx, blakey) if amount > fromBalance: ErrorNotify(ERROR_BANLANCE) return False ontam = amount / FACTOR constracthash = GetExecutingScriptHash() if transferONT(constracthash, address, ontam): if amount == fromBalance: Delete(ctx, blakey) else: Put(ctx, blakey, fromBalance - amount) Notify(["success", ontam]) return True return False
def guessForONG(player, number, amount, inviter): constracthash = GetExecutingScriptHash() #bla = balanceOf(constracthash, ONG) #ONG_max = bla / 100 if amount < ONG_MIN: #or amount > ONG_max: ErrorNotify(ERROR_AMONT) return False if CheckRange(number) == False: ErrorNotify(ERROR_NUMBER) return False if transferONG(player, constracthash, amount) == False: # 转移投注金额 ErrorNotify(ERROR_BANLANCE) return False id = Get(ctx, BET_ID_PREFIX) Put(ctx, BET_ID_PREFIX, id + 1) # 游戏次数 sysnumber = GeneratorRandom(id) if number > sysnumber: winreward = GetBetReward(number, amount) transferONG(constracthash, player, winreward) Notify(['guess', ONG,player, amount, id + 1, number, sysnumber]) rewardToken(player, constracthash, amount, ONG) if inviter != player: rewardInviterFEE(inviter, constracthash, amount, TNT) else: rewardInviterFEE(teamaddress, constracthash, amount, TNT) return True
def GetMintInfo(ctx): """ Gets information about acception coin attached to an invocation TX :return: list: A list with information about attached the acception coin ref:https://github.com/CityOfZion/neo-boa/blob/master/boa_test/example/demo/nex/txio.py """ tx = GetScriptContainer() references = tx.References receiver_addr = GetExecutingScriptHash() sender_addr = None sent_amount_ac = 0 ac = Get(ctx, "ACCEPTCOIN") if len(ac) == 32: if len(references) > 0: reference = references[0] sender_addr = reference.ScriptHash for output in tx.Outputs: if output.ScriptHash == receiver_addr: if output.AssetId == ac: sent_amount_ac += output.Value return [receiver_addr, sender_addr, sent_amount_ac]
def VerifyCaller(operation, caller, keyNo): authContractAddr = bytearray( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06' ) param = state(GetExecutingScriptHash(), caller, operation, keyNo) res = Invoke(0, authContractAddr, "verifyToken", param) Require(res)
def get_asset_attachments(): """ Gets information about NEO and Gas attached to an invocation TX :return: list: A list with information about attached neo and gas """ tx = GetScriptContainer() references = tx.References receiver_addr = GetExecutingScriptHash() print(receiver_addr) sender_addr = None sent_amount_neo = 0 sent_amount_gas = 0 if len(references) > 0: reference = references[0] sender_addr = reference.ScriptHash print(sender_addr) for output in tx.Outputs: if output.ScriptHash == receiver_addr: if output.AssetId == neo_asset_id: sent_amount_neo += output.Value print(sent_amount_neo) if output.AssetId == gas_asset_id: sent_amount_gas += output.Value print(sent_amount_gas) return [receiver_addr, sender_addr, sent_amount_neo, sent_amount_gas]
def handle_token_received(ctx, args): arglen = len(args) if arglen < 3: print('arg length incorrect') return False t_from = args[0] t_to = args[1] t_amount = args[2] king_name = None if arglen == 4: king_name = args[3] # optional 4th argument passed by transfer() if len(t_from) != 20: return False if len(t_to) != 20: return False myhash = GetExecutingScriptHash() if t_to != myhash: return False currentBalance = TUT_Contract('balanceOf', [myhash]) current_bounty = currentBalance + INCREMENT # contract owner can reset the game at will by sending low bounty if t_amount < current_bounty: if CheckWitness(OWNER): print('Game reset by contract owner!') else: print('Not enough to become king!') return False last_king = Get(ctx, KOTH_KEY) next_bounty = t_amount + INCREMENT if len(last_king) == 0: print('The first king has arrived!') Put(ctx, KOTH_KEY, t_from) KingNotify(t_from, next_bounty, king_name) return True # transfer all existing token balance to the previous king transferred = TUT_Contract('transfer', [myhash, last_king, currentBalance]) if transferred: Put(ctx, KOTH_KEY, t_from) KingNotify(t_from, next_bounty, king_name) return True else: print('Transfer of treasury to previous king failed!') return False
def deploy(): """ Initial deploy, which places initial amount into circulation Requires full owner permission ( 3 of 5 ) :return: bool: Whether the operation was successful """ if not check_owners(ctx, 3): return False if not Get(ctx, 'initialized'): # do deploy logic Put(ctx, 'initialized', 1) # who or what address do we put the initial amount to? # we will put it to the address of the contract contract_address = GetExecutingScriptHash() contract_balance_key = get_balance_key(contract_address) Put(ctx, contract_balance_key, TOKEN_INITIAL_AMOUNT) added_to_circ = add_to_circulation(ctx, TOKEN_INITIAL_AMOUNT) # dispatch mint OnTransfer(False, contract_address, TOKEN_INITIAL_AMOUNT) return added_to_circ return False
def GetToken(tokentype, amount): if (CheckWitness(superadmin)): if ONT == tokentype: constracthash = GetExecutingScriptHash() transferONT(constracthash, superadmin, amount) return True if ONG == tokentype: constracthash = GetExecutingScriptHash() transferONG(constracthash, superadmin, amount) return True if TNT == tokentype: constracthash = GetExecutingScriptHash() transferOEP4(constracthash, superadmin, amount) return True return False return False
def do_mint_token(ctx, args): """Mints a new NFT token; stores it's properties, URI info, and owner on the blockchain; updates the totalSupply :param StorageContext ctx: current store context :param list args: 0: byte[] t_owner: token owner 1: byte[] t_properties: token's read only data 2: bytes t_uri: token's uri 3: extra_arg (optional): extra arg to be passed to a smart contract :return: mint success :rtype: bool """ t_id = Get(ctx, TOKEN_CIRC_KEY) # the int 0 is represented as b'' in neo-boa, this caused bugs # throughout my code # This is the reason why token id's start at 1 instead t_id += 1 # this should never already exist if len(Get(ctx, t_id)) == 20: Notify('token already exists') return False t_owner = args[0] if len(t_owner) != 20: Notify(INVALID_ADDRESS_ERROR) return False t_properties = args[1] if len(t_properties) == b'\x00': Notify('missing properties data string') return False t_uri = args[2] if GetContract(t_owner): contract_args = [t_owner, t_id] if len(args) == 4: # append optional extra arg contract_args.append(args[3]) success = transfer_to_smart_contract(ctx, GetExecutingScriptHash(), contract_args, True) if success is False: return False Put(ctx, t_id, t_owner) # update token's owner Put(ctx, concat('properties/', t_id), t_properties) Put(ctx, concat('uri/', t_id), t_uri) add_token_to_owners_list(ctx, t_owner, t_id) Put(ctx, TOKEN_CIRC_KEY, t_id) # update total supply # Log this minting event OnMint(t_owner, 1) OnNFTMint(t_owner, t_id) return True
def do_transfer(ctx, t_from, t_to, amount, callingScriptHash): if amount <= 0: return False if len(t_to) != 20: return False # if the calling script hash is not the entry script hash # we force the `t_from` to be the address of the callingScriptHash if callingScriptHash != GetEntryScriptHash(): print("Cannot call from another contract on behalf of other addresses") print("Setting from address to callingScriptHash") t_from = callingScriptHash else: if t_from == GetExecutingScriptHash(): if not check_owners(ctx, 3): print("Must authenticate as owners") return False else: if not CheckWitness(t_from): print("Insufficient priveleges") return False from_balance_key = get_balance_key(t_from) to_balance_key = get_balance_key(t_to) from_balance = Get(ctx, from_balance_key) if from_balance < amount: Notify("insufficient funds") return False if t_from == t_to: return True if from_balance == amount: Delete(ctx, from_balance_key) else: difference = from_balance - amount Put(ctx, from_balance_key, difference) to_balance = Get(ctx, to_balance_key) to_total = to_balance + amount Put(ctx, to_balance_key, to_total) OnTransfer(t_from, t_to, amount) return True
def Init(): constracthash = GetExecutingScriptHash() key = concat(BALANCE_PREFIX,constracthash) tobla = GetStorage(key) tobla = tobla + 1000 * FACTOR PutStorage(key,tobla) key2 = concat(BALANCE_PREFIX,superadmin) PutStorage(key2,1000*FACTOR) key3 = concat(BALANCE_PREFIX,testaddress) PutStorage(key3,1000*FACTOR) return True
def Main(operation, args): trigger = GetTrigger() if trigger == Verification(): if CheckWitness(OWNER): return True return False elif trigger == Application(): if operation == 'hello': print('hello world!') totalcalls = Get('totalCalls') totalcalls = totalcalls + 1 print(totalcalls) if Put('totalCalls', totalcalls): return True print('staked storage call failed') return False return True if operation == 'ownerWithdraw': if not CheckWitness(OWNER): print( 'only the contract owner can withdraw MCT from the contract' ) return False if len(args) != 1: print('withdraw amount not specified') return False t_amount = args[0] myhash = GetExecutingScriptHash() return MCTContract('transfer', [myhash, OWNER, t_amount]) # end of normal invocations, reject any non-MCT invocations caller = GetCallingScriptHash() if caller != MCT_SCRIPTHASH: print('token type not accepted by this contract') return False if operation == 'onTokenTransfer': print('onTokenTransfer() called') return handle_token_received(caller, args) return False
def DoDeploy(ctx, accept_coin): """ Method to init totalSupply tokens to OWNER """ result = Get(ctx, "DEPLOY") if result == 1: return False me = GetExecutingScriptHash() Put(ctx, "DEPLOY", 1) Put(ctx, me, TOTAL_SUPPLY) Put(ctx, "ACCEPTCOIN", accept_coin) return True
def getTotalStaked(): """ Gets the total amount of tokens that are currently staked in the contract. :return: (int) Current amount of staked tokens """ tokenContract = getStakingContract() contractAddress = GetExecutingScriptHash() args = [contractAddress] balance = DynamicAppCall(tokenContract, 'balanceOf', args) return balance
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 _confirmPayment(_from, _amount, _orderId): originator = GetExecutingScriptHash() to = originator RequireScriptHash(_from) Require(_amount > 0) payment_key = concat(PAYMENT_PREFIX, _orderId) is_paid = Get(ctx, payment_key) Require(not is_paid) # only can be paid once Require(CallOep4Contract('transferFrom', [originator, _from, to, _amount])) Put(ctx, payment_key, _amount) return True
def withdraw(): """ Withdraws payments collected in the contract to the owner of the contract """ _onlyOwner(); originator = GetExecutingScriptHash() owner = Get(ctx, OWNER_KEY) balance = SpokkzOEP4Contract('balanceOf', [originator]) Require(balance > 0) Require(_withdraw(originator, owner, balance)) Notify(['withdraw', originator, owner, balance]) 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 get_asset_attachments(): """ Gets information about NEO and Gas attached to an invocation TX :return: Attachments: An object with information about attached neo and gas """ attachment = create_attachment() tx = GetScriptContainer() # type:Transaction references = tx.References attachment["receiver_addr"] = GetExecutingScriptHash() if len(references) > 0: reference = references[0] attachment["sender_addr"] = reference.ScriptHash sent_amount_neo = 0 sent_amount_gas = 0 received_amount_neo = 0 received_amount_gas = 0 for output in tx.Outputs: if output.ScriptHash == attachment["receiver_addr"] and output.AssetId == attachment["neo_asset_id"]: sent_amount_neo += output.Value if output.ScriptHash == attachment["receiver_addr"] and output.AssetId == attachment["gas_asset_id"]: sent_amount_gas += output.Value if output.ScriptHash == attachment["sender_addr"] and output.AssetId == attachment["neo_asset_id"]: received_amount_neo += output.Value if output.ScriptHash == attachment["sender_addr"] and output.AssetId == attachment["gas_asset_id"]: received_amount_gas += output.Value attachment.neo_attached = sent_amount_neo attachment.gas_attached = sent_amount_gas attachment.neo_attached_received = received_amount_neo attachment.gas_attached_received = received_amount_gas return attachment
def mint_remainder(): """ After the crowdsale has ended, there is anticipated to be a small amount of NEX remaining unminted from the 50,000,000 total. This operation mints this remaining amount to the contract's address :return: bool """ if not check_owners(ctx, 3): return False # check that all owners have minted if not have_all_owners_minted(ctx): print("All Owners must mint before minting remainder") return False current_time = GetTime() if current_time < ROUND2_END: return False remainder_amount = TOKEN_TOTAL_SUPPLY - get_circulation(ctx) if remainder_amount <= 0: print("No remaining tokens") return False contract_address = GetExecutingScriptHash() contract_balance_key = get_balance_key(contract_address) current_contract_balance = Get(ctx, contract_balance_key) new_contract_balance = current_contract_balance + remainder_amount Put(ctx, contract_balance_key, new_contract_balance) added_to_circ = add_to_circulation(ctx, remainder_amount) # dispatch mint OnTransfer(False, contract_address, remainder_amount) return added_to_circ
def do_approve(ctx, t_owner, t_spender, amount, callingScriptHash): if t_owner == GetExecutingScriptHash(): print("Cannot approve from contract address. Use transfer") return False # if the calling script hash is not the entry script hash # we force the `t_from` to be the address of the callingScriptHash if callingScriptHash != GetEntryScriptHash(): print("Cannot call from another contract on behalf of other addresses") print("Setting from address to callingScriptHash") t_owner = callingScriptHash else: if not CheckWitness(t_owner): print("Insufficient priveleges") return False if len(t_spender) != 20: return False if amount < 0: return False # cannot approve an amount that is # currently greater than the from balance owner_balance_key = get_balance_key(t_owner) if Get(ctx, owner_balance_key) >= amount: approval_key = get_allowance_key(t_owner, t_spender) if amount == 0: Delete(ctx, approval_key) else: Put(ctx, approval_key, amount) OnApprove(t_owner, t_spender, amount) return True print("not enough balance") return False
def registerDomain(executionerPublickey, domainName): if not CheckWitness(executionerPublickey): return False #check domain length if len(domainName) > 80: return False #check if domain exists if existDomain(domainName): return False tx = GetScriptContainer() refs = tx.References if len(refs) < 1: return False ref = refs[0] sentAsset = GetAssetId(ref) if sentAsset is not GAS_ASSET_ID: False receiver = GetExecutingScriptHash() totalReceived = 0 for output in tx.Outputs: scriptHashReceiver = GetScriptHash(output) if scriptHashReceiver == receiver: totalReceived = totalReceived + output.Value if (totalReceived < FEE): return False ctx = GetContext() #save owner Put(ctx, domainName, executionerPublickey) #save first transaction id Put(ctx, createLastTransactionKey(domainName), ("n" - 0x01)) #save score Put(ctx, createScoreKey(domainName), 0x30) tr = concat("m:", domainName) addDomainToStorage(executionerPublickey, tr) return True
def handle_token_received(chash, args): arglen = len(args) if arglen < 3: print('arg length incorrect') return False t_from = args[0] t_to = args[1] t_amount = args[2] if arglen == 4: extra_arg = args[3] # extra argument passed by transfer() if len(t_from) != 20: return False if len(t_to) != 20: return False myhash = GetExecutingScriptHash() if t_to != myhash: return False if t_from == OWNER: # topping up contract token balance, just return True to allow return True if extra_arg == 'reject-me': print('rejecting transfer') Delete(t_from) return False else: print('received MCT tokens!') totalsent = Get(t_from) totalsent = totalsent + t_amount if Put(t_from, totalsent): return True print('staked storage call failed') return False
def get_asset_attachments(): """ Gets information about NEO and Gas attached to an invocation TX :return: list: A list with information about attached neo and gas """ tx = GetScriptContainer() inputs = tx.References receiver_addr = GetExecutingScriptHash() sender_addr = False sent_amount_neo = 0 sent_amount_gas = 0 sent_from_contract_addr = False if len(inputs) > 0: for input in inputs: if input.ScriptHash == receiver_addr: sent_from_contract_addr = True else: if not sender_addr: sender_addr = input.ScriptHash for output in tx.Outputs: if output.ScriptHash == receiver_addr: if output.AssetId == neo_asset_id: sent_amount_neo += output.Value if output.AssetId == gas_asset_id: sent_amount_gas += output.Value attachments = { 'receiver': receiver_addr, 'sender': sender_addr, 'sent_neo': sent_amount_neo, 'sent_gas': sent_amount_gas, 'sent_from_contract_addr': sent_from_contract_addr } return attachments
def get_asset_attachments(args): """ Gets information about NEO and Gas attached to an invocation TX :return: list: A list with information about the tranzaction """ tx = GetScriptContainer() references = tx.References receiver_addr = GetExecutingScriptHash() sender_addr = None tokenAmount = args[1] * 100000000 if len(references) > 0: reference = references[0] sender_addr = args[0] return [receiver_addr, sender_addr, tokenAmount]