1

Install the Trust Engine SDK

Add the Trust Engine SDK to your Node.js project
npm install @trust-engine/sdk@latest
2

Set Up Your Node.js Environment

Initialize the SDK and set up basic file structure
πŸ“ IMPORTANT: You will be building ONE FILE throughout this guide. Each step adds new functions to the same trust-engine-demo.js file. DO NOT replace previous code - just keep adding to it!
Create a new file trust-engine-demo.js:
import { TrustEngineSDK } from '@trust-engine/sdk';
import fs from 'fs';
import path from 'path'

// Initialize the SDK
const sdk = new TrustEngineSDK();

// Configuration
const config = {
  userID: 'node-user-' + Date.now(), // Must be unique across your entire application
  walletAddress: null, // We'll populate this after creating a wallet
};
3

Create a Wallet

Create a managed wallet for your application or userAdd these functions to your trust-engine-demo.js file:
async function createWallet() {
  try {
    console.log('Creating wallet for user:', config.userID);
    
    const wallet = await sdk.createWallet({
      userID: config.userID // Must be unique across your entire application
    });
    
    config.walletAddress = wallet.details.walletAddress;
    
    console.log('βœ… Wallet created successfully!');
    console.log('Wallet Address:', config.walletAddress);
    console.log('Transaction:', wallet.details.transactionSignature);
    
    // Save wallet address to file for persistence
    fs.writeFileSync('wallet-config.json', JSON.stringify({
      userID: config.userID,
      walletAddress: config.walletAddress,
      createdAt: new Date().toISOString()
    }, null, 2));
    
    return wallet;
    
  } catch (error) {
    console.error('❌ Error creating wallet:', error.message);
    throw error;
  }
}

// Load existing wallet if available
function loadExistingWallet() {
  try {
    if (fs.existsSync('wallet-config.json')) {
      const walletConfig = JSON.parse(fs.readFileSync('wallet-config.json', 'utf8'));
      config.walletAddress = walletConfig.walletAddress;
      config.userID = walletConfig.userID;
      console.log('πŸ“‚ Loaded existing wallet:', config.walletAddress);
      return true;
    }
  } catch (error) {
    console.log('No existing wallet found, will create new one');
  }
  return false;
}
4

Register Files from Filesystem

Register any file from your server’s filesystem to the blockchainAdd this function to your trust-engine-demo.js file (below the previous functions):
async function registerFile(filePath, contentTitle) {
  try {
    // Check if file exists
    if (!fs.existsSync(filePath)) {
      throw new Error(`File not found: ${filePath}`);
    }
    
    if (!contentTitle) {
      throw new Error('contentTitle is required');
    }
    
    // Read file
    const fileBuffer = fs.readFileSync(filePath);
    const fileName = path.basename(filePath);
    
    // Create File object - no need for filename or MIME type
    const file = new File([fileBuffer], fileName);
    
    console.log(`πŸ“ Registering file: ${contentTitle} (${(fileBuffer.length / 1024).toFixed(1)} KB)`);
    
    const registration = await sdk.registerFile({
      file: file,
      contentTitle: contentTitle,
      walletAddress: config.walletAddress,
      walletType: 'managed',
      metadata: `Registered from Node.js server at ${new Date().toISOString()}`
    });

    console.log('βœ… File registered successfully!');
    console.log('Registration ID:', registration.details.managedTransactionId);
    console.log('Content Hash:', registration.details.contentHash);
    console.log('IPFS CID:', registration.details.ipfsCid);
    
    return registration;
    
  } catch (error) {
    console.error('❌ Error registering file:', error.message);
    throw error;
  }
}
5

Verify File Registration

Search for registered files to confirm they’re on the blockchainAdd this function to your trust-engine-demo.js file (below the previous functions):
async function verifyFile(filePath) {
  try {
    // Read the same file
    const fileBuffer = fs.readFileSync(filePath);
    const fileName = path.basename(filePath);
    
    // Create File object - no need for filename or MIME type
    const file = new File([fileBuffer], fileName);
    
    console.log(`πŸ” Searching for file at: ${filePath}`);
    
    const searchResults = await sdk.searchFile({ file });
    
    if (searchResults.totalResults > 0) {
      console.log('βœ… File found on blockchain!');
      console.log('Total registrations:', searchResults.totalResults);
      
      searchResults.registrations.forEach((reg, index) => {
        console.log(`\nRegistration ${index + 1}:`);
        console.log('  PDA Address:', reg.pdaAddress);
        console.log('  Registered by:', reg.registeredBy);
        console.log('  Timestamp:', reg.timestamp);
        console.log('  Explorer URL:', reg.explorerUrl);
      });
    } else {
      console.log('❌ File not found on blockchain');
    }
    
    return searchResults;
    
  } catch (error) {
    console.error('❌ Error verifying file:', error.message);
    throw error;
  }
}

6

Run Your Complete Demo

Now that you have all the functions in your file, let’s test them together!Add this demo code to the end of your trust-engine-demo.js file:
// Demo workflow - add this at the very end of your file
async function runDemo() {
  try {
    console.log('πŸš€ Starting Trust Engine Demo\n');

    // Step 1: Load or create wallet
    if (!loadExistingWallet()) {
      await createWallet();
    }

    // Step 2: Register a file with contentTitle
    console.log('\nπŸ“ Registering file...');
    const filePath = './package.json'; // Change this to any file you want to test
    const contentTitle = 'My Package Configuration';
    
    if (!fs.existsSync(filePath)) {
      console.log('Please create a test file or update the filePath variable');
      return;
    }
    
    const registration = await registerFile(filePath, contentTitle);
    console.log("Registration Complete:", registration)

    // Step 3: Verify the file
    console.log('\nπŸ” Verifying registration...');
    const verification = await verifyFile(filePath);
    console.log("Verification Complete", verification)

    console.log('\nβœ… Demo completed successfully!');
    
  } catch (error) {
    console.error('\n❌ Demo failed:', error.message);
  }
}

// Run the demo
runDemo();
Now run your complete file:
node trust-engine-demo.js
Your file should now have: imports β†’ config β†’ loadExistingWallet β†’ createWallet β†’ registerFile β†’ verifyFile β†’ runDemo functions, all working together!
7

Complete Reference Script

πŸ“‹ This is for reference only - if you followed the previous steps, your file should already be working! This shows the complete file structure in one place.
For reference, here’s what your complete trust-engine-demo.js file should look like:
import { TrustEngineSDK } from '@trust-engine/sdk';
import fs from 'fs';
import path from 'path';

// Initialize SDK and configuration
const sdk = new TrustEngineSDK();
const config = {
  userID: 'node-user-' + Date.now(), // Must be unique across your entire application
  walletAddress: null,
};

// Load existing wallet configuration
function loadWalletConfig() {
  try {
    if (fs.existsSync('wallet-config.json')) {
      const walletConfig = JSON.parse(fs.readFileSync('wallet-config.json', 'utf8'));
      config.walletAddress = walletConfig.walletAddress;
      config.userID = walletConfig.userID;
      console.log('πŸ“‚ Loaded existing wallet:', config.walletAddress);
      return true;
    }
  } catch (error) {
    console.log('No existing wallet found, will create new one');
  }
  return false;
}

// Create a new wallet
async function createWallet() {
  try {
    console.log('Creating wallet for user:', config.userID);
    
    const wallet = await sdk.createWallet({
      userID: config.userID // Must be unique across your entire application
    });
    
    config.walletAddress = wallet.details.walletAddress;
    
    // Save configuration
    fs.writeFileSync('wallet-config.json', JSON.stringify({
      userID: config.userID,
      walletAddress: config.walletAddress,
      createdAt: new Date().toISOString()
    }, null, 2));
    
    console.log('βœ… Wallet created successfully!');
    console.log('Wallet Address:', config.walletAddress);
    
    return wallet;
  } catch (error) {
    console.error('❌ Error creating wallet:', error.message);
    throw error;
  }
}

// Register a file
async function registerFile(filePath, contentTitle) {
  if (!config.walletAddress) {
    throw new Error('No wallet address available. Create a wallet first.');
  }

  if (!fs.existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  if (!contentTitle) {
    throw new Error('contentTitle is required');
  }

  const fileBuffer = fs.readFileSync(filePath);
  const fileName = path.basename(filePath);
  
  // Create File object - no need for filename or MIME type
  const file = new File([fileBuffer], fileName);
  
  console.log(`πŸ“ Registering: ${contentTitle} (${(fileBuffer.length / 1024).toFixed(1)} KB)`);
  
  const registration = await sdk.registerFile({
    file: file,
    contentTitle: contentTitle,
    walletAddress: config.walletAddress,
    walletType: 'managed',
    metadata: `Node.js registration - ${new Date().toISOString()}`
  });

  console.log('βœ… File registered!');
  console.log('Transaction ID:', registration.details.managedTransactionId);
  
  return registration;
}

// Verify a file
async function verifyFile(filePath) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  const fileBuffer = fs.readFileSync(filePath);
  const fileName = path.basename(filePath);
  
  // Create File object - no need for filename or MIME type
  const file = new File([fileBuffer], fileName);
  
  console.log(`πŸ” Verifying file at: ${filePath}`);
  
  const results = await sdk.searchFile({ file });
  
  if (results.totalResults > 0) {
    console.log('βœ… File found on blockchain!');
    console.log('Total registrations:', results.totalResults);
    
    results.registrations.forEach((reg, index) => {
      console.log(`\nRegistration ${index + 1}:`);
      console.log('  PDA Address:', reg.pdaAddress);
      console.log('  Registered by:', reg.registeredBy);
      console.log('  Timestamp:', reg.timestamp);
      console.log('  Explorer URL:', reg.explorerUrl);
    });
  } else {
    console.log('❌ File not found on blockchain');
  }
  
  return results;
}

// Main demo workflow
async function main() {
  try {
    console.log('πŸš€ Starting Trust Engine Demo\n');

    // Step 1: Load or create wallet
    if (!loadWalletConfig()) {
      await createWallet();
    }

    // Step 2: Register file with contentTitle
    console.log('\nπŸ“ Registering file...');
    const filePath = './package.json';
    const contentTitle = 'My Package Configuration';
    
    if (!fs.existsSync(filePath)) {
      console.log('Please create a test file or update the filePath variable');
      return;
    }
    
    const registration = await registerFile(filePath, contentTitle);
    console.log("Registration Complete:", registration)

    // Step 3: Verify file
    console.log('\nπŸ” Verifying registration...');
    const verification = await verifyFile(filePath);
    console.log("Verification Complete", verification)

    console.log('\nβœ… Demo completed successfully!');
    
    return { registration, verification };
  } catch (error) {
    console.error('\n❌ Demo failed:', error.message);
    throw error;
  }
}

// Run the demo
main().catch(console.error);
Save this as trust-engine-demo.js and run it:
node trust-engine-demo.js

What’s Next?