def _currentPrice(_auction): secondsPassed = 0 if GetTime() > _auction['startedAt']: secondsPassed = Sub(GetTime(), _auction['startedAt']) return _computeCurrentPrice(_auction['startingPrice'], _auction['endingPrice'], _auction['duration'], secondsPassed)
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 migrateContract(code, needStorage, name, version, author, email, description): assert (CheckWitness(adminAddress)) res = Migrate(code, needStorage, name, version, author, email, description) assert (res) Notify(["migrateContract", adminAddress, GetTime()]) return True
def registerDomain(fulldomain, registerdid, idx, validto): ''' register domain fulldomain: domain string registerdid: register ontid idx:owner walletid validto : valid period ''' currenttime = GetTime() if validto > 0: assert (validto > currenttime) assert (len(fulldomain) > 0) _validateDNSName(fulldomain) lowerdomain = lower(fulldomain) assert (not ownerOf(lowerdomain)) _checkParentAuth(lowerdomain, idx) Put(ctx, _concatkey(OWNER_KEY, lowerdomain), registerdid) Put(ctx, _concatkey(VALID_KEY, lowerdomain), validto) recordskey = _concatkey(RECORDS_KEY, registerdid) records = Get(ctx, recordskey) if not records: records = [lowerdomain] else: records = Deserialize(records) records.append(lowerdomain) assert (len(records) <= MAX_COUNT) Put(ctx, recordskey, Serialize(records)) RegisterDomainEvent(lowerdomain, registerdid, validto) return True
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 canPlaceBet(gameId): """ :param gameId: :return: False means can NOT place bets, True means CAN place bets. """ return GetTime() < Get(GetContext(), concatKey(GAME_BET_ENDTIME_PREFIX, gameId))
def checkIn(address, userId): assert (CheckWitness(address)) checkInDays = canCheckIn(address) assert (checkInDays > 0) Put(GetContext(), concat(PLAYER_LAST_CHECK_IN_DAY, address), checkInDays) Notify(["checkIn", address, userId, GetTime()]) return True
def preWithdraw(address, amount, ongOrOnt, userId): assert (CheckWitness(address)) assert (amount > 0) assert (ongOrOnt == 1 or ongOrOnt == 0) asset = "ONG" if ongOrOnt == 0: asset = "ONT" Notify(["preWithdraw", address, amount, asset, GetTime(), userId]) return True
def Main(opration, args): if opration == "hash": time = GetTime() height = GetHeight() header = GetHeader(height) a = args[0] / abs(GetBlockHash(header)) a = a / abs(time) now_hash = GetBlockHash(header) a = a % abs(now_hash) return a return False
def withdraw(to, amount, ongOrOnt): assert (CheckWitness(Admin)) assert (ongOrOnt == 1 or ongOrOnt == 0) asset = "ONG" nativeAssetHash = ONGAddress if ongOrOnt == 0: asset = "ONT" nativeAssetHash = ONTAddress assert (_transferNativeAsset(nativeAssetHash, SelfContractAddress, to, amount)) Notify(["withdraw", to, amount, asset, GetTime()]) return True
def createAuction(_caller, _tokenId, _startingPrice, _endingPrice, _duration, _seller): Require(_onlyDragonCore(_caller)) Require(_startingPrice >= 0) Require(_endingPrice >= 0) Require(_duration >= 0) auction = { 'seller': _seller, 'startingPrice': _startingPrice, 'endingPrice': _endingPrice, 'duration': _duration, 'startedAt': GetTime() } return _addAuction(_tokenId, auction)
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 ifCheckIn(player): """ :param player: player's account address :return: return == False => can NOT check in. return > now days => can check in. """ lastTimeCheckIn = Get(GetContext(), concatKey(PLAYER_LAST_CHECK_IN_DAY, player)) now = Add(GetTime(), Mul(8, 3600)) # to UTC8 days = Div(now, DaySeconds) if not lastTimeCheckIn: return days if days > lastTimeCheckIn: return days else: return False
def createExchange(token_hash): # Ensure token is a contract with nonzero contract hash assert (token_hash != ZERO_ADDRESS and len(token_hash) == 20) # Ensure templateCode existgetExchange templateScript = Get(GetContext(), EXCHANGE_TEMPLATE_KEY) assert (len(templateScript) > 0) # Make sure the token_hash has not been used to create exchange before assert (len(getExchange(token_hash)) == 0) tokenCount = Get(GetContext(), TOKEN_COUNT_KEY) # Append unused byte code to avm code to produce different contract hash, yet same executable opcode newTokenCount = tokenCount + 1 templateScript = concat( templateScript, concat( concat(concat(GetExecutingScriptHash(), GetCurrentBlockHash()), GetTime()), newTokenCount)) # Deploy replica contract assert (Create( templateScript, True, "uniswap_exchange", "1.0", "uniswap_factory", "email", "uniswap_exchange contract created by uniswap_factory contract")) # Invoke the newly deployed contract to set up the token exchange pair exchangeHash = AddressFromVmCode(templateScript) exchangeAddr = bytearray_reverse(exchangeHash) tokenAddr = bytearray_reverse(token_hash) assert (DynamicAppCall(exchangeAddr, "setup", [tokenAddr, GetExecutingScriptHash()])) # Store the map between token and exchange contract hash Put(GetContext(), concat(TOKEN_TO_EXCHANGE_PREFIX, token_hash), exchangeAddr) Put(GetContext(), concat(EXCHANGE_TO_TOKEN_PREFIX, exchangeHash), tokenAddr) # Add the token count Put(GetContext(), TOKEN_COUNT_KEY, newTokenCount) # Map token with token id Put(GetContext(), concat(ID_TO_TOKEN_PREFIX, newTokenCount), tokenAddr) # Fire the event NewExchangeEvent(tokenAddr, exchangeAddr) return True
def migrateContract(code, needStorage, name, version, author, email, description): RequireWitness(Admin) # == Please Make sure transfer all the asset within the old contract to the new Contract # == If you do not transfer the assets including ONG, ONT, or OEP4 out, # == that means these assets will be out of your control for good. newReversedContractHash = AddressFromVmCode(code) 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 cancelOracleRequest(sender, requestId, payment, callbackAddress, callbackFunctionId, expiration): RequireWitness(sender) expiration = expiration + 0 payment = payment + 0 paramsHash = Serialize( [payment, callbackAddress, callbackFunctionId, expiration]) originParamsHash = Get(GetContext(), concatKey(COMMITMENTS_PRIFX, requestId)) assert (paramsHash == originParamsHash) assert (expiration <= GetTime()) Delete(GetContext(), concatKey(COMMITMENTS_PRIFX, requestId)) assert (_transferLinkFromContact(bytearray_reverse(getChainLinkToken()), callbackAddress, payment)) return True
def check_bet_status(betId): """ :param betId: :return: 0 means doesn't exist, 1 means created and user can vote, 2 means voting period ends yet not pay out, 3 means end and payout. """ active_res = Get(ctx, concatkey(betId, ACTIVE_BET_PREFIX)) if not active_res: return 0 if GetTime() <= get_vote_end_time(betId): return 1 else: if active_res != 3: return 2 return active_res
def autoUnlock(account): now = GetTime() KEY_lockCount = concat(USER_LOCK_CNT_PREFIX, account) lockCount = Get(ctx, KEY_lockCount) if lockCount > 0: i = 0 while i < lockCount: lockInfo = getLockState(account, i) deserializeUserLock = Deserialize(lockInfo) releaseTime = deserializeUserLock['releaseTime'] Notify([releaseTime]) if releaseTime <= now: if unlock(account, i): i -= 1 lockCount -= 1 i += 1 return True
def deposit(address, amount, ongOrOnt, userId): """ :param userId: :param address: :param amount: Depositing ONG, amount = 1 * 10^9 when we want to transfer ONG. Depositing ONT, amount = 1 when we want to transfer ONT. :param ongOrOnt: 0 means ONT, 1 means ONG :return: """ assert (CheckWitness(address)) assert (amount > 0) assert (ongOrOnt == 1 or ongOrOnt == 0) asset = "ONG" nativeAssetHash = ONGAddress if ongOrOnt == 0: asset = "ONT" nativeAssetHash = ONTAddress assert (_transferNativeAsset(nativeAssetHash, address, SelfContractAddress, amount)) Notify(["deposit", address, amount, asset, GetTime(), userId]) return True
def teamRelease(): assert (CheckWitness(OWNER)) now = GetTime() index = 0 tryRelease = True while tryRelease == True and index < len(TEAMLOCK_END): if now > TEAMLOCK_END[index]: if not getReleaseHash(TEAMLOCK_END[index]): # Release token to team assert (_transfer(SELF_ADDRESS, TEAM_ADDRESS, TEAMCAP_AMOUNT[index] * FACTOR)) txHash = bytearray_reverse( GetTransactionHash(GetScriptContainer())) Put(GetContext(), concat(UNLOCK_HASH_PERFIX, TEAMLOCK_END[index]), txHash) ReleaseEvent(txHash) index += 1 else: tryRelease = False return True
def isDomainValid(fulldomain): ''' get domain is valid ''' currenttime = GetTime() lowerdomain = lower(fulldomain) validto = validTo(lowerdomain) if not validto: return False else: if validto > 0: return validto >= currenttime parent = _getParentDomain(lowerdomain) if len(parent) == 0: if validto == -1: return True else: return isDomainValid(parent) else: return isDomainValid(parent)
def TokenTransferFrom(exchangeId, order): """ :param exchangeId:exchange id, Invoked only by registered exchange :param order: the order is a map structure. :return:True or false, if success, the maker and taker will get purpose token. """ expireTime = order['expireTime'] require(GetTime() <= expireTime, "order expired") require(CheckWitness(exchangeId), "invalid exchange") if not Get(ctx, concatKey(EXCHANGE_ID_PREFIX, exchangeId)): return False maker = order['makerAddress'] makerAmount = order['makerAssetAmount'] makerHash = order['makerTokenHash'] taker = order['takerAddress'] takerAmount = order['takerAssetAmount'] takerHash = order['takerTokenHash'] makerFee = order['makerFee'] takerFee = order['takerFee'] feeTokenHash = order['feeTokenHash'] feeFeceiver = order['feeReceiver'] if isNativeAsset(makerHash): require( transferFromNative(makerHash, ContractAddress, maker, taker, makerAmount), "transfer from maker asset failed") else: require( DynamicAppCall(bytearray_reverse(makerHash), "transferFrom", [ContractAddress, maker, taker, makerAmount]), "transfer maker token to taker failed") Notify("111") if isNativeAsset(takerHash): require( transferFromNative(takerHash, ContractAddress, taker, maker, takerAmount), "transfer from taker asset failed") else: require( DynamicAppCall(bytearray_reverse(takerHash), "transferFrom", [ContractAddress, taker, maker, takerAmount]), "transfer taker token to maker failed") Notify("222") if isNativeAsset(feeTokenHash): require( transferFromNative(feeTokenHash, ContractAddress, maker, feeFeceiver, makerFee), "charge maker fee failed") require( transferFromNative(feeTokenHash, ContractAddress, taker, feeFeceiver, takerFee), "charge taker fee failed") else: require( DynamicAppCall(bytearray_reverse(feeTokenHash), "transferFrom", [ContractAddress, maker, feeFeceiver, makerFee]), "charge maker fee failed") require( DynamicAppCall(bytearray_reverse(feeTokenHash), "transferFrom", [ContractAddress, taker, feeFeceiver, takerFee]), "charge taker fee failed") Notify("success") return True