def testMapInMap(msg): map = msg mapInfo = Serialize(map) Notify(["mapInfo", mapInfo]) mapInfo2 = Serialize(map['key']) Put(GetContext(), 'map_key2', mapInfo2) return mapInfo
def bind(ont_id, bucket): """ bind ontID with address :param ont_id: :param bucket: storage server bucket id or url :return: """ assert CheckWitness(ADMIN) bound_bucket = Get(ctx, concat(KEY_ONT, ont_id)) if bound_bucket == bucket: raise Exception("ont id bind to the same bucket") if not bound_bucket: bind_map = get_bind_map(bucket) bind_map[ont_id] = True Put(ctx, concat(KEY_ONT, ont_id), bucket) Put(ctx, concat(KEY_BUCKET, bucket), Serialize(bind_map)) else: bound_data = Get(ctx, concat(KEY_BUCKET, bound_bucket)) bound_map = Deserialize(bound_data) bound_map.remove(ont_id) Put(ctx, concat(KEY_BUCKET, bound_bucket), Serialize(bound_map)) bind_map = get_bind_map(bucket) bind_map[ont_id] = True Put(ctx, concat(KEY_ONT, ont_id), bucket) Put(ctx, concat(KEY_BUCKET, bucket), Serialize(bind_map)) Notify(["bind", ont_id, bucket]) return True
def transferProperty(transferList): """ :param transferList: [[toAccount1, DNA1],[toAccount2, DNA2]] :return: bool """ DNACheck = transferList[0][1] account = Get(context, concatKey(DNA_PRE_KEY, DNACheck)) RequireWitness(account) for transferE in transferList: toAccount = transferE[0] DNA = transferE[1] DNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account)) DNAlist = Deserialize(DNAlist) toDNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, toAccount)) if not toDNAlist: toDNAlist = [] else: toDNAlist = Deserialize(DNAlist) num = 0 while num < len(DNAlist): if DNAlist[num] == DNA: Put(context, concatKey(DNA_PRE_KEY, DNA), toAccount) DNAlist.remove(num) toDNAlist.append(DNA) Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account), Serialize(DNAlist)) Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, toAccount), Serialize(toDNAlist)) num += 1 Notify(["Transfer property successfully"]) return True
def transfer(fulldomain, idx, todid): ''' transfer domain to other did ''' assert (len(fulldomain) > 0) lowerdomain = lower(fulldomain) assert (isDomainValid(lowerdomain)) owner = ownerOf(lowerdomain) assert (_verifyOntid(owner, idx)) Put(ctx, mulconcat(OWNER_KEY, lowerdomain), todid) fromrecordkey = _concatkey(RECORDS_KEY, owner) fromrecords = Deserialize(Get(ctx, fromrecordkey)) fromrecords = list_remove_elt(fromrecords, lowerdomain) if len(fromrecords) == 0: Delete(ctx, fromrecordkey) else: Put(ctx, fromrecordkey, Serialize(fromrecords)) torecordkey = _concatkey(RECORDS_KEY, todid) torecordsRaw = Get(ctx, torecordkey) if not torecordsRaw: torecords = [lowerdomain] Put(ctx, torecordkey, Serialize(torecords)) else: torecords = Deserialize(torecordsRaw) torecords.append(lowerdomain) assert (len(torecords) <= MAX_COUNT) Put(ctx, torecordkey, Serialize(torecords)) TransferEvent(fulldomain, owner, todid) return True
def reset(ont_id, bucket): """ bind bucket with ont id, only be invoked by the admin :param ont_id: :param bucket: :return: """ assert is_address(bucket) assert CheckWitness(get_owner()) bound_bucket = Get(ctx, concat(KEY_BUCKET, bucket)) assert bound_bucket != bucket if bound_bucket: bound_map = get_bind_map(bound_bucket) bound_map.remove(ont_id) Put(ctx, concat(KEY_BUCKET, bound_bucket), Serialize(bound_map)) bind_map = get_bind_map(bucket) bind_map[ont_id] = True Put(ctx, concat(KEY_BUCKET, bucket), Serialize(bind_map)) Put(ctx, concat(KEY_ONT, ont_id), bucket) Notify(["reset", ont_id, bucket]) return True
def setGP(gpId, gpLimit, price, gpContent): """ :param gpId: token as the identity of gift package :param price: how many ong does this gpId will be sold :param gpLimit: how many gift packages (GP) will be available. :param gpContent: [[tokenId1, amount1], [tokenId2, amount2], ..., [tokenIdN, amountN]] :return: """ RequireWitness(Admin) gpKey = _concatkey(GP_PREFIX, gpId) Require(not Get(GetContext(), gpKey)) gpMap = {"price": price} Require(gpLimit > 0) content = [] # ta means [tokenId_n, amount_n] for ta in gpContent: tokenId = ta[0] amount = ta[1] # make sure the tokenId is legal Require(tokenId >= 1001 and tokenId <= 999999) # make sure the tokenId has been created in property contract <=> name of tokenId is NOT None res = DynamicAppCall(getPropertyReversedHash(), "name", [tokenId]) Require(res) Require(amount > 0) content.append([tokenId, amount]) contentInfo = Serialize(content) gpMap["content"] = contentInfo # put the gp info into the storage Put(GetContext(), _concatkey(GP_PREFIX, gpId), Serialize(gpMap)) # update the left gift package number in storage Put(GetContext(), _concatkey(GP_LEFT_PREFIX, gpId), gpLimit) Notify(["setGP", gpId, gpLimit, price, gpContent]) return True
def create_user(address): byte_address = Base58ToAddress(address) # only the address can invoke the method assert (CheckWitness(byte_address)) # check if user list has been created. if not, initialize it user_info = Get(ctx, USERKEY) if user_info: all_users = Deserialize(user_info) else: all_users = [] if address in all_users: Notify(['User already created']) return False if len(byte_address) != 20: Notify(['Invalid address']) return False else: # check if rep map has been created. if not, initialize it rep_info = Get(ctx, REPKEY) if rep_info: rep_map = Deserialize(rep_info) else: rep_map = {} # update and put rep map rep_map[address] = (100 + 100000000) * FACTOR rep_info = Serialize(rep_map) Put(ctx, REPKEY, rep_info) Notify(['rep_map updated']) # update and put user list all_users.append(address) user_info = Serialize(all_users) Put(ctx, USERKEY, user_info) Notify(['all_users updated']) # check if bank map has been created. if not, initialize it bank_info = Get(ctx, BANKEY) if bank_info: bank_map = Deserialize(bank_info) else: bank_map = {} # update and put bank map bank_map[address] = 100 * FACTOR bank_info = Serialize(bank_map) Put(ctx, BANKEY, bank_info) Notify(['bank_map updated']) # add to wallet of user add_bank(address, 100 * FACTOR) Notify(['user wallet updated']) return True
def create_user(address): # check if user list has been created. if not, initialize it user_info = Get(ctx, USERKEY) if user_info: all_users = Deserialize(user_info) else: all_users = [] if address in all_users: Notify(['User already created']) return False byte_address = Base58ToAddress(address) if len(byte_address) != 20: Notify(['Invalid address']) return False else: # check if rep map has been created. if not, initialize it rep_info = Get(ctx, REPKEY) if rep_info: rep_map = Deserialize(rep_info) else: rep_map = {} # update and put rep map rep_map[address] = 100 rep_info = Serialize(rep_map) Put(ctx, REPKEY, rep_info) # update and put user list all_users.append(address) user_info = Serialize(all_users) Put(ctx, USERKEY, user_info) # check if bank map has been created. if not, initialize it bank_info = Get(ctx, BANKEY) if bank_info: bank_map = Deserialize(bank_info) else: bank_map = {} # update and put bank map bank_map[address] = 100 bank_info = Serialize(bank_map) Put(ctx, BANKEY, bank_info) # add to wallet of user add_bank(address, 100) return True
def oracleRequest(spender, payment, specId, callbackAddress, callbackFunctionId, nonce, dataVersion, data, callFunctionId): onlyLINK() RequireWitness(spender) payment = payment + 0 requestId = sha256(Serialize([callbackAddress, spender, nonce])) assert (not Get(GetContext(), concatKey(COMMITMENTS_PRIFX, requestId))) expiration = GetTime() + EXPIRY_TIME Put(GetContext(), concatKey(COMMITMENTS_PRIFX, requestId), Serialize([payment, callbackAddress, callbackFunctionId, expiration])) OracleRequestEvent(specId, spender, requestId, payment, callbackAddress, callbackFunctionId, expiration, dataVersion, data, callFunctionId) return True
def xshardNotify(a, b): list = [a, b] argsByteArray = Serialize(list) targetShardId = 2 res = NotifyRemoteShard(targetShardId, X_SHARD_INVOKED_CONTRACT, 30000, "notifyCallee", argsByteArray) assert (res) return True
def purchase_bank(address, amount): byte_address = Base58ToAddress(address) assert (CheckWitness(byte_address)) if len(byte_address) != 20: Notify(['Invalid address']) return False else: # check if user has been created. if not, create the user user_info = Get(ctx, USERKEY) if user_info: all_users = Deserialize(user_info) else: Notify(['No existing users']) create_user(address) if address not in all_users: Notify(['not a registered user']) create_user(address) # if the user has been created, that means the bank map exists. update the user's bank and wallet else: bank_info = Get(ctx, BANKEY) bank_map = Deserialize(bank_info) bank_map[address] += amount bank_info = Serialize(bank_map) Put(ctx, BANKEY, bank_info) Notify(['bank_map updated']) add_bank(address, amount) Notify(['user wallet updated']) return True
def lock(fee, to_chain_id, address, amount): """ lock some amount of tokens of this contract, call cross chain method to release to_amount of tokens of another chain's contract :param fee: miner fee of this cross chain tx :param to_chain_id: chain id of destination chain :param address: address of caller :param to_amount: amount to lock :return: """ if len(address) != 20: raise Exception("address length error") if CheckWitness(address) == False: raise Exception("address checkwitness failed.") # transfer asset res = transfer(address, CONTRACT_ADDRESS, amount) if not res: raise Exception("transfer failed.") # call cross chain contract input_map = {"address": address, "amount": amount} input_bytes = Serialize(input_map) destination_contract = Get(ctx, DESTINATION_CONTRACT) if destination_contract: param = state(fee, address, to_chain_id, destination_contract, "unlock", input_bytes) res = Invoke(0, CROSS_CHAIN_CONTRACT_ADDRESS, "createCrossChainTx", param) if not res: raise Exception("call cross chain contract failed.") else: raise Exception("destination contract can not be empty") LockEvent(fee, to_chain_id, destination_contract, address, amount) return True
def getAuction(_tokenId): auction = _saleInfo(_tokenId) Require(_isOnAuction(auction)) return Serialize([ auction['seller'], auction['startingPrice'], auction['endingPrice'], auction['duration'], auction['startedAt'] ])
def AddToken(symbol, hash): """ :param symbol:token symbol, like "ONT", "ONG" :param hash: token script hash,such as ONT,ONG or other token hash, if success, this token can be exchanged on the exchange. :return:True or False """ require(CheckWitness(Admin), "not admin") require(validateAddress(hash), "invalid contract hash") if Get(ctx, concatKey(TOKEN_SYMBOL_PREFIX, symbol)): return False if Get(ctx, concatKey(TOKEN_HASH_PREFIX, hash)): return False supportToken = Get(ctx, SUPPORTED_TOKEN) if not supportToken: tokenMap = {symbol: hash} else: tokenMap = Deserialize(supportToken) tokenMap[symbol] = hash Put(ctx, concatKey(TOKEN_SYMBOL_PREFIX, symbol), symbol) Put(ctx, concatKey(TOKEN_HASH_PREFIX, hash), hash) Put(ctx, SUPPORTED_TOKEN, Serialize(tokenMap)) return True
def removeProperty(removeList): """ :param removeList: [DNA1, DNA2] :return: bool """ DNACheck = removeList[0] account = Get(context, concatKey(DNA_PRE_KEY, DNACheck)) RequireScriptHash(account) RequireWitness(account) DNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account)) if DNAlist: DNAlist = Deserialize(DNAlist) else: raise Exception("NO DNA") removeListLen = len(removeList) removeListIndex = 0 while removeListIndex < removeListLen: DNA = removeList[removeListIndex] findInList = _findInList(DNA, DNAlist) if findInList >= 0: Delete(context, concatKey(DNA_PRE_KEY, DNA)) DNAlist.remove(findInList) else: raise Exception("Not found DNA to be removed") removeListIndex += 1 Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account), Serialize(DNAlist)) Notify(["Remove property successfully"]) return True
def RegisterExchange(exchangeName, exchangeId): """ :param exchangeName:exchange name, like "Huobi" :param exchangeId:exchange Id, essentially it is also a wallet address, only this exchange account can invoke token proxy smart contract :return:True or False """ require(CheckWitness(Admin), "not admin") require(validateAddress(exchangeId), "invalid exchange Id") require(exchangeName != "", "invalid exchange name") if Get(ctx, concatKey(EXCHANGE_NAME_PREFIX, exchangeName)): return False if Get(ctx, concatKey(EXCHANGE_ID_PREFIX, exchangeId)): return False registerExchange = Get(ctx, REGISTERED_EXCHANGE) if not registerExchange: exchangeMap = {exchangeName: exchangeId} else: exchangeMap = Deserialize(registerExchange) exchangeMap[exchangeName] = exchangeId Put(ctx, concatKey(EXCHANGE_NAME_PREFIX, exchangeName), exchangeName) Put(ctx, concatKey(EXCHANGE_ID_PREFIX, exchangeId), exchangeId) Put(ctx, REGISTERED_EXCHANGE, Serialize(exchangeMap))
def deleteDomain(fulldomain, idx): ''' delete domain ''' assert (len(fulldomain) > 0) #domain is exist owner = ownerOf(fulldomain) assert (owner) lowerdomain = lower(fulldomain) _checkParentAuth(lowerdomain, idx) Delete(ctx, _concatkey(OWNER_KEY, lowerdomain)) Delete(ctx, _concatkey(VALID_KEY, lowerdomain)) Delete(ctx, _concatkey(VALUE_KEY, lowerdomain)) recordkey = _concatkey(RECORDS_KEY, owner) records = Deserialize(Get(ctx, recordkey)) records = list_remove_elt(records, lowerdomain) if len(records) == 0: Delete(ctx, recordkey) else: Put(ctx, recordkey, Serialize(records)) DeleteDomainEvent(lowerdomain) return True
def xshardInvoke(a, b): list = [a, b] argsByteArray = Serialize(list) targetShardId = 2 res = InvokeRemoteShard(targetShardId, X_SHARD_INVOKED_CONTRACT, "invokeCallee", argsByteArray) Put(ctx, X_SHARD_INVOKE_KEY, Deserialize(res)) return True
def updateState(stateRootHash, height, version, depositIds, withdrawAmounts, toAddresses, assetAddresses): operator = Get(GetContext(), OPERATOR_ADDRESS) assert (CheckWitness(operator)) preHeight = Get(GetContext(), CURRENT_HEIGHT) assert (preHeight + 1 == height) Put(GetContext(), CURRENT_HEIGHT, height) stateRoot = [stateRootHash, height, version] stateRootInfo = Serialize(stateRoot) Put(GetContext(), concatKey(Current_STATE_PREFIX, height), stateRootInfo) # 返回满足条件用户的钱 currentWithDrawId = Get(GetContext(), CURRENT_WITHDRAW_ID) confirmHeight = Get(GetContext(), CONFRIM_HEIGHT) if currentWithDrawId: while currentWithDrawId > 1: withdrawStatusInfo = Get( GetContext(), concatKey(WITHDRAW_PREFIX, currentWithDrawId - 1)) withdrawStatus = Deserialize(withdrawStatusInfo) if (height - withdrawStatus[3] == confirmHeight): assert (withdraw(withdrawStatus[0])) elif height - withdrawStatus[3] > confirmHeight: break currentWithDrawId = currentWithDrawId - 1 # 更新deposit状态 _updateDepositState(depositIds) # 更新withdraw状态 _createWithdrawState(height, withdrawAmounts, toAddresses, assetAddresses) Notify([ 'updateState', stateRootHash, height, version, depositIds, withdrawAmounts, toAddresses, assetAddresses ]) return True
def unbind(ont_id, bucket): """ unbind ont id with address :param ont_id: :param bucket: bucket id or url :return: """ assert CheckWitness(ADMIN) bound_bucket = Get(ctx, concat(KEY_ONT, ont_id)) if not bound_bucket: raise Exception("ont id bind with nothing") assert bound_bucket == bucket bind_data = Get(ctx, concat(KEY_BUCKET, bucket)) bind_map = Deserialize(bind_data) bind_map.remove(ont_id) Put(ctx, concat(KEY_BUCKET, bucket), Serialize(bind_map)) Delete(ctx, concat(KEY_ONT, ont_id)) Notify(["unbind", ont_id, bucket]) return True
def lock(account, time, amount): # Permission Check onlyOwner() # Lockup amount must be smaller then real balance balance = Get(ctx, concat(BALANCE_PREFIX, account)) require(amount <= balance, "lock amount is bigger than balance") # Sub amount from Balance Put(ctx, concat(BALANCE_PREFIX, account), balance - amount) # Get User's count of lockinfo KEY_lockCount = concat(USER_LOCK_CNT_PREFIX, account) lockCount = Get(ctx, KEY_lockCount) KEY_lockInfo = concat(concat(USER_LOCK_PREFIX, account), lockCount) # Create Lockup Information setLock = { "releaseTime": time, "releaseAmount": amount, } serializeSetLock = Serialize(setLock) # Store lockInfo & increase count Put(ctx, KEY_lockInfo, serializeSetLock) Put(ctx, KEY_lockCount, lockCount + 1) Notify([serializeSetLock]) return True
def purchase_bank(address, amount): byte_address = Base58ToAddress(address) if len(byte_address) != 20: Notify(['Invalid address']) return False else: # check if user has been created. if not, create the user user_info = Get(ctx, USERKEY) all_users = Deserialize(user_info) if address not in all_users: create_user(address) # if the user has been created, that means the bank map exists. update the user's bank and wallet else: bank_info = Get(ctx, BANKEY) bank_map = Deserialize(bank_info) bank_map[address] += amount bank_info = Serialize(bank_map) Put(ctx, BANKEY, bank_info) add_bank(address, amount) return True
def create_user(address, username, bio): # only the address can invoke the method assert (CheckWitness(address)) # check if username has been created. if not, initialize it. Otherwise, rollback the transaction assert (not user_exist(address)) # check if user has been created. if not, initialize it. Otherwise, rollback the transaction assert (not get_address_by_username(username)) # mark username as being used one Put(ctx, concatkey(username, UN_EXIST_PREFIX), address) if len(bio) > 100: Notify(['Bio length exceeds 100 characters']) # create profile info list profile = [username, bio] profile_info = Serialize(profile) Put(ctx, concatkey(address, PI_PREFIX), profile_info) # update reputation of address Put(ctx, concatkey(address, REPKEY_PREFIX), (100 + 100000000) * AES_FACTOR) # distribute a certain amount of token to the newly registered user token_amount = 100 * AES_FACTOR assert (withdraw(address, token_amount)) Notify(["userCreated", address, username, bio]) 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 createProperty(createList): """ :param createList: [[account1, DNA1],[account2, DNA2]] :return: bool """ RequireWitness(Owner) for createE in createList: account = createE[0] DNA = createE[1] accountCheck = Get(context, concatKey(DNA_PRE_KEY, DNA)) Require(len(account) == 20) Require(DNA > 100000000000000) Require(DNA < 1000000000000000) Require(not accountCheck) DNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account)) if not DNAlist: DNAlist = [] else: DNAlist = Deserialize(DNAlist) DNAlist.append(DNA) Put(context, concatKey(DNA_PRE_KEY, DNA), account) Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account), Serialize(DNAlist)) Notify(["Create property successfully."]) return True
def registerDomain(fulldomain, registerdid, idx, validto): ''' register domain fulldomain: domain string registerdid: register ontid idx:owner walletid validto : valid period ''' currenttime = GetTime() if validto > 0: assert (validto > currenttime) assert (len(fulldomain) > 0) _validateDNSName(fulldomain) lowerdomain = lower(fulldomain) assert (not ownerOf(lowerdomain)) _checkParentAuth(lowerdomain, idx) Put(ctx, _concatkey(OWNER_KEY, lowerdomain), registerdid) Put(ctx, _concatkey(VALID_KEY, lowerdomain), validto) recordskey = _concatkey(RECORDS_KEY, registerdid) records = Get(ctx, recordskey) if not records: records = [lowerdomain] else: records = Deserialize(records) records.append(lowerdomain) assert (len(records) <= MAX_COUNT) Put(ctx, recordskey, Serialize(records)) RegisterDomainEvent(lowerdomain, registerdid, validto) return True
def create_bet(address, amount_staked, stock_ticker, sign, margin, date, init_price): assert (CheckWitness(address)) # check if user list exists assert (user_exist(address)) # update bet details target_price = init_price + init_price * sign * margin / 100 bet_details = { "sign": sign, "margin": margin, "target_price": target_price, "vote_end_time": date, "stock_ticker": stock_ticker, } new_bet = get_latest_bet() + 1 Put(ctx, concatkey(new_bet, BET_DETAILS_PREFIX), Serialize(bet_details)) # update latest bet Put(ctx, BETKEY, new_bet) bet_for_map = { "reputation": get_user_repution(address), "count": 1, "staked": amount_staked } bet_against_map = {"reputation": 0, "count": 0, "staked": 0} Put(ctx, concatkey(new_bet, concatkey(1, BET_CONTENT_PREFIX)), Serialize(bet_for_map)) Put(ctx, concatkey(new_bet, concatkey(0, BET_CONTENT_PREFIX)), Serialize(bet_against_map)) Put(ctx, concatkey(new_bet, concatkey(address, concatkey(1, VOTE_PREFIX))), amount_staked) Put(ctx, concatkey(new_bet, concatkey(1, BET_VOTERS_LIST)), Serialize([address])) # mark the new bet as active bet Put(ctx, concatkey(new_bet, ACTIVE_BET_PREFIX), 1) assert (deposit(address, amount_staked)) Notify( ["betCreated", address, stock_ticker, sign, margin, date, init_price]) return True
def placeBet(address, gameId, diskId, betStatus, ongAmount): RequireWitness(address) # make sure address can place bet, otherwise, raise exception Require(canPlaceBet(gameId)) if ongAmount < getMinBetAmount(): # Error 201: "Please bet more ONG!" Notify(["Error", 201]) return False Require(not getDiskStatus(diskId)) diskIdListInfo = Get(GetContext(), concatKey(GAME_DISKID_LIST_PREFIX, gameId)) if not diskIdListInfo: # Error 202: "diskId Not Exist!" Notify(["Error", 202]) return False diskIdList = Deserialize(diskIdListInfo) # make sure the passing by diskId is legal # Require(_checkInList(diskId, diskIdList)) if _checkInList(diskId, diskIdList) == False: # Error 203: "diskId illegal!" Notify(["Error", 203]) return False # betStatus can only be 0, 1 or 2 if betStatus == TieSide or betStatus == LeftSide or betStatus == RightSide: Require(_transferONG(address, ContractAddress, ongAmount)) else: # Error 204: "betStatus illegal!" Notify(["Error", 204]) return False playersList = getDiskPlayersList(diskId, betStatus) if not _checkInList(address, playersList): # update playersList playersList.append(address) Put( GetContext(), concatKey(concatKey(DISK_BET_PLAYER_LIST_PREFIX, diskId), betStatus), Serialize(playersList)) # update address's bet balance Put( GetContext(), concatKey(concatKey(DISK_PLAYER_BET_BALANCE_PREFIX, diskId), concatKey(address, betStatus)), Add(getDiskBetBalance(diskId, betStatus, address), ongAmount)) # update the disk bet amount Put( GetContext(), concatKey(concatKey(DISK_PLAYERS_BET_AMOUNT_PREFIX, diskId), betStatus), Add(getDiskBetAmount(diskId, betStatus), ongAmount)) Notify(["placeBet", address, gameId, diskId, betStatus, ongAmount]) 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 add_user_list(bet, element, prefix): list_info = Get(ctx, concatkey(bet, prefix)) lists = Deserialize(list_info) lists.append(element) list_info = Serialize(lists) Put(ctx, concatkey(bet, prefix), list_info) Notify(['add_user_list', element, prefix]) return True