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 Main(operation): # create an array stuff = ["a", 3, ["j", 3, 5], "jk", "lmnopqr"] # serialize it to_save = Serialize(stuff) Put(ctx, "serialized", to_save) if operation == 1: return to_save elif operation == 2: to_retrieve = Get(ctx, "serialized") return to_retrieve elif operation == 3: to_retrieve = Get(ctx, "serialized") deserialized = Deserialize(to_retrieve) return deserialized elif operation == 4: to_retrieve = Get(ctx, "serialized") deserialized = Deserialize(to_retrieve) return deserialized[2] return False
def endGame(gameId): RequireWitness(Operater) # make sure placing bets stage is over Require(canPlaceBet(gameId) == False) totalPayOut = 0 # maker sure the game results have been saved diskResMapInfo = Get(GetContext(), concatKey(GAME_RES_PREFIX, gameId)) Require(diskResMapInfo) diskResMap = Deserialize(diskResMapInfo) diskIdListInfo = Get(GetContext(), concatKey(GAME_DISKID_PREFIX, gameId)) Require(diskIdListInfo) diskIdList = Deserialize(diskIdListInfo) totalDiskProfitForDev = 0 for diskId in diskIdList: # if the gameId-diskId game hasn't been ended yet. if not Get(GetContext(), concatKey(concatKey(gameId, diskId), DISK_STATUS_KEY)): diskRes = diskResMap[diskId] diskProfitForDev = endDisk(gameId, diskId, diskRes) totalDiskProfitForDev = Add(totalDiskProfitForDev, diskProfitForDev) # mark the gameId-diskId game as end Put(GetContext(), concatKey(concatKey(gameId, diskId), DISK_STATUS_KEY), 1) # update the profit for dev _updateProfitForDev(totalDiskProfitForDev) 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 manualSetResult(date, index, gameid, hscore, vscore): _require(CheckWitness(operaterAddress) or CheckWitness(adminAddress)) #update the bet betKey = _concatKey(BetPrefix, gameid) betmap = Deserialize(Get(ctx, betKey)) if betmap[Finished] == True: return False gk = _concatKey(_concatKey(GamePrefix, date), index) gameMap = Deserialize(Get(ctx, gk)) _require(gameid == gameMap[GameID]) gameMap[HTeamScore] = hscore gameMap[VTeamScore] = vscore Put(ctx, gk, Serialize(gameMap)) winnerkey = HomeList betinfos = betmap[winnerkey] winnerBets = betmap['HomeTotal'] if hscore < vscore: winnerkey = VistorList winnerBets = betmap['VisitorTotal'] betmap[Finished] = True totalBets = betmap['HomeTotal'] + betmap['VisitorTotal'] _distributeRewards(totalBets, winnerBets, betinfos) Put(ctx, betKey, Serialize(betmap)) return True
def RegisterPerson(person_id, cpr_cert=""): ctx = GetContext() cpr_status = cpr_cert and VerifyPerson(person_id, 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) 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 reset(type, id, fromAcc): # 获取所有国家 regionDeserialize = Get(GetContext(), REGION) region = Deserialize(regionDeserialize) # 获取最后一个购买人 lastBuyDeserialize = Get(GetContext(), LASTBUY) lastBuy = Deserialize(lastBuyDeserialize) # 计算下一次倒计时 endTime = GetTime() + cycle # 获取合约内部的总金额 param = state(selfContractAddress) unboundOngAmount = Invoke(0, OntContract, 'balanceOf', param) # 把合约内的所有币转给最后一个购买人 paramContract = state(selfContractAddress, Base58ToAddress(lastBuy), unboundOngAmount) resContract = Invoke(0, OntContract, 'transfer', [paramContract]) # 重新设置倒计时 Put(GetContext(), ENDTIME, Serialize(endTime)) # 所有地区价格重置为2 for item in region: item[1] = 2 Put(GetContext(), REGION, Serialize(region)) if type == 1: getGlebal() if type == 2: buy(id, fromAcc)
def getDiskResult(gameId, diskId): """ :param gameId: :param diskId: :return: 3 means gameId has not been initialized. 4 means gameId has been initialized, yet diskId illegal. 5 means dev should get game results through Oracle first by invoking saveGameResultByOracleRes method. """ # make sure address can place bet, otherwise, raise exception Require(canPlaceBet(gameId) == True) diskIdListInfo = Get(GetContext(), concatKey(GAME_DISKID_LIST_PREFIX, gameId)) if not diskIdListInfo: return 3 diskIdList = Deserialize(diskIdListInfo) # make sure the passing by diskId is legal # Require(_checkInList(diskId, diskIdList)) if _checkInList(diskId, diskIdList) == False: return 4 diskResMapInfo = Get(GetContext(), concatKey(GAME_RES_PREFIX, gameId)) if not diskResMapInfo: return 5 diskResMap = Deserialize(diskResMapInfo) return diskResMap[diskId]
def testOracleRes(date): key = _concatKey(OraclePrefix, date) txhash = Get(ctx, key) res = oracleContract('GetOracleOutcome', [txhash]) if not res: return txhash a = Deserialize(res) b = Deserialize(a[0]) return _concatStrs([b[0], b[1], b[2], b[3], b[4]], ',')
def getRandom(txHash): res = oracleContract('GetOracleOutcome', [txHash]) if not res: return '' a = Deserialize(res) b = Deserialize(a[0]) Notify(b) Notify(b[0]) Notify(b[0][0]) Notify(b[0][0][0]) return True
def addList(listToBeAppend): list1Info = Get(GetContext(), LISTKEY) list1 = Deserialize(list1Info) Notify(["before add, list is ", list1]) for element in listToBeAppend: list1.append(element) list1Info = Serialize(list1) Put(GetContext(), LISTKEY, list1Info) Notify(["after add, list is ", list1]) return list1
def getWinInfo(roundNum): key = concatKey(concatKey(ROUND_PREFIX, roundNum), WINNER_KEY) winListInfo = Get(GetContext(), key) winList = Deserialize(winListInfo) generatedLuckyNumber = winList[0] actualLuckyNumberList = Deserialize(winList[1]) allWinnerList = [] for actualLuckyNumber in actualLuckyNumberList: key = concatKey(concatKey(ROUND_PREFIX, roundNum), concatKey(FILLED_NUMBER_KEY, actualLuckyNumber)) winnersListInfo = Get(GetContext(), key) winnersList = Deserialize(winnersListInfo) allWinnerList.append(winnersList) winAwardList = Deserialize(winList[2]) return [generatedLuckyNumber, actualLuckyNumberList,allWinnerList, winAwardList]
def checkList(numberList, accountList): Notify(["111", numberList, accountList]) numberListInfo = Serialize(numberList) Put(GetContext(), NUM_LIST_KEY, numberListInfo) accountListInfo = Serialize(accountList) Put(GetContext(), ACCOUNT_LIST_KEY, accountListInfo) numberListInfo1 = Get(GetContext(), NUM_LIST_KEY) numberList1 = Deserialize(numberListInfo1) accountListInfo1 = Get(GetContext(), ACCOUNT_LIST_KEY) accountList1 = Deserialize(accountListInfo1) Notify(["222", numberList1, accountList1]) return [numberList, accountList]
def addMap(key, value): map1Info = Get(GetContext(), MAPKEY) map1 = Deserialize(map1Info) Notify(["before add, map is ", map1["key1"], map1["key2"]]) map1[key] = value map1.remove("key1") map1Info = Serialize(map1) Put(GetContext(), MAPKEY, map1Info) Notify(["after add, map is ", map1["key2"], map1[key]]) return True
def del_ont_item(ont_id, ipfs_hash): if not CheckWitness(ont_id): return False item_key = concat_key(ITEM_PREFIX, ont_id) item_list_info = Get(ctx, item_key) item_list = [] if item_list_info: item_list = Deserialize(item_list_info) for item in item_list: if item[0] == ipfs_hash: item_list.remove(item) itemRemove(ipfs_hash) return True itemRemoveFail(ipfs_hash) return True
def feedPanda(assetID): ''' feedPanda only recovery the HP loss :param assetID: :return: ''' owner = ownerOf(assetID) if not owner: return False if CheckWitness(owner) == False: return False pdata = Get(ctx, concatkey(ASSET_ID_PREFIX, assetID)) panda = Deserialize(pdata) if panda[ATTRIBUTE_HP] == panda[ATTRIBUTE_HPMAX]: return True else: bamboo = Get(ctx, concatkey(BAMBOO_BALANCE, owner)) if bamboo < 1: return False increaseHP = 10 + abs(getRandom()) % 3 if panda[ATTRIBUTE_HP] + increaseHP >= panda[ATTRIBUTE_HPMAX]: panda[ATTRIBUTE_HP] = panda[ATTRIBUTE_HPMAX] else: panda[ATTRIBUTE_HP] = panda[ATTRIBUTE_HP] + increaseHP Put(ctx, concatkey(ASSET_ID_PREFIX, assetID), Serialize(panda)) 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 placeBet(address, gameID, HorV, amount): _require(amount > 0) key = _concatKey(BetPrefix, gameID) game = Get(ctx, key) _require(game) gameMap = Deserialize(game) if gameMap[BetEnd] == True: return False if gameMap[Finished] == True: return False _require(_transferONG(address, selfAddr, amount)) listkey = HomeList if HorV == 'V': listkey = VistorList gameMap['VisitorTotal'] = gameMap['VisitorTotal'] + amount else: gameMap['HomeTotal'] = gameMap['HomeTotal'] + amount betmap = gameMap[listkey] betinfo = {'address': address, 'amount': amount} if len(betmap) == 0: gameMap[listkey] = [betinfo] else: gameMap[listkey].append(betinfo) Put(ctx, key, Serialize(gameMap)) BetEvent(address, gameID, HorV, amount) return True
def get_grants(copyright): key = get_key(GRANTS_KEY_PREFIX, copyright) grants = Get(ctx, key) if not grants: return False return [Deserialize(x) for x in grants]
def getDiskPlayersList(gameId, diskId, betStatus): playersListInfo = Get(GetContext(), concatKey(concatKey(gameId, diskId), betStatus)) if not playersListInfo: return [] else: return Deserialize(playersListInfo)
def get_item_list(ont_id): item_key = concat_key(ITEM_PREFIX, ont_id) item_list_info = Get(ctx, item_key) item_list = [] if item_list_info: item_list = Deserialize(item_list_info) return item_list
def getFilledNumberList(roundNum): numberListKey = concatKey(concatKey(ROUND_PREFIX, roundNum), FILLED_NUMBER_LIST_KEY) numberListInfo = Get(GetContext(), numberListKey) numberList = [] if numberListInfo: numberList = Deserialize(numberListInfo) return numberList
def createGameByOracleRes(gameId): RequireWitness(Operater) # # make sure the result hasn't be saved before # Require(not getGameResult(gameId)) # make sure the request has been sent out to the oracle contract sentReqTxhash = Get(GetContext(), concatKey(SENTREQHASH_FORMGAME_PREFIX, gameId)) Require(sentReqTxhash) response = OracleContract('GetOracleOutcome', [sentReqTxhash]) Require(response) res = Deserialize(response) # extract game and disk info from res # make sure gameId is consistent with that provided within response # gameId, diskIdList, betEndTime diskIdList = [1, 2, 3] betEndTime = 100 Put(GetContext(), concatKey(GAME_DISKID_PREFIX, gameId), Serialize(diskIdList)) Put(GetContext(), concatKey(GAME_BET_ENDTIME_PREFIX, gameId), betEndTime) return True
def roll_gacha(): ctx = GetContext() rarity_probability = Deserialize(Get(ctx, PROB_MAP)) ssr_character = [11, 10] sr_character = [5] r_character = [4, 6] n_character = [0, 1, 2, 3, 7, 8, 9] rarity_num = _rand() % 100 if rarity_num == 0: rarity_num = 1 rarity = 'SSR' if rarity_num > rarity_probability[len(rarity_probability) - 2][1]: rarity = 'N' elif rarity_num > rarity_probability[len(rarity_probability) - 3][1]: rarity = 'R' elif rarity_num > rarity_probability[len(rarity_probability) - 4][1]: rarity = 'SR' if rarity == 'SSR': character = ssr_character[0] elif rarity == 'SR': character = sr_character[_rand() % 2] elif rarity == 'R': character = r_character[_rand() % 3] else: character = n_character[_rand() % 4] Notify(character) return True
def saveGameResultByOracleRes(gameId): RequireWitness(Operater) # # make sure the result hasn't be saved before # Require(not getGameResult(gameId)) # make sure the request has been sent out to the oracle contract sentReqTxhash = Get(GetContext(), concatKey(SENTREQHASH_SAVERES_PREFIX, gameId)) Require(sentReqTxhash) response = OracleContract('GetOracleOutcome', [sentReqTxhash]) Require(response) res = Deserialize(response) # save the match/game result requesting from oracle contract to this contract diskIdList = [1, 2, 3, 4] diskResList = [-1, 0, 1, 2] diskResMap = { diskIdList[0]: -1, diskIdList[1]: 0, diskIdList[2]: 1, diskIdList[3]: 2, } Put(GetContext(), concatKey(GAME_RES_PREFIX, gameId), Serialize(diskResMap)) Notify(["saveGameResultByOracleRes", gameId, diskIdList, diskResList]) return True
def PayInterstOrPrincipal(bondName: str, account: bytearray): if not validateBond(bondName): return False investorKey = concat(bondInvestorPrefix, bondName) investorKey = concat(investorKey, account) balance = Get(ctx, investorKey) if balance < minInvestCap: return False bond = Deserialize(GetBond(bondName)) paidKey = concat(bondPaidPrefix, bondName) paidKey = concat(paidKey, account) paidRound = Get(ctx, paidKey) currentRound = (Runtime.GetTime() - bond["purchaseEndTime"]) / bond["Interval"] if paidRound > bond["Round"]: return False if currentRound > bond["Round"]: currentRound = bond["Round"] investValue = Get(ctx, investorKey) interst = (currentRound - paidRound) * (investValue * bond.CouponRate / 100) ret = bytearray() if currentRound == bond["Round"]: ret = Invoke(0, ont_addr, "transfer", [state(bond["Account"], account, interst + investValue)]) else: ret = Invoke(0, ont_addr, "transfer", [state(bond["Account"], account, interst)]) if ret != b'\x01': return False Put(ctx, paidKey, paidRound + 1) return True
def endGame(gameIdList): RequireWitness(Operater) totalDiskProfitForDev = 0 for gameId in gameIdList: # make sure placing bets stage is over Require(canPlaceBet(gameId) == False) # maker sure the game results have been saved diskResMapInfo = Get(GetContext(), concatKey(GAME_RES_PREFIX, gameId)) Require(diskResMapInfo) diskResMap = Deserialize(diskResMapInfo) diskIdList = getDiskIdList(gameId) for diskId in diskIdList: # if the gameId-diskId game hasn't been settled yet. if getDiskStatus(diskId) == 0: diskRes = diskResMap[diskId] diskProfitForDev = _endDisk(diskId, diskRes) totalDiskProfitForDev = Add(totalDiskProfitForDev, diskProfitForDev) Notify([ "endGame", gameIdList, ]) # update the profit for dev _updateProfitForDev(totalDiskProfitForDev) return True
def getDiskIdList(gameId): diskIdListInfo = Get(GetContext(), concatKey(GAME_DISKID_LIST_PREFIX, gameId)) if not diskIdListInfo: return [] else: return Deserialize(diskIdListInfo)
def getDiskPlayersList(diskId, betStatus): playersListInfo = Get( GetContext(), concatKey(concatKey(DISK_BET_PLAYER_LIST_PREFIX, diskId), betStatus)) if not playersListInfo: return [] else: return Deserialize(playersListInfo)
def NotifyResponders(emergency_type, position): cpr_persons_list = Get(GetContext(), CPR_LIST_KEY) cpr_persons_list = Deserialize(cpr_persons_list) for i in range(len(cpr_persons_list)): Notify(['Alert:', position, cpr_persons_list[i]]) return True