def startGame(pokerHashList, playerList, gameId): """ admin send param to start game algorithm: pokeHash = abs(sha256(pokerNum) ^ sha256(salt)) :param pokerHashList: [pokerHash1, pokerHash2, pokerHash3, ..., pokerHash52] send a list include 52 pokerHash :param playerList: [address1, address2, address3...] send all player address in this game :param gameId: game's id :return: bool """ assert (CheckWitness(Admin)) playerNum = len(playerList) pokerNum = len(pokerHashList) helperRandom = abs(GetCurrentBlockHash()) % pokerNum # deal poker to player playerPokerList = [] usedPokerIndexList = [] tmp = 0 while tmp < playerNum: # deal first poker playerHandPokerList = [] helperRandom = (helperRandom + 1) % pokerNum pokerHash = pokerHashList[helperRandom] playerHandPokerList.append(pokerHash) # deal second poker helperRandom = (helperRandom + 1) % pokerNum pokerHash = pokerHashList[helperRandom] playerHandPokerList.append(pokerHash) tmp += 1 playerPokerList.append(playerHandPokerList) # deal common poker commonPokerList = [] commonPokerNum = 0 while commonPokerNum < 5: helperRandom = (helperRandom + 1) % pokerNum pokerHash = pokerHashList[helperRandom] commonPokerList.append(pokerHash) commonPokerNum += 1 Notify( ["startGame", pokerHashList, commonPokerList, playerPokerList, gameId]) return True
def migrateContract(code, needStorage, name, version, author, email, description): """ admin can migrate contract :param code: new contract's avm code :param needStorage: if need storage default true :param name: contract's name :param version: contract's version :param author: contract's author :param email: contract's email :param description: contract's description :return: bool """ assert (CheckWitness(Admin)) res = Migrate(code, needStorage, name, version, author, email, description) assert (res) Notify(["Migrate Contract successfully"]) return True
def migrate(code, needStorage, name, version, author, email, description): """ migrate this contract :param code: :param needStorage: :param name: :param version: :param author: :param email: :param description: :return: True means success, False or raising exception means failure. """ newAddr = AddressFromVmCode(code) res = Invoke(SHARD_VERSION, XSHARD_ASSET_ADDR, 'oep4Migrate', newAddr) assert (res) res = Migrate(code, needStorage, name, version, author, email, description) assert (res) Notify(["Migrate successfully"]) return True
def withdraw(): """ In case someone transfers ong or ont into this contract by accident, Admin can withdraw all the money left in the contract. :return: """ RequireWitness(Admin) param = state(SelfContractAddress) totalOngAmount = Invoke(0, ONGAddress, 'balanceOf', param) if totalOngAmount > 0: Require( _tranferNativeAsset(ONGAddress, SelfContractAddress, PreSaleReceiver, totalOngAmount)) totalOntAmount = Invoke(0, ONTAddress, 'balanceOf', param) if totalOntAmount > 0: Require( _tranferNativeAsset(ONTAddress, SelfContractAddress, PreSaleReceiver, totalOntAmount)) Notify(["withdraw", PreSaleReceiver, totalOngAmount, totalOntAmount]) return True
def migrateContract(code, needStorage, name, version, author, email, description): RequireWitness(Admin) Require(_whenNotPaused() == False) param = state(SelfContractAddress) totalOngAmount = Invoke(0, ONGAddress, 'balanceOf', param) totalOntAmount = Invoke(0, ONTAddress, 'balanceOf', param) # Option1: TODO # newContractHash = AddressFromVmCode(code) # res = _tranferNativeAsset(ONGAddress, SelfContractAddress, newContractHash, totalOngAmount) # assert (res) # Option2: make sure there is no ong left Require(totalOngAmount == 0 and totalOntAmount == 0) res = Migrate(code, needStorage, name, version, author, email, description) Require(res) Notify(["migreate"]) return True
def CreateOracleRequest(request, address): #check witness RequireWitness(address) fee = Get(GetContext(), Fee) #transfer ong to oracle Admin address res = TransferONG(address, Admin, fee) Require(res) #get transaction hash txHash = GetTransactionHash(GetScriptContainer()) #update undoRequestMap undoRequestMap = GetUndoRequestMap() undoRequestMap[txHash] = request b = Serialize(undoRequestMap) Put(GetContext(), UndoRequestKey, b) Notify(["createOracleRequest", request, address]) return True
def init(): ''' based on your requirements, initialize the tokens :return: ''' # Notify(["111_init"]) if not Get(ctx, INITED) and CheckWitness(admin) == True: Put(ctx, INITED, 'TRUE') Put(ctx, TOTAL_SUPPLY, 0) tt = createMultiTokens() if tt == True: # adminBalance = Get(ctx, concatkey(OWNER_BALANCE_PREFIX, admin)) # Put(ctx, TOTAL_SUPPLY, adminBalance) # Notify(["222_init", adminBalance]) return True return False else: Notify(["222_init"]) return False
def migrateContract(code, needStorage, name, version, author, email, description): """ only Owner can migrate contract can migrate this contract to a new contract the code is new contract's AVM code old contract's all data will transfer to new contract :param code: new contract code :param needStorage: True :param name: "" :param version: "" :param author: "" :param email: "" :param description: "" :return: bool """ RequireWitness(Owner) res = Migrate(code, needStorage, name, version, author, email, description) Require(res) Notify(["Migrate Contract successfully"]) return True
def reset(ont_id, account): """ bind account with ont id, only be invoked by the admin :param ont_id: :param account: :return: """ assert is_address(account) assert CheckWitness(get_owner()) bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account)) assert bound_ont_id != ont_id Put(ctx, concat(KEY_ACCOUNT, account), ont_id) Put(ctx, concat(KEY_ONT_ID, ont_id), account) Notify(["reset", ont_id, account]) return True
def createGameByHand(jsonIndex, gameIdList, gameEndTimeList, diskIdList): RequireWitness(Operater) gameIdLen = len(gameIdList) Require(gameIdLen == len(gameEndTimeList)) Require(gameIdLen == len(diskIdList)) index = 0 while index < gameIdLen: gameId = gameIdList[index] gameDiskIdList = diskIdList[index] betEndTime = gameEndTimeList[index] Put(GetContext(), concat(GAME_DISKID_LIST_PREFIX, gameId), Serialize(gameDiskIdList)) Put(GetContext(), concat(GAME_BET_ENDTIME_PREFIX, gameId), betEndTime) index = Add(index, 1) Notify([ "createGameByHand", jsonIndex, gameIdList, gameEndTimeList, diskIdList ]) return True
def bind(ont_id, account): """ bind ontID with address :param ont_id: :param account: ontid owner wallet address :return: """ assert CheckWitness(account) bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account)) if bound_ont_id == ont_id: raise Exception("account bind to the same ont id") Put(ctx, concat(KEY_ACCOUNT, account), ont_id) Put(ctx, concat(KEY_ONT_ID, ont_id), account) stat(1) Notify(["bind", ont_id, account]) return True
def autoUnlock(account): now = GetTime() KEY_lockCount = concat(USER_LOCK_CNT_PREFIX, account) lockCount = Get(ctx, KEY_lockCount) if lockCount > 0: i = 0 while i < lockCount: lockInfo = getLockState(account, i) deserializeUserLock = Deserialize(lockInfo) releaseTime = deserializeUserLock['releaseTime'] Notify([releaseTime]) if releaseTime <= now: if unlock(account, i): i -= 1 lockCount -= 1 i += 1 return True
def sendReqToOracle(jsonIndex): """ call oracle to get format or info of Games, including the, diskId :param jsonIndex: Int :return: """ RequireWitness(Operater) req = getOracleReq(jsonIndex) txhash = GetTransactionHash(GetScriptContainer()) if Get(GetContext(), concatKey(SENTREQHASH_FORMGAME_PREFIX, jsonIndex)): Put(GetContext(), concatKey(SENTREQHASH_SAVERES_PREFIX, jsonIndex), txhash) else: Put(GetContext(), concatKey(SENTREQHASH_FORMGAME_PREFIX, jsonIndex), txhash) res = OracleContract('CreateOracleRequest', [req, Operater]) Notify(["sendReqToOracle", txhash]) return True
def vote(bet, address, amount_staked, for_against): assert (CheckWitness(address)) # check if active bet list is populated/exists assert (check_bet_status(bet) == 1) assert (user_exist(address)) assert (for_against == False or for_against == True) if not get_voter_staked_amount(bet, address, for_against): Put( ctx, concatkey(bet, concatkey(address, concatkey(for_against, VOTE_PREFIX))), amount_staked) bet_voters = get_bet_voters(bet, for_against) Put(ctx, concatkey(bet, concatkey(for_against, BET_VOTERS_LIST)), Serialize(bet_voters.append(address))) versa_bet_voters = get_bet_voters(bet, 1 - for_against) assert (len(bet_voters) + len(versa_bet_voters) <= VOTES_PER_BET) else: Put( ctx, concatkey(bet, concatkey(address, concatkey(for_against, VOTE_PREFIX))), get_voter_staked_amount(bet, address, for_against) + amount_staked) bet_content_info = Get( ctx, concatkey(bet, concatkey(for_against, BET_CONTENT_PREFIX))) bet_content = Deserialize(bet_content_info) bet_content["reputation"] += get_user_repution(address) bet_content["count"] += 1 bet_content["staked"] += amount_staked Put(ctx, concatkey(bet, concatkey(for_against, BET_CONTENT_PREFIX)), Serialize(bet_content)) assert (deposit(address, amount_staked)) Notify(["vote", bet, address, amount_staked, for_against]) return True
def SetOracleOutcome(txHash, data, status, errMessage): #check witness syncAddress = Get(GetContext(), SyncAddress) Require(len(syncAddress) == 20) RequireWitness(syncAddress) #get undoRequest map undoRequestMap = GetUndoRequestMap() #TODO : check if key exist #put result into storage result = state(data, status, errMessage) r = Serialize(result) Put(GetContext(), txHash, r) #remove txHash from undoRequest map undoRequestMap.remove(txHash) b = Serialize(undoRequestMap) Put(GetContext(), UndoRequestKey, b) Notify(["setOracleOutcome", txHash, status, errMessage]) return True
def upgrade(code, needStorage, name, version, author, email, description): """ upgrade current smart contract to new smart contract. :param code:new smart contract avm code. :return: True or raise exception. """ assert (CheckWitness(Get(GetContext(), OPERATOR_PREFIX))) newContractHash = AddressFromVmCode(code) newContractAddr = bytearray_reverse(newContractHash) ontBalance = _getSelfONTBalance() if ontBalance > 0: res = Invoke(0, ONT_ADDRESS, "transfer", [state(CONTRACT_ADDRESS, newContractAddr, ontBalance)]) assert (res) assert (_tryUnboundOng()) ongBalance = _getSelfOngBalance() if ongBalance > 0: res = Invoke(0, ONG_ADDRESS, "transfer", [state(CONTRACT_ADDRESS, newContractAddr, ongBalance)]) assert (res) # transfer all the asset locked within lockproxy contract to the new contract fahListInfo = Get(GetContext(), FROM_ASSET_LIST_KEY) if len(fahListInfo) > 0: fahList = Deserialize(fahListInfo) for e in fahList: amount = getBalanceFor(e) if amount > 0: assert (_transferFromContract(e, newContractAddr, newContractAddr)) # upgrade smart contract res = Migrate(code, needStorage, name, version, author, email, description) assert (res) Notify(["upgrade smart contract"]) return True
def deposit(address, amount, ongOrOnt, userId): """ :param userId: :param address: :param amount: Depositing ONG, amount = 1 * 10^9 when we want to transfer ONG. Depositing ONT, amount = 1 when we want to transfer ONT. :param ongOrOnt: 0 means ONT, 1 means ONG :return: """ assert (CheckWitness(address)) assert (amount > 0) assert (ongOrOnt == 1 or ongOrOnt == 0) asset = "ONG" nativeAssetHash = ONGAddress if ongOrOnt == 0: asset = "ONT" nativeAssetHash = ONTAddress assert (_transferNativeAsset(nativeAssetHash, address, SelfContractAddress, amount)) Notify(["deposit", address, amount, asset, GetTime(), userId]) return True
def unbind(ont_id, account): """ unbind ont id with address :param ont_id: :param account: ont id owner wallet address :return: """ assert CheckWitness(account) bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account)) if not bound_ont_id: raise Exception("account not bind with any ont id") assert bound_ont_id == ont_id Delete(ctx, concat(KEY_ACCOUNT, account)) Delete(ctx, concat(KEY_ONT_ID, ont_id)) stat(-1) Notify(["unbind", ont_id, account]) 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 supply = Get(ctx, AESKEY) if supply < amount: Notify(['Not enough AES in supply']) return False param = state(byte_address) if Invoke(0, contract_address_ONG, 'balanceOf', param) < amount: Notify(['Not enough ONG in wallet']) return False # 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']) return False if address not in all_users: Notify(['not a registered user']) return False # update the user's wallet else: add_bank(address, amount) Notify(['AES added to wallet']) subtract_ong(address, amount * 10) Notify(['ONG subtracted from wallet']) return True
def transferProperty(transferList): """ one account can transfer many DNA to different other accounts :param transferList: [[toAccount1, DNA1],[toAccount2, DNA2]] :return: bool """ DNACheck = transferList[0][1] account = Get(context, concatKey(DNA_PRE_KEY, DNACheck)) RequireScriptHash(account) RequireWitness(account) DNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account)) DNAlist = Deserialize(DNAlist) transferListLen = len(transferList) transferListIndex = 0 while transferListIndex < transferListLen: toAccount = transferList[transferListIndex][0] DNA = transferList[transferListIndex][1] toDNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, toAccount)) if not toDNAlist: toDNAlist = [] else: toDNAlist = Deserialize(toDNAlist) findInList = _findInList(DNA, DNAlist) if findInList >= 0: Put(context, concatKey(DNA_PRE_KEY, DNA), toAccount) toDNAlist.append(DNA) DNAlist.remove(findInList) else: raise Exception("Not found DNA to be removed") transferListIndex += 1 Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account), Serialize(DNAlist)) Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, toAccount), Serialize(toDNAlist)) Notify(["Transfer property successfully"]) return True
def removeProperty(removeList): """ :param removeList: [DNA1, DNA2] :return: bool """ DNACheck = removeList[0] account = Get(context, concatKey(DNA_PRE_KEY, DNACheck)) RequireWitness(account) for DNA in removeList: DNAlist = Get(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account)) DNAlist = Deserialize(DNAlist) num = 0 while num < len(DNAlist): if DNAlist[num] == DNA: Delete(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account)) Delete(context, concatKey(DNA_PRE_KEY, DNA)) DNAlist.remove(num) Put(context, concatKey(PLAYER_ADDRESS_PRE_KEY, account), Serialize(DNAlist)) num += 1 Notify(["Remove property successfully"]) return True
def unpause(): RequireWitness(Admin) Put(GetContext(), PRESALE_PAUSED_KEY, "F") Notify(["unpause"]) return True
def setGPMaxPerTx(limit): RequireWitness(Admin) Require(limit > 0) Put(GetContext(), GP_MAX_PER_TX_KEY, limit) Notify(["setMaxGPperTx", limit]) return True
def setPropertyHash(propertyReversedHash): RequireWitness(Admin) Put(GetContext(), PROPERTY_REVERSED_HASH_KEY, propertyReversedHash) Notify(["setPropertyHash", propertyReversedHash]) return True
def testListAndStr(msgList, msgStr): Notify(["testListAndStr", msgList, msgStr]) resList = [] resList.append(msgList) resList.append(msgStr) return resList
def testList(msgList): Notify(["testMsgList", msgList]) return msgList
def testGetMapInMap(key): mapInfo = Get(GetContext(), 'map_key2') Notify(["testGetMapInMap", mapInfo]) map = Deserialize(mapInfo) return map[key]
def testStructListAndStr(structList, msgStr): Notify(["testStructListAndStr", structList, msgStr]) resList = [] resList.append(structList) resList.append(msgStr) return resList
def putRecord(key, value): assert (_isOwner()) Put(GetContext(), key, value) Notify(["putRecord", key, value]) return True
def testStructList(structList): Notify(["testStructList", structList]) return structList