Andamio LogoAndamio
Sdk/Npm packages/@andamio/transactions

Input Helpers

Format complex transaction inputs with type-safe helper functions

Input Helpers

Some transactions require complex input formatting (e.g., JSON strings with specific structures). Input helper functions transform data from the Database API into the required format for transaction building.

Overview

Input helpers provide:

  • Type-safe transformation using types from @andamio-platform/db-api
  • Discoverable metadata embedded in transaction definitions
  • Documented JSDoc with examples
  • Consistent patterns across all transactions

Using Input Helpers

1. Check Available Helpers

Each transaction definition includes metadata about available helpers:

import { getTransactionDefinition } from "@andamio/transactions";

const txDef = getTransactionDefinition("COURSE_TEACHER_MODULES_MANAGE");

// Check what helpers are available
console.log(txDef.buildTxConfig.inputHelpers);
// {
//   module_infos: {
//     helperName: "formatModuleInfos",
//     description: "Formats an array of course modules into the module_infos JSON string",
//     example: "const modules = await fetchModules(courseId)..."
//   }
// }

2. Import and Use the Helper

import {
  getTransactionDefinition,
  formatModulesToMint,
  computeSltHash
} from "@andamio/transactions";
import type { ListCourseModulesOutput } from "@andamio-platform/db-api";

const txDef = getTransactionDefinition("COURSE_TEACHER_MODULES_MANAGE");

// Fetch data from database API
const modules: ListCourseModulesOutput = await fetch(
  `${API_URL}/courses/${courseId}/course-modules`
).then(r => r.json());

// Use helper to format the complex field
const inputs = {
  alias: teacherAlias,
  courseId: courseNftPolicyId,
  modulesToMint: formatModulesToMint(modules),  // Helper formats data
  modulesToUpdate: [],
  modulesToBurn: [],
};

// Validate and build
const validated = txDef.buildTxConfig.inputSchema.parse(inputs);

// Preview module hashes
modules.forEach(m => {
  const hash = computeSltHash(m.slts.map(s => s.sltText));
  console.log(`${m.moduleCode}: ${hash}`);
});

Available Helpers

formatModulesToMint (V2)

Formats course modules for the COURSE_TEACHER_MODULES_MANAGE transaction.

import { formatModulesToMint, computeSltHash } from "@andamio/transactions";
import type { ListCourseModulesOutput } from "@andamio-platform/db-api";

const modules: ListCourseModulesOutput = [
  {
    id: "1",
    moduleCode: "MODULE_1",
    title: "Introduction",
    slts: [
      { id: "1", sltText: "I can mint an access token." },
      { id: "2", sltText: "I can complete an assignment." }
    ],
    // ... other fields
  }
];

const modulesToMint = formatModulesToMint(modules);
// Returns array of MintModuleV2 objects for transaction API

Input: ListCourseModulesOutput from DB API Output: Array of MintModuleV2 objects:

[
  {
    slts: ["I can mint an access token.", "I can complete an assignment."],
    allowedStudents_V2: [], // Policy IDs of allowed student groups
    prerequisiteAssignments_V2: [] // SLT hashes of prerequisites
  }
]

formatModuleInfosForMintModuleTokens (V1 Legacy)

Legacy helper for V1 MINT_MODULE_TOKENS transaction:

import { formatModuleInfosForMintModuleTokens } from "@andamio/transactions";

// Returns JSON string for V1 transaction API
const moduleInfosJson = formatModuleInfosForMintModuleTokens(modules);

Creating New Helpers

When adding a new transaction that needs input formatting:

1. Create the Helper Function

// src/helpers/my-helper.ts
import type { SomeDbApiType } from "@andamio-platform/db-api";

/**
 * Formats data for the MY_TRANSACTION transaction.
 *
 * @param data - Data from database API
 * @returns JSON string formatted for transaction API
 *
 * @example
 * ```typescript
 * const data = await fetchData(id);
 * const formatted = formatMyData(data);
 * const inputs = { ..., my_field: formatted };
 * ```
 */
export function formatMyData(data: SomeDbApiType): string {
  return JSON.stringify(
    data.map(item => ({
      // Transform to required structure
      field1: item.someField,
      field2: item.otherField,
    }))
  );
}

2. Add Helper Metadata to Transaction

// src/definitions/v2/.../my-transaction.ts
export const MY_TRANSACTION: AndamioTransactionDefinition = {
  // ...
  buildTxConfig: {
    inputSchema: z.object({
      // ...
      my_field: z.string(), // JSON string
    }),
    inputHelpers: {
      my_field: {
        helperName: "formatMyData",
        description: "Formats data from DB API into my_field JSON string",
        example: "const data = await fetchData(id); formatMyData(data)",
      },
    },
    // ...
  },
};

3. Export from Package

// src/helpers/index.ts
export { formatMyData } from "./my-helper";

// src/index.ts
export * from "./helpers";

Best Practices

1. Always Use DB API Types

Import types from @andamio-platform/db-api to ensure consistency:

import type { ListCourseModulesOutput } from "@andamio-platform/db-api";

function formatModuleInfos(modules: ListCourseModulesOutput): string {
  // ...
}

2. Validate Input Data

Helpers should handle edge cases gracefully:

function formatModuleInfos(modules: ListCourseModulesOutput): string {
  if (!modules || modules.length === 0) {
    return JSON.stringify([]);
  }

  return JSON.stringify(
    modules.map(m => ({
      moduleCode: m.moduleCode,
      moduleTitle: m.title || "Untitled",
      slts: m.slts?.map(s => s.text) ?? [],
      prerequisites: m.prerequisites ?? [],
    }))
  );
}

3. Document Thoroughly

Include JSDoc with:

  • Description of what the helper does
  • Parameter types and descriptions
  • Return value description
  • Usage example
/**
 * Formats course modules for the COURSE_TEACHER_MODULES_MANAGE transaction.
 *
 * Transforms `ListCourseModulesOutput` from the database API into the
 * JSON string format expected by the transaction API.
 *
 * @param modules - Array of course modules from DB API
 * @returns JSON string containing module infos for transaction
 *
 * @example
 * ```typescript
 * const modules = await api.get(`/courses/${id}/course-modules`);
 * const moduleInfos = formatModuleInfos(modules);
 * ```
 */
export function formatModuleInfos(modules: ListCourseModulesOutput): string {
  // ...
}

4. Keep Helpers Pure

Helpers should be pure functions with no side effects:

// Good - pure function
function formatModuleInfos(modules: ListCourseModulesOutput): string {
  return JSON.stringify(modules.map(/* ... */));
}

// Bad - has side effects
function formatModuleInfos(modules: ListCourseModulesOutput): string {
  console.log("Formatting modules...");  // Side effect!
  return JSON.stringify(modules.map(/* ... */));
}