Application of Waves smart accounts: from auctions to bonus programs

Application of Waves smart accounts: from auctions to bonus programs

Blockchain is often associated only with cryptocurrencies, but the scope of DLT technology is much wider. One of the most promising areas for the use of blockchain is a smart contract that is executed automatically and does not require trust between the parties that have concluded it.

RIDE is a language for smart contracts

Waves has developed a special language for smart contracts - RIDE. Its complete documentation is here. And here - article on this topic on Habr.

The RIDE contract is a predicate and returns "true" or "false" as output. Accordingly, the transaction is either recorded in the blockchain or rejected. A smart contract fully guarantees the fulfillment of the specified conditions. It is currently not possible to generate transactions from a contract in RIDE.

There are currently two types of Waves smart contracts: smart accounts and smart assets. A smart account is a regular user account, but a script is set for it that controls all transactions. The smart account script might look like this:

match tx {
  case t: TransferTransaction | MassTransferTransaction => false
  case _ => true
}

tx is a processing transaction that we resolve using the pattern matching mechanism only if it is not a transfer transaction. Pattern matching in RIDE is used to check the type of a transaction. In the smart account script, all existing transaction types.

Variables can also be declared in the script, β€œif-then-else” constructions and other methods of fully checking conditions can be used. In order for contracts to have provable termination and complexity (cost) that is easy to predict before the contract is executed, RIDE does not contain loops and jump statements.

Among other features of Waves accounts is the presence of a "state", that is, the state of the account. An infinite number of pairs (key, value) can be written to the account state using data transactions (DataTransaction). Further, this information can be processed both through the REST API and directly in the smart contract.

Each transaction can contain an array of proofs, in which you can enter the signature of the participant, the ID of the required transaction, etc.

Working with RIDE via IDE allows you to see the compiled view of the contract (if it is compiled), create new accounts and set scripts for it, as well as send transactions via the command line.

For a complete cycle, including creating an account, installing a smart contract on it and sending transactions, you can also use the library to interact with the REST API (for example, C#, C, Java, JavaScript, Python, Rust, Elixir). To start working with the IDE, just click the NEW button.

The possibilities of using smart contracts are wide: from prohibiting transactions to certain addresses (β€œblack list”) to complex dApps.

Now let's look at specific examples of the use of smart contracts in business: when conducting auctions, insurance, and creating loyalty programs.

Auctions

One of the conditions for a successful auction is transparency: participants must be sure that bids cannot be manipulated. This can be achieved thanks to the blockchain, where immutable data about all bets and the time when they were made will be available to all participants.

On the Waves blockchain, bids can be written to the state of the auction account via a DataTransaction.

You can also set the start and end time of the auction using block numbers: the block generation frequency in the Waves blockchain is approximately equal to 60 seconds.

1. English rising price auction

Participants in the English auction make bids, competing with each other. Each new rate must exceed the previous one. The auction ends when there are no more willing to exceed the last bid. In this case, the participant who made the highest bid must provide the declared amount.

There is also an auction option in which the seller sets the minimum price for the lot, and the final price must exceed it. Otherwise, the lot remains unsold.

In this example, we are working with an account specifically created for running an auction. The duration of the auction is 3000 blocks, and the initial price of the lot is 0,001 WAVES. A participant can place a bid by sending a DataTransaction with the key "price" and the value of their bid.

The price of the new bid must be higher than the current price for this key, and the participant must have at least [new_bid + commission] tokens in the account. The participant's address must be written in the "sender" field in the DataTransaction, and the current height of the bid block must be within the boundaries of the auction period.

If at the end of the auction the participant has set the highest price, he can send an ExchangeTransaction to pay for the corresponding lot at the specified price and currency pair.

let startHeight = 384120
let finishHeight = startHeight + 3000
let startPrice = 100000
 
#ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ адрСс отправитСля
let this = extract(tx.sender)
let token = base58'8jfD2JBLe23XtCCSQoTx5eAW5QCU6Mbxi3r78aNQLcNf'
 
match tx {
case d : DataTransaction =>
  #провСряСм, Π·Π°Π΄Π°Π½Π° Π»ΠΈ Π² стСйтС Ρ†Π΅Π½Π°
  let currentPrice = if isDefined(getInteger(this, "price"))
 
                      #ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Ρ†Π΅Π½Ρƒ ΠΈΠ· стСйта
                      then extract(getInteger(this, "price"))
                      else startPrice
 
  #ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Ρ†Π΅Π½Ρƒ ΠΈΠ· Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ
  let newPrice = extract(getInteger(d.data, "price"))
  let priceIsBigger = newPrice > currentPrice
  let fee = 700000
  let hasMoney = wavesBalance(tx.sender) + fee >= newPrice
 
  #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π² Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π΄Π²Π° поля ΠΈ Ρ‡Ρ‚ΠΎ ΠΎΡ‚ΠΏΡ€Π°Π²ΠΈΡ‚Π΅Π»ΡŒ совпадаСт с ΡƒΠΊΠ°Π·Π°Π½Π½Ρ‹ΠΌ Π² Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ
  let correctFields = size(d.data) == 2 &&      
      d.sender == addressFromString(extract(getString(d.data,"sender")))
  startHeight <= height && height <= finishHeight && priceIsBigger && hasMoney && correctFields
case e : ExchangeTransaction =>
  let senderIsWinner = e.sender == addressFromString(extract(getString(this, "sender"))) #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π»ΠΎΡ‚ ΠΎΠ±ΠΌΠ΅Π½ΠΈΠ²Π°Π΅Ρ‚ Ρ‚ΠΎΡ‚, ΠΊΡ‚ΠΎ Π΅Π³ΠΎ Π²Ρ‹ΠΈΠ³Ρ€Π°Π»
  let correctAssetPair = e.sellOrder.assetPair.amountAsset == token && ! isDefined(e.sellOrder.assetPair.priceAsset)
  let correctAmount = e.amount == 1
  let correctPrice = e.price == extract(getInteger(this, "price"))
 
  height > finishHeight && senderIsWinner && correctAssetPair && correctAmount && correctPrice
case _ => false
}

2. Dutch Declining Price Auction

In a Dutch auction, a lot is initially offered at a price higher than what the buyer is willing to pay. The price is reduced step by step until one of the participants agrees to buy the lot at the current price.

In this example, we use the same constants as in the previous one, as well as the price step when delta falls. The account script checks if the participant is indeed the first to place a bet. Otherwise, the DataTransaction is not accepted by the blockchain.

let startHeight = 384120
let finishHeight = startHeight + 3000
let startPrice = 100000000
let delta = 100
 
#ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ адрСс отправитСля
let this = extract(tx.sender)
let token = base58'8jfD2JBLe23XtCCSQoTx5eAW5QCU6Mbxi3r78aNQLcNf'
match tx {
case d : DataTransaction =>
  let currentPrice = startPrice - delta * (height - startHeight)
 
  #ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· ΠΏΠΎΡΡ‚ΡƒΠΏΠΈΠ²ΡˆΠ΅ΠΉ Π΄Π°Ρ‚Π°-Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ ΠΏΠΎΠ»Π΅ "price"
  let newPrice = extract(getInteger(d.data, "price"))
 
  #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π² стСйтС Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ Π°ΠΊΠΊΠ°ΡƒΠ½Ρ‚Π° Π½Π΅ содСрТится поля "sender"
  let noBetsBefore = !isDefined(getInteger(this, "sender"))
  let fee = 700000
  let hasMoney = wavesBalance(tx.sender) + fee >= newPrice
 
  #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π² Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π΄Π²Π° поля
  let correctFields = size(d.data) == 2 && newPrice == currentPrice && d.sender == addressFromString(extract(getString(d.data, "sender")))
  startHeight <= height && height <= finishHeight && noBetsBefore && hasMoney && correctFields
case e : ExchangeTransaction =>
 
  #убСТдаСмся, Ρ‡Ρ‚ΠΎ ΠΎΡ‚ΠΏΡ€Π°Π²ΠΈΡ‚Π΅Π»ΡŒ Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ ΡƒΠΊΠ°Π·Π°Π½ Π² стСйтС Π°ΠΊΠΊΠ°ΡƒΠ½Ρ‚Π° ΠΏΠΎ ΠΊΠ»ΡŽΡ‡Ρƒ sender
  let senderIsWinner = e.sender == addressFromString(extract(getString(this, "sender")))
 
  #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π°mount ассСта ΡƒΠΊΠ°Π·Π°Π½ ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½ΠΎ, ΠΈ Ρ‡Ρ‚ΠΎ прайс-ассСт - waves
  let correctAssetPair = e.sellOrder.assetPair.amountAsset == token && ! isDefined(e.sellOrder.assetPair.priceAsset)
  let correctAmount = e.amount == 1
  let correctPrice = e.price == extract(getInteger(this, "price"))
  height > finishHeight && senderIsWinner && correctAssetPair && correctAmount && correctPrice
case _ => false
}

3. All-pay auction

"All-pay" - an auction in which all participants pay the bid, pay, regardless of who wins the lot. Each new participant pays the bid, and the participant who made the maximum bid wins the lot.

In our example, each bidder bids via a DataTransaction with (key, value)* = ("winner", address),("price", price). Such a DataTransaction is approved only if there is already a TransferTransaction for this participant with his signature and his rate is higher than all previous ones. The auction continues until the endHeight is reached.

let startHeight = 1000
let endHeight = 2000
let this = extract(tx.sender)
let token = base58'8jfD2JBLe23XtCCSQoTx5eAW5QCU6Mbxi3r78aNQLcNf'
match tx {
 case d: DataTransaction =>
   #ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· ΠΏΠΎΡΡ‚ΡƒΠΏΠΈΠ²ΡˆΠ΅ΠΉ Π΄Π°Ρ‚Π°-Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ ΠΏΠΎΠ»Π΅ "price"
   let newPrice = extract(getInteger(d.data, "price"))
 
   #ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· ΠΏΡ€ΡƒΡ„ΠΎΠ² Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ ΠΏΡƒΠ±Π»ΠΈΡ‡Π½Ρ‹ΠΉ ΠΊΠ»ΡŽΡ‡ Π°ΠΊΠΊΠ°ΡƒΠ½Ρ‚Π°
   let pk = d.proofs[1]
   let address = addressFromPublicKey(pk)
 
   #ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΡŽ Π΄ΠΎΠΊΠ°Π·Π°Ρ‚Π΅Π»ΡŒΡΡ‚Π²ΠΎ ΠΈΠ· ΠΏΡ€ΡƒΡ„ΠΎΠ² ΠΏΠΎΡΡ‚ΡƒΠΏΠΈΠ²ΡˆΠ΅ΠΉ Π΄Π°Ρ‚Π° Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ
   let proofTx = extract(transactionById(d.proofs[2]))
   
   height > startHeight && height < endHeight
   && size(d.data) == 2
   #убСТдаСмся, Ρ‡Ρ‚ΠΎ адрСс побСдитСля, ΠΈΠ·Π²Π»Π΅Ρ‡Π΅Π½Π½Ρ‹ΠΉ ΠΈΠ· Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ, совпадаСт с адрСсом, ΠΈΠ·Π²Π»Π΅Ρ‡Π΅Π½Π½Ρ‹ΠΌ ΠΈΠ· ΠΏΡ€ΡƒΡ„ΠΎΠ²
   && extract(getString(d.data, "winner")) == toBase58String(address.bytes)
   && newPrice > extract(getInteger(this, "price"))
   #провСряСм, Ρ‡Ρ‚ΠΎ транзакция подписана
   && sigVerify(d.bodyBytes, d.proofs[0], d.proofs[1])
   #провСряСм ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½ΠΎΡΡ‚ΡŒ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ, ΡƒΠΊΠ°Π·Π°Π½Π½ΠΎΠΉ Π² ΠΏΡ€ΡƒΡ„Π°Ρ…
   && match proofTx {
     case tr : TransferTransaction =>
       tr.sender == address &&
       tr.amount == newPrice
     case _ => false
   }
 case t: TransferTransaction =>
 sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
 || (
   height > endHeight
   && extract(getString(this, "winner")) == toBase58String((addressFromRecipient(t.recipient)).bytes)
   && t.assetId == token
   && t.amount == 1
 )
 case _ => sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
}

Insurance / Crowdfunding

Consider a situation where you need to insure users' assets against financial losses. For example, a user wants a guarantee that in the event of a depreciation of the token, he will be able to return the full amount paid for these tokens, and is ready to pay a reasonable amount of insurance.

To implement this, you need to issue β€œinsurance tokens”. Then a script is installed on the policyholder's account, allowing only those ExchangeTransactions that meet certain conditions to be executed.

To prevent double spending, you need to request the user to send a DataTransaction to the policyholder's account in advance with (key, value) = (purchaseTransactionId, sellOrderId) and prohibit sending DataTransactions with an already used key.

Therefore, user proofs must contain the transaction ID of the insurance token purchase. The currency pair must be the same as in the buy transaction. The cost must also be equal to that fixed at the time of purchase, minus the price of insurance.

It is understood that subsequently the insurance account redeems insurance tokens from the user at a price not lower than the one at which he purchased them: the insurance account creates an ExchangeTransaction, the user signs the order (if the transaction is made correctly), the insurance account signs the second order and the entire transaction and sends it to the blockchain .

If no purchase occurs, the user can create an ExchangeTransaction according to the rules described in the script and send the transaction to the blockchain. So the user can return the money spent on the purchase of insured tokens.

let insuranceToken = base58'8jfD2JBLe23XtCCSQoTx5eAW5QCU6Mbxi3r78aNQLcNf'
 
#ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ адрСс отправитСля
let this = extract(tx.sender)
let freezePeriod = 150000
let insurancePrice = 10000
match tx {
 
 #убСТдаСмся, Ρ‡Ρ‚ΠΎ, Ссли поступила Π΄Π°Ρ‚Π°-транзакция, Ρ‚ΠΎ Ρƒ Π½Π΅Π΅ Ρ€ΠΎΠ²Π½ΠΎ ΠΎΠ΄Π½ΠΎ ΠΏΠΎΠ»Π΅ ΠΈ Π² стСйтС Π΅Ρ‰Π΅ Π½Π΅Ρ‚ Ρ‚Π°ΠΊΠΎΠ³ΠΎ ΠΊΠ»ΡŽΡ‡Π°
 case d : DataTransaction => size(d.data) == 1 && !isDefined(getBinary(this, d.data[0].key))
 case e : ExchangeTransaction =>
 
   #Ссли Ρƒ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π½Π΅Ρ‚ сСдьмого ΠΏΡ€ΡƒΡ„Π°, провСряСм ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½ΠΎΡΡ‚ΡŒ подписи
   if !isDefined(e.proofs[7]) then
     sigVerify(e.bodyBytes, e.proofs[0], e.senderPublicKey)
   else
     #Ссли Ρƒ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π΅ΡΡ‚ΡŒ сСдьмой ΠΏΡ€ΡƒΡ„, ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· Π½Π΅Π³ΠΎ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΡŽ ΠΈ ΡƒΠ·Π½Π°Ρ‘ΠΌ Π΅Ρ‘ высоту
     let purchaseTx = transactionById(e.proofs[7])
     let purchaseTxHeight = extract(transactionHeightById(e.proofs[7]))
    
     #ΠΎΠ±Ρ€Π°Π±Π°Ρ‚Ρ‹Π²Π°Π΅ΠΌ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΡŽ ΠΈΠ· ΠΏΡ€ΡƒΡ„Π°
     match purchaseTx {
       case purchase : ExchangeTransaction =>
         let correctSender = purchase.sender == e.sellOrder.sender
         let correctAssetPair = e.sellOrder.assetPair.amountAsset == insuranceToken &&
                                purchase.sellOrder.assetPair.amountAsset == insuranceToken &&
                                e.sellOrder.assetPair.priceAsset == purchase.sellOrder.assetPair.priceAsset
         let correctPrice = e.price == purchase.price - insurancePrice && e.amount == purchase.amount
         let correctHeight = height > purchaseTxHeight + freezePeriod
 
         #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π² Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ-ΠΏΡ€ΡƒΡ„Π΅ ΡƒΠΊΠ°Π·Π°Π½ Π²Π΅Ρ€Π½Ρ‹ΠΉ ID Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ
         let correctProof = extract(getBinary(this, toBase58String(purchase.id))) == e.sellOrder.id
         correctSender && correctAssetPair && correctPrice && correctHeight && correctProof
     case _ => false
   }
 case _ => sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
}

An insurance token can be made into a smart asset, for example, to prohibit its transfer to third parties.

This scheme can also be implemented for crowdfunding tokens, which are returned to the owners if the required amount has not been collected.

Transaction taxes

Smart contracts are also applicable in cases where it is necessary to collect tax from each transaction with several types of assets. This can be done through a new asset with installed sponsorship for transactions with smart assets:

1. Issue FeeCoin, which will be sent to users at a fixed price: 0,01 WAVES = 0,001 FeeCoin.

2. Set sponsorship for FeeCoin and exchange rate: 0,001 WAVES = 0,001 FeeCoin.

3. Set the following script for the smart asset:

let feeAssetId = base58'8jfD2JBLe23XtCCSQoTx5eAW5QCU6Mbxi3r78aNQLcNf'
let taxDivisor = 10
 
match tx {
  case t: TransferTransaction =>
    t.feeAssetId == feeAssetId && t.fee == t.amount / taxDivisor
  case e: ExchangeTransaction | MassTransferTransaction => false
  case _ => true
}

Now every time someone transfers N smart assets, they will give you a FeeCoin worth N / taxDivisor (which can be bought from you for 10 *N / taxDivisor WAVES) and you will give N / taxDivisor WAVES to the miner. As a result, your profit (tax) will be 9*N / taxDivisor WAVES.

You can also tax using a smart asset script and MassTransferTransaction:

let taxDivisor = 10
 
match tx {
  case t : MassTransferTransaction =>
    let twoTransfers = size(t.transfers) == 2
    let issuerIsRecipient = t.transfers[0].recipient == addressFromString("3MgkTXzD72BTfYpd9UW42wdqTVg8HqnXEfc")
    let taxesPaid = t.transfers[0].amount >= t.transfers[1].amount / taxDivisor
    twoTransfers && issuerIsRecipient && taxesPaid
  case _ => false
}

Cashback and loyalty programs

Cashback is a type of loyalty program in which a part of the amount spent on a product or service is returned to the buyer.

When implementing this case with a smart account, we must check the proofs in the same way as we did in the insurance case. To prevent double spending before receiving cashback, the user must send a DataTransaction with (key, value) = (purchaseTransactionId, cashbackTransactionId).

We also need to set up a ban on already existing keys using DataTransaction. cashbackDivisor - a unit divided by the cashback share. Those. if the share of cashback is 0.1, then cashbackDivisor 1 / 0.1 = 10.

let cashbackToken = base58'8jfD2JBLe23XtCCSQoTx5eAW5QCU6Mbxi3r78aNQLcNf'
 
#ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ адрСс отправитСля
let this = extract(tx.sender)
let cashbackDivisor = 10
match tx {
 
 #убСТдаСмся, Ρ‡Ρ‚ΠΎ, Ссли поступила Π΄Π°Ρ‚Π°-транзакция, Ρ‚ΠΎ Ρƒ Π½Π΅Π΅ Ρ€ΠΎΠ²Π½ΠΎ ΠΎΠ΄Π½ΠΎ ΠΏΠΎΠ»Π΅ ΠΈ Π² стСйтС Π΅Ρ‰Π΅ Π½Π΅Ρ‚ Ρ‚Π°ΠΊΠΎΠ³ΠΎ ΠΊΠ»ΡŽΡ‡Π°
 case d : DataTransaction => size(d.data) == 1 && !isDefined(getBinary(this, d.data[0].key))
 case e : TransferTransaction =>
 
   #Ссли Ρƒ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π½Π΅Ρ‚ сСдьмого ΠΏΡ€ΡƒΡ„Π°, провСряСм ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½ΠΎΡΡ‚ΡŒ подписи
   if !isDefined(e.proofs[7]) then
     sigVerify(e.bodyBytes, e.proofs[0], e.senderPublicKey)
   else
 
     #Ссли Ρƒ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ Π΅ΡΡ‚ΡŒ сСдьмой ΠΏΡ€ΡƒΡ„, ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ ΠΈΠ· Π½Π΅Π³ΠΎ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΡŽ ΠΈ ΡƒΠ·Π½Π°Ρ‘ΠΌ Π΅Ρ‘ высоту
     let purchaseTx = transactionById(e.proofs[7])
     let purchaseTxHeight = extract(transactionHeightById(e.proofs[7]))
    
     #ΠΎΠ±Ρ€Π°Π±Π°Ρ‚Ρ‹Π²Π°Π΅ΠΌ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΡŽ ΠΈΠ· ΠΏΡ€ΡƒΡ„Π°
     match purchaseTx {
       case purchase : TransferTransaction =>
         let correctSender = purchase.sender == e.sender
         let correctAsset = e.assetId == cashbackToken
         let correctPrice = e.amount == purchase.amount / cashbackDivisor
 
         #убСТдаСмся, Ρ‡Ρ‚ΠΎ Π² Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ-ΠΏΡ€ΡƒΡ„Π΅ ΡƒΠΊΠ°Π·Π°Π½ Π²Π΅Ρ€Π½Ρ‹ΠΉ ID Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ
         let correctProof = extract(getBinary(this, toBase58String(purchase.id))) == e.id
         correctSender && correctAsset && correctPrice && correctProof
     case _ => false
   }
 case _ => sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
}

Atomic Swap

Atomic swap allows users to exchange assets without the help of an exchange. With an atomic swap, both parties to the transaction are required to confirm it within a certain period of time.

If at least one of the participants does not provide a correct confirmation of the transaction within the time allotted for the transaction, the transaction is canceled and the exchange does not occur.

In our example, we will use the following smart account script:

let Bob = Address(base58'3NBVqYXrapgJP9atQccdBPAgJPwHDKkh6A8')
let Alice = Address(base58'3PNX6XwMeEXaaP1rf5MCk8weYeF7z2vJZBg')
 
let beforeHeight = 100000
 
let secret = base58'BN6RTYGWcwektQfSFzH8raYo9awaLgQ7pLyWLQY4S4F5'
match tx {
  case t: TransferTransaction =>
    let txToBob = t.recipient == Bob && sha256(t.proofs[0]) == secret && 20 + beforeHeight >= height
    let backToAliceAfterHeight = height >= 21 + beforeHeight && t.recipient == Alice
    txToBob || backToAliceAfterHeight
  case _ => false
}

In the next article, we will look at the use of smart accounts in financial instruments such as options, futures, and bills.

Source: habr.com

Add a comment