Create Publication

We are looking for publications that demonstrate building dApps or smart contracts!
See the full list of Gitcoin bounties that are eligible for rewards.

Tutorial Thumbnail
Intermediate · 30 minutes

Hash Time Lock Contract Template With JavaScript

This tutorial is intended to help you call a Hash Time Locked Contract using JavaScript. Templates are prebuilt TEAL programs that allow parameters to be injected into them from the SDKs that configure the contract. In this example, we are going to instantiate the HTLC Template and show how it can be used with a transaction.

Requirements

Background

Algorand provides many templates for Smart Contract implementation in the SDKs. The Hash Time Lock Contract is just one of the templates and is described in the reference documentation. Hash Time Lock Contracts are contract accounts that can disburse funds when the correct hash preimage (“password”) is passed as an argument. If the funds are not claimed with the password after a certain period of time, the original owner can reclaim them.

Steps

1. Create Template

The HTLC template can be instantiated with a set of predefined parameters that configure the HTLC contract. These parameters should not be confused with Transaction parameters that are passed into the contract when using the HTLC. These parameters configure how the HTLC will function:

  • TMPL_RCV: the address to send funds to when the preimage is supplied
  • TMPL_HASHFN: the specific hash function (sha256 or keccak256) to use
  • TMPL_HASHIMG: the image of the hash function for which knowing the preimage under TMPL_HASHFN will release the funds
  • TMPL_TIMEOUT: the round after which funds may be closed out to TMPL_OWN
  • TMPL_OWN: the address to refund funds to on timeout
  • TMPL_FEE: maximum fee of any transactions approved by this contract

// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const htlcTemplate = require("algosdk/src/logicTemplates/htlc");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-server>";
const port = <your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
    // Get the relevant params from the algod for the network
    let params = await algodclient.getTransactionParams();
    let endRound = params.lastRound + parseInt(1000);
    let fee = await algodclient.suggestedFee();
    // // Inputs
    let owner = "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM";
    let receiver = "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE";
    let hashFn = "sha256";
    let hashImg = "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc=";
    let expiryRound = params.lastRound + 10000;
    let maxFee = 2000;
    // Instaniate the template
    let htlc = new htlcTemplate.HTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee);
    // Outputs
    let program = htlc.getProgram();
    console.log("htlc addr: " + htlc.getAddress());
})().catch(e => {
    console.log(e);
});

2. Create the Logic Signature

Before the account can be used, it must be funded. The HTLC address represents the account’s address which we will fund using the dispenser for the purpose of this tutorial.

To use the HTLC contract in a transaction, a Logic Signature must be created. This will be used later to sign the transaction. The Logic Signature is a replacement for signing the transaction with a spending key. If you do not want to pass in parameters yet you can still create an lsig without the args. Later you can create a new lsig with the program and a set of args to be used to sign a transaction. In this example, we are passing the one transaction parameter (password) as we create the Logic Signature. Logic Signatures are further documented on the developer site.

// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const htlcTemplate = require("algosdk/src/logicTemplates/htlc");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-server>";
const port = //<your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
    // Get the relevant params from the algod for the network
    let params = await algodclient.getTransactionParams();
    let endRound = params.lastRound + parseInt(1000);
    let fee = await algodclient.suggestedFee();
    // // Inputs
    let owner = "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM";
    let receiver = "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE";
    let hashFn = "sha256";
    let hashImg = "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc=";
    let expiryRound = params.lastRound + 10000;
    let maxFee = 2000;
    // Instaniate the template
    let htlc = new htlcTemplate.HTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee);
    // Outputs
    let program = htlc.getProgram();
    console.log("htlc addr: " + htlc.getAddress());

    // Get the program and parameters and use them to create an lsig
    // For the contract account to be used in a transaction
    // In this example 'hero wisdom green split loop element vote belt' hashed with sha256 will produce our image hash
    // that was configured in step 1
    // This is the passcode for the HTLC   
    // python -c "import hashlib;print(hashlib.sha256('hero wisdom green split loop element vote belt').digest().encode('base64'))"  
    let args = ["hero wisdom green split loop element vote belt"];
    let lsig = algosdk.makeLogicSig(program, args);
})().catch(e => {
    console.log(e);
});


Learn More
- Add Funds using Dispenser
- Smart Contracts - Logic Signatures

3. Create and Sign the Transaction

A transaction can now be created that requests the funds from the HTLC Contract account. The amount should be set to 0 as the contract will close out all funds at once. The from address should be set to the contract’s address. After the transaction is created, it can be signed with the Logic Signature as shown in the highlighted code below. Note that the to field is set to the Zero address as the contract automatically closes out to the receiver that was configured in the template creation. If this field is not set to the zero address the transaction will fail.

// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const htlcTemplate = require("algosdk/src/logicTemplates/htlc");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-server>";
const port = //<your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
    // Get the relevant params from the algod for the network
    let params = await algodclient.getTransactionParams();
    let endRound = params.lastRound + parseInt(1000);
    let fee = await algodclient.suggestedFee();
    // // Inputs
    let owner = "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM";
    let receiver = "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE";
    let hashFn = "sha256";
    let hashImg = "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc=";
    let expiryRound = params.lastRound + 10000;
    let maxFee = 2000;
    // Instaniate the template
    let htlc = new htlcTemplate.HTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee);
    // Outputs
    let program = htlc.getProgram();
    console.log("htlc addr: " + htlc.getAddress());

    // Get the program and parameters and use them to create an lsig
    // For the contract account to be used in a transaction
    // In this example 'hero wisdom green split loop element vote belt' hashed with sha256 will produce our image hash
    // that was configured in step 1
    // This is the passcode for the HTLC   
    // python -c "import hashlib;print(hashlib.sha256('hero wisdom green split loop element vote belt').digest().encode('base64'))"  
    let args = ["hero wisdom green split loop element vote belt"];
    let lsig = algosdk.makeLogicSig(program, args);

   //create a transaction
    let txn = {
        "from": htlc.getAddress(),
        "to": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ",
        "fee": 1,
        "type": "pay",
        "amount": 0,
        "firstRound": params.lastRound,
        "lastRound": endRound,
        "genesisID": params.genesisID,
        "genesisHash": params.genesishashb64,
        "closeRemainderTo": "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE"
    };
    // create logic signed transaction.
    let rawSignedTxn = algosdk.signLogicSigTransaction(txn, lsig);
})().catch(e => {
    console.log(e);
});    

4. Send the Transaction to the Network

The final step is to send the transaction to the network. If the contract is funded, the transaction should succeed.

// Handle importing needed modules
const algosdk = require('algosdk');
const fs = require('fs');
const htlcTemplate = require("algosdk/src/logicTemplates/htlc");
// Retrieve the token, server and port values for your installation in the algod.net
// and algod.token files within the data directory
const token = "<your-api-token>";
const server = "http://<your-algod-server>";
const port = //<your-algod-port>;
// Instantiate the algod wrapper
let algodclient = new algosdk.Algod(token, server, port);
(async() => {
    // Get the relevant params from the algod for the network
    let params = await algodclient.getTransactionParams();
    let endRound = params.lastRound + parseInt(1000);
    let fee = await algodclient.suggestedFee();
    // // Inputs
    let owner = "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM";
    let receiver = "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE";
    let hashFn = "sha256";
    let hashImg = "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc=";
    let expiryRound = params.lastRound + 10000;
    let maxFee = 2000;
    // Instaniate the template
    let htlc = new htlcTemplate.HTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee);
    // Outputs
    let program = htlc.getProgram();
    console.log("htlc addr: " + htlc.getAddress());

    // Get the program and parameters and use them to create an lsig
    // For the contract account to be used in a transaction
    // In this example 'hero wisdom green split loop element vote belt' hashed with sha256 will produce our image hash
    // that was configured in step 1
    // This is the passcode for the HTLC   
    // python -c "import hashlib;print(hashlib.sha256('hero wisdom green split loop element vote belt').digest().encode('base64'))"  
    let args = ["hero wisdom green split loop element vote belt"];
    let lsig = algosdk.makeLogicSig(program, args);

   //create a transaction
    let txn = {
        "from": htlc.getAddress(),
        "to": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ",
        "fee": 1,
        "type": "pay",
        "amount": 0,
        "firstRound": params.lastRound,
        "lastRound": endRound,
        "genesisID": params.genesisID,
        "genesisHash": params.genesishashb64,
        "closeRemainderTo": "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE"
    };
    // create logic signed transaction.
    let rawSignedTxn = algosdk.signLogicSigTransaction(txn, lsig);

    //Submit the lsig signed transaction
    let tx = (await algodclient.sendRawTransaction(rawSignedTxn.blob));
    console.log("Transaction : " + tx.txId);
})().catch(e => {
    console.log(e);
});