def saving_ong(from_acct, amount): saving_time_key = concat_key(SAVING_ONG_TIME_PREFIX, from_acct) saving_time = Get(CTX, saving_time_key) Notify([saving_time, GetTime()]) if saving_time <= GetTime(): transfer_ong(from_acct, SAVING_POT_ADDRESS, amount) saving_amount_key = concat_key(SAVING_ONG_AMOUNT_PREFIX, from_acct) saving_amount = Get(CTX, saving_amount_key) saving_amount = add(saving_amount, amount) Put(CTX, saving_amount_key, saving_amount) Notify(['saving ong', from_acct, amount]) else: revert()
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 withdraw(account): """ account will withdraw his dividend and award to his own account :param account: :return: """ RequireWitness(account) updateDividendBalance(account) dividendBalance = getDividendBalance(account) awardBalance = getAwardBalance(account) referralBalance = getReferralBalance(account) assetToBeWithdrawn = Add(Add(dividendBalance, awardBalance), referralBalance) if assetToBeWithdrawn > 0: Require(transferONGFromContact(account, assetToBeWithdrawn)) else: return True Delete(GetContext(), concatKey(TOTAL_DIVIDEND_OF_PREFIX, account)) Delete(GetContext(), concatKey(AWARD_BALANCE_OF_PREFFIX, account)) Delete(GetContext(), concatKey(REFERRAL_BALANCE_OF_PREFIX, account)) Put(GetContext(), concatKey(WITHDRAWN_BALANCEOF_PREFFIX, account), Add(assetToBeWithdrawn, getWithdrawnBalance(account))) Notify( ["withdraw", ContractAddress, account, assetToBeWithdrawn, GetTime()]) 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 canCheckIn(account): """ :param account: :return: return == 0 => can NOT check in. return > 0 => can check in. """ lastTimeCheckIn = Get(GetContext(), concatKey(PLAYER_LAST_CHECK_IN_DAY, account)) if not lastTimeCheckIn: return Div(GetTime(), DaySeconds) now = GetTime() days = Div(now, DaySeconds) if days > lastTimeCheckIn: return days else: return 0
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 set_buyer_address(order_id, buyer): saved_initiator = Get(context, ConcatKey(order_id, INITIATOR)) WitnessRequire(saved_initiator) Put(context, ConcatKey(order_id, BUYER), buyer) timelock = GetTime() + REFUND_TIMELOCK_DURATION Put(context, ConcatKey(order_id, REFUND_TIMELOCK), timelock)
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 canPlaceBet(gameId): """ :param gameId: :return: False means can NOT place bets, True means CAN place bets. """ return GetTime() < Get(GetContext(), concatKey(gameId, GAME_BET_ENDTIME_PREFIX))
def withdraw(account): """ account will withdraw his dividend and award to his own account :param account: :return: """ RequireWitness(account) updateDividendBalance(account) dividendBalance = getDividendBalance(account) awardBalance = getAwardBalance(account) referralBalance = getReferralBalance(account) assetToBeWithdrawn = Add(Add(dividendBalance, awardBalance), referralBalance) Require(assetToBeWithdrawn > 0) Require(transferONGFromContact(account, assetToBeWithdrawn)) # if assetToBeWithdrawn > 0: # if transferONGFromContact(account, assetToBeWithdrawn) == False: # Notify(["WithdrawError", "transfer ONG failed"]) # return False # else: # return False Delete(GetContext(), concatKey(TOTAL_DIVIDEND_OF_PREFIX, account)) Delete(GetContext(), concatKey(AWARD_BALANCE_OF_PREFFIX, account)) Delete(GetContext(), concatKey(REFERRAL_BALANCE_OF_PREFIX, account)) # update total ong amount Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONGAmount(), assetToBeWithdrawn)) Notify(["withdraw", ContractAddress, account, assetToBeWithdrawn, GetTime()]) return True
def buyPaper(account, paperAmount): RequireWitness(account) currentRound = getCurrentRound() Require(getGameStatus(currentRound) == STATUS_ON) ongAmount = paperToONG(paperAmount) Require(transferONG(account, ContractAddress, ongAmount)) # PaperHolderPercentage = 50 dividend1 = Div(Mul(ongAmount, PaperHolderPercentage), 100) # update referral balance <---> Get(GetContext(), concatKey(REFERRAL_PREFIX, account)) referral = getReferral(account) referralAmount = 0 if referral: # ReferralAwardPercentage = 1 referralAmount = Div(Mul(ongAmount, ReferralAwardPercentage), 100) Put(GetContext(), concatKey(REFERRAL_BALANCE_OF_PREFIX, referral), Add(referralAmount, getReferralBalance(referral))) dividend = Sub(dividend1, referralAmount) # update award vault, AwardPercentage = 45 awardVaultToBeAdd = Div(Mul(ongAmount, AwardPercentage), 100) awardVaultKey = concatKey(concatKey(ROUND_PREFIX, currentRound), AWARD_VAULT_KEY) Put(GetContext(), awardVaultKey, Add(awardVaultToBeAdd, getAwardVault(currentRound))) # update gas vault gasVaultToBeAdd = Sub(Sub(ongAmount, dividend1), awardVaultToBeAdd) Put(GetContext(), GAS_VAULT_KEY, Add(gasVaultToBeAdd, getGasVault())) oldProfitPerPaper = Get(GetContext(), PROFIT_PER_PAPER_KEY) oldTotalPaperAmount = getTotalPaper() if oldTotalPaperAmount != 0: # profitPerPaperToBeAdd = Div(dividend, totalPaperAmount) profitPerPaperToBeAdd = Div(Mul(dividend, MagnitudeForProfitPerPaper), oldTotalPaperAmount) # update profitPerPaper\ Put(GetContext(), PROFIT_PER_PAPER_KEY, Add(profitPerPaperToBeAdd, oldProfitPerPaper)) else: # if current total paper is ZERO, the dividend will be assigned as the commission part Put(GetContext(), COMMISSION_KEY, Add(dividend, getCommissionAmount())) updateDividendBalance(account) # update paper balance of account Put(GetContext(), concatKey(PAPER_BALANCE_PREFIX, account), Add(paperAmount, getPaperBalance(account))) # update total paper amount Put(GetContext(), TOTAL_PAPER_KEY, Add(paperAmount, getTotalPaper())) # update total ONG Put(GetContext(), TOTAL_ONG_KEY, Add(getTotalONGAmount(), ongAmount)) Notify(["buyPaper", account, ongAmount, paperAmount, GetTime()]) return True
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 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 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 assignPaper(account, paperAmount): RequireWitness(Admin) # update account paper balance accountKey = concatKey(PAPER_BALANCE_PREFIX, account) Put(GetContext(), accountKey, Add(paperAmount, getPaperBalance(account))) Notify(["assignPaper", account, paperAmount, GetTime()]) # update total paper amount Put(GetContext(), TOTAL_PAPER, Add(paperAmount, getTotalPaper())) return True
def refund(order_id): saved_initiator = Get(context, ConcatKey(order_id, INITIATOR)) WitnessRequire(saved_initiator) timelock = Get(context, ConcatKey(order_id, REFUND_TIMELOCK)) if timelock is None: timelock = 0 Require(GetTime() >= timelock) ont_to_sell = Get(context, ConcatKey(order_id, ONT_TO_SELL)) transfer_ont(GetExecutingScriptHash(), saved_initiator, ont_to_sell)
def Main(operation, args): Notify(GetTime()) user = bytearray([ 248, 142, 51, 220, 214, 177, 110, 235, 27, 218, 59, 86, 23, 47, 140, 20, 114, 119, 159, 152 ]) CheckWitness(user) Notify("Hi BlockChain") Notify("s1", "s2", 1, 2, 3) Log("log message")
def create_ong_pot(from_acct, time_limit): require_witness(from_acct) saving_time_key = concat_key(SAVING_ONG_TIME_PREFIX, from_acct) if Get(CTX, saving_time_key): revert() else: saving_time = add(GetTime(), time_limit) Put(CTX, saving_time_key, time_limit) Notify(['saving time', saving_time]) saving_amount_key = concat_key(SAVING_ONG_AMOUNT_PREFIX, from_acct) Put(CTX, saving_amount_key, 0)
def take_ong_out(to_acct): require_witness(to_acct) saving_time_key = concat_key(SAVING_ONT_TIME_PREFIX, to_acct) saving_time = Get(CTX, saving_time_key) if saving_time < GetTime(): saving_amount_key = concat_key(SAVING_ONG_AMOUNT_PREFIX, to_acct) saving_amount = Get(CTX, saving_amount_key) transfer_ong(SAVING_POT_ADDRESS, to_acct, saving_amount) Delete(CTX, saving_amount_key) Notify(['take ong out', to_acct, saving_amount]) else: revert()
def migrateContract(code, needStorage, name, version, author, email, description, newReversedContractHash): RequireWitness(Admin) res = _transferONGFromContact(newReversedContractHash, getTotalONG()) Require(res) if res == True: res = Migrate(code, needStorage, name, version, author, email, description) Require(res) Notify(["Migrate Contract successfully", Admin, GetTime()]) return True else: Notify(["MigrateContractError", "transfer ONG to new contract error"]) return False
def assignPaper(account, paperAmount): RequireWitness(Admin) # update account paper balance accountKey = concatKey(PAPER_BALANCE_PREFIX, account) Put(GetContext(), accountKey, Add(paperAmount, getPaperBalance(account))) # update total paper amount Put(GetContext(), TOTAL_PAPER, Add(paperAmount, getTotalPaper())) # update the sold paper amount in this round currentRound = getCurrentRound() Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), ROUND_PAPER_AMOUNT), Add(paperAmount, getRoundSoldPaperAmount(currentRound))) Notify(["assignPaper", account, paperAmount, GetTime()]) return True
def startNewRound(): """ Only admin can start new round :return: """ RequireWitness(Admin) currentRound = getCurrentRound() nextRoundNum = Add(currentRound, 1) Put(GetContext(), concatKey(concatKey(ROUND_PREFIX, nextRoundNum), ROUND_STATUS_KEY), STATUS_ON) Put(GetContext(), CURRET_ROUND_NUM_KEY, nextRoundNum) Notify(["startRound", nextRoundNum, GetTime()]) return True
def check_copyright(copyright, address): copyright = sha256(copyright) owner = get_owner(copyright) if owner == address: return True grants = get_grants(copyright) if not grants: return False for grant, expired in grants: if grant == address: return expired is None or expired > GetTime() return False
def migrateContract(code, needStorage, name, version, author, email, description, newContractHash): RequireWitness(Admin) param = state(ContractAddress) totalOngAmount = Invoke(0, ONGAddress, 'balanceOf', param) res = _transferONGFromContact(newContractHash, totalOngAmount) Require(res) if res == True: res = Migrate(code, needStorage, name, version, author, email, description) Require(res) Notify(["Migrate Contract successfully", Admin, GetTime()]) return True else: Notify(["MigrateContractError", "transfer ONG to new contract error"]) return False
def endCurrentRoundWithCost(explodePoint, effectiveEscapeAcctPointList): RequireWitness(Admin) currentRound = getCurrentRound() Require(GetTime() > Add(3600, getRoundBetsEndTime(currentRound))) Put( GetContext(), concatKey(concatKey(ROUND_PREFIX, currentRound), ROUND_EXPLODE_NUM_KEY), explodePoint) effectiveEscapeAcctPointOddsProfitList = _settleAccounts( currentRound, explodePoint, effectiveEscapeAcctPointList) Require(_closeRound(currentRound)) Notify([ "endCurrentRoundWithCost", currentRound, explodePoint, effectiveEscapeAcctPointOddsProfitList ]) return True
def getGlebal(): # 获取 和 判断倒计时是否结束 endTimeDeserialize = Get(GetContext(), ENDTIME) endTime = Deserialize(endTimeDeserialize) if GetTime() >= endTime: reset(1, 1, 1) else: glebal = [] # 获取合约余额 param = state(selfContractAddress) unboundOngAmount = Invoke(0, OntContract, 'balanceOf', param) # 获取最后一次购买人 lastBuyDeserialize = Get(GetContext(), LASTBUY) lastBuy = Deserialize(lastBuyDeserialize) glebal = [endTime, lastBuy, unboundOngAmount] Notify(glebal) return glebal
def _newBlock(): bH=blockIndex() if bH>0: pB=indexToBlock(bH) preHash=pB['hash'] hash=nextHash(preHash) else: hash=nextHash(0) preHash=hash bH+=1 key=getBlockKey(0,0,False,bH) bonus=blockBonus() b=Block(bH,hash,preHash,key,BLOCK_TYPE_MINE,bonus,'',GetTime()) saveBlockIndex(bH) saveIndexToBlock(bH,b) return bH
def createAsset(name, url, type): ''' create a new asset :param name: :param url: :param type: :return: ''' timestamp = GetTime() totalcount = Get(ctx, TOTAL_ASSET_COUNT) Put(ctx, TOTAL_ASSET_COUNT, totalcount + 1) tmp = concatkey(concatkey(selfAddr, timestamp), totalcount + 1) assetID = sha256(tmp) asset = {'ID': assetID, 'Name': name, 'Image': url, 'Type': type} Put(ctx, concatkey(ASSET_INDEX_PREFIX, totalcount + 1), assetID) Put(ctx, concatkey(ASSET_ID_PREFIX, assetID), Serialize(asset)) 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 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