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);