def checkTokenId(tokenId): # here we check if the tokenId is legal with the help of getting its name if Get(GetContext(), concatkey(tokenId, NAME)): return True else: return False #################### Optional methods defination starts ######################
def disableInitialStage(addr): """ In case the amassador quota is not met, the administrator can manually disable the ambassador phase. """ Require(checkAdmin(addr)) Put(GetContext(), ANTI_EARLY_WHALE_KEY, False) return True
def totalOngBalance(): """ :return: total ong balance of this contract """ value = Get(GetContext(), TOTAL_ONG_KEY) if value: return value else: return 0
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 addManager(adminAddr, newManagerAddr): """ Add manager, only admin can add new manager :param addr: the address that will be added as a new manager :return: """ # check if the address is legal nouse = RequireScriptHash(adminAddr) nouse = RequireScriptHash(newManagerAddr) # check if adminAddr is admin nouse = Require(checkAdmin(adminAddr)) key = concatKey(newManagerAddr, MANAGER_SUFFIX) Put(GetContext(), key, _POSITIVE_) Notify("111111 in addManager") if Get(GetContext(), concatKey(newManagerAddr, MANAGER_SUFFIX)) == _POSITIVE_: Notify("new Manager added successfuly") Notify("2222222 in addManager") return True
def totalSupply(): """ :return: token supply """ value = Get(GetContext(), TOTAL_SUPPLY_KEY) if value: return value else: return 0
def updateDividendBalance(account): """ reset PROFIT_PER_PAPER_FROM_PREFIX of account and update account's dividend till now :param account: :return: """ # RequireWitness(account) key = concatKey(PROFIT_PER_PAPER_FROM_PREFIX, account) profitPerPaperFrom = Get(GetContext(), key) profitPerPaperNow = getProfitPerPaper() profitPerPaper = Sub(profitPerPaperNow, profitPerPaperFrom) if profitPerPaper != 0: # profit = Mul(profitPerPaper, getPaperBalance(account)) Put(GetContext(), concatKey(TOTAL_DIVIDEND_OF_PREFIX, account), getDividendBalance(account)) Put(GetContext(), concatKey(PROFIT_PER_PAPER_FROM_PREFIX, account), profitPerPaperNow) 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 withdrawGas(): """ Only admin can withdraw :return: """ RequireWitness(Admin) # if CheckWitness(Admin) == False: # Notify(["withdrawGas checkwitness failed"]) # return False Require(transferONGFromContact(Admin, getGasVault())) # if transferONGFromContact(Admin, getGasVault()) == False: # Notify(["withdrawGas transfer failed"]) # return False # update total ong amount Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONGAmount(), getGasVault())) Delete(GetContext(), GAS_VAULT_KEY) return True
def assignPaper(account, paperAmount): RequireWitness(Admin) updateDividendBalance(account) # update account's profit per paper from value Put(GetContext(), concatKey(PROFIT_PER_PAPER_FROM_PREFIX, account), getProfitPerPaper()) # update account paper balance balanceKey = concatKey(PAPER_BALANCE_PREFIX, account) Put(GetContext(), balanceKey, Add(paperAmount, getPaperBalance(account))) # update total paper amount Put(GetContext(), TOTAL_PAPER_KEY, Add(paperAmount, getTotalPaper())) Notify(["assignPaper", account, paperAmount, GetTime()]) return True
def getPlayersList(roundNum, guessNumber): numberPlayersKey = concatKey(concatKey(ROUND_PREFIX, roundNum), concatKey(FILLED_NUMBER_KEY, guessNumber)) numberPlayersInfo = Get(GetContext(), numberPlayersKey) numberPlayers = [] if numberPlayersInfo: numberPlayers = Deserialize(numberPlayersInfo) return numberPlayers
def checkTokenPrefix(tokenPrefix): # here we check if the tokenPrefix is legal with the help of getting its name if Get(GetContext(), concatkey(tokenPrefix, NAME)): return True else: return False #################### For testing usage only ends ######################
def Mint(_to, _amount): """ Mints the amount of MZK token. :param _to: address to receive token. :param _amount: the amount to mint. """ ctx = GetContext() _onlyOwner(ctx) # only owner can mint token return _mint(ctx, _to, _amount)
def getDiskStatus(diskId): """ :param diskId: :return: 0 means the diskId has NOT been ended yet. 1 means the diskId has already been ended. ENDED means all the players' accounts have been settled. """ return Get(GetContext(), concatKey(DISK_STATUS_PERFIX, diskId))
def withdrawGas(): """ Only admin can withdraw :return: """ RequireWitness(Admin) Require(transferONGFromContact(Admin, getGasVault())) Delete(GetContext(), GAS_VAULT_KEY) return True
def Query(domain): context = GetContext() owner = Get(context, domain) Notify('query', domain) if owner != None: return owner return False
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 Register(domain, owner): context = GetContext() occupy = Get(context, domain) if occupy != None: return False Put(context, domain, owner) Notify('Register', domain, owner) return True
def getLuckyToOngRate(): """ Div(Mul(Mul(lucky, LuckyMagnitude), Magnitude), Mul(ong, ONGMagnitude)) lucky * 10^8 ------------- * Magnitude ong * 10^9 :return: """ return Get(GetContext(), LUCKY_TO_ONG_RATE_KEY)
def allowance(owner, spender, tokenId): """ :param owner: :param spender: :param tokenId: :return: """ key = concatkey(concatkey(concatkey(tokenId, APPROVE), owner), spender) return Get(GetContext(), key)
def getBankerEarning(account): currentRound = getCurrentRound() lastTimeUpdateEarnRound = getBankersLastTimeUpdateEarnRound(account) earningInStorage = Get(GetContext(), concatKey(BANKER_EARNING_BALANCE_PREFIX, account)) unsharedProfitOngAmount = 0 while (lastTimeUpdateEarnRound <= currentRound): profitPerRunVaultShare = getProfitPerRunningVaultShare(lastTimeUpdateEarnRound) profitPerRunVaultShareFromKey = concatKey(concatKey(ROUND_PREFIX, lastTimeUpdateEarnRound), concatKey(PROFIT_PER_RUNNING_VAULT_SHARE_FROM_KEY, account)) profitPerRunVaultShareFrom = Get(GetContext(), profitPerRunVaultShareFromKey) unsharedProfitPerRunVaultShare = Sub(profitPerRunVaultShare, profitPerRunVaultShareFrom) bankerBalanceInRunVault = getBankerBalanceInRunVault(lastTimeUpdateEarnRound, account) if unsharedProfitPerRunVaultShare > 0 and bankerBalanceInRunVault > 0: unsharedProfit = Mul(bankerBalanceInRunVault, unsharedProfitPerRunVaultShare) unsharedProfitOngAmount = Add(unsharedProfitOngAmount, unsharedProfit) lastTimeUpdateEarnRound = Add(lastTimeUpdateEarnRound, 1) unsharedProfitOngAmount = Div(unsharedProfitOngAmount, MagnitudeForProfitPerSth) return Add(earningInStorage, unsharedProfitOngAmount)
def addReferral(toBeReferred, referral): RequireWitness(Admin) RequireScriptHash(toBeReferred) RequireScriptHash(referral) Require(not getReferral(toBeReferred)) Require(toBeReferred != referral) Put(GetContext(), concatKey(PLAYER_REFERRAL_KEY, toBeReferred), referral) Notify(["addReferral", toBeReferred, referral]) 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 updateDividend(account): profitPerLucky = Get(GetContext(), PROFIT_PER_LUCKY_KEY) profitPerLuckyFrom = Get(GetContext(), concatKey(PROFIT_PER_LUCKY_FROM_KEY, account)) unsharedProfitPerLucky = Sub(profitPerLucky, profitPerLuckyFrom) luckyBalance = getLuckyBalanceOf(account) if luckyBalance == 0 and unsharedProfitPerLucky > 0: Put(GetContext(), concatKey(PROFIT_PER_LUCKY_FROM_KEY, account), profitPerLucky) return True # if unsharedProfitPerLucky == 0: # Put(GetContext(), concatKey(DIVIDEND_BALANCE_KEY, account), getDividendBalanceOf(account)) # Put(GetContext(), concatKey(PROFIT_PER_LUCKY_FROM_KEY, account), profitPerLucky) if unsharedProfitPerLucky > 0 and luckyBalance > 0: Put(GetContext(), concatKey(DIVIDEND_BALANCE_KEY, account), getDividendBalanceOf(account)) Put(GetContext(), concatKey(PROFIT_PER_LUCKY_FROM_KEY, account), profitPerLucky) return True
def compound(acct): """ Compound the first seven tokens into the precious (8-th) token, the first seven tokens of acct will disappear and the precious tokens will be generated :param acct: :return: """ RequireWitness(acct) RequireScriptHash(acct) normalIndex = [0, 1, 2, 3, 4, 5, 6] normalBalances = [0, 0, 0, 0, 0, 0, 0] # here minValue should be the maximum totalSupply minValue = 700 for index in normalIndex: tmpBalance = balanceOf(acct, TOKEN_ID_LIST[index]) normalBalances[index] = tmpBalance if minValue > tmpBalance: minValue = tmpBalance for index in normalIndex: tmpKey = concatkey(concatkey(TOKEN_ID_LIST[index], BALANCE), acct) Put(GetContext(), tmpKey, normalBalances[index] - minValue) Put(GetContext(), concatkey(TOKEN_ID_LIST[index], TOTAL_SUPPLY), totalSupply(TOKEN_ID_LIST[index]) - minValue) # tokenName = Get(GetContext(), concatkey(TOKEN_ID_LIST[index], NAME)) # Notify(["transfer", acct, '', TOKEN_ID_LIST[index], minValue]) TransferEvent(acct, '', TOKEN_ID_LIST[index], minValue) preciousTokenID = TOKEN_ID_LIST[7] preciousTokenSupply = totalSupply(preciousTokenID) Put(GetContext(), concatkey(preciousTokenID, TOTAL_SUPPLY), preciousTokenSupply + minValue) Put(GetContext(), concatkey(concatkey(preciousTokenID, BALANCE), acct), balanceOf(acct, preciousTokenID) + minValue) tokenName = Get(GetContext(), concatkey(preciousTokenID, NAME)) # Notify(["transfer", '', acct, preciousTokenID, minValue]) TransferEvent('', acct, preciousTokenID, minValue) 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 setParameters(dividendForBankersPercentage, runningVaultPercentage): RequireWitness(Admin) currentRound = getCurrentRound() nextRound = Add(currentRound, 1) Require(Add(dividendForBankersPercentage, runningVaultPercentage) == 98) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, nextRound), DIVIDEND_FOR_BANKERS_PERCENTAGE), dividendForBankersPercentage) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, nextRound), RUNNING_VAULT_PERCENTAGE), runningVaultPercentage) Notify([ "setParameters", nextRound, dividendForBankersPercentage, runningVaultPercentage ]) return True
def updateDividendBalance(account): """ reset PROFIT_PER_PAPER_FROM_PREFIX of account and update account's dividend till now :param account: :return: """ # Require(CheckWitness(account) or CheckWitness(Admin)) key = concatKey(PROFIT_PER_PAPER_FROM_PREFIX, account) profitPerPaperFrom = Get(GetContext(), key) profitPerPaperNow = Get(GetContext(), PROFIT_PER_PAPER_KEY) profitPerPaper = Sub(profitPerPaperNow, profitPerPaperFrom) # Notify(["update", profitPerPaperNow, profitPerPaperFrom, profitPerPaper]) # profit = 0 if profitPerPaper != 0: # profit = Mul(profitPerPaper, getPaperBalance(account)) Put(GetContext(), concatKey(TOTAL_DIVIDEND_OF_PREFIX, account), getDividendBalance(account)) Put(GetContext(), concatKey(PROFIT_PER_PAPER_FROM_PREFIX, account), profitPerPaperNow) return True
def getBankerDividend(account): currentRound = getCurrentRound() lastTimeUpdateDividendRound = getBankersLastTimeUpdateDividendRound(account) dividendInStorage = Get(GetContext(), concatKey(BANKER_DIVIDEND_BALANCE_PREFIX, account)) unsharedProfitOngAmount = 0 while (lastTimeUpdateDividendRound <= currentRound): profitPerInvestmentForBankers = getProfitPerInvestmentForBankers(lastTimeUpdateDividendRound) profitPerInvestmentForBankerFromKey = concatKey(concatKey(ROUND_PREFIX, lastTimeUpdateDividendRound), concatKey(PROFIT_PER_INVESTMENT_FOR_BANKER_FROM_KEY, account)) profitPerInvestmentForBankerFrom = Get(GetContext(), profitPerInvestmentForBankerFromKey) unsharedProfitPerInvestmentForBanker = Sub(profitPerInvestmentForBankers, profitPerInvestmentForBankerFrom) bankerInvestment = getBankerInvestment(lastTimeUpdateDividendRound, account) if unsharedProfitPerInvestmentForBanker != 0 and bankerInvestment != 0: unsharedProfit = Mul(unsharedProfitPerInvestmentForBanker, bankerInvestment) unsharedProfitOngAmount = Add(unsharedProfit, unsharedProfitOngAmount) lastTimeUpdateDividendRound = Add(lastTimeUpdateDividendRound, 1) unsharedProfitOngAmount = Div(unsharedProfitOngAmount, MagnitudeForProfitPerSth) return Add(dividendInStorage, unsharedProfitOngAmount)
def Approve(_from, _to, _amount): """ Approves `to` address to withdraw MZK token from the invoker's address. It overwrites the previous approval value. :param _from: invoker address. :param _to: address to approve. :param _amount: MZK amount to approve. """ RequireWitness(_from) # only the token owner can approve return _approve(GetContext(), _from, _to, _amount)