Atomic Swap on Bitcoin SV
Atomic swap is the trustless exchange of different assets without counterparty risk. We show a general method to achieve atomic swap of bitcoins and tokens on the same underlying BSV blockchain.
Token Sale Contract
We develop a token sale contract which trades bitcoins for layer 1 tokens without the risk of one party defaulting. Anyone can purchase tokens by sending bitcoin payments to the contract and is guaranteed to get tokens at predefined price automatically, enforced at the consensus layer. It is built atop our technology of maintaining state and layer 1 tokens in Bitcoin smart contracts. The full contract is shown below with comments inline.
As in the previous articles, Line 15 & 17 ensure the preimage is from the current transaction. Line 23 reads previous contract balance, i.e., amount of bitcoins in the output spent by this input. Line 25 calculates new contract balance. Line 28 allocates tokens to the buyer. The rest validates new bitcoin and token balances are in the new output. Here is some sample code using this contract.
We only demonstrate the basics of atomic swaps. There are many ways to extend it to be more practical and powerful. Some examples are:
- swap bitcoins for layer 2 tokens; layer 1 tokens for layer 2 tokens; one layer 1/2 token for another layer 1/2 token
- add another public function for the issuer(s) to redeem the funds in the contract
- vary token price based on purchase time and setup token release time, by obtaining time using techniques in contract CheckLockTimeVerify
- merge token records if same buyer purchases multiple times
There are several salient features distinguishing this approach from existing atomic swaps.
- It is non-interactive. It requires no back and forth communication or cooperation between involved parties. Thus many issues caused by one party becoming unresponsive are completely avoided.
- It does not require timelocks and thus does not lockup funds.
A swap is contained in a single transaction calling the contract. Either it is accepted, bitcoins and tokens are exchanged instantly; or it is rejected and the exchange does not happen at all. It is truly atomic since there is no intermediate state for the transaction.
Bill from BitShizzle has improved the basic TokenSale contract and demonstrated it on the live bitcoin network, where five consecutive token purchases are made¹ at the price of 1000 satoshis/token: purchase 1 token, purchase 3 tokens, purchase 5 tokens , purchase 7 tokens, purchase 9 tokens. Eventually, the contract is paid 25000 satoshis and the token table is updated correctly as follows:
Disclaimer: this article focuses on technical aspects of atomic swaps and does not cover legal aspects.
 For simplicity, same buyer (i.e., public key) is used. It is trivial to change to multiple public keys, each representing a buyer.