unfortunately I had not seen this proposal before approval to show my disagreement.
some points:
atomic swaps is an exchange business model like other centralized or decentralized exchanges, so if Free TON community invest in writing the code then the Free TON community should follow to implement and marketing it !!! (it is not the community job)
if other third party company want to do marketing and implement the written code so that company also should pay the costs not the Free TON !!!
Free TON Community just should create different SDKs and libraries as facilitators, so other exchanges (any type of exchange) can easily adapt their systems with the Free TON blockchain .
atomic swap model is some how a failed model. so called successful atomic swaps(for example Changelly) never became a real atomic swap exchanges (the reason is low liquidity) and finally became just an intermediary between centralized exchanges and the trader.
so finally: 1. if the Free TON community don’t want to implement it why we should have this contest? 2. isn’t it better to have this approach in the Free TON community facilitating for other devs to adapt TON in their systems instead of creating systems
Здесь суть задания как раз создать такие контракты, которые бы не позволяли владельцу обменника влиять на процесс совершения сделки, чтобы не возникало кастоди и не нарушалась приватность участников сделки. Но, поскольку он обеспечивает фронт и поддержку, он должен иметь возможность задать комиссию от сделки, которая автоматически будет уходить на его адрес по её завершении.
Исходники должны быть выложены в Open Source с открытой лицензией, т.е. стать общественным достоянием - это позволит любому желающему провести аудит их безопасности и улучшать их.
Что касается второй части, то тут скорее вопрос - как убедиться, что владелец обменника использует именно те исходники, которые провалидированы сообществом. Этот вопрос выходит за рамки данного конкурса, но мы можем вынести его в отдельное обсуждение.
Hello @nAMI, thanks for your opinion.
It is very good that you have addressed these points.
Let me try to oppose them.
On the goal of the contest
Ultimate goals of all FreeTON contests are decentralization, market penetration, and token distribution in the as short term as possible. However, we should not forget that FreeTON doesn’t exist in a vacuum and first needs to plug into the existing market architecture to succeed.
Creating technology that will help existing businesses (exchanges, wallets, OTC desks, and so on) to start accepting and exchanging crystals against popular coins and tokens will foster the liquidity flow and speed up FreeTON acceptance by people outside the FreeTON community.
On the reward
You stress that FreeTON pays contest winners for something, which is not true. The winners are rewarded for their impact on reaching FreeTON’s goals.
We are a decentralized organization that asks the community to help in the popularization of its values and benefits in exchange for some virtual assets, and not an institution running a tender and paying to the contractor.
On the tools created by the community
Free TON Community just should create different SDKs and libraries as facilitators
I disagree with such narrow positioning as it completely devalues the efforts of blockchain developers who invest their time in learning FreeTON smart contracts both in Fift and Solidity. Contests like this tease their professionalism and help them grow, at the same time creating a ground for discussion and rapid creation of industry standards.
Atomic Swaps is a challenging task that may be used as a basis for future technologies and growing popularity of FreeTON.
On failed model
atomic swap model is some how a failed model
This is a very strong argument, please ground it with facts.
The world of DeFi and DeX is booming, and atomic swaps and uniswaps are one of the core technologies. FreeTON IMHO is an ideal blockchain for DeFi projects, and having the solutions that are elaborated and validated by the community will help FreeTON to become very competitive.
On a community will
the Free TON community don’t want to implement it
I have published the contest proposal more than week and a half ago and invited the community to object. Vice a versa, I see really strong support from other members and their readiness to even participate in this contest.
The only fair criticism I have seen so far is the one from @Mitja who accented that it was worth to first have a design contest for this task. However, there are so many good examples from Ethereum and Bitcoin that we agreed to provide them here as a benchmark.
@cryonyx thanks a lot for your response (you easily could ignore my comment because any way the jurors have approved this contest and I am respectful also about their decision)
1.
about the failure of atomic swaps (because of liquidity problem):
1.1. I refer you to this article of Vitalik. he mentioned:
The main challenge that I see with the MKR market, etherdelta and other markets right now is the high spreads, often 10% or even higher.
he don’t use the word atomic swap but atomic swaps also include so later Vitalik wrote a new article to introduce what called x*y=k market makers that later inspired by Hayden Adams to create uniswap.org (we don’t have uniswaps it is just one exchange with x*y=k market maker idea)
1.2. this article explain that other alleged atomic swaps like Changelly and Shape Shift are not actually atomic swaps so the author called them instant exchanges. but the author don’t know that they wanted to be real atomic swaps and lack of liquidity forced them to became intermediaries between central exchanges and the customers. it is the reason that founders of Changelly had created a wallet an named it Atomic Wallet it wanted to be a real atomic exchange. I wish Konstantin Gladych again join to Free TON also as he was part of TON community in the past.
2.
no stress. i even think we should even reward to the proposal writers as well as contestants between 0-100k TON based on judge valuation their proposal (as I had explained in my proposal for idea management system contest at the end of page 5).
3.
you have answered @Aleksandr that have asked some how my first question
and you think that it is possible to fully implement an atomic swap on the blockchain as a smart contract with no dependancy to outer systems.
something by using a tool like SPV Verification that @Mitja mentioned. it is OK and so good so I think the contest should was a contest to create a tool like SPV Verification tool.
thanks @Mitja for sharing this link i really don’t know if their SPV tool work with no fault or not (even the possibility needs to be checked)
when I talk about different SDK and libraries the SPV Verification tool can be a good example it will facilitate any on chain exchange (atomic swap , uniswap or others) to work with the TON blockchain.
anyway thanks you and mitja for the contribution. I am learning also.
Colleagues, what is the reason to combine all this into one competition? These are large tasks, and the implementation of each of them requires a lot of resources. At the same time, these tasks do not depend on each other, they can simply be divided into different contests.
I have been writing a smart contract for trustless exchanging TON Crystal for Bitcoin using SPV for some time (very short announce). I started in early August. The implementation is still not ready, but at this point in time it took more than a month. And of course I want to take part in this contest. But the conditions are such that you simply cut off the participant, requiring 3 unrelated exchangers to be implemented in 3 weeks. This can only be done by a large team or if you prepare for the contest in advance.
I propose changing the terms of participation in the contest so that you can provide separate implementations of BTC and ETH and even separate native ETH and ERC20. Or even better, launch separate contests for different blockchains. Otherwise it’s just too hard.
What is the point of a contest that only the organizers take part in?
I agree with you. The task is big and you need more time or more experts. The competition is organized for its creators. In the next topic, I raised this issue. To which I was told that any member of the community can create contests according to their skills, in addition, it is difficult to find specialists for such a task. I would also take part, but physically I will not have time, as I am engaged in another contest.
@creator, @Dekan I’m personally on your side and did what I could. However, the governance strongly objected to extend the deadline…
This is what the decentralization is
But still, I invite you to participate in the discussion and development of other DeFi elements and also participate in the Jury contest. We need such passionate members as you.
Our team is pleased to present you a fully decentralized infrastructure for two-way exchange between the following blockchains / tokens:
Free TON <-> Ethereum
Free TON <-> ERC20 Token (currently USDT supported)
Free TON <-> Bitcoin in progress…
The exchange is based on HTLC Smart Contracts on each blockchain. This type of contracts allows exchanges between blockchains with guaranteed atomicity - that is, the exchange will either take place, or you will receive your funds back.
At the moment, HTLC smart contracts have been implemented for the following blockchains:
Bitcoin Script for Hashlock & Timelock (built into js library)
Distributed backend
To place / search for orders, as well as synchronize the exchange between participants, an order book based on a smart contract in the TON network is used. It allows you to place orders for both buy and sell tokens with an indication of the volume range, exchange rate and maximum time for blocking funds.
Work with a smart contract is carried out by depositing TON CRYSTALS to the account of the order book contract, after which the funds are blocked for the duration of the exchange. This makes it possible to guarantee the receipt of funds by the buyer, and prevents the placement of a large number of fake orders.
Since there is no intermediary when exchanging through the Free TON smart contract, you do not need to pay commissions for the exchange, only commissions for the transactions themselves. When you make a deposit, the amount required to cover the storage fees of the smart contract data is debited from you (after the automatic calculation of the storage cost function is implemented, this amount will not exceed 0.001 TON CRYSTAL).
User support can be provided on a paid basis as an additional service (which is often found in the open source world).
To demonstrate the possibility of exchange and debugging of the solution, a JavaScript application for browsers was developed. It allows you to make a deposit / withdrawal of funds, place and confirm orders, and exchange or refund funds in a fully automatic mode.
https://youtu.be/cYRapYvWuFo - This video demonstrates the automatic exchange between USDT <-> TON CRYSTAL with comments (on test networks ropsten and net.ton.dev). Links to transactions are provided in the video description.
https://youtu.be/kz50UGwD01Y - This video demonstrates the automatic exchange between ETH <-> TON CRYSTAL with partial closing of the order volume.
Further tasks
To add a new coin, the target blockchain does not need to support a Turing-complete language, only 3 conditions must be met:
It should be possible to block funds by sha256 hashsum
It should be possible to block funds by time
The participant exchange data must fit into 32 bytes (we will expand it later, since the bitcoin Public Key requires 33 bytes)
During the development, a number of ideas were put forward to improve the exchange protocol, which are planned to be implemented in the future. Among them:
Purchase of TON CRYSTALS by participants who do not have this tokens (gas credit in TON allows you to do it).
Completion of the exchange protocol by third parties for a small reward in case of deviations from the protocol by participants, which increases the stability of the exchange.
Collecting verified statistics of participants will allow you to exchange with those participants who have proven themselves well.
Disclaimer:
Due to the extremely limited time for the contest, this software is for testing purposes only . The production-ready solution requires much more time. Thank you for understanding.
License:
Source code licensed under the MIT license.
Implementation and demonstration smart contracts of Atomic Swaps:
Ton Crystal, Native Ether, Ethereum ERC20, Bitcoin
Motivation
Develop an infrastructure that allows users to perform transactions between different blockchains without escrow in an untrusted environment. It will make the exchange market around TON Crystal more secure for OTC transactions.
Abstract
Atomic Swap — a smart contract technology enables the exchange of one cryptocurrency for another without using centralized intermediaries (such as exchanges).
I’ve learned two ways of swaps:
By using Hashed TimeLock Contract
By using Simplified Payment Verification.
HTLC — the most simple. It requires supporting common hash function (e.g. sha256) from blockchain and TimeLock contract functionality. + Сan be fully decentralised - Requires side communication between participants and locking money on specific time
SPV requires from one of two blockchains supporting runnig complex smart contracts (e.g. Ethereum or Ton) to verify transaction’s Merke Proof of transfer. + Transfer can be fast and automatic - Requires solution to identify the source of the transaction: mainnet / testnet / side blockchain by using oracles smart contracts / supporting SPV verification by validators.
I chose HTLC, because:
Time of contest is limited to 3 weeks
High transmission speed can be achieved through automation Atomic Swap Wallet, which supports SPV verification different blockchains off-chain.
Implementation
Tech Stack
FreeTon: TON-Solidity-Compiler, Solidity, JS for testing Ethereum: Truffle, Solidity, JS for testing Bitcoin (Work in progress): bitcoinjs-lib, JS
Repository structure
./ton - Atomic Swap Contracts for FreeTon blockchain ./eth - Atomic Swap Contracts for Ethereum blockchain ./btc - Atomic Swap Contracts for Bitcoin blockchain ./app - App for demostrating working of Smart Contracts at testnets. Not used in production, only for learning purpose
Part A have to generate the secret limited by 32 bytes and store it securely. Next, Part Ainitiate and create contract with hash of secret and participant’s address. In this contract the locktime should be doubled to avoid scam (e. g. 24h * 2 = 48h). After that, Part A have to send transaction or smart contract address to Part B.
Part B have to verify Part A’s contract: participant’s address, lockTime, amount, hash of code. If everything is OK — Part B should participate and create contract with Part A’s secret hash, otherwise Part B can do nothing. Part B should be careful, lockTime should be less Part A’s lockTime at the moment of creating contract. After, Part B have to send transaction or smart contract address to Part A.
Part A have to verify Part B’s contract. If everything is OK — Part A can redeem from Part B’s contract and reveal secret, otherwise Part A can wait timeLock and refund his transfer.
Part B should extract secret and redeem from Part A’s contract.
The most part of steps can be automated by wallet, with the exception of exchange address and transactions
./test/AtomicSwapMultisigWalletTest.js - Testing Atomic Swap case without AtomicSwapWallet, using only SetcodeMultisigWallet from Surf. Deploy Atomic Swap by external message.
./test/AtomicSwapTest.js - Testing standard Atomic Swap case, transfering ton crystals from one AtomicSwapWallet and redeem by another AtomicSwapWallet.
contract AtomicSwap - This contract implements Hashed TimeLock Contract. Lock ton crystals until lock time or redeem by secret.
constructor(address initiator, address participant, uint128 amount, uint32 timeLock) public - Constructor for creating Atomic Swap. Initiator must ptovide all required params. Constructor can be called in two ways: by external or external message. At first case, initator should send a small amount ton crystals to UNINIT account before deploying with bounce=false. After deploying initiator must send rest ton crystals. At second case, internal message, initiator must send required amount of ton crystals with internal deploy message.
function redeem(bytes secret) external; - Redeem Atomic Swap by participant before time lock. Emit Redeemed event to reveal secret. Sender must be participant. Destruct contract after execution.
function refund() external; - Refund Atomic Swap by initiator after time lock. Sender must be initiator. Destruct contract after execution.
function params() public view returns (address initiator, address participant, uint32 timeLock, uint32 now, uint256 secretHash, uint128 amount, uint256 balance) - Fetch params of Atomic Swap to verify it.
Bitcoin Atomic Swap Smart Contract
Description
Here is implementation of Hashed TimeLock Contract for Bitcoin using Script. This library doesn’t interact with blockchain and don’t implement wallet logic. Using this lib you can create raw transactions or calculate p2sh address of Atomic Swap. For interacting with bitcoin blockchain you should use your wallet, but I reccomend bitcoin-core.
Command line interface for testing bitcoin Atomic Swap contracts on regtest. To run it you should run regtest bitcoin network and send bitcoins to Alice’s and Dave’s p2wpkh addresses. In this exmaple Dave want to transfer btc to Alice using Atomic Swap.
node ./test/AtomicSwapTest.js create - creates p2sh address of Atomic Swap contract. Next you should send required bitcoins to this address using your bitcoin-core wallet from Dave p2wpkh address. At this step we store params, secretHash adn etc. in file ./test/db.json to avoid passing them through cli.
node ./test/AtomicSwapTest.js verify <p2shAddress> - Alice should verify that p2shAdress have right params. Participant and Initiator public keys, secretHash, timeLock.
node ./test/AtomicSwapTest.js redeem <tx-id> <tx-vout> <tx-hex> - to redeem Atomic Swap you need to provide params of transaction, that was send with bitcoins to p2shAddress. You can use bitcoin-core to get it. This command returns hex of transaction that you need to send using sendrawtransaction in bitcoin-core. After this step Atomic Swap transfer is redeemed by Alice.
node ./test/AtomicSwapTest.js refund <tx-id> <tx-vout> <tx-hex> - to refund Atomic Swap you need to provide params of transaction, that was send with bitcoins to p2shAddress. You can use bitcoin-core to get it. This command returns hex of transaction that you need to send using sendrawtransaction in bitcoin-core. After this step Atomic Swap transfer is refunded by Dave.
Specification AtomicSwapContrcats.js
This contract implements Hashed TimeLock Contract. Lock bitcoins until lock time or redeem by secret. I’ve used in contract OP_CHECKLOCKTIMEVERIFY and OP_SHA256.
function createAtomicSwapScript(secretHash, initiatorPubKey, participantPubKey, lockTime) - creates an atomic swap contract using Bitcoin Script.
function createAtomicSwapRedeemScript(signature, participantPubKey, secret) - creates an atomic swap redeem script. Can be used together with #createAtomicSwapScript.
function createAtomicSwapRefundScript(signature, initiatorPubKey) - creates an atomic swap redeem script. Can be used together with #createAtomicSwapScript.
contract AtomicSwap - implements Hashed TimeLock Contract. Lock native ethers or ERC20 tokens until lock time or redeem by secret. Everyone can deploy this contract or use already deployed contract by another person.
function createSwap(uint256 secretHash, address participant, uint256 value, uint256 timeLock) external payable - creates Atomic Swap transfer from sender to participant. Lock native ether value until timeLock or redeem. secretHash is unique identifier for Atomic Swap. Be careful while generating secret.
function createSwapErc20(uint256 secretHash, address participant, uint256 alue, uint256 timeLock, address tokenAddr) external - creates Atomic Swap transfer from sender to participant. Lock erc20 tokens value until timeLock or redeem. secretHash is unique identifier for Atomic Swap. Be careful while generating secret. tokenAddr is address of ERC20 compatible smart contract.
function redeem(bytes calldata secret) external - redeem Atomic Swap by participant before time lock. Emit Redeemed event to reveal secret. Sender must be participant.
function refund(uint256 secretHash) external - refund Atomic Swap by initiator after time lock. Sender must be initiator.
function params(uint256 secretHash) public view returns (address initiator, address participant, uint256 timeLock, uint256 currTime, uint256 value, address tokenAddr, SwapType swapType) - fetch params of Atomic Swap to verify it.
2 users participate in this example: 0-Alice and 1-Bob. Alice has ton rubins and want to buy Ether. Bob has Ether, want to buy ton rubins.
I will use Atomic Swap cli interface.
Atomic Swap cli help message:
$ node ./app/app.js -h
Usage: app [options] [command]
Options:
-V, --version output the version number
-u, --user <number> user id, can be used to specify user (default: 0)
-h, --help display help for command
Commands:
ton command for freeton blockchain
eth command for ethereum blockchain
btc command for bitcoin blockchain
reset reset keys and wallets
help [command] display help for command
Preparation
Need to check users have working wallets and positive balances. Deploy wallet if need.
-u 0 - parameter for Alice -u 1 - parameter for Bob
Bob received address of Atomic Swap contract from Alice and verified it. Timelock in 2 days, balance of Atomic Swap is sufficient, code hash is correct.
The only drawback, as it seems to me, is that there is little originality in this competition, everyone went the same way and uses HTLC. Perhaps the next competition will be for the implementation of Bitcoin SPV, as mentioned in the link above. I have just worked out in this direction, the code turns out to be really more complex.
Tell me, is any of the works production-ready?
Personally, I make my own just so that I can use it myself later. If there are ready-made ones, I would use them for exchanges. And if not, what are the plans to bring the contest works to working condition?
Is it possible to verify Ethereum’s Merkle tree with keccak256 and check ethash PoW in TON VM?
Or verify TON Ed25519 signature in Ethereum VM?
HTLC require only the presence of a sha256, which is found in many blockchains. In this sense it is much more versatile.
I can only say for our project. It is not production-ready, it will take several months to complete.
Improvement is required not only in the part of the UI, but also a number of problems need to be solved, for example, the possibility of loss of funds, which I wrote about in an article on Medium (only in Russian)
idk, to my shame. That’s why I didn’t plan to integrate with Ethereum at first. In any case, this would be too expensive for SPV due to more frequent transactions. So for a combined BTC-ETH contest, the HTLC seems the only right solution, agree.
Tell me, which of you added this functionality to your solution?
Please do not be angry if I was inconsiderate and did not see this in your submission. Just answer. Thank.
My second question is how long will it take for you to get a stable solution into production?
One of the tough conditions for implementation was this:
Tell me, which of you added this functionality to your solution?
Please do not be angry if I was inconsiderate and did not see this in your submission. Just answer. Thank.
Here I see some lack of specifics in the assignment. Who is a broker? The presence of the owner person, in the sense that he is the only one organizing the exchange, makes the solution partially centralized, and the owner - the main point of failure. This means that the service cannot be highly reliable. The arrest and shutdown of some centralized mixers and exchanges is a clear confirmation of this.
Therefore, we designed our solution with decentralization in mind. There is no “owner” here, only the “creator”. Which deploys a TON Orderbook smart contract and that’s it. He does not incur any operating costs and does not receive any fees. In our solution, the broker is a smart contract. It collects a constant fee when depositing (see the receive () function in tonorderbook.sol) to cover the smc storage fee (it is also constant).
This is the same approach as in uniswap and other contract-based exchanges. And it is very reliable.
Of course, we could make it possible to collect fees for the creator. However, it doesn’t make any sense. Since all sources are distributed under a free license, anyone can deploy the same smart contract except that it does not charge a fee. And users will prefer it.
If Satoshi charged his own fee in every Bitcoin transaction, how quickly would the fork appear without it?
My second question is how long will it take for you to get a stable solution into production?
approx. 3-5 months.
The most difficult tasks that need to be implemented for a production-ready solution are the ability to complete the last part of the transaction by a third party and the ability to buy crystals by a person who does not have them.