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 PayInterstOrPrincipal(bondName: str, account: bytearray): if not validateBond(bondName): return False investorKey = concat(bondInvestorPrefix, bondName) investorKey = concat(investorKey, account) balance = Get(ctx, investorKey) if balance < minInvestCap: return False bond = Deserialize(GetBond(bondName)) paidKey = concat(bondPaidPrefix, bondName) paidKey = concat(paidKey, account) paidRound = Get(ctx, paidKey) currentRound = (Runtime.GetTime() - bond["purchaseEndTime"]) / bond["Interval"] if paidRound > bond["Round"]: return False if currentRound > bond["Round"]: currentRound = bond["Round"] investValue = Get(ctx, investorKey) interst = (currentRound - paidRound) * (investValue * bond.CouponRate / 100) ret = bytearray() if currentRound == bond["Round"]: ret = Invoke(0, ont_addr, "transfer", [state(bond["Account"], account, interst + investValue)]) else: ret = Invoke(0, ont_addr, "transfer", [state(bond["Account"], account, interst)]) if ret != b'\x01': return False Put(ctx, paidKey, paidRound + 1) 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 RecycleAsset(from_acct: bytearray, to_acct: bytearray, ont: int, ong: int): ret = bytearray() transfer = state(from_acct, to_acct, ont) ret = Invoke(0, OntContract, "transfer", [transfer]) if ret != b'\x01': raise Exception("tansfer ont error.") transfer = state(from_acct, to_acct, ong) ret = Invoke(0, OngContract, "transfer", [transfer]) if ret != b'\x01': raise Exception("tansfer ont error.") return True
def join(acc, amount): """ 玩家入局,执行游戏逻辑 :param acc: 用户账户,具体输入格式不明,toScriptHash?? :param amount: 金额 :return: 完成返回True,结束 """ players_in_game = Get(CTX, 'players_in_game') if players_in_game is None: players_in_game = 0 round_num = players_in_game / 3 id_in_round = players_in_game % 3 dice = random.randint(1, 6) param = [acc, SELF_ADDR, amount] res = Invoke(ver=1, contractAddress=CONTRACT_ADDR, method='transfer', param=[param]) if not res or res != b'\x01': Notify('bet tranfer failed') return False player_id = concat(concat(str(round_num), '_'), str(id_in_round)) Put(CTX, player_id, sc_list([acc, dice, amount])) Put(CTX, 'players_in_game', players_in_game + 1) # 并发问题???应该没有 res_info = '' if id_in_round == 2: acc_list = [ Get(CTX, concat(concat(str(round_num), '_'), str(i))) for i in sc_range(0, 3) ] max_dice = 0 max_acc = acc_list[0][0] for i in sc_range(0, 3): if acc_list[i][1] > max_dice: max_dice = acc_list[i][1] max_acc = acc_list[i][0] bonus = sum([acc_list[i][2] for i in sc_range(0, 3)]) param = [SELF_ADDR, max_acc, bonus] res = Invoke(ver=1, contractAddress=CONTRACT_ADDR, method='transfer', param=[param]) if not res or res != b'\x01': Notify('settle transfer failed') return False res_info = concat(concat(max_acc, ' win '), str(bonus)) Notify( concat( concat(concat('your dice is ', str(dice)), concat(' your id is ', player_id)), res_info)) return True
def TransferOntOng(from_acct, to_acct, ont, ong): param = state(from_acct, to_acct, ont) res = Invoke(0, OntContract, "transfer", [param]) if res != b'\x01': Notify("transferONT succeed") raise Exception("tansfer ont error.") param = state(from_acct, to_acct, ong) ret = Invoke(0, OngContract, "transfer", [param]) if ret != b'\x01': Notify("transferONG succeed") raise Exception("tansfer ong error.") return True
def transferOntOng(fromAcct, toAcct, ontAmount, ongAmount): param = state(fromAcct, toAcct, ontAmount) res = Invoke(0, OntContract, "transfer", [param]) if res != b'\x01': raise Exception("transfer ont error.") param = state(fromAcct, toAcct, ongAmount) Notify("transferONT succeed") res = Invoke(0, OngContract, "transfer", [param]) if res != b'\x01': raise Exception("transfer ong error.") Notify("transferONG succeed") return True
def balanceOf(address, tokenType): if tokenType == ONG: param = state(address) res = Invoke(0, OngContract, 'balanceOf', param) return res if tokenType == ONT: param = state(address) res = Invoke(0, OntContract, 'balanceOf', param) return res if tokenType == TNT: return banlanceOEP4(address) if tokenType == TONT: return banlanceTONT(address) return 0
def _transferOntOngtoAccount(_account, _ontAmount, _ongAmount): param = state(selfContractAddress, Base58ToAddress(_account), _ontAmount) res = Invoke(0, OntContractAddress, 'transfer', [param]) if res != b'\x01': Notify('transfer ont error.\n') return False Notify("transferONT succeed") param = state(selfContractAddress, Base58ToAddress(_account), _ongAmount) res = Invoke(0, OngContractAddress, 'transfer', [param]) if res != b'\x01': Notify('transfer ong error.\n') return False Notify("transferONG succeed") return True
def checkBalanceOf(ongFlag, account): param = state(ContractAddress) # do not use [param] res = Invoke(0, ONGAddress, 'balanceOf', param) Notify(["ContractAddress", ContractAddress, res]) param = state(account) if ongFlag == 1: Notify(["ongFlag", ongFlag]) res = Invoke(0, ONGAddress, 'balanceOf', param) else: Notify(["ongFlag", ongFlag]) res = Invoke(0, ONTAddress, 'balanceOf', param) Notify(["checkBalanceOf", account, res]) return res
def transferONT(fromacct, toacct, amount): """ transfer ONT :param fromacct: :param toacct: :param amount: :return: """ if CheckWitness(fromacct): param = makeState(fromacct, toacct, amount) res = Invoke(1, contractAddress, 'transfer', [param]) Notify(["11111", res]) if res and res == b'\x01': Notify('transfer succeed') return True else: Notify('transfer failed') return False else: Notify('checkWitness failed') return False
def _transferONGFromContact(toAcct, amount): param = state(ContractAddress, toAcct, amount) res = Invoke(0, ONGAddress, 'transfer', [param]) if res and res == b'\x01': return True else: return False
def RecordShare(owner, signId, symbol, amount, amount2, sponsor): # owner ownerAddress = Base58ToAddress(owner) RequireWitness(ownerAddress) if symbol == 'ONT': contract = OntContract tokenContractAddress = OntContractAddress if symbol == 'ONG': contract = OngContract tokenContractAddress = OngContractAddress param = state(ownerAddress, selfContractAddress, amount) res = Invoke(0, tokenContractAddress, 'transfer', [param]) if res != b'\x01': Notify('RecordShare error.\n') return False share = { "contract": contract, "symbol": symbol, "amount": amount, "amount2": amount, "sponsor": sponsor, } shareKey = concat(owner, signId) _saveShareRecord(shareKey, share) return True
def transfer_ont(from_acct, to_acct, amount): require_witness(from_acct) transfer_param = state(from_acct, to_acct, amount) res = Invoke(0, ONT_ADDRESS, 'transfer', [transfer_param]) if res == b'\x01': return True else: return False
def withdrawOng(toAcct): param = state(ONTAddress, ContractAddress) unboundOngAmount = Invoke(0, ONGAddress, 'allowance', param) Notify(["unboundOngAmount", unboundOngAmount]) if unboundOngAmount > 0: unboundOngAmount = 147 params = state(ContractAddress, ONTAddress, toAcct, unboundOngAmount) res = Invoke(0, ONGAddress, "transferFrom", params) if res and res == b'\x01': Notify(["withdraw ong successful!"]) return True else: Notify(["withdraw ong failed!"]) return False else: Notify(["Not enough unboundOngAmount", unboundOngAmount]) return False
def transferOngToContract(fromAccount, ongAmount): Notify(["111_transferOngToContract", selfContractAddress]) param = state(fromAccount, selfContractAddress, ongAmount) res = Invoke(0, OngContract, 'transfer', [param]) if res and res == b'\x01': Notify('transfer Ong succeed') return True else: Notify('transfer Ong failed') return False
def checkWithdraw(account): allowanceOng = checkAllowance(account) withdrawOngAmount = allowanceOng / 2 params = state(account, ONTAddress, account, withdrawOngAmount) res = Invoke(0, ONGAddress, 'transferFrom', params) if res and res == b'\x01': Notify(["withdraw ong successful!"]) return True else: Notify(["withdraw ong failed!"]) return False
def withdraw(_account): """ Withdraw all the caller earning including dividends and referral bonus and the ong balance from selling the keys :param _account: :return: the withdrawn ong amount """ nouse = Require(CheckWitness(_account)) # put present dividend into dividend vault, update profit per token and dividend vault nouse = collectDividendOf(_account) # add dividend vault and referral balance together to get _dividends _dividends = dividendsOf(_account) # _account balance from selling keys _ongBalance = ongBalanceOf(_account) # add two together as earnings _accountEarnings = Add(_dividends, _ongBalance) # make sure _account has some earnings nouse = Require(_accountEarnings > 0) # transfer _dividends ( his ONG ) to _account params = state(selfContractAddr_, _account, _accountEarnings) res = Invoke(0, ONGContractAddress_, "transfer", [params]) if res and res == b'\x01': # emit event OnWithdraw(_account, _accountEarnings) else: raise Exception("withdraw ong error.") # Update dividend Delete(GetContext(), concatKey(_account, DIVIDEND_VAULT_SUFFIX)) # Update referral bonus Delete(GetContext(), concatKey(_account, REFERRAL_BALANCE_SUFFIX)) # # Update ong balance of _account # Delete(GetContext(), concatKey(_account, ONG_BALANCE_SUFFIX)) if balanceOf(_account) > 0: # update the _profitPerToken value after the _account withdraw to count his share till _profitPerToken later _profitPerToken = Get(GetContext(), PROFIT_PER_TOKEN_KEY) Put(GetContext(), concatKey(_account, PROFIT_PER_TOKEN_AFTER_SUFFIX), _profitPerToken) else: Delete(GetContext(), concatKey(_account, PROFIT_PER_TOKEN_AFTER_SUFFIX)) # Update withdrawn earnings ledger _newWithdrawnEarnings = Add(withdrawnEarnings(_account), _accountEarnings) Put(GetContext(), concatKey(_account, WITHDRAWN_EARNINGS_SUFFIX), _newWithdrawnEarnings) # Update ONG balance of this contract (need to be updated only when withdraw() is invoked) _totalOngBalance = Sub(totalOngBalance(), _accountEarnings) Put(GetContext(), TOTAL_ONG_KEY, _totalOngBalance) # Update ONG balance of this contract for key (no need to update since its done within sell method # Put(GetContext(), TOTAL_ONG_FOR_KEY_KEY, Add(totalOngForKey(), _ongBalance)) return _accountEarnings
def invest(account, ontAmount): # make sure the caller is actually the account if not CheckWitness(account): # if the caller is not the account return False # make sure the caller has transferred the correct amount of ONT into this contract(or account) params = state(account, selfContractAddress, ontAmount) res = Invoke(0, OntContract, "transfer", params) if not res: # the account should transfer ontAmount of ONT into this contract as investment, but he failed. return False # then, for example, we can record that the account has transferred amount of ONT into this GetContract return True
def transferONG(fromAcct, toAcct, amount): """ transfer ONG :param fromacct: :param toacct: :param amount: :return: """ RequireWitness(fromAcct) param = state(fromAcct, toAcct, amount) res = Invoke(0, ONGAddress, 'transfer', [param]) if res and res == b'\x01': return True else: return False
def checkAllowance(account): # param = state(ONTAddress, account) # if ongFlag == 1: # Notify(["ongFlag", ongFlag]) # unboundOngAmount = Invoke(0, ONGAddress, 'allowance', param) # else: # Notify(["ongFlag", ongFlag]) # unboundOngAmount = Invoke(0, ONTAddress, 'allowance', param) # Notify(["checkAllowance", account, unboundOngAmount]) param = state(ONTAddress, account) unboundOngAmount = Invoke(0, ONGAddress, 'allowance', param) Notify(["checkAllowance", account, unboundOngAmount]) return unboundOngAmount
def buy_copyright(copyright, address): copyright = sha256(copyright) if check_owner(copyright): return False owner_adr = get_owner(copyright) Notify(['buy', copyright, address]) param = state(address, owner_adr, 10) OntContract = ToScriptHash("AFmseVrdL9f9oyCzZefL9tG6UbvhUMqNMV") res = Invoke(0, OntContract, "transfer", [param]) if res != b'\x01': raise Exception("transfer ont error.") Notify("transferONT succeed") return put_grants(copyright, address, 120)
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 transferONT(fromAcct, toAcct, ontAmount): """ transfer ONG :param fromacct: :param toacct: :param amount: :return: """ param = state(fromAcct, toAcct, ontAmount) res = Invoke(0, ONTAddress, 'transfer', [param]) if res and res == b'\x01': Notify(["transfer ONT successful!"]) return True else: Notify(["transfer ONT failed!"]) return False
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 createShare(owner, signId, income, referral): # owner RequireScriptHash(owner) RequireWitness(owner) ownerPInfo = _getPlayerInfo(owner) # sign sSign = Get(GetContext(), concat(SIGN_PREFIX, signId)) Require(sSign) sign = Deserialize(sSign) author = sign[0] fissionFactor = sign[1] authorPInfo = _getPlayerInfo(author) # owner sign share Require(not signId in ownerPInfo[2]) param = state(Base58ToAddress(owner), safeHouseAddress, income) res = Invoke(0, OntContract, "transfer", [param]) if res != b'\x01': Notify("createShare error.") return False #paramContract = state(Base58ToAddress(fromAcc), selfContractAddress, 1) #resContract = Invoke(0, OntContract, 'transfer', [paramContract]) income = 0 if referral != '': RequireScriptHash(referral) if referral != owner: referralPInfo = _getPlayerInfo(referral) quota = referralPInfo[2][signId] if quota: delta = quota if quota < income else income SubQuota(referral, referralPInfo, signId, delta) AddShareIncome(referral, referralPInfo, delta) #Notify(referral, "got share income", income, "ONT\n") income -= delta ownerPInfo[2][signId] = Div(Mul(income, fissionFactor), 1000) _savePlayer(owner, ownerPInfo) AddSignIncome(author, authorPInfo, income) #Notify(author, "got sign income", income, "ONT\n") #Notify(owner, "create a share success.\n") return True
def innerWithdraw(toAcct, amount): RequireWitness(Admin) balanceKey = concatkey(BALANCE, toAcct) balance = Get(ctx, balanceKey) if balance < amount: return False _amount = Sub(balance, amount) Put(ctx, balanceKey, _amount) param = state(selfContractAddress, toAcct, amount) res = Invoke(0, OngContract, 'transfer', [param]) if res and res == b'\x01': return amount else: Notify('inner withdraw operation failed') return False
def transferONTFromContract(toacct, amount): """ transfer ONT from contract :param fromacct: :param toacct: :param amount: :return: """ # ONT native contract address contractAddress = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01') param = state(selfAddr, toacct, amount) res = Invoke(0, contractAddress, 'transfer', [param]) if res and res == b'\x01': return True else: return False
def PlayGame(addr, bet_ong_amount, room_id): if CheckWitness(Base58ToAddress(addr)) == False: Notify("not sender") return True if bet_ong_amount < 0: Notify("bet amount is zero") return True if room_id < 0: Notify("falsy room_id") return True room_setting_raw = Get(ctx, room_id) room_setting = Serialize(room_setting_raw) # FIXME if we can convert str into int we're able to check minbet < bet_ong_amount minbet = room_setting["minbet"] # TODO CHECK minbet < bet_ong_amount # issue game_id ctx = GetContext() latest_game_id = Get(ctx, MAX_GAME_ID) new_game_id = latest_game_id + 1 ## if we can convert str -> int (we can set the rate in storage) dealer_rate = 10 #(%) # player deposits bet_ong_amount to contract param = state(Base58ToAddress(addr), selfContractAddress, DECIMAL_FACTOR * bet_ong_amount) res = Invoke(0, OngContractAddress, 'transfer', [param]) # PlayGame(Call Contract Function) ## TODO rename function name into Play ChinciroDiceContract("DiceResult") if res and res == b'\x01': Notify(["PlayGame", room_id, new_game_id]) Notify(["PlayGame", addr, room_id, bet_ong_amount]) return True else: Notify('transfer Ong failed') return False
def migrateContract(code, needStorage, name, version, author, email, description, newReversedContractHash): RequireWitness(Admin) param = state(ContractAddress) totalOngAmount = Invoke(0, ONGAddress, 'balanceOf', param) if totalOngAmount > 0: res = _transferONGFromContact(newReversedContractHash, totalOngAmount) Require(res) revesedContractAddress = Get(GetContext(), LUCKY_CONTRACT_HASH_KEY) params = [ContractAddress] totalLuckyAmount = DynamicAppCall(revesedContractAddress, "balanceOf", params) if totalLuckyAmount > 0: params = [ContractAddress, newReversedContractHash, totalLuckyAmount] res = DynamicAppCall(revesedContractAddress, "transfer", params) Require(res) res = Migrate(code, needStorage, name, version, author, email, description) Require(res) Notify(["Migrate Contract successfully"]) return True