def bindAssetHash(fromAssetHash, toChainId, toAssetHash): assert (CheckWitness(Get(GetContext(), OPERATOR_PREFIX))) assert (_addFromAssetHash(fromAssetHash)) Put(GetContext(), concat(ASSET_HASH, concat(fromAssetHash, toChainId)), toAssetHash) curBalance = getBalanceFor(fromAssetHash) Notify(["bindAssetHash", fromAssetHash, toChainId, toAssetHash, curBalance]) return True
def burnToken(account, tokenId, amount): Require(_whenNotPaused()) assert (_onlyCLevel() or isAuthorizedLevel(account)) # make sure the tokenId has been created already Require(_tokenExist(tokenId)) # make sure the amount is legal, which is greater than ZERO balance = balanceOf(account, tokenId) #assert (amount > 0 and amount <= balance) Require(amount <= balance) Require(amount > 0) # update the to account balance if amount == balance: Delete(GetContext(), _concatkey(_concatkey(BALANCE_PREFIX, tokenId), account)) else: Put(GetContext(), _concatkey(_concatkey(BALANCE_PREFIX, tokenId), account), Sub(balance, amount)) # update the total supply _totalSupply = totalSupply(tokenId) if _totalSupply == amount: Delete(GetContext(), _concatkey(TOTAL_SUPPLY_PREFIX, tokenId)) else: Put(GetContext(), _concatkey(TOTAL_SUPPLY_PREFIX, tokenId), Sub(_totalSupply, amount)) # Notify the event to the block chain TransferEvent(account, "", tokenId, amount) 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 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 or amount <= 0: return False if amount == fromBalance: Delete(GetContext(), fromKey) else: Put(GetContext(), fromKey, Sub(fromBalance, amount)) toKey = concatkey(balanceKey, toAcct) toBalance = Get(GetContext(), toKey) Put(GetContext(), toKey, Add(toBalance, amount)) TransferEvent(fromAcct, toAcct, tokenId, amount) return True
def setGP(gpId, gpLimit, price, gpContent): """ :param gpId: token as the identity of gift package :param price: how many ong does this gpId will be sold :param gpLimit: how many gift packages (GP) will be available. :param gpContent: [[tokenId1, amount1], [tokenId2, amount2], ..., [tokenIdN, amountN]] :return: """ RequireWitness(Admin) gpKey = _concatkey(GP_PREFIX, gpId) Require(not Get(GetContext(), gpKey)) gpMap = {"price": price} Require(gpLimit > 0) content = [] # ta means [tokenId_n, amount_n] for ta in gpContent: tokenId = ta[0] amount = ta[1] # make sure the tokenId is legal Require(tokenId >= 1001 and tokenId <= 999999) # make sure the tokenId has been created in property contract <=> name of tokenId is NOT None res = DynamicAppCall(getPropertyReversedHash(), "name", [tokenId]) Require(res) Require(amount > 0) content.append([tokenId, amount]) contentInfo = Serialize(content) gpMap["content"] = contentInfo # put the gp info into the storage Put(GetContext(), _concatkey(GP_PREFIX, gpId), Serialize(gpMap)) # update the left gift package number in storage Put(GetContext(), _concatkey(GP_LEFT_PREFIX, gpId), gpLimit) Notify(["setGP", gpId, gpLimit, price, gpContent]) return True
def sendReqToOracle(jsonIndex, formOrSave): """ call oracle to get format or info of Games, including the, diskId :param jsonIndex: Int :param formOrSave: 0 means to form game, 1 means to save res :return: """ RequireWitness(Operater) req = getOracleReq(jsonIndex) txhash = GetTransactionHash(GetScriptContainer()) if formOrSave == 0: Put(GetContext(), concatKey(SENTREQHASH_FORMGAME_PREFIX, jsonIndex), txhash) elif formOrSave == 1: Put(GetContext(), concatKey(SENTREQHASH_SAVERES_PREFIX, jsonIndex), txhash) else: raise Exception("illegal formOrSame!") # if Get(GetContext(), concatKey(SENTREQHASH_FORMGAME_PREFIX, jsonIndex)): # Put(GetContext(), concatKey(SENTREQHASH_SAVERES_PREFIX, jsonIndex), txhash) # else: # Put(GetContext(), concatKey(SENTREQHASH_FORMGAME_PREFIX, jsonIndex), txhash) res = OracleContract('CreateOracleRequest', [req, Operater]) Notify(["sendReqToOracle", txhash]) return True
def placeBet(address, gameId, diskId, betStatus, ongAmount): RequireWitness(address) # make sure address can place bet, otherwise, raise exception Require(canPlaceBet(gameId)) if ongAmount < getMinBetAmount(): # Error 201: "Please bet more ONG!" Notify(["Error", 201]) return False Require(not getDiskStatus(diskId)) diskIdListInfo = Get(GetContext(), concatKey(GAME_DISKID_LIST_PREFIX, gameId)) if not diskIdListInfo: # Error 202: "diskId Not Exist!" Notify(["Error", 202]) return False diskIdList = Deserialize(diskIdListInfo) # make sure the passing by diskId is legal # Require(_checkInList(diskId, diskIdList)) if _checkInList(diskId, diskIdList) == False: # Error 203: "diskId illegal!" Notify(["Error", 203]) return False # betStatus can only be 0, 1 or 2 if betStatus == TieSide or betStatus == LeftSide or betStatus == RightSide: Require(_transferONG(address, ContractAddress, ongAmount)) else: # Error 204: "betStatus illegal!" Notify(["Error", 204]) return False playersList = getDiskPlayersList(diskId, betStatus) if not _checkInList(address, playersList): # update playersList playersList.append(address) Put( GetContext(), concatKey(concatKey(DISK_BET_PLAYER_LIST_PREFIX, diskId), betStatus), Serialize(playersList)) # update address's bet balance Put( GetContext(), concatKey(concatKey(DISK_PLAYER_BET_BALANCE_PREFIX, diskId), concatKey(address, betStatus)), Add(getDiskBetBalance(diskId, betStatus, address), ongAmount)) # update the disk bet amount Put( GetContext(), concatKey(concatKey(DISK_PLAYERS_BET_AMOUNT_PREFIX, diskId), betStatus), Add(getDiskBetAmount(diskId, betStatus), ongAmount)) Notify(["placeBet", address, gameId, diskId, betStatus, ongAmount]) return True
def init(addr): if len(Get(GetContext(), KeyOwnerAddress)) == 0: Put(GetContext(), KeyOwnerAddress, addr) Notify(["init True"]) return True else: Notify(["init False"]) return False
def cancelChainlinkRequest(sender, requestId, payment, callbackFunctionId, expiration): RequireWitness(sender) oracle = Get(GetContext(), concatKey(PENDING_REQUESTS_PREFIX, requestId)) params = [sender, requestId, payment, GetCallingScriptHash(), callbackFunctionId, expiration] assert (DynamicCallFunction(bytearray_reverse(oracle), "cancelOracleRequest", params)) Delete(GetContext(), concatKey(PENDING_REQUESTS_PREFIX, requestId)) ChainlinkCancelledEvent(requestId) return True
def init(): supply = Get(GetContext(), TOTAL_SUPPLY_KEY) assert (supply == 0) total = TotalSupply * FACTOR Put(GetContext(), TOTAL_SUPPLY_KEY, total) Put(GetContext(), concat(BALANCE_PREFIX, Admin), total) TransferEvent(ZERO_ADDRESS, Admin, total) return True
def fulfill(requestId, price): chainlinkClient = Get(GetContext(), CHAINLINK_CLIENT) assert (DynamicCallFunction( bytearray_reverse(chainlinkClient), 'recordChainlinkFulfillment', [bytearray_reverse(GetCallingScriptHash()), requestId])) Put(GetContext(), CURRENT_PRICE, price) return True
def _updateProfitForDev(profitPorDev): RequireWitness(Operater) dev1Percentage = getDev1Percentage() dev1Share = Div(Mul(profitPorDev, dev1Percentage), 100) Put(GetContext(), concatKey(DEV_PROFIT_PREFIX, Dev1), Add(getDevProfit(Dev1), dev1Share)) Put(GetContext(), concatKey(DEV_PROFIT_PREFIX, Dev2), Add(getDevProfit(Dev2), Sub(profitPorDev, dev1Share))) return True
def deposit(account, ongAmount): RequireWitness(account) Require(_transferONG(account, ContractAddress, ongAmount)) Put(GetContext(), concat("D_ONG", account), getDepositAmount(account) + ongAmount) Put(GetContext(), TOTAL_ONG_KEY, getTotalOng() + ongAmount) Notify(["deposit", account, ongAmount]) return True
def removeFromAssetFromList(index): assert (CheckWitness(Get(GetContext(), OPERATOR_PREFIX))) fahListInfo = Get(GetContext(), FROM_ASSET_LIST_KEY) if not fahListInfo: return True fahList = Deserialize(fahListInfo) fahList.remove(index) Put(GetContext(), FROM_ASSET_LIST_KEY, Serialize(fahList)) Notify(["removeFromAssetFromList", index]) return True
def _transfer(_from, _to, _amount): fromKey = concat(BALANCE_PREFIX, _from) fromBalance = Get(GetContext(), fromKey) assert (_amount <= fromBalance) if _amount == fromBalance: Delete(GetContext(), concat(BALANCE_PREFIX, _from)) else: Put(GetContext(), fromKey, fromBalance - _amount) Put(GetContext(), concat(BALANCE_PREFIX, _to), balanceOf(_to) + _amount) TransferEvent(_from, _to, _amount) return True
def init(link): RequireWitness(OWNER) # inited = Get(GetContext(), INITIALIZED) # if inited: # Notify(["idiot admin, you have initialized the contract"]) # return False # else: Put(GetContext(), INITIALIZED, 1) Put(GetContext(), LINKTOKEN_ADDRESS, link) Notify(["Initialized contract successfully!!!!!!!!"]) return True
def createToken(tokenId, name, symbol): RequireWitness(CEOAddress) Require(not _tokenExist(tokenId)) Require(_checkLegalTokenId(tokenId)) # Put name and symbol in storage Put(GetContext(), _concatkey(NAME_PREFIX, tokenId), name) Put(GetContext(), _concatkey(SYMBOL_PREFIX, tokenId), symbol) # By default, the total supply is zero Notify(["createToken", tokenId, name, symbol]) return True
def setAuthorizedLevel(account): assert (CheckWitness(CEOAddress)) assert (len(account) == 20) isAuthorized = Get(GetContext(), _concatkey(AUTHORIZED_LEVEL_PREFIX, account)) if isAuthorized == "T": Notify(["alreadyInAuthorizedLevel", account]) return True if not isAuthorized: Put(GetContext(), _concatkey(AUTHORIZED_LEVEL_PREFIX, account), "T") Notify(["setAuthorizedLevel", account]) return True
def init(owner, feeCollector, lockProxy): """ owner: address type feeCollector: address receiving fee lockProxy: lockProxy hash """ assert (CheckWitness(owner)) Put(GetContext(), OWNER_KEY, owner) Put(GetContext(), FEE_COLLECTOR_KEY, feeCollector) Put(GetContext(), LOCK_PROXY_KEY, bytearray_reverse(lockProxy)) TransferOwnership("", owner) return True
def addFromAssetFromList(fromAssetHash): assert (CheckWitness(Get(GetContext(), OPERATOR_PREFIX))) fahListInfo = Get(GetContext(), FROM_ASSET_LIST_KEY) fahList = [] if not fahListInfo: fahList.append(fromAssetHash) else: fahList = Deserialize(fahListInfo) fahList.append(fromAssetHash) Put(GetContext(), FROM_ASSET_LIST_KEY, Serialize(fahList)) Notify(["addFromAssetFromList", fromAssetHash]) return True
def StoreHash(args): if len(args) != 1: return False addr = Get(GetContext(), KeyOwnerAddress) assert (len(addr) != 0) assert (CheckWitness(addr)) inputHash = args[0] Put(GetContext(), inputHash, 1) Notify([inputHash]) return True
def _updateDepositState(depositIds): for i in range(len(depositIds)): depositStatusInfo = Get(GetContext(), concatKey(DEPOSIT_PREFIX, depositIds[i])) if depositStatusInfo: depositStatus = Deserialize(depositStatusInfo) assert (depositStatus[3] == 0) depositStatus[3] = 1 depositStatusInfo = Serialize(depositStatus) Put(GetContext(), concatKey(DEPOSIT_PREFIX, depositIds[i]), depositStatusInfo) Notify(['updateDepositState', depositIds[i]]) return True
def addList(listToBeAppend): list1Info = Get(GetContext(), LISTKEY) list1 = Deserialize(list1Info) Notify(["before add, list is ", list1]) for element in listToBeAppend: list1.append(element) list1Info = Serialize(list1) Put(GetContext(), LISTKEY, list1Info) Notify(["after add, list is ", list1]) return list1
def addMap(key, value): map1Info = Get(GetContext(), MAPKEY) map1 = Deserialize(map1Info) Notify(["before add, map is ", map1["key1"], map1["key2"]]) map1[key] = value map1.remove("key1") map1Info = Serialize(map1) Put(GetContext(), MAPKEY, map1Info) Notify(["after add, map is ", map1["key2"], map1[key]]) return True
def transferFrom(spender, from_acct, to_acct, amount): """ spender spends amount of tokens on the behalf of from_acct, spender makes a transaction of amount of tokens from from_acct to to_acct :param spender: :param from_acct: :param to_acct: :param amount: :return: """ assert (len(spender) == 20 and len(from_acct) == 20 and len(to_acct) == 20) assert (CheckWitness(spender)) fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(GetContext(), fromKey) assert (amount <= fromBalance and amount >= 0) approveKey = concat(concat(APPROVE_PREFIX, from_acct), spender) approvedAmount = Get(GetContext(), approveKey) toKey = concat(BALANCE_PREFIX, to_acct) assert (amount <= approvedAmount) if amount == approvedAmount: Delete(GetContext(), approveKey) Put(GetContext(), fromKey, fromBalance - amount) else: Put(GetContext(), approveKey, approvedAmount - amount) Put(GetContext(), fromKey, fromBalance - amount) toBalance = Get(GetContext(), toKey) Put(GetContext(), toKey, toBalance + amount) TransferEvent(from_acct, to_acct, amount) return True
def _addFromAssetHash(fromAssetHash): fahListInfo = Get(GetContext(), FROM_ASSET_LIST_KEY) fahList = [] if len(fahListInfo) == 0: fahList = [fromAssetHash] else: fahList = Deserialize(fahListInfo) # check exist in current list if not _checkExistInList(fromAssetHash, fahList): # 1024 is the maximum length of an array supported in NeoVM if len(fahList) >= 1024: return False fahList.append(fromAssetHash) Put(GetContext(), FROM_ASSET_LIST_KEY, Serialize(fahList)) return True
def oracleRequest(spender, payment, specId, callbackAddress, callbackFunctionId, nonce, dataVersion, data, callFunctionId): onlyLINK() RequireWitness(spender) payment = payment + 0 requestId = sha256(Serialize([callbackAddress, spender, nonce])) assert (not Get(GetContext(), concatKey(COMMITMENTS_PRIFX, requestId))) expiration = GetTime() + EXPIRY_TIME Put(GetContext(), concatKey(COMMITMENTS_PRIFX, requestId), Serialize([payment, callbackAddress, callbackFunctionId, expiration])) OracleRequestEvent(specId, spender, requestId, payment, callbackAddress, callbackFunctionId, expiration, dataVersion, data, callFunctionId) return True
def removeAuthorizedLevel(account): assert (CheckWitness(CEOAddress)) assert (len(account) == 20) authorizedAddressListInfo = Get(GetContext(), AUTHORIZED_ADDRESS_LIST_KEY) assert (authorizedAddressListInfo) authorizedAddressList = Deserialize(authorizedAddressListInfo) assert (_checkInList(account, authorizedAddressList)) index = _findInList(account, authorizedAddressList) # make sure index did exist in authorizedAddressList assert (index < len(authorizedAddressList)) authorizedAddressList.remove(index) Put(GetContext(), AUTHORIZED_ADDRESS_LIST_KEY, Serialize(authorizedAddressList)) Notify(["removeAuthorizedLevel", account]) return True
def sendChainlinkRequestTo(caller, oracle, req, payment): RequireWitness(caller) requestCount = Get(GetContext(), REQUEST_COUNT) requestId = sha256(Serialize([req[1], caller, requestCount])) req[3] = requestCount Put(GetContext(), concatKey(PENDING_REQUESTS_PREFIX, requestId), oracle) ChainlinkRequestedEvent(requestId) link = Get(GetContext(), LINK_ADDRESS) params = [caller, oracle, payment, [SENDER_OVERRIDE, AMOUNT_OVERRIDE, req[0], req[1], req[2], req[3], ARGS_VERSION, req[4], 'oracleRequest']] assert (DynamicCallFunction(bytearray_reverse(link), "transferAndCall", params)) Put(GetContext(), REQUEST_COUNT, requestCount + 1) return True
def updateBreadInfo(childAddress, value): res = CheckWitness(Base58ToAddress(childAddress)) if res: msg = Get(GetContext(), childAddress) if value == msg: state = "finish" Put(GetContext(), childAddress, state) Notify(["updateBreadInfo", childAddress, value, state]) elif value < msg: state = "inProgress" Put(GetContext(), childAddress, msg - value) Notify(["updateBreadInfo", childAddress, value, state]) else: Notify(["Identity wrong"]) return True