def bankerInvest(account, ongAmount): """ invest ong to become a banker :param account: :return: """ currentRound = getCurrentRound() if getRoundGameStatus(currentRound) == STATUS_OFF: newRound = Add(currentRound, 1) RequireWitness(account) if Add(getRunningVaultPercentage(newRound), getDividendForBankersPercentage(newRound)) != 98: runVaultPercentage = getRunningVaultPercentage(currentRound) dividendPercentage = getDividendForBankersPercentage(currentRound) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), DIVIDEND_FOR_BANKERS_PERCENTAGE), dividendPercentage) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), RUNNING_VAULT_PERCENTAGE), runVaultPercentage) Notify([ "setParameters", newRound, runVaultPercentage, dividendPercentage ]) Put(GetContext(), CURRENT_ROUND_KEY, newRound) Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), ROUND_STATUS), STATUS_ON) Notify(["startNewRound", newRound]) _bankerInvest(account, ongAmount) return True
def transferONT(fromacct, toacct, amount): """ transfer ONT :param fromacct: :param toacct: :param amount: :return: """ if CheckWitness(fromacct): param = makeState(fromacct, toacct, amount) res = Invoke(1, contractAddress, 'transfer', [param]) Notify(["11111", res]) if res and res == b'\x01': Notify('transfer succeed') return True else: Notify('transfer failed') return False else: Notify('checkWitness failed') return False
def RegisterPerson(person_id, phone_number, cpr_cert=""): ctx = GetContext() cpr_status = cpr_cert and VerifyPerson(cpr_cert) Notify('verified') person = {'cpr': cpr_status} Put(ctx, PERSON_KEY + person_id, Serialize(person)) if cpr_status: # create persons list cpr_persons_list = Get(ctx, CPR_LIST_KEY) Notify(['in cpr_status', CPR_LIST_KEY]) if cpr_persons_list is not None: cpr_persons_list = Deserialize(cpr_persons_list) else: cpr_persons_list = [] cpr_persons_list.append([person_id, phone_number]) Put(ctx, CPR_LIST_KEY, Serialize(cpr_persons_list)) # persons_list = Get(ctx, PERSONS_LIST_KEY) # if persons_list is not None: # persons_list = Deserialize(persons_list) # else: # persons_list = [] # persons_list.append(person_id) # Notify('Persons List') # Put(ctx, PERSONS_LIST_KEY, Serialize(persons_list)) return True
def RegisterDomain(domain_name, owner): msg = concat("RegisterDomain: ", domain_name) Notify(msg) ''' Check if the domain contain . if ture then return false ''' if detectStr(domain_name) == 1: Notify("Domain has incorrect char inside") return False 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) msg2 = [domain_name, "is owned by ", owner] Notify(msg2) return True
def _canSendMessage(message, from_address): # make array message_array = [] Notify(message) i = 0 while i < len(message): # Notify(str[i:i+1]) message_array.append(message[i:i+1]) i = i + 1 # not initialized me if not _isInitialized(from_address): return False Notify('initialized') # count word word_to_count_map = _fetchCharaSetMap() for word in message_array: word_to_count_map[word] = word_to_count_map[word] + 1 balanceMap = _fetchBalanceMap() # enough word balance check for chara in CHARALIST: need_count = word_to_count_map[chara] user_count = balanceMap[from_address][chara] if need_count > user_count: return False Notify('count ok') return True
def bankerWithdrawBeforeExit(account): if CheckWitness(account) == False: # bankerWithdrawBeforeExit: Check witness failed! Notify(["Error", 401]) return 0 ongShareInRunningVault = getRunVaultShare(account) if ongShareInRunningVault <= 0: # bankerWithdrawBeforeExit: banker's dividend is not greater than 0 Notify(["noShare", account]) return 0 currentRound = getCurrentRound() bankerBalanceInRunVault = getBankerBalanceInRunVault(currentRound, account) if getRoundGameStatus(currentRound) == STATUS_ON and bankerBalanceInRunVault > 0: # update the bankers' investment amount oldBankersInvestment = getBankersInvestment(currentRound) Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), BANKERS_INVESTMENT_KEY), Sub(oldBankersInvestment, getBankerInvestment(currentRound, account))) # delete the banker's investment balance Delete(GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), concatKey(BANKER_INVEST_BALANCE_PREFIX, account))) Require(_transferONGFromContact(account, ongShareInRunningVault)) # update total ong Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONG(), ongShareInRunningVault)) # update real time run vault Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), REAL_TIME_RUNNING_VAULT), Sub(getRealTimeRunningVault(currentRound), ongShareInRunningVault)) Notify(["bankerWithdrawShare", currentRound, account, ongShareInRunningVault]) return ongShareInRunningVault
def bankerWithdrawDividend(account): # RequireWitness(account) if CheckWitness(account) == False: # bankerWithdrawDividend: Check witness failed!, Notify(["Error", 201]) return 0 # update the banker's dividend and earning updateBankerDividend(account) bankerDividend = getBankerDividend(account) # Require(bankerDividend > 0) if bankerDividend <= 0: # bankerWithdrawDividend: Banker has no dividend Notify(["noDividend", account]) return 0 # Require(_transferONGFromContact(account, bankerDividend)) res = _transferONGFromContact(account, bankerDividend) if res == False: # bankerWithdrawDividend: Transfer dividend to banker failed! Notify(["Error", 202]) return 0 Delete(GetContext(), concatKey(BANKER_DIVIDEND_BALANCE_PREFIX, account)) # update the total ong amount Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONG(), bankerDividend)) Notify( ["bankerWithdrawDividend", getCurrentRound(), account, bankerDividend]) return bankerDividend
def get(key): key1 = key + 4294967295 a = Get(ctx, _concatkey(testKey, key1)) #Deserialize( c = Deserialize(a) Notify(["222", key1]) Notify([c['index'], c['value']]) return True
def join(addr, amount): # 临时这么搞 info = { 0: 'count', 1: 'acc1', 2: 'amount1', 3: 'acc2', 4: 'amount2', 5: 'acc3', 6: 'amount3' } context = GetContext() count = Get(context, 'count') if count is None: count = 0 count += 1 if count >= 3: Notify('No more seat') return False acc_key = info[2 * count - 1] amount_key = info[count * 2] Put(context, acc_key, addr) Put(context, amount_key, float(amount)) Put(context, 'count', count) Notify(acc_key) return True
def RunTimeTest(user): Log("11111111") res = CheckWitness(user) Log(res) Notify("Hi BlockChain") Notify("s1", "s2", 1, 2, 3) Log("log message")
def createOneToken(name, url, type): ''' create a new token :param name: :param url: :param type: :return: ''' Notify(["111_createOneToken begins"]) # generate tokenID timestamp = GetTime() totalSupply = Get(ctx, TOTAL_SUPPLY) newTotalSupply = totalSupply + 1 Put(ctx, TOTAL_SUPPLY, newTotalSupply) tmp = concatkey(concatkey(selfAddr, timestamp), newTotalSupply) tokenID = sha256(tmp) # construct token map token = {'ID': tokenID, 'Name': name, 'Image': url, 'Type': type} Notify([ "222_createOneToken", newTotalSupply, tokenID, concatkey(TOKEN_ID_PREFIX, tokenID) ]) Put(ctx, concatkey(TOKEN_INDEX_PREFIX, newTotalSupply), tokenID) ownerKey = concatkey(OWNER_OF_TOKEN_PREFIX, tokenID) Put(ctx, ownerKey, admin) Put(ctx, concatkey(TOKEN_ID_PREFIX, tokenID), Serialize(token)) # add to adminBalance adminBalance = Get(ctx, concatkey(OWNER_BALANCE_PREFIX, admin)) Put(ctx, concatkey(OWNER_BALANCE_PREFIX, admin), adminBalance + 1) Notify(["333_createOneToken ends"]) return True #################### For testing usage only ends ######################
def bankerWithdrawEarning(account): # RequireWitness(account) if CheckWitness(account) == False: # bankerWithdrawEarning: Check witness failed!, Notify(["Error", 301]) return 0 updateBankerEarning(account) # update the banker's earning bankerEarning = getBankerEarning(account) # RequireWitness(bankerEarning > 0) if bankerEarning <= 0: # banker's dividend is not greater than 0 Notify(["noEarning", account]) return 0 # Require(_transferONGFromContact(account, bankerEarning)) res = _transferONGFromContact(account, bankerEarning) if res == False: # bankerWithdrawEarning: Transfer ONG failed! Notify(["Error", 302]) return 0 Delete(GetContext(), concatKey(BANKER_EARNING_BALANCE_PREFIX, account)) # update the total ong amount Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONG(), bankerEarning)) Notify( ["bankerWithdrawEarning", getCurrentRound(), account, bankerEarning]) return bankerEarning
def invokeB(param): Notify(["111_invokeB", param]) # to prevent hack from other contract callerHash = GetCallingScriptHash() entryHash = GetEntryScriptHash() Notify([callerHash, entryHash, ContractAddress]) return True
def setStakeRequirement(admin, _stakeRequirement): nouse = Require(checkAdmin(admin)) Put(GetContext(), REFERRAL_STAKE_REQUIREMENT_KEY, _stakeRequirement) Notify(["statingRequirement for vice manager", _stakeRequirement]) if Get(GetContext(), REFERRAL_STAKE_REQUIREMENT_KEY) == _stakeRequirement: Notify("set StakeRequirement successfuly") return True
def checkHash(): Notify(["111_checkHash"]) # to prevent hack from other contract callerHash = GetCallingScriptHash() entryHash = GetEntryScriptHash() Notify([callerHash, entryHash, ContractAddress]) return True
def buy(id, fromAcc): # 获取倒计时结束时间 并判断 是否已结束 endTimeDeserialize = Get(GetContext(), ENDTIME) endTime = Deserialize(endTimeDeserialize) if GetTime() >= endTime: reset(2, id, fromAcc) else: # 获取所有国家 regionDeserialize = Get(GetContext(), REGION) region = Deserialize(regionDeserialize) for item in region: if item[0] == id: # 拿到目标购买国家进行交易 param = state(Base58ToAddress(fromAcc), Base58ToAddress(item[2]), item[1] - 1) res = Invoke(0, OntContract, "transfer", [param]) if res != b'\x01': Notify("buy error.") return False # 每一次给合约内部转1个币 paramContract = state(Base58ToAddress(fromAcc), selfContractAddress, 1) resContract = Invoke(0, OntContract, 'transfer', [paramContract]) # 倒计时增加用户消耗的币 * 10 秒 endTime = endTime + item[1] * 10 Put(GetContext(), ENDTIME, Serialize(endTime)) # 将购买用户设置为最后一次购买人 Put(GetContext(), LASTBUY, Serialize(fromAcc)) # 更新国家信息以及价格 item[1] = (item[1] - 1) * 2 + 1 item[2] = fromAcc Put(GetContext(), REGION, Serialize(region)) Notify("buy success.") return True
def CloseAuction(personAddr): # get highest bid highestBids = getHighestBid(personAddr) amount = highestBids['price'] nextCompanyAddress = highestBids['company_address'] Notify("amount") Notify(amount) Notify("nextCompanyAddress") Notify(nextCompanyAddress) # check amount of next company address # if amount > BalanceOf(nextCompanyAddress): # return False # get current company address person = Get(ctx, concatAll(["person_", personAddr, '_map'])) personData = Deserialize(person) currentCompanyAddress = personData['company_address'] # transfer transfer(nextCompanyAddress, currentCompanyAddress, amount) # change company company = Get(ctx, concat('company_', nextCompanyAddress)) personData['company'] = company Put(ctx, concatAll(["person_", personAddr, '_map']), Serialize(personData)) return True
def RegisterCompanyPerson(companyAddr, personAddr): key = concatAll(['company_', companyAddr, '_persons']) Notify(key) keyM = concatAll(['company_', companyAddr, '_persons_map']) Notify(keyM) curVal = Get(ctx, keyM) curValList = [] if curVal is not None: curValList = Deserialize(curVal) for i in range(0, len(curValList)): if personAddr == curValList[i]: Notify('duplicated') return True curValList.append(personAddr) val = makeValue(curValList, '$') # company address person = Deserialize(Get(ctx, concatAll(['person_', personAddr, '_map']))) person["company_address"] = companyAddr Put(ctx, concatAll(['person_', personAddr, '_map']), Serialize(person)) Put(ctx, key, val) Put(ctx, keyM, Serialize(curValList)) Put(ctx, concat("person_", personAddr), companyAddr) return True
def TestStorage(): Put(ctx, "key", 100) v = Get(ctx, "key") Notify(v) Delete(ctx, "key") Notify(Get(ctx, "key"))
def Main(operation, args): if operation == 'name': return name() if operation == 'hello': if len(args) != 1: return False msg = args[0] return hello(msg) if operation == 'testHello': if len(args) != 5: return False msgBool = args[0] msgInt = args[1] msgByteArray = args[2] msgStr = args[3] msgAddress = args[4] return testHello(msgBool, msgInt, msgByteArray, msgStr, msgAddress) if operation == 'testList': if len(args) != 1: return False msgList = args[0] return testList(msgList) if operation == 'testListAndStr': Notify([args]) if len(args) != 2: return False msgList = args[0] msgStr = args[1] return testListAndStr(msgList, msgStr) if operation == 'testStructList': Notify(args) structList = args[0] return testStructList(structList) if operation == 'testStructListAndStr': if len(args) != 2: return False structList = args[0] msgStr = args[1] return testStructListAndStr(structList, msgStr) if operation == 'testMap': msg = args[0] return testMap(msg) if operation == 'testGetMap': if len(args) != 1: return False key = args[0] return testGetMap(key) if operation == 'testMapInMap': msg = args[0] return testMapInMap(msg) if operation == 'testGetMapInMap': if len(args) != 1: return False key = args[0] return testGetMapInMap(key) if operation == 'transferMulti': states = args[0] return transferMulti(states) return False
def testStorage(): Put(ctx, "key", 100) v = Get(ctx, "key") Notify(v) Delete(ctx, "key") Notify(Get(ctx, "key")) return True
def avoidToBeInvokedByContract(): callerHash = GetCallingScriptHash() entryHash = GetEntryScriptHash() if callerHash != entryHash: Notify(["You are not allowed to invoke this method through contract"]) return False else: Notify(["You can implement what you need to do here!"]) return True
def _endDisk(diskId, diskRes): """ settle all the accounts within diskId disk bet. :param gameId: :param diskId: :param diskRes: could be -2, -1, 0, 1, 2 :return: profit for dev """ RequireWitness(Operater) # Require(not getDiskStatus(diskId)) # Require(diskRes != -2) if getDiskStatus(diskId) == 1 or diskRes == -2: return 0 if diskRes == AbortSide: # pay back the money to the players, respectively _payBackToPlayers(diskId) Notify(["endDisk", diskId, diskRes]) return 0 leftBetAmount = getDiskBetAmount(diskId, LeftSide) rightBetAmount = getDiskBetAmount(diskId, RightSide) tieBetAmount = getDiskBetAmount(diskId, TieSide) # get winners list winnersList = getDiskPlayersList(diskId, diskRes) # if nobody wins: if len(winnersList) == 0: Notify(["endDisk", diskId, diskRes]) return Add(Add(leftBetAmount, rightBetAmount), tieBetAmount) odds = 0 FeePercentage = getFeePercentage() if diskRes == TieSide: odds = Add(leftBetAmount, rightBetAmount) * Magnitude * ( 100 - FeePercentage) / tieBetAmount if diskRes == LeftSide: odds = Add(rightBetAmount, tieBetAmount) * Magnitude * ( 100 - FeePercentage) / leftBetAmount if diskRes == RightSide: odds = Add(leftBetAmount, tieBetAmount) * Magnitude * ( 100 - FeePercentage) / rightBetAmount totalPayOut = 0 winnerPayAmountList = [] for winner in winnersList: winnerBetBalance = getDiskBetBalance(diskId, diskRes, winner) payToWinner = winnerBetBalance * odds / Magnitude + winnerBetBalance totalPayOut = Add(totalPayOut, payToWinner) Require(_transferONGFromContact(winner, payToWinner)) winnerPayAmountList.append([winner, payToWinner]) # mark the diskId game as end Put(GetContext(), concatKey(DISK_STATUS_PERFIX, diskId), 1) Notify(["endDisk", diskId, diskRes, winnerPayAmountList]) return Sub(Add(rightBetAmount, leftBetAmount), totalPayOut)
def _antiEarlyWhale(_account, _ongAmount): """ :param _account: :param _ongAmount: :return: """ nouse = Require(CheckWitness(_account)) _AntiEarlyWhale = Get(GetContext(), ANTI_EARLY_WHALE_KEY) # Still in the early stage if _AntiEarlyWhale == _POSITIVE_: # total ONG is less than 20000 if totalOngBalance() <= AntiEarlyWhaleQuota_: # if _account is admin, can also use [if checkAdmin(_account):] # if Get(GetContext(), concatKey(_account, ADMIN_SUFFIX)) == _POSITIVE_: Notify(["111_antiEarlyWhale", checkAdmin(_account) ]) if checkAdmin(_account) == True: key = concatKey(_account, TOKEN_BALANCE_SUFFIX) # How many token admin holds _adminTokenBalance = Get(GetContext(), key) # How many ong do these tokens equal _adminBoughtOng = _tokenToOng(_adminTokenBalance) Notify(["222_antiEarlyWhale", _adminBoughtOng]) if Add(_adminBoughtOng, _ongAmount) <= adminQuota_: return True else: Notify(["Idiot admin, you cannot buy too many tokens"]) return False # _account is manager # elif Get(GetContext(), concatKey(_account, MANAGER_SUFFIX)) == _POSITIVE_: elif checkManager(_account) == True: key = concatKey(_account, TOKEN_BALANCE_SUFFIX) # How many token the manager holds _managerTokenBalance = Get(GetContext(), key) # How many ong do these tokens equal _managerBoughtOng = _tokenToOng(_managerTokenBalance) if Add(_managerBoughtOng, _ongAmount) <= managerQuota_: return True else: Notify(["Big head manager, you cannot buy too many tokens"]) return False # _account is customer else: key = concatKey(_account, TOKEN_BALANCE_SUFFIX) # How many token the manager holds _customerTokenBalance = Get(GetContext(), key) # How many ong do these tokens equal _customerBoughtOng = _tokenToOng(_customerTokenBalance) if Add(_customerBoughtOng, _ongAmount) <= customerQuota_: return True else: Notify(["Man, you are too greedy", _account]) return False else: Put(GetContext(), ANTI_EARLY_WHALE_KEY, _NEGATIVE_) return True return True
def addDividendToLuckyHolders(ongAmount): RequireWitness(Admin) luckySupply = getLuckySupply() if luckySupply == 0: Notify(["noLucky"]) return False profitPerLuckyToBeAdd = Div(Mul(ongAmount, Magnitude), getLuckySupply()) Put(GetContext(), PROFIT_PER_LUCKY_KEY, profitPerLuckyToBeAdd) Notify(["addDividendToLuckyHolders", ongAmount]) return True
def transferOngToContract(fromAccount, ongAmount): Notify(["111_transferOngToContract", selfContractAddress]) param = state(fromAccount, selfContractAddress, ongAmount) res = Invoke(0, OngContract, 'transfer', [param]) if res and res == b'\x01': Notify('transfer Ong succeed') return True else: Notify('transfer Ong failed') return False
def Main(operation, args): Notify(GetTime()) user = bytearray([ 248, 142, 51, 220, 214, 177, 110, 235, 27, 218, 59, 86, 23, 47, 140, 20, 114, 119, 159, 152 ]) CheckWitness(user) Notify("Hi BlockChain") Notify("s1", "s2", 1, 2, 3) Log("log message")
def Init(): if Get(ctx, SUPPLY_KEY): Notify('Already initialized!') return False else: total = TOTAL_AMOUNT * FACTOR Put(ctx, SUPPLY_KEY, total) Put(ctx, concat(TRANSFER_PREFIX, OWNER), total) Notify(['transfer', '', OWNER, total]) return True
def init(): RequireWitness(Admin) inited = Get(GetContext(), INIIT) if inited: Notify(["idiot admin, you have initialized the contract"]) return False else: Put(GetContext(), INIIT, 1) Notify(["Initialized contract successfully"]) # startNewRound() return True
def checkWithdraw(account): allowanceOng = checkAllowance(account) withdrawOngAmount = allowanceOng / 2 params = state(account, ONTAddress, account, withdrawOngAmount) res = Invoke(0, ONGAddress, 'transferFrom', params) if res and res == b'\x01': Notify(["withdraw ong successful!"]) return True else: Notify(["withdraw ong failed!"]) return False