DEV Community

Cover image for Learning Xahau: Automating Hook Execution with Cron Transactions
Ekiserrepe
Ekiserrepe

Posted on

Learning Xahau: Automating Hook Execution with Cron Transactions

Welcome to a new chapter of Learning Xahau, where we explore the theoretical and practical aspects of the Xahau blockchain. If you're new to Xahau, I recommend checking out the first article in the series to understand the basics.

Today, we're diving into Cron Transactions—a powerful feature that brings scheduled automation to the Xahau blockchain. If you've ever wondered how to make your Hooks execute automatically at specific intervals without manual intervention, this article is for you.

What Are Cron Transactions?

If you're familiar with Unix/Linux systems, you've probably heard of cron jobs—scheduled tasks that run automatically at specified times. Xahau brings this concept to the blockchain with CronSet transactions, allowing you to schedule Hook callbacks at regular intervals.

Think of Cron Transactions as your blockchain alarm clock. Instead of waking you up, they wake up your Hooks and tell them: "Hey, it's time to execute your logic!" This happens automatically, on-chain, without needing external triggers or services.

Why Do We Need Cron Transactions?

In traditional blockchain environments, smart contracts typically react to external transactions. Someone or something needs to call them. This creates several challenges:

  • Manual Intervention: Regular tasks require someone to trigger them manually
  • External Dependencies: You need off-chain services (bots, servers) to trigger on-chain actions
  • Cost Inefficiency: Each manual trigger costs transaction fees
  • Reliability Issues: External services can fail, forget, or experience downtime

Cron Transactions solve these problems by moving the scheduling logic on-chain. Your Hook can be programmed to execute at specific intervals, creating truly autonomous on-chain processes.

Real-World Use Cases

Before diving into the technical implementation, let's explore practical scenarios where Cron Transactions shine:

1. Automated Reward Distribution

Imagine a staking system where rewards need to be calculated and distributed daily. Instead of running an external bot, a Cron Transaction can trigger your Hook every 24 hours to process rewards automatically.

2. Regular Data Updates

If you're using Remarks (as discussed in my previous article) to create a price oracle, Cron Transactions can update prices at regular intervals without external intervention.

3. Subscription Management

For subscription-based services, Cron Transactions can automatically check and process payments, update subscription statuses, or trigger access revocations when subscriptions expire.

4. Automated Maintenance Tasks

Hooks that need to perform cleanup operations, reset counters, or archive old data can use Cron Transactions to execute these tasks periodically.

How Cron Transactions Work

The workflow for implementing Cron Transactions involves several steps:

  1. Install a Hook with the hsfCOLLECT flag enabled
  2. Enable Transaction Signature Hook Collection on your account
  3. Create a CronSet transaction with your scheduling parameters
  4. Let Xahau handle the rest—your Hook will execute automatically

Let's break down each component:

The CronSet Transaction Structure

{
  "TransactionType": "CronSet",
  "Account": "rYourAccountAddress",
  "StartTime": 816348759,      // When to start (Ripple Epoch)
  "RepeatCount": 3,             // How many times to execute
  "DelaySeconds": 120           // Interval between executions
}
Enter fullscreen mode Exit fullscreen mode
  • StartTime: When the first execution should occur (0 for immediate start)
  • RepeatCount: Total number of times the Hook should be triggered
  • DelaySeconds: Time interval between each execution

Important: Ripple Epoch Time

Xahau uses Ripple Epoch time, which counts seconds from January 1, 2000 (not Unix time which starts from 1970). Here's how to convert:

const RIPPLE_EPOCH_OFFSET = 946684800;
const rippleEpochTime = Math.floor(Date.now() / 1000) - RIPPLE_EPOCH_OFFSET;
Enter fullscreen mode Exit fullscreen mode

Hands-On Implementation

Now let's get practical. The cron-transaction-xahau repository provides ready-to-use examples for implementing Cron Transactions.

Step 1: Prerequisites

First, you'll need a Xahau testnet account. Get one at https://xahau-test.net which will provide you with:

  • An account address (starts with 'r')
  • A seed/secret (starts with 's')

Security Note: Never share your seed! It's your private key. The examples use testnet seeds, but in production, use environment variables or secure key management.

Step 2: Install a Hook with Collection Enabled

The Hook must be installed with the hsfCOLLECT flag (value: 4) to enable callback functionality:

const xahau = require('xahau');
const { derive, utils, signAndSubmit } = require("xrpl-accountlib");

const seed = 'yourSeed'; // Replace with your actual seed, get one at https://xahau-test.net/
const network = "wss://xahau-test.net";

async function installHook() {
  const client = new xahau.Client(network);
  const account = derive.familySeed(seed, { algorithm: "secp256k1" });
  console.log(`Account: ${account.address}`);

  try {
    await client.connect();
    console.log('Connected to Xahau');

    const networkInfo = await utils.txNetworkAndAccountValues(network, account);

    const prepared = {
      "TransactionType": "SetHook",
      "Account": account.address,
      "Hooks": [
        {
          "Hook": {
            "HookHash": "83A41BE45166B33E66EF653512396409E1BF9FA85A7C15D0ABC81C24E2890CB3",
            "HookNamespace": "0000000000000000000000000000000000000000000000000000000000000000",
            "HookOn": "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFBFFFFF",
            "Flags": 4
          }
        }
      ],
      ...networkInfo.txValues,
    };

    console.log("Prepared SetHook transaction:", JSON.stringify(prepared, null, 2));

    const tx = await signAndSubmit(prepared, network, account);
    console.log("Transaction result:", JSON.stringify(tx, null, 2));

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.disconnect();
    console.log('Disconnected from Xahau');
  }
}

installHook();
Enter fullscreen mode Exit fullscreen mode

Step 3: Enable Account Collection

Your account needs the asfTshCollect flag enabled:

const xahau = require('xahau');
const { derive, utils, signAndSubmit } = require("xrpl-accountlib");

const seed = 'yourSeed'; // Replace with your actual seed, get one at https://xahau-test.net/
const network = "wss://xahau-test.net";

async function setAccountFlag() {
  const client = new xahau.Client(network);
  const account = derive.familySeed(seed, { algorithm: "secp256k1" });
  console.log(`Account: ${account.address}`);

  try {
    await client.connect();
    console.log('Connected to Xahau');

    const networkInfo = await utils.txNetworkAndAccountValues(network, account);

    const prepared = {
      "TransactionType": "AccountSet",
      "Account": account.address,
      "SetFlag": 11, // asfTshCollect - Enable Transaction Signature Hook Collection
      ...networkInfo.txValues,
    };

    console.log("Prepared AccountSet transaction:", JSON.stringify(prepared, null, 2));

    const tx = await signAndSubmit(prepared, network, account);
    console.log("Transaction result:", JSON.stringify(tx, null, 2));

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.disconnect();
    console.log('Disconnected from Xahau');
  }
}

setAccountFlag();
Enter fullscreen mode Exit fullscreen mode

Step 4: Schedule Your Cron Job

Once your Hook is installed and your account is configured, create the CronSet transaction:

const xahau = require('xahau');
const { derive, utils, signAndSubmit } = require("xrpl-accountlib");

const seed = 'yourSeed'; // Replace with your seed
const network = "wss://xahau-test.net";

async function createCronSet() {
  const client = new xahau.Client(network);
  const account = derive.familySeed(seed, { algorithm: "secp256k1" });
  console.log(`Account: ${account.address}`);

  try {
    await client.connect();
    console.log('Connected to Xahau');

    const networkInfo = await utils.txNetworkAndAccountValues(network, account);

    // Convert current time to Ripple Epoch (seconds since January 1, 2000 00:00 UTC)
    const RIPPLE_EPOCH_OFFSET = 946684800;
    const currentUnixTime = Math.floor(Date.now() / 1000);
    const startTimeRippleEpoch = currentUnixTime - RIPPLE_EPOCH_OFFSET + 60; // Start in 1 minute

    const prepared = {
      "TransactionType": "CronSet",
      "Account": account.address, // Your Hook address
      "StartTime": startTimeRippleEpoch, // Or use 0 for immediate start
      "RepeatCount": 3, // Number of times to repeat the task
      "DelaySeconds": 120, // 2 minutes
      ...networkInfo.txValues,
    };

    console.log("Prepared CronSet transaction:", JSON.stringify(prepared, null, 2));

    const tx = await signAndSubmit(prepared, network, account);
    console.log("Transaction result:", JSON.stringify(tx, null, 2));

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.disconnect();
    console.log('Disconnected from Xahau');
  }
}

createCronSet();
Enter fullscreen mode Exit fullscreen mode

This schedules your Hook to execute based on your specified parameters.

Step 5: Monitor and Manage

You can check your scheduled executions on explorers like XRPLWin. To stop a scheduled Cron job:

const xahau = require('xahau');
const { derive, utils, signAndSubmit } = require("xrpl-accountlib");

const seed = 'yourSeed'; // Replace with your seed
const network = "wss://xahau-test.net";

async function removeCronSet() {
  const client = new xahau.Client(network);
  const account = derive.familySeed(seed, { algorithm: "secp256k1" });
  console.log(`Account: ${account.address}`);

  try {
    await client.connect();
    console.log('Connected to Xahau');

    const networkInfo = await utils.txNetworkAndAccountValues(network, account);

    const prepared = {
      "TransactionType": "CronSet",
      "Account": account.address, // Your Hook address
      "Flags": 1, // tfCronUnset - this removes the cron job
      ...networkInfo.txValues,
    };

    console.log("Prepared CronUnset transaction:", JSON.stringify(prepared, null, 2));

    const tx = await signAndSubmit(prepared, network, account);
    console.log("Transaction result:", JSON.stringify(tx, null, 2));

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.disconnect();
    console.log('Disconnected from Xahau');
  }
}

removeCronSet();
Enter fullscreen mode Exit fullscreen mode

The No-Code Alternative: HookStore

For Non-Technical Users

Not everyone is comfortable working with code, and that's perfectly fine! The Xahau ecosystem provides user-friendly alternatives for those who want to leverage the power of Cron Transactions without diving into technical implementation.

The HookStore (https://hookstore.xahau.network) is a public marketplace where developers publish their Hooks, making them accessible to everyone through a simple interface. Think of it as an "app store" for Xahau Hooks.

Using Ping-Cron Through Xaman

Our process is available on the HookStore as Ping-Cron, which you can find at:
👉 https://hookstore.xahau.network/hooks/ping-cron

This process is specifically designed for implementing Cron functionality without writing a single line of code. Here's what makes it special:

  1. Xaman Integration: The entire process is managed through the Xaman wallet app—no terminal, no coding required
  2. Visual Interface: Configure your scheduling parameters through an intuitive interface
  3. One-Click Installation: Install the Hook directly to your account with proper configuration
  4. Automatic Setup: The HookStore handles all the technical details, including flags and parameters

How It Works for End Users

The process is remarkably simple:

  1. Open the HookStore link in your browser
  2. Review the Hook details including what it does
  3. Click on Install below the README notes
  4. Configure your schedule using the provided interface:
    • Set when you want it to start
    • Choose how many times it should run
    • Define the interval between executions
  5. Sign the transactions in Xaman
  6. Done! Your example is installed and working!

Benefits of Using HookStore

  • No Technical Knowledge Required: Perfect for business users, traders, and anyone who needs automation without coding
  • Verified Hooks: Hooks on the HookStore are reviewed and documented
  • Community Support: Each Hook has its own page with descriptions and usage instructions
  • Safe Testing: You can try Hooks on testnet before using them on mainnet

When to Choose HookStore vs. Custom Implementation

Use HookStore when:

  • You need a quick solution without development time
  • You're not comfortable with coding
  • You want to test functionalities before building custom solutions
  • You need standard automation patterns that already exist

Build custom implementations when:

  • You need specific business logic not available in existing Hooks
  • You want complete control over the Hook's behavior
  • You're building a unique application with proprietary features
  • You need to optimize for specific performance requirements

The beauty of Xahau is that both approaches are valid and serve different audiences. The HookStore democratizes access to blockchain automation, while custom development enables innovation and specialized solutions.


The Bigger Picture

Cron Transactions represent a significant step toward truly autonomous blockchain applications. Combined with Xahau's other features like Hooks, Remarks, and URITokens, developers can build sophisticated decentralized applications that operate independently.

This automation capability opens doors for:

  • DeFi protocols with automated rebalancing
  • Gaming systems with scheduled events
  • Supply chain solutions with periodic updates
  • Governance mechanisms with automated proposal processing

As I mentioned in my article about building your own business layer, Xahau empowers developers to create their own logic without permission. Cron Transactions extend this freedom by adding the dimension of time-based automation.

Final Thoughts and Resources

Cron Transactions showcase Xahau's commitment to providing developers with powerful, practical tools. By moving scheduling on-chain, Xahau eliminates external dependencies and creates truly autonomous applications.

The complete working code for this article is available at:
👉 https://github.com/Ekiserrepe/cron-transaction-xahau

Remember, we're still in the early days of Xahau. If you have ideas for using Cron Transactions in innovative ways, now is the perfect time to experiment and potentially become a pioneer in this space.

Feel free to reach out with questions, or join the Xahau Contributors Discord server, where we'll be happy to help you implement your automated Hook solutions.

Links

Top comments (0)