Using CashScript with CashConnect
Introduction
The previous chapter only demonstrated sending using CashConnect. But, for msot real-world use-cases, you'll also need to unlock those UTXOs that you create.
The below will demonstrate how to do this using Cashscript.
Defining the contract
We're going to use a very simple (and relatively useless) example: A password protected Smart Contract that must be unlocked using the Password "pass":
pragma cashscript ~0.12.0;
contract Password() {
function unlock(bytes password) {
require(password == bytes("pass"), "Password must be pass");
}
}The @cashconnect-js/templates-dev package then has a utility class to help convert this into template format.
INFO
Note that the resulting script format is very similar to LibAuth Template format but, if debug is set, CashScript sourcemaps will also be included (The BlockchainTest util has partial support for these).
Building the template
Let's build a template using the above code and CashScript utils:
There are a few things to note in the above:
- We now have two actions: one for locking the contract and one for unlocking the contract.
- We use a Util from the
@cashconnect-js/templates-devpackage to add the Locking/Unlocking scripts to our global list of scripts in the template. - We set a
debug: trueproperty so that we can get CashScript Source Maps when using with outBlockchainTestinstance later
DANGER
Some of the above will be refactored when an outpoint variable type is supported. See Roadmap.
Testing the Template
As with the previous chapter, let's now create a TestEnv to test our template.
In the above, we are first executing an action to create the Password Protected UTXO and then following up with an action to Unlock/Spend it.
Note that in the unlock, we spread the returned data of the Lock Action into the parameters of the Unlock Action. This is a pattern that will likely be repeated often in CashConnect as it the recommended way to model and handle Contract Systems. We will be diving into this in the next chapter on "Modeling Contract Systems".