def update_score(user_address, score): if len(user_address) == 34: user_address = Base58ToAddress(user_address) assert (len(user_address) == 20 and user_address != ZERO_ADDRESS) user_name = Get(ctx, concat(user_address, USER_KEY)) if not user_name: raise Exception("username not exist") assert (CheckWitness(user_address)) Put(ctx, concat(user_address, SCORE_KEY), score) updateScoreEvent(user_address, user_name, score) return True
def mintToken(mintAcct, toAcct, tokenId, amount): assert (CheckWitness(mintAcct)) assert (_whenNotPaused()) assert (_onlyCLevel() or isAuthorizedLevel(mintAcct)) # make sure the to address is legal assert (len(toAcct) == 20) # make sure the tokenId has been created already assert (_tokenExist(tokenId)) # make sure the amount is legal, which is greater than ZERO assert (amount > 0) # update the to account balance Put(GetContext(), _concatkey(_concatkey(BALANCE_PREFIX, tokenId), toAcct), balanceOf(toAcct, tokenId) + amount) # update the total supply Put(GetContext(), _concatkey(TOTAL_SUPPLY_PREFIX, tokenId), totalSupply(tokenId) + amount) # make sure the total supply is not greater than 1 billion assert (totalSupply(tokenId) <= 10000000000) # Notify the event to the block chain TransferEvent("", toAcct, tokenId, amount) # Notify(["transfer", "", toAcct, tokenId, amount]) return True
def bind(ont_id, account): """ bind ontID with address :param ont_id: :param account: ontid owner wallet address :return: """ assert CheckWitness(account) bound_ont_id = Get(ctx, concat(KEY_ACCOUNT, account)) if bound_ont_id == ont_id: raise Exception("account bind to the same ont id") Put(ctx, concat(KEY_ACCOUNT, account), ont_id) Put(ctx, concat(KEY_ONT_ID, ont_id), account) stat(1) Notify(["bind", ont_id, account]) return True
def depositOng(account, amount): """ :param account: the account who wants to deposit ont into the contract. :param amount: the amount of ong. If you want to deposit 1 ONG, you need to pass amount as 1 * 10 ** 9. :return: """ assert (CheckWitness(account)) assert (_transferONG(account, SelfContractAddr, amount)) Put(GetContext(), _concatKey(ONG_BALANCE_PREFIX, account), getOngBalance(account) + amount) Notify(["depositOng", account, amount]) 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 bindValue(fulldomain, idx, ctype, inputvalue): ''' bindValue to domain ''' owner = ownerOf(fulldomain) assert (_verifyOntid(owner, idx)) assert (isDomainValid(fulldomain)) value = [ctype, inputvalue] lowerdomain = lower(fulldomain) Put(ctx, _concatkey(VALUE_KEY, lowerdomain), Serialize(value)) BindValueEvent(lowerdomain, ctype, inputvalue) return True
def addAdmin(Account): """ :param Account: new admin's address :return: """ RequireWitness(Owner) adminList = Get(context, ADMIN_ADDRESS_KEY) adminList = Deserialize(adminList) adminList.append(Account) Put(context, ADMIN_ADDRESS_KEY, Serialize(adminList)) Notify(["Now admin address is", adminList]) return True
def init(): """ initialize the contract, put some important info into the storage in the blockchain :return: """ if len(OWNER) != 20: Notify(["Owner illegal!"]) return False if Get(ctx,SUPPLY_KEY): Notify("Already initialized!") return False else: total = TOTAL_AMOUNT * FACTOR Put(ctx,SUPPLY_KEY,total) Put(ctx,concat(BALANCE_PREFIX,OWNER),total) # Notify(["transfer", "", Base58ToAddress(OWNER), total]) # ownerBase58 = AddressToBase58(OWNER) TransferEvent("", OWNER, total) return True
def endGame(gameId, salt): """ send game id and salt to :param gameId: game's id :param salt: salt number :return: bool """ assert (CheckWitness(Admin)) # set salt Put(GetContext(), concatKey(gameId, GAME_SALT_KEY), salt) Notify(["endGame", gameId, salt]) return True
def transferOwnership(newOwner): """ transfer contract ownership from current owner to new owner account. :param newOwner: new smart contract owner. :return:True or raise exception. """ assert (isAddress(newOwner)) assert (CheckWitness(getOwner())) Put(ctx, OWNER_KEY, newOwner) TransferOwnerEvent(getOwner(), newOwner) return True
def setSupplyController(address): """ Set new supply controller account. :param address: new supply controller account. :return: """ assert (isAddress(address)) assert (CheckWitness(getSupplyController())) Put(ctx, SUPPLY_CONTROLLER_KEY, address) SetSupplyControllerEvent(address) return True
def setAuthorizedLevel(account): RequireWitness(CEOAddress) Require(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 freeze(address): """ Freeze specific acccount, it will not be traded unless it will be unfreez. :param address: Frozen account. :return:True or raise exception. """ assert (isAddress(address)) assert (CheckWitness(getEnforcementRole())) Put(ctx, concat(FROZEN_PREFIX, address), True) FrozenEvent(address) return True
def init(): if Get(ctx, BETKEY): Notify(['Already initialized']) return False else: BETID = 1 Put(ctx, BETKEY, BETID) Notify(['BETID inited']) aes_amount = 10000 * AES_FACTOR subtract_bank(token_owner, aes_amount) Put(ctx, AESKEY, aes_amount) Notify(['AES transferred to contract']) ong_amount = 1000 * ONG_FACTOR subtract_ong(token_owner, ong_amount) Put(ctx, ONGKEY, ong_amount) Notify(['ONG transferred to contract']) Notify(['Successfully inited']) return True
def sendReqToOracle(jsonIndex): """ call oracle to get format or info of Games, including the, diskId :param jsonIndex: Int :return: """ RequireWitness(Operater) req = getOracleReq(jsonIndex) txhash = GetTransactionHash(GetScriptContainer()) 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 delegateToProxy(proxyReversedHash, amount): """ initialize the contract, put some important info into the storage in the blockchain :return: """ assert (CheckWitness(Operator)) storedProxy = getProxyHash() if not storedProxy: Put(ctx, PROXY_HASH_KEY, proxyReversedHash) maxS = MaxSupply * FACTOR Put(ctx, SUPPLY_KEY, maxS) Put(ctx, concat(BALANCE_PREFIX, SelfContractAddress), maxS) TransferEvent("", proxyReversedHash, maxS) else: assert (proxyReversedHash == storedProxy) assert(_transfer(SelfContractAddress, proxyReversedHash, amount)) 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: """ if len(spender) != 20 or len(from_acct) != 20 or len(to_acct) != 20: raise Exception("Address length error") if CheckWitness(spender) == False: return False fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) if amount > fromBalance: return False approveKey = concat(concat(APPROVE_PREFIX,from_acct),spender) approvedAmount = Get(ctx,approveKey) toKey = concat(BALANCE_PREFIX,to_acct) toBalance = Get(ctx, toKey) if amount > approvedAmount: return False elif amount == approvedAmount: Delete(ctx,approveKey) Put(ctx, fromKey, fromBalance - amount) else: Put(ctx,approveKey,approvedAmount - amount) Put(ctx, fromKey, fromBalance - amount) Put(ctx, toKey, toBalance + amount) # Notify(["transfer", AddressToBase58(from_acct), AddressToBase58(to_acct), amount]) # TransferEvent(AddressToBase58(from_acct), AddressToBase58(to_acct), amount) TransferEvent(from_acct, to_acct, amount) return True
def vote(bet, address, amount_staked, for_against): assert (CheckWitness(address)) # check if active bet list is populated/exists assert (check_bet_status(bet) == 1) assert (user_exist(address)) assert (for_against == False or for_against == True) if not get_voter_staked_amount(bet, address, for_against): Put( ctx, concatkey(bet, concatkey(address, concatkey(for_against, VOTE_PREFIX))), amount_staked) bet_voters = get_bet_voters(bet, for_against) Put(ctx, concatkey(bet, concatkey(for_against, BET_VOTERS_LIST)), Serialize(bet_voters.append(address))) versa_bet_voters = get_bet_voters(bet, 1 - for_against) assert (len(bet_voters) + len(versa_bet_voters) <= VOTES_PER_BET) else: Put( ctx, concatkey(bet, concatkey(address, concatkey(for_against, VOTE_PREFIX))), get_voter_staked_amount(bet, address, for_against) + amount_staked) bet_content_info = Get( ctx, concatkey(bet, concatkey(for_against, BET_CONTENT_PREFIX))) bet_content = Deserialize(bet_content_info) bet_content["reputation"] += get_user_repution(address) bet_content["count"] += 1 bet_content["staked"] += amount_staked Put(ctx, concatkey(bet, concatkey(for_against, BET_CONTENT_PREFIX)), Serialize(bet_content)) assert (deposit(address, amount_staked)) Notify(["vote", bet, address, amount_staked, for_against]) return True
def transferFrom(spender, from_address, to_address, amount): """ The spender address sends amount of tokens from the from_address to the to_address :param spender: The address sending the funds :param from_address: The address whose funds are being sent :param to_address: The receiving address :param amount: The amounts of tokens being transferred Returns True on success, otherwise raises an exception """ RequireIsAddress(spender) RequireIsAddress(from_address) RequireIsAddress(to_address) RequireWitness(spender) Require(amount >= 0) fromKey = getBalanceKey(from_address) fromBalance = Get(ctx, fromKey) Require(amount <= fromBalance) approveKey = getApprovalKey(from_address, spender) approvedAmount = Get(ctx, approveKey) Require(amount <= approvedAmount) if amount == approvedAmount: Delete(ctx, approveKey) else: Put(ctx, approveKey, approvedAmount - amount) if amount == fromBalance: Delete(ctx, fromKey) else: Put(ctx, fromKey, fromBalance - amount) toKey = getBalanceKey(to_address) toBalance = Get(ctx, toKey) Put(ctx, toKey, toBalance + amount) TransferEvent(from_address, to_address, amount) 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(to_acct) == 20) assert (len(from_acct) == 20) assert (len(spender) == 20) assert (amount >= 0) assert (CheckWitness(spender)) fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) assert (fromBalance >= amount) approveKey = concat(concat(APPROVE_PREFIX, from_acct), spender) approvedAmount = Get(ctx, approveKey) toKey = concat(BALANCE_PREFIX, to_acct) assert (approvedAmount >= amount) if amount == approvedAmount: Delete(ctx, approveKey) Put(ctx, fromKey, fromBalance - amount) else: Put(ctx, approveKey, approvedAmount - amount) Put(ctx, fromKey, fromBalance - amount) toBalance = Get(ctx, toKey) Put(ctx, toKey, toBalance + amount) TransferEvent(from_acct, to_acct, amount) return True
def init(): """ initialize the contract, put some important info into the storage in the blockchain :return: """ if len(OWNER) != 20: Notify(["Owner illegal!"]) return False if len(CONTRACT_ADDRESS) != 20: Notify(["Owner illegal!"]) return False if Get(ctx, SUPPLY_KEY): Notify("Already initialized!") return False else: total = TOTAL_AMOUNT * FACTOR Put(ctx, SUPPLY_KEY, total) Put(ctx, concat(BALANCE_PREFIX, CONTRACT_ADDRESS), total) TransferEvent("", CONTRACT_ADDRESS, total) return True
def SetOracleOutcome(txHash, data, status, errMessage): #check witness syncAddress = Get(GetContext(), SyncAddress) Require(len(syncAddress) == 20) RequireWitness(syncAddress) #get undoRequest map undoRequestMap = GetUndoRequestMap() #TODO : check if key exist #put result into storage result = state(data, status, errMessage) r = Serialize(result) Put(GetContext(), txHash, r) #remove txHash from undoRequest map undoRequestMap.remove(txHash) b = Serialize(undoRequestMap) Put(GetContext(), UndoRequestKey, b) Notify(["setOracleOutcome", txHash, status, errMessage]) 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 checkIn(player): """ check in function :param account: player's account addresss :return: bool """ assert (CheckWitness(player)) checkInDays = ifCheckIn(player) assert (checkInDays) Put(GetContext(), concatKey(PLAYER_LAST_CHECK_IN_DAY, player), checkInDays) Notify(["checkIn", player, checkInDays]) return True
def _transfer(from_acct, to_acct, amount): assert (len(to_acct) == 20) assert (len(from_acct) == 20) assert (amount > 0) fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) assert (fromBalance >= amount) 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) TransferEvent(from_acct, to_acct, amount) return True
def burnToken(account, tokenId, amount): assert (_whenNotPaused()) assert (_onlyCLevel() or isAuthorizedLevel(account)) # make sure the tokenId has been created already assert (_tokenExist(tokenId)) # make sure the amount is legal, which is greater than ZERO balance = balanceOf(account, tokenId) assert (amount > 0 and amount <= balance) # 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), 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), _totalSupply - amount) # Notify the event to the block chain TransferEvent(account, "", tokenId, amount) return True
def init(): assert (not Get(ctx, BETKEY)) BETID = 1 Put(ctx, BETKEY, BETID) aes_amount = 10000 * AES_FACTOR assert (deposit(token_owner, aes_amount)) ong_amount = 1000 * ONG_FACTOR assert (deposit_ong(token_owner, ong_amount)) Notify(['Successfully inited']) return True
def transfer(from_acct, to_acct, amount): if not CheckWitness(from_acct): return False fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) # 检测转账余额是否满足要求 VaasAssert(amount > 0) VaasAssert(fromBalance >= amount) 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) TransferEvent(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. """ require( len(to_acct) == 20 and len(from_acct) == 20, "address length error") require(CheckWitness(from_acct) == True, "Invalid invoker") require(amount > 0, "Invalid Amount") whenNotPaused() requireNotFreeze(from_acct) requireNotFreeze(to_acct) # if from_acct has lockinfo, it will be unlock autoUnlock(from_acct) fromKey = concat(BALANCE_PREFIX, from_acct) fromBalance = Get(ctx, fromKey) require(amount <= fromBalance, "Not enough balance") 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) TransferEvent(from_acct, to_acct, amount) 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