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 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 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 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, 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 init(): # init list list1 = [1, 2, 3] list1Info = Serialize(list1) Put(GetContext(), LISTKEY, list1Info) # init map map1 = {"key1": 1, "key2": 2} map1Info = Serialize(map1) Put(GetContext(), MAPKEY, map1Info) Notify(["init list is ", list1]) Notify(["init map is ", map1["key1"], map1["key2"]]) return True
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 update_prob(rarity, v): if (v < 0) or (v > 100): return v ctx = GetContext() prob_map_raw = Deserialize(Get(ctx, PROB_MAP_RAW)) prob_map_raw = update_prob(prob_map_raw, rarity, v) prob_map_raw_s = Serialize(prob_map_raw) Put(ctx, PROB_MAP_RAW, prob_map_raw_s) prob_map = _sum_cum(prob_map_raw) s = Serialize(prob_map) Put(ctx, PROB_MAP, s) Notify(['update_prob', prob_map_raw]) 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 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 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(["111_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 sendMessage(from_addr, to_addr, encrypt, message): ''' send message to some address :param from_addr: :param to_addr: :param encrypt: :param message: :return: ''' if CheckWitness(from_addr) == False: return False timestamp = GetTime() msg = { 'FROM': from_addr, 'ENCRYPT': encrypt, 'MESSAGE': message, 'TIMESTAMP': timestamp } countkey = concatkey(messageCountPrefix, to_addr) count = Get(ctx, countkey) Put(ctx, concatkey(concatkey(messageboxPrefix, to_addr), count + 1), Serialize(msg)) Put(ctx, countkey, count + 1) Notify(['sendMessage', from_addr, to_addr, count + 1]) return True
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 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 _saveShareRecord(shareKey, shareData): _shareKey = concat(SHARE_PREFIX, shareKey) _saveData(_shareKey, Serialize(shareData)) Notify([ _shareKey, shareData['contract'], shareData['symbol'], shareData['amount'], shareData['sponsor'] ])
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 put(key): a = {'index': 16, 'value': 16} # c = 16 # Notify([c]) # Put(ctx, _concatkey(testKey, 16), Serialize(a)) Put(ctx, _concatkey(testKey, key), Serialize(a)) 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 Save_Manufacture_Data(manufacture_date,manufacture_time,manufacture_origin,manufacture_company,manufacture_people,manufacture_medicine_name,manufacture_expiry_date,manufacture_ingredient1,manufacture_amount1,manufacture_ingredient2,manufacture_amount2,manufacture_ingredient3,manufacture_amount3,manufacture_ingredient4,manufacture_amount4,manufacture_ingredient5,manufacture_amount5,manufacture_ingredient6,manufacture_amount6,manufacture_ingredient7,manufacture_amount7,manufacture_ingredient8,manufacture_amount8): context = GetContext() manufacture_data = { 'manufacture_date':manufacture_date, 'manufacture_time':manufacture_time, 'manufacture_origin':manufacture_origin, 'manufacture_company':manufacture_company, 'manufacture_people':manufacture_people, 'manufacture_medicine_name':manufacture_medicine_name, 'manufacture_expiry_date':manufacture_expiry_date, 'manufacture_ingredient1':manufacture_ingredient1, 'manufacture_amount1':manufacture_amount1, 'manufacture_ingredient2':manufacture_ingredient2, 'manufacture_amount2':manufacture_amount2, 'manufacture_ingredient3':manufacture_ingredient3, 'manufacture_amount3':manufacture_amount3, 'manufacture_ingredient4':manufacture_ingredient4, 'manufacture_amount4':manufacture_amount4, 'manufacture_ingredient5':manufacture_ingredient5, 'manufacture_amount5':manufacture_amount5, 'manufacture_ingredient6':manufacture_ingredient6, 'manufacture_amount6':manufacture_amount6, 'manufacture_ingredient7':manufacture_ingredient7, 'manufacture_amount7':manufacture_amount7, 'manufacture_ingredient8':manufacture_ingredient8, 'manufacture_amount8':manufacture_amount8 } manufacture_data2 = Serialize(manufacture_data) Put(context, "manufacture_data", manufacture_data2) return True
def put(key): a = {'index': 16, 'value': 16} # base_ = 0xffffffff base_ = 4294967295 c = key + base_ # c = 4294967296 Put(ctx, _concatkey(testKey, c), Serialize(a)) Notify(["111", c]) return True
def init(): # 此函数只执行一次,如果已初始化就什么也不做,没初始化就初始化 mapList = Get(GetContext(), REGION) if not mapList: regionList = [] i = 0 while i <= 220: regionList.append([i, 2, developerAcc]) i += 1 Put(GetContext(), REGION, Serialize(regionList)) endTime = GetTime() + cycle Put(GetContext(), ENDTIME, Serialize(endTime)) Put(GetContext(), LASTBUY, Serialize(developerAcc)) Notify(["init region List success "]) return True else: Notify('already inited') return False
def save(): #a = [1, 2, 3, 4] c = {'a':1,'b':2} b = Serialize(c) Put(ctx,'test',b) Notify('saved') return True
def add_storage(key, value): ctx = GetContext() prob_map = Deserialize(Get(ctx, PROB_MAP)) prob_map[key] = value serialized_map = Serialize(prob_map) Put(ctx, PROB_MAP, serialized_map) Notify(prob_map[key]) return True
def GeneratorRandom(id): txid = GetTransactionHash(GetScriptContainer()) blockHeigt = GetHeight() + 1 blockTime = GetTime() blockHash = GetCurrentBlockHash() sysseed = [0, id, blockHeigt, blockTime, blockHash] sysseed = sha256(Serialize(sysseed)) resseed = sha256(Serialize([txid, sysseed])) resseed = sha256(Serialize([resseed, resseed])) res = abs(resseed) number = res % 100 number = number + 1 return number
def add_key_value_in_dict(key, value): new_dict = {} new_dict_info = Get(CTX, 'new_dict') if new_dict_info: new_dict = Deserialize(new_dict_info) new_dict[key] = value new_dict_info = Serialize(new_dict) Put(CTX, 'new_dict', new_dict_info) Notify(['add key value in dict', key, value, new_dict_info])
def adventure(assetID, lv): owner = ownerOf(assetID) if not owner: return False if CheckWitness(owner) == False: return False lastADTime = Get(ctx, concatkey(LAST_ADVENTURE_TIME, assetID)) currentTime = GetTime() period = currentTime - lastADTime pdata = Get(ctx, concatkey(ASSET_ID_PREFIX, assetID)) panda = Deserialize(pdata) if panda[ATTRIBUTE_HP] == 0: return False pandaLV = panda[ATTRIBUTE_LEVEL] qty = panda[ATTRIBUTE_Qty] # canAD = False # if qty == QUANLITY_GOLD: # if period > 5 * 60: # canAD = True # elif qty == QUANLITY_SILVER: # if period > 10 * 60: # canAD = True # elif qty == QUANLITY_COPPER: # if period > 30 * 60: # canAD = True # elif qty == QUANLITY_IRON: # if period > 60 * 60: # canAD = True # elif qty == QUANLITY_WOOD: # if period > 90 * 60: # canAD = True # # if canAD == False: # return False tmpRandom = (abs(getRandom()) >> (lv % 5 + 1)) % (panda[ATTRIBUTE_HPMAX] + lv + pandaLV) magicno = abs(sha1(getRandom() >> (lv % 8 + 1))) % (pandaLV + lv) resist = (panda[ATTRIBUTE_ATK] * 35 + panda[ATTRIBUTE_HPMAX] / 10 * 50 + magicno * 20) / (panda[ATTRIBUTE_ATK] + panda[ATTRIBUTE_HPMAX] / 10 + pandaLV - lv) injuredHP = (tmpRandom * 100 - resist) / 100 passed = False if injuredHP >= panda[ATTRIBUTE_HP]: panda[ATTRIBUTE_HP] = 0 else: passed = True panda[ATTRIBUTE_HP] = panda[ATTRIBUTE_HP] - injuredHP gotExp = abs(sha1(getRandom() >> (lv % 8 + 1))) % 10 newExp = panda[ATTRIBUTE_EXP] + gotExp if newExp >= panda[ATTRIBUTE_EXPCAP]: panda = levelUp(panda, panda[ATTRIBUTE_EXP] + gotExp - panda[ATTRIBUTE_EXPCAP]) else: panda[ATTRIBUTE_EXP] = newExp Put(ctx, concatkey(ASSET_ID_PREFIX, assetID), Serialize(panda))
def random(min,max,salt):# min>=x and x<=max txid = GetTransactionHash(GetScriptContainer()) blockTime = GetTime() blockHash = GetCurrentBlockHash() sysseed = [txid,blockHash, salt, blockTime] sysseed = sha256(Serialize(sysseed)) res = abs(sysseed) number = res % (max-min+1) number = number + min return number
def init(): ctx = GetContext() prob = [ ['SSR', 1], ['SR', 5], ['R', 10], ['N', 84], ] prob_map = _sum_cum(prob) prob_s = Serialize(prob) Put(ctx, PROB_MAP_RAW, prob_s) # add_card('SSR', 1) # remove_card('SSR', 1) # change_prob('SSR', 80) s = Serialize(prob_map) Put(ctx, PROB_MAP, s) Notify(['prob', prob_map]) return True
def put_grants(copyright, address, expired): key = get_key(GRANTS_KEY_PREFIX, copyright) grants = get_grants(copyright) if not grants: grants = [] grants.append([address, GetTime() + expired if expired != 0 else None]) serialized = [Serialize(x) for x in grants] return Put(ctx, key, serialized)
def RegisterBid(personAddr, companyAddr, price): # check date auction = Get(ctx, concatAll(['auction_', personAddr, '_map'])) if auction is not None: auction = Deserialize(auction) now = GetTime() # TODO Notify(now) # read last bids bidsStrKey = concatAll(['bids_', personAddr]) bidsListKey = concatAll([bidsStrKey, '_list']) bidsTmp = Get(ctx, bidsListKey) bidsList = [] if bidsTmp is not None: bidsList = Deserialize(bidsTmp) # create value bidStr = makeValue([companyAddr, price], '$') bidsList.append(bidStr) bidsStr = makeValue(bidsList, '#') Put(ctx, bidsStrKey, bidsStr) Put(ctx, bidsListKey, Serialize(bidsList)) # register highest bid curBid = {'company_address': companyAddr, 'price': price} hKey = concat('highest_bid_', personAddr) hMapKey = concat(hKey, '_map') if (len(bidsList) == 0): Put(ctx, hKey, bidStr) Put(ctx, hMapKey, Serialize(curBid)) else: highestBid = Get(ctx, hMapKey) if highestBid is not None: highestBid = Deserialize(highestBid) if highestBid['price'] <= price: Put(ctx, hKey, bidStr) Put(ctx, hMapKey, Serialize(curBid)) else: Put(ctx, hKey, bidStr) Put(ctx, hMapKey, Serialize(curBid)) return True