Recently, smart contracts have been widely used in the Ethereum network, mainly for ICO and management of released tokens. Such contracts exist as long as this is necessary for maintaining projects, and thus they provide uninterrupted interaction with thousands of customers and accept thousands of transactions per months and years. We will call them “long-term” smart contracts.

However, certain tasks require a smart contract to be executed in minutes, and then it is not needed anymore. Thereby each user may need some personal contract parameters, and in some cases it’s more practical to implement such a logic with small, once-used contract. Such smart contracts execute needed action once, organizing a single deal between fixed set of participants, and will be thrown away after use. We wil call such contracts as “short-term “smart contracts. In this article, we will examine them in more detail.

Smart Contract Deployment

A smart contract can be presented as an automated wallet: you put money in it, it checks the conditions and either returns the money or sends them to another wallet or to ten such wallets. This analogy is incomplete, because we missed the process of contract deployment to decentralized network. Let us try another analogy.

Let us compare a smart contract with a website. You have developed a website, put it on the Internet, and the provider has registered in DNS that there is a certain website at www.company.com. Putting a contract on the Ethereum network can be envisaged in a similar way: you develop a code, put it on the network (it means, you send a special transaction “create a contract”), and the contract acquires its own address in Ethereum, similar to any other address you would give someone to send Ether to you.

Such a “website” in Ethereum has some useful properties for smart contracts:

The “website” code cannot be changed . It can only be killed if you preprogram the option of killing the contract after receiving a special message. This does not mean that the code will disappear or the smart contract will be erased. It is just that any transaction sent to it will return an error

. It can only be killed if you preprogram the option of killing the contract after receiving a special message. This does not mean that the code will disappear or the smart contract will be erased. It is just that any transaction sent to it will return an error Each request to the “website” is an indisputable transaction, stored permanently in the blockchain . For ICO, you sent one Ether and got 10 tokens; the record that you have 10 tokens has appeared inside the contract. Your request has changed the status of the contract. Every such transaction is technically indisputable, because you can always prove that the transaction took place and it was signed by you (if you have the required secret key).

. For ICO, you sent one Ether and got 10 tokens; the record that you have 10 tokens has appeared inside the contract. Your request has changed the status of the contract. Every such transaction is technically indisputable, because you can always prove that the transaction took place and it was signed by you (if you have the required secret key). Each request from a user to the “website” can contain any amount of funds . If we view a smart contract as a website, then every request to the “website” can include Ether. Imagine a website where you can assign any amount of money to any button click, and the website understands how much was sent to it, can return change, etc.

. If we view a smart contract as a website, then every request to the “website” can include Ether. Imagine a website where you can assign any amount of money to any button click, and the website understands how much was sent to it, can return change, etc. Every request is visible to everyone. You cannot limit the visibility of the requests to the “website”. If you send a request to a smart contract and something went wrong during the execution, this is a standard situation for Ethereum and the transaction that has caused the error will still be put in the blocks, and the miners will still receive their fee for the execution of the contract code (from your Ether, of course).

After the network “accepts” the code of the new contract (all the miners have checked the code, put it in the block, locked the block, published it on the network), the contract gets its own address and can accept transactions. Do not forget that every transaction sent to the block is data signed by an electronic signature with all its advantages (confirmation of authorship, at least). When talking about secure processing of transactions, banking, ownership the usual question is “Why is a blockchain needed here? Why the bank cannot do the same things on its side?”.

The main answer to this question in terms of security is: “because there is no shared secrets between participants in this scheme”. There is no security data, known to two parties: PIN, hash of user password, unsafe web session: all of them are examples of data, that can be used by attacker. In decentralized networks, the only secret is the client’s secret key, everything else does not require any secure communication channels or authorization.

Also, one should note that none of the parties can do something unnoticed by another: every change in the status of the contract is recorded, even failed or malicious transactions. The blockchain records any operation that changes something inside the storage of each smart contract. The operation can be simple, and can do rather complicated things, and any network member can be absolutely sure that the contract code works for all the participants exactly in the same way as it does on the member’s machine.

Even in the minimal variant (in the “short-term” versions), smart contracts are great tools for accounting and fixing events. They are extremely convenient to use in almost any project, since we get a secure and fault-tolerant system right out of the box. As we will see, sometimes even a minimum of the standard functions is enough to implement a lot of interesting tasks.

Long-Term and Short-Term Contracts

In this article, the “long” and “short” term of a smart contract means not only the time but also the number of transactions serviced by the contract. If the contract works for a long time, accepts and sends many transactions, it is considered “long-term”. If it accepts few transactions or runs for a limited time and then closes, it is a “short-term” one. We made this distinction after gaining experience in developing several contracts and designing communication protocols. Some tasks requires long-term storage, single contract address, large amount of data in contract storage, but, if we want many independent personalized contracts, we can design a system, that will deploy many small contracts instead of work with the single big contract.

These types of contracts have different gas economy, creation complexity, way of putting them on the network, and they help to solve different business tasks. That is why we have called the contracts “long-term” and “short-term” at a rough estimate. If you have ideas on how to make the naming more precise, you are welcome.

Long-Term Smart Contracts. Typically, the business model of a long-term smart contract looks like this: we have put it on the Ethereum network and now thousands of users go to a contract and do something in it. As an example, here is a token smart contract. We put a contract that stores the users’ balances on the network. Thousands of investors come to us, and the information about the number of received tokens for each investor is put in a token contract storage. Each time you send tokens to another address, you access the same smart contract at the same address and instruct the contract to change the token balances(the recipient’s and yours) in the same storage.

A smart contract has a lot of data and lives as long as your project. Tokens can move within it for years. There are no restrictions on transferring tokens within the contract, and it will work as long as the network exists.

Another example of a long-term smart contract is Equity (share ownership). Let us consider the example of a company in which you distribute shares: 10% for Alice, 10% for Bob, and 80% for you. You want all of the company’s profits to be distributed accordingly: if 100 ETH come, Alice and Bob get 10 ETH each, and you get 80 ETH. Equity contract divides the money into flows, distributing the incoming funds, and allows the participants to receive their shares unquestionably, at the same time recording all payments and amounts in blockchain. Since it is planned that the company will work for a long time, that is why you ask the programmer to put your smart contract on the network only once, and then you use it for years without any extra effort, only redistributing shares sometimes.

Short-Term Smart Contracts. They live for a short time (hours, days) or include few operations (single payment, a couple of event records). These contracts are created for a single deal, for few fixed users and/or limited time. For example, if you sell washing machines, you can put on the network a selling contract for each machine separately. User interacts with such a contract only few times — pays for machine for example, and can organize a cashback if seller agreed to return money. Аfter “cashback possible” period the interaction with contract ends — it cannot accept transaction, but stay in blockchain as a fact of purchase. Such contracts can hold the presonalized data for each machine separately, f.e. encrypted serial numbers, service information, etc.

We need short-term smart contracts for tasks like one-time deposit/withdrawal of funds with the necessary control checks, or just for recording some important actions in the blockchain. Any transaction, with or without Ether, is useful information -it’s actually electronically signed approve of user to do something. We don’t even have to put something in it: it already has the sender’s signature and the timestamp — in many cases this is enough to fix the event, like purchase, confirmation or any other business “checkpoint”.

If a smart contract can only accept and give out a fixed amount of funds (and return change, for example), then any successful transaction becomes an analog of a cash voucher, and the blockchain — a convenient storage for transaction data. If the transaction was successful, it means the purchase is made. Showing the store’s ETH address in the Federal Tax Service, you can explain: “Here are our vouchers and our sales.” Generally, this relieves stores of the need to have cash registers, now their concern is to register keys and addresses belonging to the store and ensure their safety and the ability to change them if hacked. You can also easily implement a tax payment directly at the purchase with a couple of lines, if only there is a known destination address for the payment.

Short-term smart contracts have their advantages and disadvantages. The fact that there are a lot of contracts and they are small greatly increases the expenses for putting them on the Ethereum network, because this is a quite expensive operation. In the same time, short-term contracts are responsible for relatively small amounts, they are much easier to replace, simply switching to a new version. There are much less security risks due to the code simplicity and the small amount of data. Code simplicity also means that it is cheaper for the users (not contract creators). So the questions about advantages and disadvantages are not simple, we will come back to them later.

We will describe these basic types of simple short-term smart contracts as an example:

invoice-paid;

commit-reveal;

one-time multisig.

The first one is an analogue of a payment invoice, the second one allows you to “promise to pay” and “allow to receive the payment, having proved the accomplishment of the task”, the third one is to resolve the dispute, “whose money”, with the help of an arbitrator. Here we go.

Invoice-paid

In fact, it is a price tag. Imagine that we sell watermelons. We issue a price tag for a specific watermelon with a specific weight, we put it on it and write: “Costs 1 ETH.” After that, we need the price tag either to accept 1 ETH, or “die” after 24 hours, because we want to be able to change price once per day. This “allowance to change price once per day” can be included in contract code, so your customers can be absolutely sure about rules of pricing.

So, we publish our short-term smart contract for a specific product (watermelon) for a limited period of time. We describe only basic schemes, so, the internal data of the contract only includes the price and the time when the contract will become invalid (if no other restrictions are implemented).

When someone wants to buy a product, he/she sends Ether to address of our smart contract and it, in turn, sends Ether to the ETH address of the store, sends change (if necessary) and closes. The blockchain saves the transaction, and it is easy to get the entire sales history by analyzing transactions from smart contracts created by the store. At the time of purchase, the smart contract can also pay a tax or a fee to the person who brought the customer to it.

Another fairly close analogy for such a price tag contract is an invoice. This is why we called the contract invoice-paid: these are its two working states. In the invoice mode, it waits for payment; in the paid mode, it has accepted the payment and does nothing. The third state, when the TTL (time-to-live) is expired, is the standard state for all short-term smart contracts. The expired TTL causes the contract to self-destruct or simply ignore any incoming transaction.

It is possible to include useful data in an invoice-paid contract, for example to put such invoice to a specific address just at the moment when the buyer has decided to purchase the product. In this case, the smart contract receives Ether strictly from the given address. You can add a hash of any data in the contract: photos of the product, the id of the ad on some site, an archive with a document package, etc. Such contracts are also very suitable to implement regulation rights, for example, to deny price change on some product by more than 1% per day.

Commit-reveal

This simple scheme is used in decentralized networks to “promise” to do something and then to “prove” that the deal was done.

Let us recall one feature of the blockchain. When you send a transaction to the network, any node that passes the transaction through a P2P network can analyze the contents of the transaction before it is put on the block. Such a node can create its own transaction with a high fee, which block producers are more likely to include in the block and which will appear higher in the transaction list than the original one. Therefore, one cannot play the rock-paper-scissors game, sending transactions directly. It is clear that I would not send “scissors” to the contract: my opponent can look at the public transaction and create his own one, with a “stone”.

The solution to this problem is the scheme where the proving party (in our example there are two of them, I and my opponent) “promises” to show some meaning in the future, which is secret for the moment (our “scissors” or “paper”). To do this, we send the cryptographic hash from the word “scissors” (I) to the smart contract, then a hash from the word “paper” (my opponent).

Only after these two “commitments” I can openly publish the “scissors”, and the opponent can publish the “paper”. It is impossible to cheat here: I will open the “scissors” only when I see the hash of the opponent’s decision; the same applies to the opponent. “Commit” well conveys the meaning of the hash phase allocation, and “reveal” conveys the disclosure step, hence the name.

We have to point out that before calculating the hash, the string (“scissors” or “paper”) is necessarily supplemented with a random number. The ability to “guess” the choice of an opponent on the published hash depends on the cryptographic strength of the number, so its generation should be approached utmost care. This number is a temporary secret, it is published along with the string at the reveal stage, so that the participants can check the correctness of the hash.

Let us consider a commit-reveal contract for courier delivery payment. The store sends a courier to bring the product to the customer and wants the courier to receive the payment only if the product is delivered within three hours and handed personally to the customer. To do this, the store generates a secret word, creates a contract, places a hash of the word and time (three hours), after which the store can simply return its funds by sending a refund transaction to the smart contract. The store gives the courier (through the mobile application or browser) the address of the smart contract, and the courier sees that the payment can be collected within three hours with the secret word. The store sends the word to the customer in a text message. This phrase describes the contract logic: “If within three hours the courier sends in the correct word (used to construct a hash when creating the contract) — I send the money to the courier.”

In case of a conflict with the buyer, the store can unlock the funds for the courier independently, by simply sending that secret word by itself.

Of course, for real use, the smart contracts also contain modifications, additional data and control checks, fees, entry thresholds, dynamic change of the delivery cost, etc. This part of connection between real word and smart-contract is the most complicated part of such systems. But the basic “commit-reveal” scheme still the same, allowing construction of many different protocols for the interaction of the business agents.

One-time Multisig

This smart contract is the address from which one can withdraw funds by providing N of the M signatures.

Suppose that a husband and his wife decided to keep part of the family savings in the cryptocurrency. It is desirable, that the contract accepts and stores the funds, but does not allow to withdraw them from the contract until it receives at least two of three confirmations, from the husband, the wife or the bank. If the wife’s phone is stolen, her husband can go to the bank and, having received the bank signature, withdraw the money. In the normal mode, funds are withdrawn from the smart contract, when both husband and wife provide their signatures. This is extremely convenient, because hacking one of the participants will not result in an unauthorized withdrawal of funds.

In general, multisig can operate with arbitrary N and M, but the “two out of three” option covers a huge number of business tasks where a third party is required. When you buy an apartment and the bank gives the keys to the cell only when it receives documents for the property, this is multisig 2/3. Money is put to the multisig address, where the seller of an apartment, the buyer and the bank participate. As soon as the bank sees the change of ownership agreement, it gives its electronic signature. Such a contract also includes time limits and, of course, a fee for the bank. For single tasks that operate with large amounts, it is reasonable to use one-time contracts. The vulnerability in a huge universal contract that manages all letters of credit can lead to far more serious consequences than a successful attack on a one-time contract with limited lifetime.

In decentralized networks, multisig contract is like a Kalashnikov rifle — it’s used in many types of deals with many participants. In “2/2” variant multisig contracts allow to open payment channels and make secure funds addresses, in “2/3” variant — make any deals with escrow, arbitrage, allowance to perform critical actions. Bigger N and M numbers in multisig leads to deals, requiring a collective solution, deals with shared property rights management etc. Dynamic changing of N and M allows to create DAOs, decentralized voting and management systems.

Advantages of Short-Term Smart Contracts

Simplicity and security as a result. In Solidity, you literally have to think over every step; every operation costs some gas, every extra call to an external smart contract is a potential vulnerability. Most of security bugs come from interaction between contracts… A short-term smart contract contains little code and does not require interaction with other contracts; therefore, it is safer than its elder long-term brother. The less code, the cheaper. It is cheaper to publish, develop and write tests for it. A simple contract has a simpler and more unified interface, which you can safely place outside in any designer kit. This allows other developers to work with your smart contracts, easily adapting them to their needs. Short-term smart contracts can easily be transferred to other blockchains. If you create a simple short-term smart contract, then, most likely, you can implement it on any other smart-contract platform with minimal amount of problems. Simple logic makes it more likely to be already implemented on competing engines, which means cheaper development and a more reliable contract. Very convenient to fix. A security bug in the token is a serious problem. You have to replace the token and move the balances, it costs a huge amount of gas. In the case of short-term versions, we do not deploy smart contracts but fix their versions and then just wait for the bad contracts to “die” and be replaced by new versions. By destroying smart contracts correctly, we clean local storage for clients, optimizing the used space. Correct using of selfdestruct() after contract TTL is expired, or deal closed, allows to keep the blockhain volume down. We can just delete expired contracts form blockchain saving disk and index space. TTL. If we look for “invoice-paid” contracts in the blockchain and we know that they live no more than a day, then the search engine over our blockchain can be set to work only with the blockchain from the last 24 hours. This makes such search engines convenient and fast, as there is little data, and it makes the websites working with short-term smart contracts very fast and functional. Otherwise, to look through hundreds of gigabytes of blockchain blocks, tracking thousands of accounts, is not an easy task for programmers.

Problems and Solutions

Nothing can be perfect. The first problem here is the gas. You have to spend gas for every smart contract deployment. A service, which operates tens of thousands of smart contracts requires serious research and balancing. Today, in Ethereum you can send a transaction at a gas price of 5 Gwei, and it will arrive in a minute. And sometimes you have to pay 50 Gwei for gas and wait for an hour. Those who use smart contracts are not very happy with the growth of the Ether rate, because this means a rise in the cost of sending contracts to the network. Putting a contract on the network is expensive, so the short-term smart contracts are not cheap.

We consider not only Ethereum, and on our platform we will use several networks that work with smart contracts. The problem of the execution cost is their common problem. Sooner or later, it will be resolved, or the competition for the execution cost of one line of the contract will greatly reduce the cost. In addition, it is likely that even the same types of transactions will differ in cost, so the emergence of strategies such as “execute contracts with cryptographic computation in one blockchain”, and “contracts with string operations in another blockchain” is quite possible.

The second problem is contracts which are dead but not finished by the selfdestruct() method. We created a smart contract, paid for it, and it did nothing and died in the blockchain. This is not good for the state-database, and we are thinking how to solve this problem. The right way is to do it with the last transaction (if it comes), but situation with “lost” contract is still possible. Probably, future contracts will include a possibility to be killed by special “sweeper” contracts, called outside, that will kill expired contracts for a small fee. :)

The third problem is the complex infrastructure for sending contracts to the network. Managing so many smart contracts, deploying and monitoring them requires a serious development work “around” Ethereum and other blockchains. This includes a blockchain search engines, an automatic deployer, queues for managing pushes for mobile clients, gaz economy station, management funds with large amounts of Ether, addresses and keys. All this is a very serious issue for both security and architecture.

Conclusion

We looked at some of the features of smart contracts, described several cases, and talked a little about their problems and solutions. The construction of a platform that can support launching a large number of different types of contracts without sacrificing security and decentralization is already under way, it is smartz.io.

Smartz offers an infrastructure for launching decentralized applications (DApps) in several networks. It can launch the smart-contracts for deals in c2c, b2c and b2b sectors, deploying not only smart-contract, but also the ready personalized interfaces to these contracts, allowing people to start work with blockchain from their browser or mobile app. Users on Smartz platform have a convenient way to launch smart-contract in a few clicks and start using one of the many useful DApps for multiple purposes.

Smartz will provide contracts dashboards, optimization of gas costs, production-ready API as well as many services that facilitate the interaction of users and businesses with all significant decentralized networks.

The platform gives developers and small teams the opportunity to earn money when placing their DApps; their security and quality will be confirmed by an independent audit and arbitration of the platform participants.

Nice to meet you! :)