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 Go

This tutorial is intended to help you call a Hash Time Locked Contract using Go. 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

package main

import (
    "encoding/base64"
    "fmt"
    "os"
    "golang.org/x/crypto/ed25519"

    "github.com/algorand/go-algorand-sdk/client/algod"
    "github.com/algorand/go-algorand-sdk/crypto"
    "github.com/algorand/go-algorand-sdk/templates"
    "github.com/algorand/go-algorand-sdk/transaction"
)
// This example creates a contract account
func main() {
    const algodAddress = "http://<your-algod-host>:<your-algod-port>"
    const algodToken = "<your-api-token>"
    //Blank values as we are creating an escrow account
    var sk ed25519.PrivateKey
    var ma crypto.MultisigAccount
    // Create an algod client
    algodClient, err := algod.MakeClient(algodAddress, algodToken)
    if err != nil {
        fmt.Printf("failed to make algod client: %s\n", err)
        return
    }
    // Get suggested params for the transaction
    txParams, err := algodClient.SuggestedParams()
    if err != nil {
            fmt.Printf("error getting suggested tx params: %s\n", err)
            return
    }   
    // Inputs 
    owner := "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM"
    receiver := "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE"
    hashFn := "sha256"
    hashImg := "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc="
    expiryRound := txParams.LastRound + uint64(10000)
    maxFee := uint64(2000)
    //Instaniate the Template
    c, err := templates.MakeHTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee)
    program := c.GetProgram()
    addr := c.GetAddress() 
    fmt.Printf("Escrow Address: %s\n" , addr )  
}   

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.

package main

import (
    "encoding/base64"
    "fmt"
    "os"
    "golang.org/x/crypto/ed25519"

    "github.com/algorand/go-algorand-sdk/client/algod"
    "github.com/algorand/go-algorand-sdk/crypto"
    "github.com/algorand/go-algorand-sdk/templates"
    "github.com/algorand/go-algorand-sdk/transaction"
)
// This example creates a contract account
func main() {
    const algodAddress = "http://<your-algod-host>:<your-algod-port>"
    const algodToken = "<your-api-token>"
    //Blank values as we are creating an escrow account
    var sk ed25519.PrivateKey
    var ma crypto.MultisigAccount
    // Create an algod client
    algodClient, err := algod.MakeClient(algodAddress, algodToken)
    if err != nil {
        fmt.Printf("failed to make algod client: %s\n", err)
        return
    }
    // Get suggested params for the transaction
    txParams, err := algodClient.SuggestedParams()
    if err != nil {
            fmt.Printf("error getting suggested tx params: %s\n", err)
            return
    }   
    // Inputs 
    owner := "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM"
    receiver := "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE"
    hashFn := "sha256"
    hashImg := "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc="
    expiryRound := txParams.LastRound + uint64(10000)
    maxFee := uint64(2000)
    //Instaniate the Template
    c, err := templates.MakeHTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee)
    program := c.GetProgram()
    addr := c.GetAddress() 
    fmt.Printf("Escrow Address: %s\n" , addr )  
    // 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
    // This is the passcode for the HTLC  
    args := make([][]byte, 1)
    args[0] = []byte("hero wisdom green split loop element vote belt")

    // Next we create a LogicSig using blank private key
    // and blank multisig account because we are creating
    // a escrow contract account
    lsig, err := crypto.MakeLogicSig(program, args, sk, ma)
    if err != nil {
        fmt.Printf("Make Logic Sig Failed %v", err)
        return
    }   
}   


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 sender 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 receiver 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.

package main

import (
    "encoding/base64"
    "fmt"
    "os"
    "golang.org/x/crypto/ed25519"

    "github.com/algorand/go-algorand-sdk/client/algod"
    "github.com/algorand/go-algorand-sdk/crypto"
    "github.com/algorand/go-algorand-sdk/templates"
    "github.com/algorand/go-algorand-sdk/transaction"
)
// This example creates a contract account
func main() {
    const algodAddress = "http://<your-algod-host>:<your-algod-port>"
    const algodToken = "<your-api-token>"
    //Blank values as we are creating an escrow account
    var sk ed25519.PrivateKey
    var ma crypto.MultisigAccount
    // Create an algod client
    algodClient, err := algod.MakeClient(algodAddress, algodToken)
    if err != nil {
        fmt.Printf("failed to make algod client: %s\n", err)
        return
    }
    // Get suggested params for the transaction
    txParams, err := algodClient.SuggestedParams()
    if err != nil {
            fmt.Printf("error getting suggested tx params: %s\n", err)
            return
    }   
    // Inputs 
    owner := "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM"
    receiver := "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE"
    hashFn := "sha256"
    hashImg := "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc="
    expiryRound := txParams.LastRound + uint64(10000)
    maxFee := uint64(2000)
    //Instaniate the Template
    c, err := templates.MakeHTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee)
    program := c.GetProgram()
    addr := c.GetAddress() 
    fmt.Printf("Escrow Address: %s\n" , addr )  
    // 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
    // This is the passcode for the HTLC  
    args := make([][]byte, 1)
    args[0] = []byte("hero wisdom green split loop element vote belt")

    // Next we create a LogicSig using blank private key
    // and blank multisig account because we are creating
    // a escrow contract account
    lsig, err := crypto.MakeLogicSig(program, args, sk, ma)
    if err != nil {
        fmt.Printf("Make Logic Sig Failed %v", err)
        return
    }   
    //Setup a transaction as normal
    const fee = 1000
    const amount = 0
    var note []byte
    // Make transaction
    genID := txParams.GenesisID
    genHash := txParams.GenesisHash
    tx, err := transaction.MakePaymentTxnWithFlatFee(
        addr, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ", fee, amount, txParams.LastRound, txParams.LastRound + 1000,
        note, receiver, genID, genHash)

    // Sign transaction with logicSig 
    txid, stx, err := crypto.SignLogicsigTransaction(lsig, tx)
    if err != nil {
        fmt.Printf("Signing failed with %v", err)
        return
    }
    fmt.Printf("Signed tx: %v\n", txid)
}   

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.

package main

import (
    "encoding/base64"
    "fmt"
    "os"
    "golang.org/x/crypto/ed25519"

    "github.com/algorand/go-algorand-sdk/client/algod"
    "github.com/algorand/go-algorand-sdk/crypto"
    "github.com/algorand/go-algorand-sdk/templates"
    "github.com/algorand/go-algorand-sdk/transaction"
)
// This example creates a contract account
func main() {
    const algodAddress = "http://<your-algod-host>:<your-algod-port>"
    const algodToken = "<your-api-token>"
    //Blank values as we are creating an escrow account
    var sk ed25519.PrivateKey
    var ma crypto.MultisigAccount
    // Create an algod client
    algodClient, err := algod.MakeClient(algodAddress, algodToken)
    if err != nil {
        fmt.Printf("failed to make algod client: %s\n", err)
        return
    }
    // Get suggested params for the transaction
    txParams, err := algodClient.SuggestedParams()
    if err != nil {
            fmt.Printf("error getting suggested tx params: %s\n", err)
            return
    }   
    // Inputs 
    owner := "726KBOYUJJNE5J5UHCSGQGWIBZWKCBN4WYD7YVSTEXEVNFPWUIJ7TAEOPM"
    receiver := "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE"
    hashFn := "sha256"
    hashImg := "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc="
    expiryRound := txParams.LastRound + uint64(10000)
    maxFee := uint64(2000)
    //Instaniate the Template
    c, err := templates.MakeHTLC(owner, receiver, hashFn, hashImg, expiryRound, maxFee)
    program := c.GetProgram()
    addr := c.GetAddress() 
    fmt.Printf("Escrow Address: %s\n" , addr )  
    // 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
    // This is the passcode for the HTLC  
    args := make([][]byte, 1)
    args[0] = []byte("hero wisdom green split loop element vote belt")

    // Next we create a LogicSig using blank private key
    // and blank multisig account because we are creating
    // a escrow contract account
    lsig, err := crypto.MakeLogicSig(program, args, sk, ma)
    if err != nil {
        fmt.Printf("Make Logic Sig Failed %v", err)
        return
    }   
    //Setup a transaction as normal
    const fee = 1000
    const amount = 0
    var note []byte
    // Make transaction
    genID := txParams.GenesisID
    genHash := txParams.GenesisHash
    tx, err := transaction.MakePaymentTxnWithFlatFee(
        addr, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ", fee, amount, txParams.LastRound, txParams.LastRound + 1000,
        note, receiver, genID, genHash)

    // Sign transaction with logicSig 
    txid, stx, err := crypto.SignLogicsigTransaction(lsig, tx)
    if err != nil {
        fmt.Printf("Signing failed with %v", err)
        return
    }
    fmt.Printf("Signed tx: %v\n", txid)
    // Submit the raw transaction as normal
    transactionID, err := algodClient.SendRawTransaction(stx)
    if err != nil {
        fmt.Printf("Sending failed with %v\n", err)
    }
    fmt.Printf("Transaction ID: %v\n", transactionID)   
}