Hook Components

Hook Components are reusable code snippets designed to simplify the integration of specific functionalities within a project, particularly when working with smart contracts and blockchain interactions. These components serve as building blocks that developers can easily copy and paste into their applications, allowing for rapid development and reducing the need to write boilerplate code from scratch.

Each Hook Component typically encapsulates a specific behavior or functionality, such as handling transactions, managing state, or interacting with APIs. By leveraging these components, developers can focus on the unique aspects of their applications while relying on the tested and proven logic contained within the hooks.

Essential Functions

trace

The trace function is used for logging information during the execution of a hook. It helps developers debug their code by outputting messages and data to the trace log of nodes. This function is particularly useful for tracking the flow of execution and understanding the state of variables at various points in the hook.

Usage:

  • Parameters:
    • message: A string that serves as the logging key (can be null).
    • data: The data to log.
    • hex (optional): A boolean indicating whether to log the data in HEX format (default is false).
  • Returns: An error code indicating success (0) or failure (negative value).
const Hook = (arg: any) => {
  const data = { user: 'Alice', action: 'transfer' }
  trace("User action", data, false)
}
export { Hook }

accept

The accept function is used to finalize the execution of a hook successfully. When called, it commits any changes made by the hook and allows the originating transaction to continue. This function records a return message and a return code in the transaction metadata.

Usage:

  • Parameters:
    • msg: A string to be stored in the execution metadata.
    • code: A return code specific to the hook, with zero typically indicating success.
  • Returns: This function does not return a value, as it ends the hook's execution.
const Hook = (arg: any) => {
  // Perform some logic here
  accept('Transaction completed successfully', 0)
}
export { Hook }

rollback

The rollback function is used to reject the originating transaction and discard any changes made by the hook. When invoked, it ends the hook's execution with a status of rejection, recording an error message and code in the transaction metadata.

Usage:

  • Parameters:
    • error_msg: A string to be stored in the execution metadata.
    • error_code: A return code specific to the hook, with zero typically indicating success.
  • Returns: Similar to accept, this function does not return a value, as it ends the hook's execution.
const Hook = (arg: any) => {
  // Check for an error condition
  const errorCondition = true
  if (errorCondition) {
    rollback('Transaction failed due to an error', -1)
  }
}
export { Hook }

Hook Transaction Details

On every hook execution there is an attached transaction. The type of transaction is specified in the HookOn field. Here is an example of how to perform functions on the originating transaction json.

import { Payment } from '@transia/xahau-models'

const Hook = (arg: any) => {
  const txn = otxn_json() as Payment
  trace("txn.Amount", txn.Amount, false)
  // txn.Amount: 100000
  accept('', 0)
}
export { Hook }


Hook Parameters Overview

In the context of Hook Components, there are two types of parameters that developers can utilize: Hook Parameters and OTXN Parameters.

For more detailed information, please refer to the Hook Parameter Documentation.

Hook Parameters

Hook Parameters are key-value pairs that can be set during the installation of a Hook. These parameters allow subsequent installers to modify certain behaviors of the Hook without the need for recompilation or re-uploading. Each Hook can have up to 16 parameters, which are defined in the SetHook Transaction. The first user to set a novel Hook can define Default Parameters, which will be inherited by subsequent users unless overridden.

import { 
  encodeString,
  decodeJson 
} from 'jshooks-api'
const Hook = (arg: any) => {
  const result = hook_param(encodeString("myjson"))
  if (result < 0) {
    trace("Failed to get Hook Parameter", result, false)
  } else {
    trace("Hook Parameter", decodeJson(result), false)
  }
  accept('', 0)
}
export { Hook }

OTXN Parameters

OTXN Parameters can be included at the top level of any transaction type on the Xahau. These parameters can be accessed within a Hook using the otxn_param API, allowing for dynamic behavior based on transaction-level data.

import { 
  encodeString,
  decodeJson 
} from 'jshooks-api'
const Hook = (arg: any) => {
  const result = otxn_param(encodeString("myjson"))
  f (result < 0) {
    trace("Failed to get OTXN Parameter", result, false)
  } else {
    trace("OTXN Parameter", decodeJson(result), false)
  }
  accept('', 0)
}
export { Hook }

Hook State Overview

Hook State refers to a key-value mapping that exists for each account on the XRP Ledger, allowing for persistent storage of data between executions of hooks. Each key is a fixed size of 32 bytes (unsigned 256-bit integer), while the values can vary in length, with a maximum size determined by validator voting (currently 256 bytes). This state management enables hooks to store and retrieve data efficiently, facilitating complex interactions and behaviors.

For more detailed information, please refer to the Hook State Documentation.

Setting a Value in Hook State

The following example demonstrates how to use the state_set function to store a value in Hook State:

import { encodeString, encodeJson } from 'jshooks-api'

const Hook = (arg: any) => {
  const key = encodeString("myKey")
  const value = encodeJson({ "key": "value" })
  const result = state_set(value, key)
  // `result` == the number of bytes written
  if (result < 0) {
    trace("Failed to set state", result, false)
  } else {
    trace("State set successfully", result, false)
  }
  accept('', 0)
}
export { Hook }

Retrieving a Value from Hook State

In this example, we retrieve a value from Hook State using the state function:

import { encodeString, decodeJson } from 'jshooks-api'

const Hook = (arg: any) => {
  const key = encodeString("myKey")
  const result = state(key)
  // `result` == state as number[]
  if (result < 0) {
    trace("Failed to fetch state", result, false)
  } else {
    trace("Fetched state value", decodeJson(value), false)
  }
  accept('', 0)
}
export { Hook }

Was this page helpful?