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 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 callOracle(date): _require(CheckWitness(operaterAddress) or CheckWitness(adminAddress)) req = getOracleReq(date) key = _concatKey(OraclePrefix, date) txhash = GetTransactionHash(GetScriptContainer()) Put(ctx, key, txhash) oracleContract('CreateOracleRequest', [req, selfAddr]) Notify([txhash]) return True
def addReferral(toBeReferred, referral): RequireScriptHash(toBeReferred) RequireScriptHash(referral) if CheckWitness(Admin) or CheckWitness(toBeReferred): if not getReferral(toBeReferred): Put(GetContext(), concatKey(PLAYER_REFERRAL_KEY, toBeReferred), referral) Notify(["addReferral", toBeReferred, referral]) return True else: raise Exception("Not allow to reset Referral") else: raise Exception("CheckWitness failed")
def bankerWithdrawDividend(account): # RequireWitness(account) if CheckWitness(account) == False: # bankerWithdrawDividend: Check witness failed!, Notify(["Error", 201]) return 0 # update the banker's dividend and earning updateBankerDividend(account) bankerDividend = getBankerDividend(account) # Require(bankerDividend > 0) if bankerDividend <= 0: # bankerWithdrawDividend: Banker has no dividend Notify(["noDividend", account]) return 0 # Require(_transferONGFromContact(account, bankerDividend)) res = _transferONGFromContact(account, bankerDividend) if res == False: # bankerWithdrawDividend: Transfer dividend to banker failed! Notify(["Error", 202]) return 0 Delete(GetContext(), concatKey(BANKER_DIVIDEND_BALANCE_PREFIX, account)) # update the total ong amount Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONG(), bankerDividend)) Notify( ["bankerWithdrawDividend", getCurrentRound(), account, bankerDividend]) return bankerDividend
def bankerWithdrawEarning(account): # RequireWitness(account) if CheckWitness(account) == False: # bankerWithdrawEarning: Check witness failed!, Notify(["Error", 301]) return 0 updateBankerEarning(account) # update the banker's earning bankerEarning = getBankerEarning(account) # RequireWitness(bankerEarning > 0) if bankerEarning <= 0: # banker's dividend is not greater than 0 Notify(["noEarning", account]) return 0 # Require(_transferONGFromContact(account, bankerEarning)) res = _transferONGFromContact(account, bankerEarning) if res == False: # bankerWithdrawEarning: Transfer ONG failed! Notify(["Error", 302]) return 0 Delete(GetContext(), concatKey(BANKER_EARNING_BALANCE_PREFIX, account)) # update the total ong amount Put(GetContext(), TOTAL_ONG_KEY, Sub(getTotalONG(), bankerEarning)) Notify( ["bankerWithdrawEarning", getCurrentRound(), account, bankerEarning]) return bankerEarning
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 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(acc_from, acc_to, value): """ 转账 :param acc_from: 长度必为20,输入为bytearray :param acc_to: 同上 :param value: 非负整数,1 = 1e-8 ZOU :return: """ if acc_from == acc_to or value == 0: return True if value < 0 or not CheckWitness(acc_from) or len(acc_to) != 20: return False from_key = concat(TRANSFER_PREFIX, acc_from) from_amount = Get(ctx, from_key) if from_amount is None or from_amount < value: return False if from_amount == value: Delete(ctx, from_key) else: Put(ctx, from_key, from_amount - value) to_key = concat(TRANSFER_PREFIX, acc_to) to_amount = Get(ctx, to_key) Put(ctx, to_key, to_amount + value) Notify(['transfer', acc_from, acc_to, value]) 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 takeOwnership(toAcct, assetID): ''' take the approved asset :param toAcct: :param assetID: :return: ''' if CheckWitness(toAcct) == False: return False assetOwner = ownerOf(assetID) if not assetOwner: return False removeUserAsset(assetOwner, assetID) # key = concatkey(concatkey(APPROVE_PREFIX, assetOwner), assetID) key = concatkey(APPROVE_PREFIX, assetID) approver = Get(ctx, key) if approver != toAcct: return False Delete(ctx, key) ownerKey = concatkey(OWNER_OF_ASSET_PREFIX, assetID) Put(ctx, ownerKey, toAcct) newbalance = increaseOwnerBalance(toAcct) addUserAsset(toAcct, assetID, newbalance) Notify(['transfer', assetOwner, toAcct, assetID]) 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 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 _dividendsOf(_account, _includeReferralBonus): Require(CheckWitness(_account)) _divendend = dividendOf(_account) if _includeReferralBonus: return Add(_divendend, referralBalanceOf(_account)) else: return _divendend
def dividendOf(addr): Require(CheckWitness(addr)) value = Get(GetContext(), concat(addr, DIVIDEND_SUFFIX)) if value: return value else: return 0
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 mine(addr,uni): if not CheckWitness(addr): return Error('auth failed') uid=addrToUserId(addr) if uid is None: uid=_regis(addr) u=indexToUser(uid) bH=blockIndex() if bH==0: return Error('not start') b=indexToBlock(bH) if b['type'] == BLOCK_TYPE_OUT: return Error('block is out') key=getBlockKey(uid,bH,uni,bH) saveUidBidKeyToMineState(uid,bH,key,True) isKey=key==b['key'] if isKey: _newBlock() b['miner']=u['addr'] b['type']=BLOCK_TYPE_OUT if transferONG(SELF_CONTRACT,addr,b['bonus']): u['bonus']+=b['bonus'] u['bids'].append(sstr(bH)) saveIndexToBlock(bH,b) pm=concat(sstr(bH),concat('#',concat(sstr(key),concat('#',sstr(isKey))))) u['mt']+=1 u['pm']=pm saveIndexToUser(uid,u) return Success(pm)
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 :return: True means success, False or raising exception means failure. """ if from_acct == to_acct or amount == 0: return True if CheckWitness(from_acct) == False: return False if len(to_acct) != 20 or len(from_acct) != 20: return False if 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',from_acct,to_acct,amount]) 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 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 RunTimeTest(user): Log("11111111") res = CheckWitness(user) Log(res) Notify("Hi BlockChain") Notify("s1", "s2", 1, 2, 3) Log("log message")
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 RegisterDomain(domain_name, owner): msg = concat("RegisterDomain: ", domain_name) Notify(msg) ''' Check if the domain contain . if ture then return false ''' if detectStr(domain_name) == 1: Notify("Domain has incorrect char inside") return False if not CheckWitness(owner): Notify("Owner argument is not the same as the sender") return False context = GetContext() exists = Get(context, domain_name) if exists: Notify("Domain is already registered") return False Put(context, domain_name, owner) msg2 = [domain_name, "is owned by ", owner] Notify(msg2) 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
def Withdraw(address, amount): if len(address) != 20: return False if CheckWitness(address) != True: return False if amount % FACTOR != 0: ErrorNotify(ERROR_TONT_WITHDRAW) return False blakey = concat(BALANCE_PREFIX, address) fromBalance = Get(ctx, blakey) if amount > fromBalance: ErrorNotify(ERROR_BANLANCE) return False ontam = amount / FACTOR constracthash = GetExecutingScriptHash() if transferONT(constracthash, address, ontam): if amount == fromBalance: Delete(ctx, blakey) else: Put(ctx, blakey, fromBalance - amount) Notify(["success", ontam]) return True return False
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 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 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 feedPanda(assetID): ''' feedPanda only recovery the HP loss :param assetID: :return: ''' owner = ownerOf(assetID) if not owner: return False if CheckWitness(owner) == False: return False pdata = Get(ctx, concatkey(ASSET_ID_PREFIX, assetID)) panda = Deserialize(pdata) if panda[ATTRIBUTE_HP] == panda[ATTRIBUTE_HPMAX]: return True else: bamboo = Get(ctx, concatkey(BAMBOO_BALANCE, owner)) if bamboo < 1: return False increaseHP = 10 + abs(getRandom()) % 3 if panda[ATTRIBUTE_HP] + increaseHP >= panda[ATTRIBUTE_HPMAX]: panda[ATTRIBUTE_HP] = panda[ATTRIBUTE_HPMAX] else: panda[ATTRIBUTE_HP] = panda[ATTRIBUTE_HP] + increaseHP Put(ctx, concatkey(ASSET_ID_PREFIX, assetID), Serialize(panda)) return True
def buyBamboo(account, ontcount): if CheckWitness(account) == False: return False if transferONT(account, selfAddr, ontcount): bbBalance = Get(ctx, concatkey(BAMBOO_BALANCE, account)) Put(ctx, concatkey(BAMBOO_BALANCE, account), bbBalance + 10 * ontcount) return True return False
def RequireWitness(witness): """ Checks the transaction sender is equal to the witness. If not satisfying, revert the transaction. :param witness: required transaction sender :return: True if transaction sender or revert the transaction. """ Require(CheckWitness(witness)) return True