Blockchain

Lessons Learned on Deploying Smart Contracts, Part 2

single-image

bitbond bitcoin lending

This is the second article in our series on integrating payment channels on Telegram Open Network. In the first part, we introduced the network, detailed our experience of the contest, and explained how synchronous and asynchronous smart contracts work. As the next addition to the series, this article details how we built a synchronous payment channel on the network during TON’s contest back in September. Here, we will be talking only about Fift (TON’s general-purpose programming language) and FunC (TON’s programming language for writing smart contracts).

The TON white paper provides more in-depth information about payment channels, but we will briefly explain them again.

Related: Behind the Scenes of TON: Lessons Learned on Deploying Smart Contracts, Part 1

A synchronous payment channel allows sending transactions between two users off-chain using on-chain assets. In our case — GRAMs. It is impossible for one party to cheat the other off-chain, and transactions are made much faster than executing layer-one blockchain transactions, as only user devices are used to complete them without having to write to the blockchain. There are two basic operations: deposit and withdraw. The withdrawal is the most challenging one to implement.

To make a correct withdrawal, users need to provide the latest information about the state of their channel. The state consists of the steps and digital signatures of each participant, which means it’s not possible to provide a correct state with data that has not been approved by both parties.

To deploy a smart contract, you need to write a deploy script in Fift and compile it to a .boc (bag of cells) file. Doing this makes multiple cells that will be linked to each other. GRAMs then need to be sent to the address that was received during deploy script execution. Once GRAMs are on the address, send the .boc file to the network and the contract will be deployed.

To make a function call, write a script that will send an external message to the deployed smart contract.

Basically, anything on TON is a cell with some references. A bag of cells is a data structure that was designed by the Telegram team. It is an actor model. More details are at TON whitepaper: “everything is a bag of cells.” You are building a cell that will interact with another cell when it is deployed.

Each peer-to-peer payment channel is a single smart contract. Let’s take a look at the segments of a smart contract.

Related: What to Expect From the Telegram Open Network: A Developer’s Perspective

Deployment part

A serialized Fift script is used to deploy a contract. It is saved to a .boc file and sent to the network via TON Cli, the network’s light client.

The latest cell on the stack is the result of executing the above Fift script.

The usual segments of a Fift deploy script include (but are not limited to):

  1. Code of the smart contract as a single cell (usually written in FunC, then compiled into Fift ASM code and included in the main .fif file using path-to-compiled-asm.fif).
  2. Initial storage of the smart contract (see below).
  3. New smart contract address (the hash from the initial state of the smart contract that also includes the smart contract code cell and the initial storage cell).
  4. Arguments of the first call of the recv_external function (the amount of arguments and type depends on the contract).
  5. An external message cell for initialization, which will be serialized into bytes and packed to the .boc file, which consists of all the data from points 1–4 and some additional ones that are still lacking documentation.

When the .boc is compiled, a specific amount of GRAMs need to be sent to the smart contract address. The .boc file must be sent to the network to initialize the smart contract. The amount of GRAMs depends on the size and volume of calculations of the deployed smart contract’s external message cell (not only the code of it). Gas × gas price is taken from the deployed smart contract balance. This amount is the minimum needed to pay for gas during the deployment.

A representation of the storage:

  1. seqno 32 bits
  2. contract_status 4 bits
  3. first_user_pubkey. The first party’s public key 256 bits
  4. second_user_pubkey. The second party’s public key 256 bits
  5. time_to_send. Time to send after the first actual state being submitted 32 bits (valid until 2038)
  6. depositSum. The deposited sum of two participants up to 121 bits
  7. state_num 64 bits. The current amount of states that occurred

A cell contains up to 1023 bits and four references to other cells. We were able to fit the entire storage onto one cell without a single reference. Our storage can take up a maximum of 765 bits.

All smart contract states

0x0 — Deployment state

0x1 — Channel opened and ready for deposit

0x2 — Deposit by user 1

0x3 — Deposit by user 2

0x4 — The deposit is blocked. It is possible to provide a state to the smart contract

0x5 — User 1 has provided the state

0x6 — User 2 has provided the state

0x7 — The channel is closed

Depositing

The deposit function receives a message from a simple wallet (transfer) with an additional body payload.

Depositing GRAMs to the channel:

  1. The user generates an additional body payload that includes a message (for example, 1 bit) and its signature in a separate .fif file.
  2. Body payload is compiled to a .boc file.
  3. Body payload is loaded from this .boc file into a .fif file as a body-cell “transferring” reference (the .fif is responsible for transferring GRAMs from the wallet).
  4. The recv_external function is called with arguments (the deposit amount and the destination address of the channel) when the compiled .fif file is sent to the network.
  5. The send_raw_message function is executed. Deposited GRAMs and additional body payload is sent to a P2P channel smart contract destination address.
  6. The recv_internal function of the P2P channel smart contract is called. GRAMs are received by channel contracts. 

The deposit function can be called if the state of the P2P channel smart contract is 0x1 or 0x2 or 0x3.

FunC code that checks the state:

1

Only the owners of the public keys (written in the initial storage) are allowed to make a deposit. The smart contract checks the signature of each internal message that will be received through the recv_internal function. If the message is signed by one of the public key owners, the contract status changes to 0x2 or 0x3 (0x2 if it is public key 1 and 0x3 if it is public key 2). If all users have made a deposit, the contract status changes to 0x4 on the same function call.

The FunC code responsible for changing contract status:

2

Refund

Funds can be returned if a counterparty has not made a deposit on time.

To do that, a user needs to provide their address and signature via external message. The funds will be refunded if the provided signature belongs to public key 1 or public key 2 (persons who made a deposit) and the contract status is 0x2 or 0x3.

FunC code that is responsible for verifying the refund application:

3

Withdrawal

Each person should provide an exit state, the signature of this state, and signature of the body message.

State details:

  1. Smart contract address (to exclude the possibility of entering the correct state from the previous P2P channel with the same participants).
  2. The final balance of the first participant.
  3. The final balance of the second participant.
  4. State number.

The body message signature is stored in the main slice, the state is stored in a separate reference, and state signatures are stored as references to a “signatures” reference to avoid cell overflow.

Withdrawal steps:

  1. Check the body message signature and determine the participant.

4

  1. Check that it is the turn of the participant or 24 hours have passed since the last entered state. Write the turn of the current participant (0x5 or 0x6) to the contract status.

An example of a correct signature of the body message for the owner of first_user_pubkey:

5

We then need to verify that the smart contract address written to the state is the actual contract address:

6

Next, we need to verify signatures under the state:

7

After that, there are two assertions:

  1. The deposited amount from the storage should be equal to the sum of the total balances of the participants.
  2. The new entered state number must be greater than or equal to the previous one.

8

In case of new_state_num > state_num we need to store new_state_num with the new time_to_send equaling to now() + 86401 (24 hours from the current time), and also write the actual contract status (0x5 if first participant made a call, otherwise 0x6).

In another case, if new_state_num == state_num we need to put an additional two references to the “signatures” reference with addresses of each participant and signatures under their addresses.

If the signatures are correct, GRAMs are withdrawn from one address and put into the owner’s address.

9

Each time a successful call happens, we need to store all storage data even if it doesn’t change.

Unsolved issues

The assumption is that the first user deployed the contract and the participants agreed on commissions. The agreement on commissions in our case is reaching off-chain.

We have not yet figured out how to calculate the total commission, taking into account the fact that players can write an irrelevant state and record actual states after that. Keep in mind that we need to pay fees from the P2P channel smart contract each time we successfully call recv_internal or recv_external functions.

As mentioned earlier, we need to add some amount of GRAMs to a non-bounceable future smart contract address in order to initialize it.

On the last day of the competition, TON’s developers made a commit to the stdlib.fc library with a new function that allows getting the actual smart contract balance.

10

Suggestions for possible solutions to this problem are welcome!

Conclusion

FunC and Fift allow any developer access to the low-level world of software engineering, opening new opportunities and features for blockchain developers who have already gotten used to Ethereum or any other smart contract platform. It is important that TON is a sharded blockchain, so implementing smart contracts on it is more challenging. For example, Ethereum’s contracts run synchronously and do not require handling situations such as waiting for an answer from another contract.

The asynchronous way of smart contract communication is the only option to make it scalable, and TON has these options. Our solution ended up being more difficult to implement than Solidity, but there is always a trade-off. It is definitely possible to build an advanced smart contract on TON, and the way that TON’s team handled it is very impressive. We are looking forward to seeing more libraries and tools that will help to deploy and build FunC contracts.

We thoroughly enjoyed all the tasks and wish that we’d had more time to implement all of them. Nevertheless, we won two prizes at TON Contest: first place for best synchronous payment channel as well as third place for best asynchronous payment channel.

We will share our own personal feedback in part three.

The views, thoughts and opinions expressed here are the authors’ alone and do not necessarily reflect or represent the views and opinions of Cointelegraph.

This article was co-authored by Nick Kozlov and Kirill Kuznetsov.

Nick Kozlov is the CTO and co-founder of Button Wallet, a software developer and researcher, as well as one of the winners of the TON contest.

Kirill Kuznetsov is the co-founder of Button Wallet, as well as one of the winners of the TON contest.

 





Source

Leave a Reply

avatar
  Subscribe  
Notify of

You may also like

Bitcoin

BTC, ETH, XRP, BCH, BSV, LTC, EOS, BNB, XTZ, LINK

single-image

bitbond bitcoin lending

Binance CEO Changpeng Zhao believes that the upcoming Bitcoin halving has not been priced in to the digital asset’s current price action. The reduction in miner rewards will increase the cost of mining each Bitcoin, meaning, miners are unlikely to sell below their cost of production. 

Bitcoin’s supply will decrease with the halving but its demand has also been increasing, creating a situation where prices are likely to driven higher. Although CZ’s statement can be interpreted as bullish, the CEO personally believes that Bitcoin’s price might gravitate around $10,000 levels for a few more days as round numbers are known to act as psychological barriers.  

The traded volumes in major cryptocurrencies have skyrocketed in the past year and this shows greater participation by the traders. Currently, Tether (USDT) is the most frequently traded crypto asset, followed by Bitcoin and Ether (ETH). Liquidity…

View More Article
Ethereum

Vitalik Buterin Reveals Ethereum 2.0 Roadmap to Cointelegraph

single-image

bitbond bitcoin lending

Ethereum co-founder Vitalik Buterin discussed plans for Ethereum 2.0 during an exclusive interview with Cointelegraph on Feb.19 at the Stanford Blockchain Conference. Buterin explained that the major development for ETH 2.0 over the course of this year is the launch of Phase 0. He said:

“Phase 0 is the first phase of the Ethereum 2.0 launch. This will release the proof-of-stake network, which will come online this year.”

While the official launch date of Phase 0 is still unknown, Buterin explained that Phase 0 is close to having a multi-client testnet and audits of the existing code. He noted:

“A lot of optimization is currently underway with Phase 0, which we will continue to refine over the next few months.”

Ethereum 2.0 roadmap

Following the launch of Phase 0, Buterin stated that ETH 2.0 will begin as an independent PoS network. He explained that the purpose behind this…


View More Article
Bitcoin

Irish Drug Dealer Tells Police That Keys to $56M in Confiscated BTC Are Lost

single-image

bitbond bitcoin lending

Dubliner Clifton Collins, who was recently imprisoned for drug trafficking, claims that robbers took the keys to the $56 million in Bitcoin (BTC) Irish High Court had ruled should be confiscated.

After obtaining more than 6,000 BTC by 2017, Collins decided to insure himself against hackers by distributing the cryptocurrency across 12 newly created accounts. Thus, he transferred 500 BTC into each of them, the Irish Times reported on Feb. 21. As of press time, that would leave each wallet worth roughly $4.87 million.

A punishment for his own stupidity?

Collins then printed out the keys for all of his 12 BTC accounts onto a piece of paper, which he says he stored in an aluminium cap of his fishing rod case. This he stored in a house which he rented in County Galway, Ireland. However, when he was arrested for…


View More Article
Bitcoin

Bitcoin’s Lightning Network Found More Centralized Than Expected by Researchers

single-image

bitbond bitcoin lending

The Lightning Network’s (LN) configuration is becoming increasingly centralized, with multiple hubs being formed. This is the finding of a yet-to-be-reviewed research paper, released on pre-print site arXiv on Feb. 7.

A team of academics from Switzerland, France, Italy and Canada authored the paper. Jian Hong-Lin and Kevin Primicerio conducted the analysis, while others, including Blockstream Inc. researcher Christian Decker, designed the research.

Core-periphery model

The team gathered Lightning Network information for a period of 18 months from Jan. 18, 2018 to July 13, 2019. Researchers then analyzed the payment network in terms of its node and wealth distribution.

They discovered that the network showed high Gini coefficients both in terms of node centralization and wealth distribution. Notably, the values were found to rise as more nodes were added.

The distributions of Bitcoin (BTC) across every node in the network was found to be extremely…

View More Article
Bitcoin

Riot’s Stock Dips 5% as It Focuses on Bitcoin Mining Ahead of Halving

single-image

bitbond bitcoin lending

Riot Blockchain, a Nasdaq-listed crypto firm in the United States, plans to sell its exchange to focus on Bitcoin (BTC) mining ahead of the halving.

According to an official announcement on Feb. 20, Riot has “opted to sunset further development of Riot’s U.S.-based digital currency exchange” in order to focus on cryptocurrency mining as part of its updated strategic priorities for 2020.

Following the announcement to shift its focus on Bitcoin mining, the company’s shares dropped more than 5%, trading at $1.40 at press time, according to CNBC data.

Industry experts disagree on the potential price impact of May 2020 Bitcoin halving — an event which will decrease block rewards on the Bitcoin blockchain. Changpeng Zhao, the CEO of major crypto exchange Binance, recently predicted that, since miners will have to…


View More Article
Blockchain

Cyprus SEC Embraces Blockchain Despite Unregulated Status of Crypto

single-image

bitbond bitcoin lending

The Cyprus Securities and Exchange Commission (CySEC) recently published a report discussing the ongoing activities of its Innovation Hub — a cooperative entity that was launched in October 2018 as a platform for engagement between CySEC and entities operating in the fintech and regtech sectors. 

Nineteen different companies directly engage with the platform, nine of which comprised projects utilizing blockchain. Among these companies were several projects using distributed ledger technology (DLT) to transfer and verify ownership of financial instruments, trading facilities that operate using blockchain, and a venture capital fund investing in virtual currency startups.

The Hub is intended to facilitate knowledge-sharing between regulators and innovators, promote the development of regulations that foster innovation, and ensure compliance within dynamic and emerging tech industries. It also engages with third parties seeking to participate with emerging financial…


View More Article
Blockchain

Expert Says New Blockchain Regulation Should ‘Nudge’ Rather Than Push

single-image

bitbond bitcoin lending

Regulators should aim to influence public behavior rather than rule with an iron fist when it comes to emerging industries such as blockchain.

Two Israel-based academics, Hada Jabotinsky and Nassim Cohen argued this point in a new paper and accompanying brief, published to the University of Oxford Law Department blog on Feb. 21.

The paper proposes an approach that would result neither in an under-regulated free-for-all that leaves consumers vulnerable, nor in heavy-handed prohibitions that stifle technological progress.

Complex new technologies such as blockchain, cryptocurrencies, Internet of Things, and automated cars require ever higher levels of technological literacy. The paper states that, as the pace of innovation gathers speed, regulators struggle to grasp the implications of the products and inventions brought before them. 

What does a “nudge” involve?

The authors argue, “A nudge is ‘any aspect of the…


View More Article
Bitcoin

Bitcoin Price Drop Mirrors Last Golden Cross Which Led to 170% Gains

single-image

bitbond bitcoin lending

Bitcoin (BTC) may not see a 170% increase after its fifth “golden cross” price event, historical data suggests as markets stay down 8%.

Analysis of price movements since 2009 shows Bitcoin has had a total of ten “golden cross” and “death cross” moments in its lifespan. 

BTC price dip challenges December 2017

A “golden cross” is when BTC/USD sees its 50-day moving average rise to cross over its 200-day moving average. A “death cross” is the opposite. 

As Cointelegraph reported, hopes are currently high that the most recent golden cross will spark an identical reaction to the previous one — a 170% price surge in just two months. 

Overall, however, two out of four golden crosses have resulted in gains, while the other two in fact saw price losses. Similarly, some death crosses were followed by price gains.

Bitcoin traders continue to dig for answers after BTC/USD abruptly dropped $1,000 in…

View More Article