Examples
An extensive collection of examples is available in the GitHub repository. Below we discuss a few of these examples in more details. These examples focus mainly on the use of the SDK, while the Examples page in the language section focuses more on the CashScript syntax.
Transfer With Timeout
The idea of this smart contract is explained on the Language Examples page. The gist is that it allows you to send an amount of BCH to someone, but if they don't claim the sent amount, it can be recovered by the sender.
Now to put this smart contract in use in a JavaScript application we have to use the CashScript SDK in combination with a BCH library such as BCHJS, bitcore-lib-cash or Libauth. These libraries are used to generate public/private keys for the contract participants. Then these keys can be used in the CashScript SDK. The key generation code is left out of this example, since this works differently for every library.
Memo.cash Announcement
Memo.cash is a Twitter-like social network based on Bitcoin Cash. It uses OP_RETURN
outputs to post messages on-chain. By using a covenant we can create an example contract whose only job is to post Isaac Asimov's first law of smart contracts to Memo.cash. Just to remind its fellow smart contracts.
This contract expects a hardcoded transaction fee of 1000 satoshis. This is necessary due to the nature of covenants (See the Licho's Mecenas example for more information on this). The remaining balance after this transaction fee might end up being lower than 1000 satoshis, which means that the contract does not have enough leftover to make another announcement.
To ensure that this leftover money does not get lost in the contract, the contract performs an extra check, and adds the remainder to the transaction fee if it's too low.
The CashScript code above ensures that the smart contract can only be used in the way specified in the code. But the transaction needs to be created by the SDK, and to ensure that it complies with the rules of the smart contract, we need to use some of the more advanced options of the SDK.