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 TransferFrom(sender, from_acct, to_acct, amount): if amount < 0: return False if CheckWitness(sender) == False: return False if len(to_acct) != 20: return False appoveKey = concat(concat(APPROVE_PREFIX, from_acct), sender) approvedAmount = Get(ctx, appoveKey) if approvedAmount < amount: return False if approvedAmount == amount: Delete(ctx, appoveKey) else: Put(ctx, appoveKey, approvedAmount - amount) fromKey = concat(TRANSFER_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) if fromBalance < amount: return False if fromBalance == amount: Delete(ctx, fromKey) else: Put(ctx, fromKey, fromBalance - amount) tokey = concat(TRANSFER_PREFIX, to_acct) toBalance = Get(ctx, tokey) Put(ctx, tokey, toBalance + amount) Notify(['transfer', from_acct, to_acct, amount]) return True
def transfer(from_acct, to_acct, amount): """ Transfer amount of tokens from from_acct to to_acct :param from_acct: the account from which the amount of tokens will be transferred :param to_acct: the account to which the amount of tokens will be transferred :param amount: the amount of the tokens to be transferred, >= 0 :return: True means success, False or raising exception means failure. """ if len(to_acct) != 20 or len(from_acct) != 20: raise Exception("address length error") if CheckWitness(from_acct) == False: return False # This part is marked as commits since transferring of 0 MYT should fire event, too. # if from_acct == to_acct or amount == 0: # return True fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) if amount > fromBalance: return False if amount == fromBalance: Delete(ctx, fromKey) else: Put(ctx, fromKey, fromBalance - amount) toKey = concat(BALANCE_PREFIX, to_acct) toBalance = Get(ctx, toKey) Put(ctx, toKey, toBalance + amount) Notify(['transfer', from_acct, to_acct, amount]) return True
def _settleAccounts(roundNumber, explodePoint, effectiveEscapeAcctPointList): effectiveEscapeAcctPointOddsProfitList = [] totalOngForAdminToBeSub = 0 for effectiveEscapeAcctPoint in effectiveEscapeAcctPointList: account = effectiveEscapeAcctPoint[0] escapePoint = effectiveEscapeAcctPoint[1] # Require(escapePoint < explodePoint) if escapePoint < explodePoint and escapePoint >= 100: odds = escapePoint betBalance = getPlayerBetBalance(roundNumber, account) ongBalanceForPlayerToBeAdd = Div(Mul(betBalance, odds), OddsMagnitude) totalOngForAdminToBeSub = Add(totalOngForAdminToBeSub, ongBalanceForPlayerToBeAdd) effectiveEscapeAcctPointOddsProfit = [] effectiveEscapeAcctPointOddsProfit.append(account) effectiveEscapeAcctPointOddsProfit.append(escapePoint) effectiveEscapeAcctPointOddsProfit.append( Sub(ongBalanceForPlayerToBeAdd, betBalance)) effectiveEscapeAcctPointOddsProfitList.append( effectiveEscapeAcctPointOddsProfit) Put(GetContext(), concatKey(ONG_BALANCE_KEY, account), Add(getOngBalanceOf(account), ongBalanceForPlayerToBeAdd)) Put(GetContext(), TOTAL_ONG_FOR_ADMIN, Sub(getTotalOngForAdmin(), totalOngForAdminToBeSub)) return effectiveEscapeAcctPointOddsProfitList
def join(addr, amount): # 临时这么搞 info = { 0: 'count', 1: 'acc1', 2: 'amount1', 3: 'acc2', 4: 'amount2', 5: 'acc3', 6: 'amount3' } context = GetContext() count = Get(context, 'count') if count is None: count = 0 count += 1 if count >= 3: Notify('No more seat') return False acc_key = info[2 * count - 1] amount_key = info[count * 2] Put(context, acc_key, addr) Put(context, amount_key, float(amount)) Put(context, 'count', count) Notify(acc_key) return True
def bankerInvest(account, ongAmount): """ invest ong to become a banker :param account: :return: """ currentRound = getCurrentRound() if getRoundGameStatus(currentRound) == STATUS_OFF: newRound = Add(currentRound, 1) RequireWitness(account) if Add(getRunningVaultPercentage(newRound), getDividendForBankersPercentage(newRound)) != 98: runVaultPercentage = getRunningVaultPercentage(currentRound) dividendPercentage = getDividendForBankersPercentage(currentRound) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), DIVIDEND_FOR_BANKERS_PERCENTAGE), dividendPercentage) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), RUNNING_VAULT_PERCENTAGE), runVaultPercentage) Notify([ "setParameters", newRound, runVaultPercentage, dividendPercentage ]) Put(GetContext(), CURRENT_ROUND_KEY, newRound) Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), ROUND_STATUS), STATUS_ON) Notify(["startNewRound", newRound]) _bankerInvest(account, ongAmount) return True
def createMultiTypeToken(): Index = [0, 1, 2, 3, 4, 5, 6, 7] tokenNameList = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8'] tokenSymbolList = ['PS1', 'PS2', 'PS3', 'PS4', 'PS5', 'PS6', 'PS7', 'PS8'] tokenSupplyList = [100, 200, 300, 400, 500, 600, 700, 0] for index in Index: # get name, symbol, totalsupply tokenName = tokenNameList[index] tokenSymbol = tokenSymbolList[index] tokenTotalSupply = tokenSupplyList[index] tokenId = TOKEN_ID_LIST[index] # initiate token name Put(GetContext(), concatkey(tokenId, NAME), tokenName) # initiate token symbol Put(GetContext(), concatkey(tokenId, SYMBOL), tokenSymbol) # initiate token totalSupply Put(GetContext(), concatkey(tokenId, TOTAL_SUPPLY), tokenTotalSupply) # transfer all the tokens to admin Put(GetContext(), concatkey(concatkey(tokenId, BALANCE), admin), tokenTotalSupply) # Notify(['transfer', '', admin, tokenId, tokenTotalSupply]) TransferEvent('', admin, tokenId, tokenTotalSupply) 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 createMultiKindsPumpkin(): Index = [0, 1, 2, 3, 4, 5, 6, 7] # pumpkinKindsID = [PUMPKIN_ID1, PUMPKIN_ID2, PUMPKIN_ID3,PUMPKIN_ID4, PUMPKIN_ID5, PUMPKIN_ID6, PUMPKIN_ID7, PUMPKIN_ID8] pumpkinKindsName = [ 'name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8' ] pumpkinKindsSymbol = [ 'PS1', 'PS2', 'PS3', 'PS4', 'PS5', 'PS6', 'PS7', 'PS8' ] pumpkinKindsTotalSupply = [100, 200, 300, 400, 500, 600, 700, 0] for index in Index: # get name, symbol, totalsupply tokenName = pumpkinKindsName[index] tokenSymbol = pumpkinKindsSymbol[index] tokenTotalSupply = pumpkinKindsTotalSupply[index] tokenId = TOKEN_ID_LIST[index] # initiate token name Put(GetContext(), concatkey(tokenId, NAME), tokenName) # initiate token symbol Put(GetContext(), concatkey(tokenId, SYMBOL), tokenSymbol) # initiate token totalSupply Put(GetContext(), concatkey(tokenId, TOTAL_SUPPLY), tokenTotalSupply) # transfer all the pumpkin tokens to admin Put(GetContext(), concatkey(concatkey(tokenId, BALANCE), admin), tokenTotalSupply) # Notify(['transfer', '', admin, tokenId, tokenTotalSupply]) TransferEvent('', admin, tokenId, tokenTotalSupply) return True
def createMultiTypeToken(): Index = [0, 1, 2, 3, 4] tokenNameList = [ 'TokenNameFirst', 'TokenNameSecond', 'TokenNameThird', 'TokenNameFourth', 'TokenNameFifth' ] tokenSymbolList = ['TNF', 'TNS', 'TNH', 'TNO', 'TNI'] tokenSupplyList = [100000, 200000, 300000, 400000, 500000] for index in Index: # get name, symbol, totalsupply tokenName = tokenNameList[index] tokenSymbol = tokenSymbolList[index] tokenTotalSupply = tokenSupplyList[index] tokenId = TOKEN_ID_LIST[index] # initiate token name Put(GetContext(), concatkey(tokenId, NAME), tokenName) # initiate token symbol Put(GetContext(), concatkey(tokenId, SYMBOL), tokenSymbol) # initiate token totalSupply Put(GetContext(), concatkey(tokenId, TOTAL_SUPPLY), tokenTotalSupply) # transfer all the tokens to admin Put(GetContext(), concatkey(concatkey(tokenId, BALANCE), admin), tokenTotalSupply) TransferEvent('', admin, tokenId, tokenTotalSupply) return True
def sell(_account, _tokenAmount): """ """ # setup data # burn the sold tokens # update dividends tracker # update the amount of dividends per P3D # emit the onTokenSell event Require(CheckWitness(_account)) # Make sure _account's balance is greater than _tokenAmount that is gonna be sold _tokenBalance = balanceOf(_account) Require(_tokenAmount <= _tokenBalance) _ongAmount = _tokenToOng(_tokenAmount) _dividendsOng = Div(Mul(_ongAmount, dividendFee_), 100) _taxedOng = Sub(_ongAmount, _dividendsOng) # burn the sold token Put(GetContext(), TOTAL_SUPPLY_KEY, Sub(totalSupply(), _tokenAmount)) # Update the token balance of _account Put(GetContext(), concatKey(_account, TOKENBALANCE_SUFFIX), Sub(_tokenBalance, _tokenAmount)) # Update pricePerToken_ _totalSupply = totalSupply() if _totalSupply > 0: _pricePerToken = Get(GetContext(), PRICE_PER_TOKEN_KEY) _pricePerToken_Increase = Div(Mul(_dividendsOng, ongMagnitude_), _totalSupply) Put(GetContext(), PRICE_PER_TOKEN_KEY, Add(_pricePerToken, _pricePerToken_Increase)) # emit event OnTokenSell(_account, _tokenAmount, _taxedOng)
def bet(account, ongAmount): RequireWitness(account) currentRound = getCurrentRound() Require(getRoundStatus(currentRound) == STATUS_ON) Require(getRoundBetStatus(currentRound)) Require(_transferONG(account, ContractAddress, ongAmount)) Put(GetContext(), TOTAL_ONG_FOR_ADMIN, Add(getTotalOngForAdmin(), ongAmount)) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), concatKey(ROUND_PLAYER_BET_BALANCE_KEY, account)), Add(getPlayerBetBalance(currentRound, account), ongAmount)) # roundPlayersList = getRoundPlayersList(currentRound) # if not _checkIsInRoundPlayersList(account, roundPlayersList): # roundPlayersList.append(account) # Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), ROUND_PLAYER_ADDRESS_LIST_KEY), Serialize(roundPlayersList)) updateDividend(account) luckyBalanceToBeAdd = 0 if _checkReferral(account): # give the referral 10% more Lucky luckyBalanceToBeAdd = Div( Div(Mul(Mul(ongAmount, getLuckyToOngRate()), 110), 100), Magnitude) else: luckyBalanceToBeAdd = Div(Mul(ongAmount, getLuckyToOngRate()), Magnitude) Put(GetContext(), concatKey(LUCKY_BALANCE_KEY, account), Add(getLuckyBalanceOf(account), luckyBalanceToBeAdd)) Put(GetContext(), LUCKY_TOTAL_SUPPLY_KEY, Add(getLuckySupply(), luckyBalanceToBeAdd)) Notify(["bet", currentRound, account, ongAmount]) 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 payToPlay(account, ongAmount): RequireWitness(account) Require(ongAmount >= 100000000) currentId = Add(getCurrentRound(), 1) Require(_transferONG(account, ContractAddress, ongAmount)) Put(GetContext(), ROUND_ID_NUMBER_KEY, currentId) Put(GetContext(), concatKey(currentId, ID_UNPAID_PLAYER_KEY), account) Put(GetContext(), concatKey(currentId, account), ongAmount) Put(GetContext(), TOTAL_ONG_FOR_ADMIN, Add(getTotalOngForAdmin(), ongAmount)) # deal with Lucky sending and referral Lucky sending _referralLuckyBalanceToBeAdd = 0 acctLuckyBalanceToBeAdd = Div(Mul(ongAmount, getLuckyToOngRate()), Magnitude) ############### Transfer Lucky TWO times to account and referral ############### # transfer LUCKY to account params = [ContractAddress, account, acctLuckyBalanceToBeAdd] revesedContractAddress = Get(GetContext(), LUCKY_CONTRACT_HASH_KEY) res = DynamicAppCall(revesedContractAddress, "transfer", params) Require(res) referral = getReferral(account) if len(referral) == 20: # transfer LUCKY to referral _referralLuckyBalanceToBeAdd = Div( Mul(acctLuckyBalanceToBeAdd, getReferralBonusPercentage()), 100) params = [ContractAddress, referral, _referralLuckyBalanceToBeAdd] res = DynamicAppCall(revesedContractAddress, "transfer", params) Require(res) Notify(["payToPlay", currentId, account, ongAmount]) return True
def takeOwnership(toAcct, tokenID): """ transfer the approved tokenId token to toAcct the invoker can be the owner or the approved account toAcct can be any address :param toAcct: the account that will be assigned as the new owner of tokenId :param tokenID: the tokenId token will be assigned to toAcct :return: False or True """ if len(toAcct) != 20: raise Exception("toAcct illegal!") tokenOwner = ownerOf(tokenID) if not tokenOwner: return False approveKey = concatkey(APPROVE_PREFIX, tokenID) approvedAcct = Get(ctx, approveKey) if CheckWitness(tokenOwner) != True and CheckWitness(approvedAcct) != True: return False Delete(ctx, approveKey) ownerKey = concatkey(OWNER_OF_TOKEN_PREFIX, tokenID) Put(ctx, ownerKey, toAcct) fromBalance = balanceOf(tokenOwner) toBalance = balanceOf(toAcct) # to avoid overflow if fromBalance >= 1 and toBalance < toBalance + 1: Put(ctx, concatkey(OWNER_BALANCE_PREFIX, tokenOwner), fromBalance - 1) Put(ctx, concatkey(OWNER_BALANCE_PREFIX, toAcct), toBalance + 1) Notify(['transfer', tokenOwner, toAcct, tokenID]) 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 transfer(toAcct, tokenID): """ transfer the token with tokenID to the toAcct :param toAcct: to account address :param tokenID: the unique token's ID, type should be ByteArray :return: False means failure, True means success. """ tokenOwner = ownerOf(tokenID) if CheckWitness(tokenOwner) == False: return False if len(toAcct) != 20: raise Exception('address length error!') ownerKey = concatkey(OWNER_OF_TOKEN_PREFIX, tokenID) fromAcct = Get(ctx, ownerKey) balanceKey = concatkey(OWNER_BALANCE_PREFIX, fromAcct) fromBalance = Get(ctx, balanceKey) if fromBalance >= 1: # decrease fromAccount token balance Put(ctx, balanceKey, fromBalance - 1) else: raise Exception('fromBalance error') # set the owner of tokenID to toAcct Put(ctx, ownerKey, toAcct) # increase toAccount token balance balanceKey = concatkey(OWNER_BALANCE_PREFIX, toAcct) Put(ctx, balanceKey, balanceOf(toAcct) + 1) Notify(['transfer', fromAcct, toAcct, tokenID]) return True
def transfer(fromAcct, toAcct, tokenId, amount): """ transfer amount of tokens in terms of tokenId token from fromAcct to the toAcct :param fromAcct: :param toAcct: :param tokenId: :param amount: :return: """ RequireWitness(fromAcct) Require(checkTokenId(tokenId)) RequireScriptHash(fromAcct) RequireScriptHash(toAcct) balanceKey = concatkey(tokenId, BALANCE) fromKey = concatkey(balanceKey, fromAcct) fromBalance = Get(GetContext(), fromKey) if amount > fromBalance: return False if amount == fromBalance: Delete(GetContext(), fromKey) else: Put(GetContext(), fromKey, fromBalance - amount) toKey = concatkey(balanceKey, toAcct) toBalance = Get(GetContext(), toKey) Put(GetContext(), toKey, toBalance + amount) # Notify(["transfer", fromAcct, toAcct, tokenId, amount]) TransferEvent(fromAcct, toAcct, tokenId, amount) return True
def takeOwnership(toAcct, tokenID): """ take the approved token :param toAcct: spender :param tokenID: this tokenID should be approved by its owner to toAcct :return: False or True """ if CheckWitness(toAcct) == False: return False tokenOwner = ownerOf(tokenID) if not tokenOwner: return False approveKey = concatkey(APPROVE_PREFIX, tokenID) approvedAcct = Get(ctx, approveKey) if approvedAcct != toAcct: return False Delete(ctx, approveKey) ownerKey = concatkey(OWNER_OF_TOKEN_PREFIX, tokenID) Put(ctx, ownerKey, toAcct) fromBalance = balanceOf(tokenOwner) toBalance = balanceOf(toAcct) # to avoid overflow if fromBalance >= 1 and toBalance < toBalance + 1: Put(ctx, concatkey(OWNER_BALANCE_PREFIX, tokenOwner), fromBalance - 1) Put(ctx, concatkey(OWNER_BALANCE_PREFIX, toAcct), toBalance + 1) Notify(['transfer', tokenOwner, toAcct, tokenID]) return True
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 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 transfer(from_acct,to_acct,amount): """ Transfer amount of tokens from from_acct to to_acct :param from_acct: the account from which the amount of tokens will be transferred :param to_acct: the account to which the amount of tokens will be transferred :param amount: the amount of the tokens to be transferred, >= 0 :return: True means success, False or raising exception means failure. """ if len(to_acct) != 20 or len(from_acct) != 20: raise Exception("address length error") if CheckWitness(from_acct) == False or amount < 0: return False fromKey = concat(BALANCE_PREFIX,from_acct) fromBalance = Get(ctx,fromKey) if amount > fromBalance: return False if amount == fromBalance: Delete(ctx,fromKey) else: Put(ctx,fromKey,fromBalance - amount) toKey = concat(BALANCE_PREFIX,to_acct) toBalance = Get(ctx,toKey) Put(ctx,toKey,toBalance + amount) # Notify(["transfer", AddressToBase58(from_acct), AddressToBase58(to_acct), amount]) # TransferEvent(AddressToBase58(from_acct), AddressToBase58(to_acct), amount) Notify(['Transfer successful', from_acct, to_acct, amount]) TransferEvent(from_acct, to_acct, amount) return True
def bankerInvest(account, ongAmount): """ invest ong to become a banker :param account: :return: """ currentRound = getCurrentRound() if getRoundGameStatus(currentRound) == STATUS_OFF: newRound = Add(currentRound, 1) if currentRound == 0: RequireWitness(Admin) else: RequireWitness(account) if Add(getRunningVaultPercentage(newRound), getDividendForBankersPercentage(newRound)) != 98: setParameters(getDividendForBankersPercentage(currentRound), getRunningVaultPercentage(currentRound)) Put(GetContext(), CURRENT_ROUND_KEY, newRound) Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, newRound), ROUND_STATUS), STATUS_ON) Notify(["startNewRound", newRound]) _bankerInvest(account, ongAmount) return True
def Settle(outcome): context = GetContext() settlementBeginTimestamp = Get(context, SETTLEMENT_BEGIN_TIMESTAMP_KEY) if settlementBeginTimestamp == None: date = currentTimestamp() Put(context, SETTLEMENT_BEGIN_TIMESTAMP_KEY, date) settlementsCount = Get(context, SETTLEMENT_COUNT_KEY) if len(settlementsCount) == 0: settlementsCount = 1 else: settlementsCount += 1 Put(context, SETTLEMENT_COUNT_KEY, settlementsCount) count = Get(context, BETS_COUNT_KEY) i = 0 while i < count: betOutcomeKey = concat(BET_OUTCOME_KEY, i) betOutcome = Get(context, betOutcomeKey) if (betOutcome == outcome): #Player won playerAddressKey = concat(BET_ADDRESS_KEY, i) playerAddress = Get(context, playerAddressKey) betAmountKey = concat(BET_AMOUNT_KEY, i) betAmount = Get(context, betAmountKey) transfer(OWNER_ADDRESS, playerAddress, betAmount) i += 1 Put(context, SETTLEMENT_END_TIMESTAMP_KEY, currentTimestamp()) 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 Transfer(from_acct, to_acct, amount): if from_acct == to_acct: return True if amount == 0: return True if amount < 0: return False if CheckWitness(from_acct) == False: return False if len(to_acct) != 20: return False fromKey = concat(TRANSFER_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) if fromBalance < amount: return False if fromBalance == amount: Delete(ctx, fromKey) else: Put(ctx, fromKey, fromBalance - amount) tokey = concat(TRANSFER_PREFIX, to_acct) toBalance = Get(ctx, tokey) Put(ctx, tokey, toBalance + amount) Notify(['transfer', from_acct, to_acct, amount]) return True
def Deploy(): """ Constructor of this contract. Only deployer hard-coded can call this function and cannot call this function after called once. Followings are initialization list for this token 1. Transfer the owner to the deployer. (Owner can mint and burn the token) 2. Supply initial coin to the deployer. """ ctx = GetContext() Require(CheckWitness(DEPLOYER)) # only can be initialized by deployer Require(not Get(ctx, 'DEPLOYED')) # only can deploy once # disable to deploy again Put(ctx, 'DEPLOYED', 1) # the first owner is the deployer # can transfer ownership to other by calling `TransferOwner` function Put(ctx, OWNER_KEY, DEPLOYER) # supply the coin. All coin will be belong to deployer. Put(ctx, MZK_SUPPLY_KEY, INIT_SUPPLY * FACTOR) Put(ctx, concat(OWN_PREFIX, DEPLOYER), INIT_SUPPLY * FACTOR) 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 collectDividendOf(addr): """ put present dividend into dividend vault, update profit per token and dividend vault :param addr: :return: True means it has been successfully run """ nouse = Require(CheckWitness(addr)) unsharedProfitPerTokenBefore = profitPerTokenAfterOf(addr) _profitPerToken = Get(GetContext(), PROFIT_PER_TOKEN_KEY) # if addr is a manager, he will share 25% more of holder dividends _unsharedProfitIntervalPerToken = Sub(_profitPerToken, unsharedProfitPerTokenBefore) ### # _addrTokenBalance = balanceOf(addr) # Notify(["1111 in collectDividendOf", _profitPerToken, unsharedProfitPerTokenBefore, _addrTokenBalance]) ### _sharedRawProfitTillNow = 0 if checkManager(addr): _sharedRawProfitTillNow = Mul(_unsharedProfitIntervalPerToken, Div(Mul(balanceOf(addr),125), 100)) else: _sharedRawProfitTillNow = Mul(_unsharedProfitIntervalPerToken, balanceOf(addr)) # collect the present dividend to dividend vault _sharedProfitTillNow = Div(_sharedRawProfitTillNow, largeNumber_) _dividendVault = dividendOf(addr) _newDividendVault = Add(_dividendVault, _sharedProfitTillNow) Put(GetContext(), concatKey(addr, DIVIDEND_VAULT_SUFFIX), _newDividendVault) # reset the PROFIT_PER_TOKEN_AFTER_SUFFIX Put(GetContext(), concatKey(addr, PROFIT_PER_TOKEN_AFTER_SUFFIX), _profitPerToken) # Notify(["2222 in collectDividendOf", _dividendVault, _sharedProfitTillNow, _newDividendVault]) return _newDividendVault