Skip to main content

Vesting

Now that we are a bit more famliar on how to interact properly with a smart contract let's do a step forward and see if we can come up with a sligthly more complex contract.

The final result can be found at HarmonicLabs/vesting-pluts.

info

Check package.json file at HarmonicLabs/vesting-pluts for versions of packages used lately.

Project set up

We will once again start from the plu-ts-starter template (with the plu-ts version ~0.8.0) :

git clone https://github.com/HarmonicLabs/plu-ts-starter.git
mv plu-ts-starter vesting-pluts
cd vesting-pluts
git remote remove origin

this gives us a simple project structure:

./vesting-pluts
├── package.json
├── package-lock.json
├── Introduction
├── src
│ ├── contract.ts
│ ├── index.ts
│ ├── MyDatum
│ │ └── index.ts
│ └── MyRedeemer
│ └── index.ts
└── tsconfig.json

Add dependencies

Just like the Hello plu-ts example; this project already comes with plu-ts as dependecy; all we need to do to then is to run

npm install

This time instead of working with Browser wallets, we will generate key pairs using Web Crypto API and thus generate address. We will also be making use of Blockfrost API to interact with the contract, address, transaction on/to-be-on chain (enabled with the package @harmoniclabs/blockfrost-pluts)

Template overview

Before we dive in let's get familiar with the starter template.

If we now navigate to src/contract.ts we see we have a very simple validator already!

src/contract.ts
import { Address, bool, compile, makeValidator, Credential, pBool, pfn, Script, ScriptType, V2 } from "@harmoniclabs/plu-ts";
import MyDatum from "./MyDatum";
import MyRedeemer from "./MyRedeemer";


export const contract = pfn([
MyDatum.type,
MyRedeemer.type,
V2.PScriptContext.type
], bool)
(( datum, redeemer, ctx ) =>
// always suceeds
pBool( true )
);


///////////////////////////////////////////////////////////////////
// ------------------------------------------------------------- //
// ------------------------- utilities ------------------------- //
// ------------------------------------------------------------- //
///////////////////////////////////////////////////////////////////

export const untypedValidator = makeValidator( contract );

export const compiledContract = compile( untypedValidator );

export const script = new Script(
ScriptType.PlutusV2,
compiledContract
);

export const scriptMainnetAddr = new Address(
"mainnet",
new Credential(
"script",
script.hash
)
);

export const scriptTestnetAddr = new Address(
"testnet",
new Credential(
"script",
script.hash.clone()
)
);

export default contract;

Let's focus only on the contract for now;

This contract expects a MyDatum, a MyRedeemer and finally a PScriptContext to validate a transaction.

All of the three above are just Structs.

MyDatum and MyRedeemer are user-defined types respectively in src/MyDatum/index.ts and src/MyRedeemer/index.ts.

src/MyDatum/index.ts
import { int, pstruct } from "@harmoniclabs/plu-ts";

// modify the Datum as you prefer
const MyDatum = pstruct({
Num: {
number: int
},
NoDatum: {}
});

export default MyDatum;
src/MyRedeemer/index.ts
import { pstruct } from "@harmoniclabs/plu-ts";

// modify the Redeemer as you prefer
const MyRedeemer = pstruct({
Option1: {},
Option2: {}
});

export default MyRedeemer;

Whereas, PScriptContex is a predefined data structure that is passed by the cardano-node itself that will run our smart contract.

Finally, the contract is used in src/index.ts which is our entry point.

src/index.ts
import { script } from "./contract";

console.log("validator compiled succesfully! 🎉\n");
console.log(
JSON.stringify(
script.toJson(),
undefined,
2
)
);

The index just imports script from src/contract.ts and prints it out in the json form.

If we go back to src/contract.ts we see that the script is obtained using the following steps:

  1. Adapting the validator to the standard using makeValidator
src/contract.ts
/* ... */

export const untypedValidator = makeValidator( contract );

export const compiledContract = compile( untypedValidator );

export const script = new Script(
ScriptType.PlutusV2,
compiledContract
);

/* ... */
  1. Compiling the validator with compile
src/contract.ts
/* ... */

export const untypedValidator = makeValidator( contract );

export const compiledContract = compile( untypedValidator );

export const script = new Script(
ScriptType.PlutusV2,
compiledContract
);

/* ... */
  1. Wrapping it in a Script that can be used offchain
src/contract.ts
/* ... */

export const untypedValidator = makeValidator( contract );

export const compiledContract = compile( untypedValidator );

export const script = new Script(
ScriptType.PlutusV2,
compiledContract
);

/* ... */

That is all we need for now.

Run the template

If we did every step above correctly, we should be able to run

npm run start

and the output should look like:

validator compiled succesfully! 🎉

{
"type": "PlutusScriptV2",
"description": "",
"cborHex": "56550100002225333573466644494400c0080045261601"
}

Well congratulations 🥳!

This is your first compiled smart contract 🎉!

But we won't stop here for sure!

Let's personalize this smart contract.

The contract

The contract should succeed if the following two conditions are met:

  • the transaction is signed by the PPubKeyHash defined in the UTxO datum;
  • the transaction lower bound is Finite and greather than the datum deadline field;

VestingDatum

The first thing we notice is that we need a custom datum.

Let's rename the MyDatum folder to VestingDatum and modify src/contract.ts as follows

src/contract.ts
import { PPubKeyHash, int, pstruct } from "@harmoniclabs/plu-ts";

// modify the Datum as you prefer
const VestingDatum = pstruct({
VestingDatum: {
beneficiary: PPubKeyHash.type,
deadline: int // posix time
}
});

export default VestingDatum;

Contract signature

Now that we have our datum structure we can use it in the contract definition.

Since we are changing the contract signature, we also know that we don't need any particular redeemer; so we can just change it to a simple data type;

We can also delete the MyRedeemer directory, if we want, since we don't need it anymore.

src/contract.ts
/* imports */

export const contract = pfn([
VestingDatum.type,
data,
PScriptContext.type
], bool)
(( datum, _redeemer, ctx ) =>
// always succeeds
pBool( true )
);

/* other code */

Contract logic

As for now our contract succeeds every time we use it.

That definitely doesn't meet the specifications; so we need to change the function body too.

We know for sure that we need 2 conditions; so we will check them separately using two terms: signedByBeneficiary and deadlineReached

src/contract.ts
/* imports */

export const contract = pfn([
VestingDatum.type,
data,
PScriptContext.type
], bool)
(( datum, _redeemer, ctx ) => {

// inlined
const signedByBeneficiary = pBool( false );

// inlined
const deadlineReached = pBool( false );

return signedByBeneficiary.and( deadlineReached );
});

/* other code */

We just initialize them to pBool( false ) so that if we forget them the contract fails.

But we can already see the structure of the contract this way: we have two conditions, and we want bot to be true.

What's // inlined for?

As defined above the terms are inlined every time that are used.

This is because we are not using plet to create an actual plu-ts variable.

Instead we are just holding a reference to that piece of code.

This is not necessarly bad because it helps making the contract more readable (and plet would have inlined the term anyway in this particular case for efficiency).

But it is definitely useful to keep in mind that what we have is always inlined with a small comment.

signedByBeneficiary

The first condtion for the contract to succeed is:

the transaction is signed by the PPubKeyHash defined in the UTxO datum;

To check that we can use the signatories field defined in the PTxInfo struct.

We can access the field from the context using the dot notation:

ctx.tx.signatories

the signatories field is a list of PPubKeyHash; so we have access to all the TermList methods.

so we can use the some method to check that at least one element of the list satisfies a given predicate.

In our case:

ctx.tx.signatories.some( signer => signer.eq( datum.beneficiary ) );

Or the equivalent (but sligthly more efficient)

ctx.tx.signatories.some( datum.beneficiary.eqTerm );

And that's it!

Our signedByBeneficiary condition becomes the one-liner

src/contract.ts
// inlined
const signedByBeneficiary = ctx.tx.signatories.some( datum.beneficiary.eqTerm );

deadlineReached

Now we can pass at the second condtion:

the transaction lower bound is Finite and greather than the datum deadline field

but what do we mean by "transaciton lower bound"?

That is due to how time is handled on-chain.

Handling time on chain is definitely not something simple due to the fact that the underlying system is distributed.

That means that we can't really be 100% sure of the exact moment the script is executed.

To work around this problem, time is represented on chain with a range in which the transaction is considered valid.

If ever the transaction where sent outside of the range it would be rejected by the node before even executing the script!

So we can at least be sure that the script is excuted in the given time range.

We can access the transaction validity time range trough the interval property of the PTxInfo struct.

this is done once again using the dot notation:

ctx.tx.interval

The interval type is somewhat complex due to the nested structure; we have

  • two initial properties (from and to) representing the lower and upper bound.
  • both the properties then have a bound property and an inclusive property which is a boolean (of the two we are only interested in the bound one)
  • finally the bound has 3 constructors as below
const PExtended = pstruct({
PNegInf: {},
PFinite: { _0: int },
PPosInf: {}
});

where the PFinite one is the one we are interested in.

so reaching the bound field is the easy part and can be done as follows:

ctx.tx.interval.from.bound

but then we have to use pmatch to understand what constructor was used;

in particular we are only interested in the PFinite one so we'll use the underscore (_) wildcard to match the other two.

pmatch( ctx.tx.interval.from.bound )
.onPFinite(({ _0: lowerInterval }) => ... )
._( _ => pBool( false ) )

and now that we have access to the transaction lower bound we can finally check for the deadline to have been passed

datum.deadline.ltEq( lowerInterval ) 

So the final deadlineReached condition becomes:

src/contract.ts
// inlined
const deadlineReached =
pmatch( ctx.tx.interval.from.bound )
.onPFinite(({ _0: lowerInterval }) =>
datum.deadline.ltEq( lowerInterval )
)
._( _ => pBool( false ) )

For debugging closely in case the contract fails due to deadlineReached condition, and to throw a specific error in that case, we can add pTrace to the return statement and thus modify it as:

src/contract.ts
return signedByBeneficiary.and( ptraceIfFalse.$(pdelay(pStr("deadline not reached or not specified"))).$( deadlineReached ) )

Compiling the contract

Now our smart contract should look something like this:

src/contract.ts
export const contract = pfn([
VestingDatum.type,
data,
PScriptContext.type
], bool)
(( datum, _redeemer, ctx ) => {

// inlined
const signedByBeneficiary = ctx.tx.signatories.some( datum.beneficiary.eqTerm );

// inlined
const deadlineReached =
pmatch( ctx.tx.interval.from.bound )
.onPFinite(({ _0: lowerInterval }) =>
datum.deadline.ltEq( lowerInterval )
)
._( _ => pBool( false ) )

return signedByBeneficiary.and( ptraceIfFalse.$(pdelay(pStr("deadline not reached or not specified"))).$( deadlineReached ) )
});

As we saw in the Hello plu-ts example project, we can compile the contract by first passing the term to makeValidator and then pass the result to the compile function.

We finally pass the compiled Contract to the Script constructor so that we can use it properly.

src/contract.ts
/* contract definition above */

export const untypedValidator = makeValidator( contract );

export const compiledContract = compile( untypedValidator );

export const script = new Script(
ScriptType.PlutusV2,
compiledContract
);

/* some other code */

So now running the project using

npm run start

we should see something like this

validator compiled succesfully! 🎉

{
"type": "PlutusScriptV2",
"description": "",
"cborHex": "5901a259019f0100003232323232322225333573466644464646644a666ae68008004528198070a4811c4572726f7220696e207369676e6564427942656e6966696369617279003323300c214a04446644a666ae68008528800980200109801800919b8f375c6ae84008004cc8cc8c0308d5d01801000800a5eb11d71bac32357426ae88d5d11aba2357446ae88d5d11aba23574400200426601c2920125646561646c696e65206e6f742072656163686564206f72206e6f742073706563696669656400323333222232332533357346002900008018a999ab9a300148008401054ccd5cd1800a4008200a2c6e1cd55ce8009aab9e00137540086ae84c028d5d09805191aba1357446ae88d5d11aba2357446ae88d5d1000801800919b89375a646ae84d5d10008019bad357420020024940c020010c01cd5d098038008018010008a4c2c46aae78dd5000911980190801111198028011801800980111111919980318020009801800801198020018011112999aab9f001003133002357420026ae880048c8c0088cc0080080048c0088cc008008004894ccd5cd0008a511335738a004941"
}

Interacting with the contract

We will use the native npm script functionality to define some scripts to interact arbitrarly with our new contract.

We can define a new script by adding an entry in the scripts field of the package.json file that you find in the root of the project.

Right now you should see something like this:

package.json
"scripts": {
"build": "tsc -p ./tsconfig.json && tsc-alias -p ./tsconfig.json",
"start": "npm run build && node dist/index.js"
},

We can add our own scripts by specifying the script name as key and the command to execute as value.

As an example, say we want a better name for the "start" script, we could do something like:

package.json
"scripts": {
"build": "tsc -p ./tsconfig.json && tsc-alias -p ./tsconfig.json",
"start": "npm run build && node dist/index.js",
"vesting:compile": "npm run start"
},

Now running

npm run vesting:compile

is equivalent to npm run start.

To keep the project clean we'll create a new directory under src called app where all our scripts will be.

./vesting-pluts
└── src
└── app

Save the script

Now we can start working with the off-chain part of plu-ts.

Let's start by saving the compiled script to a file when we compile it.

In the src/index.ts file add the following:

src/index.ts
import { existsSync } from "fs";
import { mkdir, writeFile } from "fs/promises";

/* old code */

async function main()
{
if( !existsSync("./testnet") )
{
await mkdir("./testnet");
}
await writeFile("./testnet/vesting.plutus.json", JSON.stringify(script.toJson(), undefined, 4))
}
main();

Now running

npm run vesting:compile

should still print the old result; but it will also create a new testnet directory with the file vesting.plutus.json in it.

Get some keys

Depending on if you are working in private or public testnet, there are 2 way to get your keys and start creating transactions.

You can generate your own key pair using generateKey() method from Crypto Web API. Read more about this here.

Using this, to generate 2 pairs of keys, create a file genKeys.ts in the app folder that looks like this

src/app/genKeys.ts
import { existsSync } from "fs";
import { Address, Credential, PublicKey, PrivateKey, PubKeyHash } from "@harmoniclabs/plu-ts";
import { config } from "dotenv";
import { mkdir, writeFile } from "fs/promises";

import pkg from 'blakejs';
const { blake2b } = pkg;

config();

async function genKeys()
{
const nKeys = 2;

const promises: Promise<any>[] = [];

if( !existsSync("./testnet") )
{
await mkdir("./testnet");
}

for( let i = 1; i <= nKeys; i++ )
{
// generate public-private keypair
let keyPair = await globalThis.crypto.subtle.generateKey(
{
name: "Ed25519",
namedCurve: "Ed25519"
},
true,
["sign", "verify"]
);


// convert keyPair.(publicKey|privateKey)<CryptoKeyPair> ultimately to PublicKey which can be converted to cborString to store it for future reference

// Export public key in a way compatible to Cardano CLI
const publicKeyArrayBuffer = await globalThis.crypto.subtle.exportKey('raw', keyPair.publicKey);
const publicKeyUint8Array = new Uint8Array(publicKeyArrayBuffer);
const publicKey = new PublicKey(publicKeyUint8Array);
const publicKeyHash = new PubKeyHash(blake2b(publicKeyUint8Array, undefined, 28)); // to build Credential
const pubKeyJsonObj = {
type: "PaymentVerificationKeyShelley_ed25519",
description: "Payment Verification Key",
cborHex: publicKey.toCbor().toString()
}; // JSON structure similar to the one generated when by Cardano CLI
const pubKeyJsonStr = JSON.stringify(pubKeyJsonObj, null, 4);
await writeFile(`./testnet/payment${i}.vkey`, pubKeyJsonStr);

// Export of the private key in a way that's compatible with the Cardano CLI
const privateKeyArrayBuffer = await globalThis.crypto.subtle.exportKey('pkcs8', keyPair.privateKey); // privateKey cannot be exported 'raw' hence 'pkcs8'
const privateKeyUint8Array = new Uint8Array(privateKeyArrayBuffer.slice(-32));
const privateKey = new PrivateKey(privateKeyUint8Array);
const pvtKeyJsonObj = {
type: "PaymentSigningKeyShelley_ed25519",
description: "Payment Signing Key",
cborHex: privateKey.toCbor().toString()
}; // JSON structure similar to the one generated when by Cardano CLI
const pvtKeyJsonStr = JSON.stringify(pvtKeyJsonObj, null, 4);
await writeFile(`./testnet/payment${i}.skey`, pvtKeyJsonStr);

// Check that the derivations went fine
const pubKeyfromPriv = privateKey.derivePublicKey();
if (pubKeyfromPriv.toString() !== publicKey.toString()) {
throw new Error("\tPublic key derivation from private key failed");
}
else {
console.log("\tPublic key derivation from private key succeeded");
}

// Create the address
const credential = Credential.keyHash(publicKeyHash);
const address = new Address("testnet", credential);
await writeFile(`./testnet/address${i}.addr`, address.toString());
}

// wait for all files to be copied
await Promise.all( promises );
}
genKeys();

Add a new npm script vesting:genKeys

package.json
"scripts": {
// ...
"vesting:genKeys": "npm run build:light && node dist/app/genKeys.js"
}

so that running

npm run vesting:genKeys

should give us 2 pairs of keys and 2 addresses under the testnet folder.

get some funds

Remember to fund the addresses. In this example, make sure to fund address1 and address2; just so that there has been some transactions involving these addresses, and they appear on blockchain and inturn be visible for Blockfrost. Read more about such possible Blockfrost error here.

You can use the Cardano Testnet Faucet to get some testnet funds.

Just be sure to select the Preprod testnet (as we opted here).

Setup Blockfrost API

First and foremost, we need to setup Blockfrost API to use in our app.

It is enabled by the package @harmoniclabs/blockfrost-pluts. In your terminal, do

npm install @harmoniclabs/blockfrost-pluts

Go to https://blockfrost.io/ and create a new project for this example (a free plan is more than enough for now). Make sure to pick Preprod as your preferred network.

Once done, navigate to the Dashboard and copy over PROJECT_ID to setup.

Now, create file blockfrost.ts within src/app:

src/app/blockfrost.ts
import { BlockfrostPluts } from "@harmoniclabs/blockfrost-pluts";

function blockfrost () {
const provider = new BlockfrostPluts({
projectId: "Paste your PROJECT_ID here"
});
return provider;
}

export default blockfrost;

Make sure to not check-in your PROJECT_ID into any versioning systems. Alternatively, you can always use environment variables here.

To enable blockfrost within other files, we will instantiate blockfrost() with the PROJECT_ID.

To perform transactions through Blockfrost, we need to instantiate our TxBuilder with Blockfrost.

Create file getTxBuilder.ts within src/app, exporting method getTxBuilder() which will thus be used to instantiate an instance of TxBuilder and further used.

src/app/getTxBuilder.ts
import { TxBuilder } from "@harmoniclabs/plu-ts";
import { BlockfrostPluts } from "@harmoniclabs/blockfrost-pluts";

/**
* we don't want to do too many API call if we already have our `txBuilder`
*
* so after the first call we'll store a copy here.
**/
let _cachedTxBuilder: TxBuilder | undefined = undefined

export default async function getTxBuilder(Blockfrost: BlockfrostPluts): Promise<TxBuilder>
{
if(!( _cachedTxBuilder instanceof TxBuilder ))
{
const parameters = await Blockfrost.getProtocolParameters();
_cachedTxBuilder = new TxBuilder(parameters);
}

return _cachedTxBuilder;
}

Create a vesting utxo

Now we can finally start playing around with the vesting contract.

Read the script

Since we already have our file compiled and saved, it is probably a good idea to read the compiled result instead of re-compiling the contract each time we run the script.

To do so, we can always read the saved Script. First we need to read the vesting.plutus.json file as string.

const scriptFile = await readFile("./testnet/vesting.plutus.json", { encoding: "utf-8" });

Then, to utimately retrieve the Script from the cborHex in the JSON file:

const script = Script.fromCbor(JSON.parse(scriptFile).cborHex)

From here we can generate the script address using the Address class (from the offchain of plu-ts) and the Script as Credential.

const scriptAddr = new Address(
"testnet",
new Credential(CredentialType.Script, script.hash)
);
Generate Address

Instead of new Address("testnet", ...), we can also do Address.testnet(...). Read more here.

Get your address

Now, to build and send our transaction we are just missing the sender key, address and the beneficiary public key.

Once again we retrieve them from our saved files using node.js readFile.

const privateKeyFile = await readFile("./testnet/payment1.skey", { encoding: "utf-8" });
const privateKey = PrivateKey.fromCbor( JSON.parse(privateKeyFile).cborHex );

const addr = await readFile("./testnet/address1.addr", { encoding: "utf-8" });
const address = Address.fromString(addr);

const publicKeyFile = await readFile("./testnet/payment2.vkey", { encoding: "utf-8" });
const pkh = PublicKey.fromCbor( JSON.parse(publicKeyFile).cborHex ).hash;

Query the address utxos

Before we really start building our transaction we need some utxos to use as input. We can query the utxos available in our address through Blockfrost. Make sure to populate both the addresses with some funds.

const utxos = await Blockfrost.addressUtxos( address );
info

Instead of blindly assigning the first utxo of the utxos[] as input, let us assure that we use the utxo that has atleast 10 ada in it just to avoid possible failures.

const utxo = utxos.find(utxo => utxo.resolved.value.lovelaces >= 10_000_000)!;

Build the Transaciton

Our transaction will be constructed as follows:

  • our UTxO as input
  • an output to the contract with an attached VestingDatum
  • the change going back to the address

which translates to the following code

let tx = await cli.transaction.build({
inputs: [{ utxo: utxo }],
collaterals: [ utxo ],
outputs: [
{
address: scriptAddr,
value: Value.lovelaces( 10_000_000 ),
datum: VestingDatum.VestingDatum({
beneficiary: pBSToData.$( pByteString( pkh.toBuffer() ) ),
deadline: pIntToData.$( nowPosix + 10_000 )
})
}
],
changeAddress: addr
});
Have you noticed?

The datum attached to the output is generated using on-chain code!

This is done, thanks to plu-ts, being able to evaluate on-chain code and use the result as Data.

This way we can use the on-chain types to describe the plutus data off-chain, without the need to use low level Data elements!

Sign and Submit

Now that we have our transaciton, all we need is just to Sign and Submit it.

And guess what? This is now extremly easy with plu-ts and Blockfrost.

await tx.signWith( new PrivateKey(privateKey) );

const submittedTx = await Blockfrost.submitTx( tx );

All we need to do now is to put it all together in a file createVesting.ts under the app folder.

src/app/createVesting.ts
import { Address, Credential, Hash28, PrivateKey, Value, pBSToData, pByteString, pIntToData, CredentialType, PublicKey, Script } from "@harmoniclabs/plu-ts";
import VestingDatum from "../VestingDatum";
import getTxBuilder from "./getTxBuilder";
import { BlockfrostPluts } from "@harmoniclabs/blockfrost-pluts";
import blockfrost from "./blockfrost";
import { readFile } from "fs/promises";

async function createVesting(Blockfrost: BlockfrostPluts)
{
const txBuilder = await getTxBuilder(Blockfrost);

const scriptFile = await readFile("./testnet/vesting.plutus.json", { encoding: "utf-8" });
const script = Script.fromCbor(JSON.parse(scriptFile).cborHex)
const scriptAddr = new Address(
"testnet",
new Credential(CredentialType.Script, script.hash)
);

const privateKeyFile = await readFile("./testnet/payment1.skey", { encoding: "utf-8" });
const privateKey = PrivateKey.fromCbor( JSON.parse(privateKeyFile).cborHex );

const addr = await readFile("./testnet/address1.addr", { encoding: "utf-8" });
const address = Address.fromString(addr);

const publicKeyFile = await readFile("./testnet/payment2.vkey", { encoding: "utf-8" });
const pkh = PublicKey.fromCbor( JSON.parse(publicKeyFile).cborHex ).hash;

const utxos = await Blockfrost.addressUtxos( address )
.catch( e => { throw new Error ("unable to find utxos at " + addr) })

// atleast has 10 ada
const utxo = utxos.find(utxo => utxo.resolved.value.lovelaces >= 10_000_000)!;
if (!utxo) {
throw new Error("No utxo with more than 10 ada");
}

const nowPosix = Date.now();

let tx = await txBuilder.buildSync({
inputs: [{ utxo: utxo }],
collaterals: [ utxo ],
outputs: [
{
address: scriptAddr,
value: Value.lovelaces( 10_000_000 ),
datum: VestingDatum.VestingDatum({
beneficiary: pBSToData.$( pByteString( pkh.toBuffer() ) ),
deadline: pIntToData.$( nowPosix + 10_000 )
})
}
],
changeAddress: address
});

await tx.signWith( new PrivateKey(privateKey) );

const submittedTx = await Blockfrost.submitTx( tx );
console.log(submittedTx);

}

if( process.argv[1].includes("createVesting") )
{
createVesting(blockfrost());
}

For the ease of use, let's add a new npm script in package.json

package.json
"scripts": {
// ...
"vesting:create": "npm run build:light && node dist/app/createVesting.js"
}

now running

npm run vesting:create

will generate a new utxo for the smart contract ready to be spent!

We should also see the respective transaction hash in the console now.

8b3deb9095898c4d1385269f0af00febaa547e4b4365978d073519caa52f791e

Spend the locked utxo

Get all you need

You know the process now:

  • read the script
  • build the script address
  • read address and keys
  • query utxo

These are the steps needed before we can start to build the transaction and are often very similar.

import { Address, DataI, Credential, PrivateKey, CredentialType, Script, DataConstr, DataB, PublicKey, defaultPreprodGenesisInfos } from "@harmoniclabs/plu-ts";
import getTxBuilder from "./getTxBuilder";
import { BlockfrostPluts } from "@harmoniclabs/blockfrost-pluts";
import blockfrost from "./blockfrost";
import { readFile } from "fs/promises";

async function claimVesting(Blockfrost: BlockfrostPluts)
{
const txBuilder = await getTxBuilder(Blockfrost);

const scriptFile = await readFile("./testnet/vesting.plutus.json", { encoding: "utf-8" });
const script = Script.fromCbor(JSON.parse(scriptFile).cborHex)
const scriptAddr = new Address(
"testnet",
new Credential(CredentialType.Script, script.hash)
);

const privateKeyFile = await readFile("./testnet/payment2.skey", { encoding: "utf-8" });
const privateKey = PrivateKey.fromCbor( JSON.parse(privateKeyFile).cborHex );

const addr = await readFile("./testnet/address2.addr", { encoding: "utf-8" });
const address = Address.fromString(addr);

const publicKeyFile = await readFile("./testnet/payment2.vkey", { encoding: "utf-8" });
const pkh = PublicKey.fromCbor( JSON.parse(publicKeyFile).cborHex ).hash;

const utxos = await Blockfrost.addressUtxos( address )
.catch( e => { throw new Error ("unable to find utxos at " + addr) });
// atleast has 10 ada
const utxo = utxos.find(utxo => utxo.resolved.value.lovelaces >= 10_000_000);
if (!utxo) {
throw new Error("No utxo with more than 10 ada");
}

/// ...to be continued
}

Query the scriptUtxos, to specifically use the utxo that matches publicKeyHash within its datum.

    const scriptUtxos = await Blockfrost.addressUtxos( scriptAddr )
.catch( e => { throw new Error ("unable to find utxos at " + addr) });
// matches with the pkh
const scriptUtxo = scriptUtxos.find(utxo => {
if (utxo.resolved.datum instanceof DataConstr) {
const pkhData = utxo.resolved.datum.fields[0];
if (pkhData instanceof DataB) {
return pkh.toString() == Buffer.from( pkhData.bytes.toBuffer() ).toString("hex")
}
}
return false;
});
if (!scriptUtxo) {
throw new Error ("No script utxo found for the pkh")
}
use the beneficiary keys!

Note that we are reading the keys(both private and public) of the beneficiary we setted in the previous script here.

If we used the other keys the script would fail each time!

Build the Transaciton

This time our transaction will be formed as follows

  • one of our utxos
  • the utxo locked at the script address (with corresponding Script in order to validate the spending of it)
  • the public key hash as requiredSigners element so that it is aviable in ctx.tx.signatories
  • our utxo as collateral input that MUST be present every time a script is included in the transaciton
  • the invalidBefore field corresponding to the last slot heigth (otherwise the transaciton interval is negative infinite and the contract will fail!)

Of the above, the last one sounds courious... How do we get the last slot of the blockchain?

Blockfrost helps us with that!

we just have to do,

(await Blockfrost.getChainTip()).slot!

Before building the transaction, we have to ensure the txBuilder genesisInfo is set to its Preprod defaults, by:

txBuilder.setGenesisInfos( defaultPreprodGenesisInfos )

Now the Transaction can be built as follows:

let tx = await txBuilder.buildSync({
inputs: [
{ utxo: utxo },
{
utxo: scriptUtxo,
inputScript: {
script: script,
datum: "inline",
redeemer: new DataI( 0 )
}
}
],
requiredSigners: [ pkh ], // required to be included in script context
collaterals: [ utxo ],
changeAddress: address,
invalidBefore: (await Blockfrost.getChainTip()).slot!
});

Finally, after we add the Sign and Submit code as done previously:

await tx.signWith( privateKey );

const submittedTx = await Blockfrost.submitTx( tx )

we can put all together in a claimVesting.ts file in the app folder:

src/app/claimVesting.ts
import { Address, DataI, Credential, PrivateKey, CredentialType, Script, DataConstr, DataB, PublicKey, defaultPreprodGenesisInfos } from "@harmoniclabs/plu-ts";
import getTxBuilder from "./getTxBuilder";
import { BlockfrostPluts } from "@harmoniclabs/blockfrost-pluts";
import blockfrost from "./blockfrost";
import { readFile } from "fs/promises";

async function claimVesting(Blockfrost: BlockfrostPluts)
{
const txBuilder = await getTxBuilder(Blockfrost);

const scriptFile = await readFile("./testnet/vesting.plutus.json", { encoding: "utf-8" });
const script = Script.fromCbor(JSON.parse(scriptFile).cborHex)
const scriptAddr = new Address(
"testnet",
new Credential(CredentialType.Script, script.hash)
);

const privateKeyFile = await readFile("./testnet/payment2.skey", { encoding: "utf-8" });
const privateKey = PrivateKey.fromCbor( JSON.parse(privateKeyFile).cborHex );

const addr = await readFile("./testnet/address2.addr", { encoding: "utf-8" });
const address = Address.fromString(addr);

const publicKeyFile = await readFile("./testnet/payment2.vkey", { encoding: "utf-8" });
const pkh = PublicKey.fromCbor( JSON.parse(publicKeyFile).cborHex ).hash;

const utxos = await Blockfrost.addressUtxos( address )
.catch( e => { throw new Error ("unable to find utxos at " + addr) });
// atleast has 10 ada
const utxo = utxos.find(utxo => utxo.resolved.value.lovelaces >= 10_000_000);
if (!utxo) {
throw new Error("No utxo with more than 10 ada");
}

const scriptUtxos = await Blockfrost.addressUtxos( scriptAddr )
.catch( e => { throw new Error ("unable to find utxos at " + addr) });
// matches with the pkh
const scriptUtxo = scriptUtxos.find(utxo => {
if (utxo.resolved.datum instanceof DataConstr) {
const pkhData = utxo.resolved.datum.fields[0];
if (pkhData instanceof DataB) {
return pkh.toString() == Buffer.from( pkhData.bytes.toBuffer() ).toString("hex")
}
}
return false;
});
if (!scriptUtxo) {
throw new Error ("No script utxo found for the pkh")
}

txBuilder.setGenesisInfos( defaultPreprodGenesisInfos )

if (Buffer.from(script.hash.toBuffer()).toString("hex") !== Buffer.from(scriptAddr.paymentCreds.hash.toBuffer()).toString("hex")) {
throw new Error("Script hash and script address hash do not match");
}

let tx = await txBuilder.buildSync({
inputs: [
{ utxo: utxo },
{
utxo: scriptUtxo,
inputScript: {
script: script,
datum: "inline",
redeemer: new DataI( 0 )
}
}
],
requiredSigners: [ pkh ], // required to be included in script context
collaterals: [ utxo ],
changeAddress: address,
invalidBefore: (await Blockfrost.getChainTip()).slot!
});

await tx.signWith( privateKey )

const submittedTx = await Blockfrost.submitTx( tx );
console.log(submittedTx);

}

if( process.argv[1].includes("claimVesting") )
{
claimVesting(blockfrost());
}

After adding a new npm script in package.json

package.json
"scripts": {
// ...
"vesting:claim": "npm run build:light && node dist/app/claimVesting.js"
}

to try claim the utxo, we can run:

npm run vesting:claim
Wait some seconds

If you run the script shortly after you created and locked the utxo the script will fail!

In the previous script, we had set a locking period of 10 seconds.

So you just have to have a little patience :)

If everything goes correctly, the program should terminate without errors. It will definitely console back the transaction hash in the terminal.

Bonus: Return the tADA

If you were in public testnet remember to return the tADA to the faucet.

For this, you can add the following file and script to automate everything.

src/app/returnFaucet.ts
import { BlockfrostPluts } from "@harmoniclabs/blockfrost-pluts";
import { Address, ITxBuildInput, IUTxO, PrivateKey } from "@harmoniclabs/plu-ts";
import { readFile } from "fs/promises";
import blockfrost from "./blockfrost";
import getTxBuilder from "./getTxBuilder";

async function returnFaucet(Blockfrost: BlockfrostPluts)
{
const utxos: (ITxBuildInput | IUTxO)[] = [];
const pvtKeys: PrivateKey[] = [];

for( let i = 1; i <= 2; i++ )
{
const pvtKeyFile = await readFile(`./testnet/payment${i}.skey`, { encoding: "utf-8" })
const pvtKey = PrivateKey.fromCbor( JSON.parse(pvtKeyFile).cborHex );
pvtKeys.push( pvtKey );

const addr = await readFile(`./testnet/address${i}.addr`, { encoding: "utf-8" });
const address = Address.fromString(addr);

const addrUtxos = await Blockfrost.addressUtxos( address )
addrUtxos.forEach( utxo => utxos.push({ utxo: utxo }) )
}


const txBuilder = await getTxBuilder(Blockfrost);

let returnTADATx = await txBuilder.buildSync({
inputs: utxos as any,
// the faucet address
changeAddress: "addr_test1qqr585tvlc7ylnqvz8pyqwauzrdu0mxag3m7q56grgmgu7sxu2hyfhlkwuxupa9d5085eunq2qywy7hvmvej456flknswgndm3"
});

for(const privateKey of pvtKeys)
{
await returnTADATx.signWith( privateKey );
}

const submittedTx = await Blockfrost.submitTx( returnTADATx );
console.log(submittedTx);
}
if( process.argv[1].includes("returnFaucet") )
{
returnFaucet(blockfrost());
}
package.json
"scripts": {
// ...
"vesting:returnFaucet": "npm run build:light && node dist/app/returnFaucet.js"
}
npm run vesting:returnFaucet