def InvestLiquidity(self, params): minShares = params.minShares candidate = params.candidate sp.verify(sp.amount > sp.mutez(0), message="Wrong amount") sp.verify(minShares > sp.nat(0), message="Wrong tokenAmount") tezPerShare = sp.split_tokens(self.data.tezPool, sp.nat(1), self.data.totalShares) sp.verify(sp.amount >= tezPerShare, message="Wrong tezPerShare") sharesPurchased = sp.fst(sp.ediv(sp.amount, tezPerShare).open_some()) sp.verify(sharesPurchased >= minShares, message="Wrong sharesPurchased") tokensPerShare = self.data.tokenPool / self.data.totalShares tokensRequired = sharesPurchased * tokensPerShare share = sp.local("share", self.data.shares.get(sp.sender, 0)).value self.data.shares[sp.sender] = share + sharesPurchased self.data.tezPool += sp.amount self.data.tokenPool += tokensRequired self.data.invariant = sp.split_tokens(self.data.tezPool, self.data.tokenPool, sp.nat(1)) self.data.totalShares += sharesPurchased sp.if self.data.candidates.contains(sp.sender): prevVotes = self.data.votes.get(self.data.candidates[sp.sender], 0) self.data.votes[self.data.candidates[sp.sender]] = abs( prevVotes - share)
def TezToToken(self, recipient: sp.TAddress, tezIn: sp.TNat, minTokensOut: sp.TNat): this = self.data.address sp.verify(tezIn > sp.mutez(0), message="Wrong tezIn") sp.verify(minTokensOut > 0, message="Wrong minTokensOut") fee = sp.fst(sp.ediv(tezIn, self.data.feeRate).open_some()) # TODO: ???? newTezPool = sp.local("newTezPool", self.data.tezPool).value + tezIn tempTezPool = abs(newTezPool - fee) newTokenPool = sp.fst(sp.ediv(sp.local( "newTokenPool", self.data.invariant).value, tempTezPool).open_some()) tokensOut = abs( sp.local("tokensOut", self.data.tokenPool).value - newTokenPool) sp.verify(tokensOut >= minTokensOut, message="Wrong minTokensOut") sp.verify(tokensOut <= self.data.tokenPool, message="Wrong tokenPool") self.data.tezPool = newTezPool self.data.tokenPool = newTokenPool self.data.invariant = sp.split_tokens(newTezPool, newTokenPool, sp.nat(1)) token_contract = sp.contract( sp.TRecord(account_from=sp.TAddress, destination=sp.TAddress, value=sp.TNat), address=self.data.tokenAddress, entry_point="Transfer" ).open_some() sp.transfer(sp.record(account_from=this, destination=recipient, value=tokensOut), sp.mutez(0), token_contract)
def hasWon(self,cycle,range): betsByCycle = self.data.bettors[sp.sender] betAmount = sp.local("betAmount",sp.mutez(0)) betAmount = betsByCycle[cycle].amount totalRewards = sp.local("totalRewards",sp.mutez(0)) totalRewards = sp.split_tokens(self.data.cycleData[cycle].totalAmount , sp.as_nat(sp.fst(self.data.cycleData[cycle].roi)) , sp.as_nat(sp.snd(self.data.cycleData[cycle].roi))) totalRewards = sp.split_tokens(totalRewards , sp.nat(98) , sp.nat(100)) reward = sp.split_tokens(totalRewards , sp.fst(sp.ediv(betAmount , sp.mutez(1)).open_some()) , sp.fst(sp.ediv(self.data.cycleData[cycle].amountByRange[range],sp.mutez(1)).open_some()) ) betsByCycle[cycle].withdrawn=True betsByCycle[cycle].withdrawnAmount = betsByCycle[cycle].amount + reward sp.send(sp.sender , betsByCycle[cycle].amount + reward)
def InitializeExchange(self, params): token_amount = sp.as_nat(params.token_amount) candidate = params.candidate sp.verify(self.data.invariant == sp.mutez(0), message="Wrong invariant") sp.verify(self.data.totalShares == 0, message="Wrong totalShares") sp.verify(((sp.amount > sp.mutez(1)) & ( sp.amount < sp.tez(500000000))), message="Wrong amount") sp.verify(token_amount > sp.nat(10), message="Wrong tokenAmount") self.data.tokenPool = token_amount self.data.tezPool = sp.amount self.data.invariant = sp.split_tokens(self.data.tezPool, self.data.tokenPool, sp.nat(1)) self.data.shares[sp.sender] = sp.nat(1000) self.data.totalShares = sp.nat(1000) token_contract = sp.contract( sp.TRecord(account_from=sp.TAddress, destination=sp.TAddress, value=sp.TNat), address=self.data.tokenAddress, entry_point="Transfer" ).open_some() sp.transfer(sp.record(account_from=sp.sender, destination=self.data.address, value=token_amount), sp.mutez(0), token_contract) self.data.candidates[sp.sender] = candidate self.data.votes[candidate] = sp.as_nat(1000) self.data.delegated = candidate sp.set_delegate(sp.some(candidate))
def DivestLiquidity(self, params): sharesBurned = params.sharesBurned minTez = params.minTez minTokens = params.minTokens sp.verify(sharesBurned > 0, message="Wrong sharesBurned") share = sp.local("share", self.data.shares.get(sp.sender, 0)).value sp.verify(sharesBurned > share, message="Sender shares are too low") self.data.shares[sp.sender] = abs(share - sharesBurned) tezPerShare = sp.split_tokens(self.data.tezPool, sp.nat(1), self.data.totalShares) tokensPerShare = sp.nat(self.data.tokenPool / self.data.totalShares) tezDivested = sp.split_tokens(tezPerShare, sharesBurned, sp.nat(1)) tokensDivested = tokensPerShare * sharesBurned sp.verify(tezDivested >= minTez, message="Wrong minTez") sp.verify(tokensDivested >= minTokens, message="Wrong minTokens") self.data.totalShares -= sharesBurned self.data.tezPool -= tezDivested self.data.tokenPool -= tokensDivested sp.if self.data.totalShares == 0: self.data.invariant = sp.mutez(0)
def redeem(self, params): sp.verify(self.data.balances.contains(sp.sender), message = "Address has no balance") sp.verify(self.data.balances[sp.sender].balance >= params.tokenAmount, message = "Insufficient token balance") period = self.getPeriod() # TODO: needs a concept of minimum holding period xtzBalance = sp.split_tokens(self.data.schedule[period], params.tokenAmount, 1) releasedCollateral = sp.tez(params.tokenAmount) - xtzBalance self.data.freeCollateral += releasedCollateral self.data.balances[sp.sender].balance = sp.as_nat(self.data.balances[sp.sender].balance - params.tokenAmount) sp.send(sp.sender, xtzBalance)
def withdraw(self, params): bal = self.data.withdrawBalances[sp.sender] sp.verify(bal != -1, message = "Account already withdrew") #value has increased due to baking val = sp.split_tokens( sp.balance, abs(bal), self.data.totalTokens) sp.send(sp.sender, val) self.data.withdrawBalances[sp.sender ] = -1 self.data.totalTokens = abs( self.data.totalTokens - abs(bal) )
def withdraw(self, auction_id): sp.set_type(auction_id, sp.TNat) auction = self.data.auctions[auction_id] sp.verify(sp.now>auction.end_timestamp,message=AuctionErrorMessage.AUCTION_IS_ONGOING) token_contract = sp.contract(BatchTransfer.get_type(), auction.token_address, entry_point = "transfer").open_some() sp.if auction.bidder != auction.seller: seller_portion = sp.local("seller_portion", auction.bid_amount) token_address_ledger_key = LedgerKey.make(auction.token_address, auction.token_id) sp.if self.data.token_royalties.contains(token_address_ledger_key): royalty_data = self.data.token_royalties[token_address_ledger_key] royalty_payment = sp.split_tokens(auction.bid_amount, royalty_data.fraction, 1 << 32) seller_portion.value -= royalty_payment sp.if ~self.data.accumulated_royalties.contains(royalty_data.recipient): self.data.accumulated_royalties[royalty_data.recipient] = royalty_payment
def deposit(self, params): sp.verify(sp.amount > sp.mutez(0), message = "Deposit too low") contractbal = sp.ediv(sp.balance, sp.tez(1)) sp.if (contractbal.is_some() ): bal = sp.fst(contractbal.open_some()) val = sp.split_tokens( sp.amount, self.data.totalTokens, bal) _natVal = sp.ediv(val, sp.tez(1)) sp.if (_natVal.is_some() ): natVal = sp.fst(_natVal.open_some()) self.data.withdrawBalances[params] = sp.to_int(natVal) self.data.totalTokens += natVal
def create_certificate(self, params): # 0) verify that lock period is not more than 2 years sp.verify(params.months < 25) # 1) get tez value mintAmount = sp.split_tokens(sp.amount, 100, 100) coins = sp.ediv(mintAmount, sp.mutez(1) ) principal = sp.to_int( sp.fst(coins.open_some()) ) # 2) get timestamp end_time = sp.now.add_days(params.months*30) # 3) calculate payout w = sp.local('w', 1) y = sp.local('y', 0) sp.while y.value < params.months: w.value = 10033*w.value y.value = y.value + 1
def liquidate(self): sp.verify( self.data.owners.contains(sp.sender) & self.data.closed # Must be closed before you can withdraw ) # This should equal the sum of all money ever contributed to contract # Via either people or sales. real_total = sp.balance + self.data.total_liquidated # Calculate your split of the balance based on your equity amount_to_send = sp.local("amount_to_send", sp.mutez(0)) amount_to_send.value = sp.split_tokens( self.data.equity[sp.sender], sp.utils.mutez_to_nat(real_total), sp.utils.mutez_to_nat(self.data.total_contributed) ) - self.data.liquidated_ledger.get(sp.sender, sp.mutez(0)) sp.verify(amount_to_send.value > sp.mutez(0)) sp.if self.data.liquidated_ledger.contains(sp.sender): self.data.liquidated_ledger[sp.sender] += amount_to_send.value
def getCost(self, amount, duration): # calculate actual cost of duration intervals = sp.as_nat(duration) / sp.as_nat(self.data.interval) # validate amount sp.verify(self.checkAmount(amount, intervals), message = "Insufficient payment") return sp.split_tokens(self.data.price, intervals, 1)
def end(self, params): sp.verify(sp.sender == self.data.manager) sp.verify(self.data.hasEnded == False) sp.for candidate in self.data.ballot.keys(): sp.if self.data.ballot[candidate].numberOfVotes != 0: sp.send(candidate, sp.split_tokens(sp.balance, sp.as_nat(self.data.ballot[candidate].numberOfVotes), sp.as_nat(self.data.totalNumberOfVotes)))
def collect(self, amount): sp.verify(sp.sender == self.data.owner, 'Only owner can collect.') max_collect = sp.compute(sp.split_tokens(sp.balance,sp.nat(100),self.data.max_collect_percent)) sp.verify(amount <= max_collect, 'Withdrawal amount exceeds allowed limit.') sp.if (self.data.next_collect.is_some()): sp.verify(sp.some(sp.now) > self.data.next_collect, 'Withdrawal frequency exceeds limit.')
class TezosBettingApp(sp.Contract): def __init__(self, track, hashedSecret): # Race details self.init( # The race track track = track, # The owner owner = sp.none, # Horses on the track horses = {}, # Bets placed bets = {}, # Hashed secret to verify owner hashedSecret = hashedSecret, winnerHorse = 0, winningPool = sp.tez(0) ) @sp.entry_point def changeTrack(self, params): # verify the secret to ensure that # the owner of the contract calls it sp.verify(sp.blake2b(params.secret) == self.data.hashedSecret) # set the owner self.data.track = params.track @sp.entry_point def addOwner(self, params): # verify the secret to ensure that # the owner of the contract calls it sp.verify(sp.blake2b(params.secret) == self.data.hashedSecret) # set the owner self.data.owner = sp.some(sp.sender) @sp.entry_point def addHorse(self, params): # verify the secret to ensure that # the owner of the contract calls it sp.verify(sp.blake2b(params.secret) == self.data.hashedSecret) # Setting types sp.set_type(params.horseId, sp.TInt) sp.set_type(params.horseName, sp.TString) # Adding the horse self.data.horses[params.horseId] = { "horseName": params.horseName } @sp.entry_point def placeBet(self, params): # Setting types sp.set_type(params.betHorseId, sp.TInt) # store the bets details # Note: one bet per participant self.data.bets[sp.sender] = { params.betHorseId: sp.amount } @sp.entry_point def runRace(self, params): # verify the secret to ensure that # the owner of the contract calls it sp.verify(sp.blake2b(params.secret) == self.data.hashedSecret) # select a winner winnerHorse = 1 self.data.winnerHorse = winnerHorse # compute pool of the winning horse sp.for bet in self.data.bets.values(): self.data.winningPool += bet.get(winnerHorse, sp.tez(0)) # Distribute the winning sp.for item in self.data.bets.items(): winningBetAmount = item.value.get(self.data.winnerHorse, sp.tez(0)) sp.if winningBetAmount != sp.tez(0): # split the pool toSend = sp.split_tokens(sp.balance, winningBetAmount, self.data.winningPool) sp.send(item.key, toSend)
from_user = self.ledger_key.make(sp.sender, params.token_id) to_user = self.ledger_key.make(highest_bidder.value.bidder, params.token_id) self.data.ledger[from_user].balance = sp.as_nat( self.data.ledger[from_user].balance - params.nft_amount) sp.if self.data.ledger.contains(to_user): self.data.ledger[to_user].balance += params.nft_amount sp.else: self.data.ledger[to_user] = FA2.Ledger_value.make(params.nft_amount) # transfer bid amount to seller # take out x percentage and send it to admin account # 10% commission commission = sp.split_tokens(highest_bidder.value.bid_value, sp.nat(10), sp.nat(100)) # Transfer xtz to the seller sp.send(sp.sender, highest_bidder.value.bid_value - commission) # Transfer commission to the admin sp.send(self.data.administrator, commission) # return the xtz amount to the rest of the bidders if any sp.for bidder in self.data.bid[params.token_id]: sp.if bidder.bidder != highest_bidder.value.bidder: sp.send(bidder.bidder, bidder.bid_value) del self.data.offer[params.token_id] del self.data.bid[params.token_id]
sp.verify(sp.sender == self.data.nuki) self.data.grace_ended = True sp.send(self.data.host, sp.split_tokens(self.data.rent, 1, 2)) # End of play: Nuki notifies that the flat has been left. # C pays what due at the successful completion of the agreement. # If G has left, or has not entered the flat, H gets all # def End_Of_Rent(self): sp.verify(sp.sender == self.data.nuki) sp.if ( (~ (self.data.active)) | (~ (self.data.in_house)) ): sp.send(self.data.host, sp.balance) sp.if (self.data.refund & self.data.in_house): # H gets 1/4 rent + deposit sp.send(self.data.host, sp.split_tokens(self.data.rent, 1, 4)) sp.send(self.data.host, self.data.h_deposit) # G gets 1/4 rent (refund) + deposit sp.send(self.data.guest, sp.split_tokens(self.data.rent, 1, 4)) sp.send(self.data.guest, self.data.g_deposit) sp.if ( ~(self.data.refund) & self.data.in_house): # H gets the remaining 1/2 rent + deposit sp.send(self.data.host, sp.split_tokens(self.data.rent, 1, 2)) sp.send(self.data.host, self.data.h_deposit) # G gets deposit sp.send(self.data.guest, self.data.g_deposit) self.data.in_house = False # ABORT CONTRACT
def Grace_Period_Ended(self): sp.verify(sp.sender == self.data.nuki) self.data.grace_ended = True sp.send(self.data.host, sp.split_tokens(self.data.rent, 1, 2))
def checkAmount(self, amount, intervals): return sp.split_tokens(self.data.price, intervals, 1) <= amount
self.data.shares[sp.sender] = abs(share - sharesBurned) tezPerShare = sp.split_tokens(self.data.tezPool, sp.nat(1), self.data.totalShares) tokensPerShare = sp.nat(self.data.tokenPool / self.data.totalShares) tezDivested = sp.split_tokens(tezPerShare, sharesBurned, sp.nat(1)) tokensDivested = tokensPerShare * sharesBurned sp.verify(tezDivested >= minTez, message="Wrong minTez") sp.verify(tokensDivested >= minTokens, message="Wrong minTokens") self.data.totalShares -= sharesBurned self.data.tezPool -= tezDivested self.data.tokenPool -= tokensDivested sp.if self.data.totalShares == 0: self.data.invariant = sp.mutez(0) sp.else: self.data.invariant = sp.split_tokens(self.data.tezPool, self.data.tokenPool, sp.nat(1)) sp.if self.data.candidates.contains(sp.sender): prevVotes = self.data.votes.get(self.data.candidates[sp.sender], 0) self.data.votes[self.data.candidates[sp.sender]] = abs( prevVotes - sharesBurned) token_contract = sp.contract( sp.TRecord(account_from=sp.TAddress, destination=sp.TAddress, value=sp.TNat), address=self.data.tokenAddress, entry_point="Transfer" ).open_some() sp.transfer(sp.record(account_from=self.data.address,