Skip to main content

Vanilla JavaScript Integration

Simple JavaScript implementation for Hyve platform iframe authentication and telemetry.

Overview

This guide provides vanilla JavaScript code for:

  • Parsing and validating the hyve-token URL parameter
  • Sending telemetry events to the Hyve platform

Note: Session management is up to you - implement it however works best for your game.

Authentication

Parsing the hyve-token

When your game loads in the Hyve iframe, authentication is passed via the hyve-token URL parameter.

// Parse URL parameters
function parseHyveToken() {
const params = new URLSearchParams(window.location.search);
const token = params.get('hyve-token');
return token;
}

Token Validation

The hyve-token format is: signature.message

function validateHyveToken(token) {
if (!token) {
console.error('No hyve-token found');
return null;
}

try {
// Split token into signature and message
const parts = token.split('.');
if (parts.length !== 2) {
console.error('Invalid token format');
return null;
}

const [signature, message] = parts;

// Decode the message (base64 encoded JSON)
let messageData;
try {
const decoded = atob(message);
messageData = JSON.parse(decoded);
} catch (error) {
console.error('Failed to decode token message:', error);
return null;
}

// Check expiration if present
if (messageData.expiration && Date.now() > messageData.expiration) {
console.error('Token has expired');
return null;
}

// Return validated session data
return {
walletAddress: messageData.address || messageData.userId,
userId: messageData.userId || messageData.address,
expiration: messageData.expiration,
isValid: true
};
} catch (error) {
console.error('Token validation failed:', error);
return null;
}
}

Complete Auth Example

// Initialize authentication
function initHyveAuth() {
const token = parseHyveToken();
const session = validateHyveToken(token);

if (session) {
console.log('✅ Authenticated:', session.walletAddress);

// Clear token from URL for security
const url = new URL(window.location);
url.searchParams.delete('hyve-token');
window.history.replaceState({}, document.title, url.pathname + url.search);

// Store the wallet address and user ID however you want
// (localStorage, sessionStorage, memory, etc.)
return session;
} else {
console.error('❌ Authentication failed');
return null;
}
}

Telemetry

Getting Your Telemetry Credentials

Contact us at support@hyve.gg to receive:

  • Telemetry API endpoint URL
  • Authentication token

These are required to send analytics events to the Hyve platform.

Event Structure

The Hyve telemetry API uses a hierarchical event structure:

{
session_id: "sess_123", // Your session identifier
hyve_user_id: "0x1234...", // User's wallet address
event_location: "game", // Where: game, menu, shop, etc.
event_category: "gameplay", // What: gameplay, ui, loading, etc.
event_sub_category: "level_1", // Specific context (optional)
event_action: "start", // Action: start, complete, click, etc.
event_sub_action: "new_game", // Sub-action (optional)
event_details: { // Custom data (optional)
score: 1500,
time: 120,
difficulty: "hard"
}
}

Sending Events

// Configuration - contact support@hyve.gg for these values
const HYVE_API_URL = 'YOUR_API_URL_HERE'; // Provided by Hyve
const TELEMETRY_TOKEN = 'YOUR_TOKEN_HERE'; // Provided by Hyve

async function sendHyveEvent({
sessionId, // Your game's session identifier
walletAddress, // User's wallet address from hyve-token
eventLocation,
eventCategory,
eventSubCategory,
eventAction,
eventSubAction, // Optional
eventDetails = {}
}) {
const payload = {
session_id: sessionId,
hyve_user_id: walletAddress,
event_location: eventLocation,
event_category: eventCategory,
event_sub_category: eventSubCategory,
event_action: eventAction,
event_sub_action: eventSubAction,
event_details: {
...eventDetails,
timestamp: new Date().toISOString()
}
};

try {
const response = await fetch(`${HYVE_API_URL}/api/v1/partners/analytics/events`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${TELEMETRY_TOKEN}`
},
body: JSON.stringify(payload)
});

if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}

console.log('📊 Event sent:', eventLocation, '>', eventCategory, '>', eventAction);
return { success: true };
} catch (error) {
console.error('❌ Telemetry failed:', error);
return { success: false, error };
}
}

Common Game Events

// Assuming you have these from your session management
const sessionId = 'your-session-id';
const walletAddress = '0x1234...'; // from validated hyve-token

// Game started
await sendHyveEvent({
sessionId,
walletAddress,
eventLocation: 'game',
eventCategory: 'gameplay',
eventSubCategory: 'level_1',
eventAction: 'start',
eventDetails: {
game_mode: 'single_player',
difficulty: 'normal'
}
});

// Level completed
await sendHyveEvent({
sessionId,
walletAddress,
eventLocation: 'game',
eventCategory: 'gameplay',
eventSubCategory: 'level_1',
eventAction: 'complete',
eventDetails: {
score: 1500,
time_seconds: 120,
stars: 3
}
});

// Game over
await sendHyveEvent({
sessionId,
walletAddress,
eventLocation: 'game',
eventCategory: 'gameplay',
eventAction: 'end',
eventDetails: {
final_score: 5000,
levels_completed: 5,
duration_seconds: 600
}
});

// UI interaction
await sendHyveEvent({
sessionId,
walletAddress,
eventLocation: 'menu',
eventCategory: 'ui',
eventAction: 'click',
eventSubAction: 'settings',
eventDetails: {
button_id: 'audio_settings'
}
});

// In-game purchase
await sendHyveEvent({
sessionId,
walletAddress,
eventLocation: 'shop',
eventCategory: 'purchase',
eventAction: 'complete',
eventDetails: {
item_id: 'extra_life',
price: 100,
currency: 'coins'
}
});

// Error tracking
await sendHyveEvent({
sessionId,
walletAddress,
eventLocation: 'game',
eventCategory: 'error',
eventAction: 'runtime',
eventDetails: {
error_message: error.message,
error_stack: error.stack
}
});

Event Queue (Optional)

For better reliability, you can implement a simple queue to batch events:

const TelemetryQueue = {
queue: [],
batchSize: 5,
flushInterval: 5000,

init() {
// Auto-flush every 5 seconds
setInterval(() => this.flush(), this.flushInterval);

// Flush on page unload
window.addEventListener('beforeunload', () => this.flush());
},

add(eventData) {
this.queue.push(eventData);
if (this.queue.length >= this.batchSize) {
this.flush();
}
},

async flush() {
if (this.queue.length === 0) return;

const events = this.queue.splice(0, this.batchSize);

for (const event of events) {
await sendHyveEvent(event);
}
}
};

// Initialize queue
TelemetryQueue.init();

// Use queue instead of direct send
TelemetryQueue.add({
sessionId: 'your-session-id',
walletAddress: '0x1234...',
eventLocation: 'game',
eventCategory: 'gameplay',
eventAction: 'start'
});

Complete Integration Example

<!DOCTYPE html>
<html>
<head>
<title>Hyve Game Integration</title>
</head>
<body>
<div id="game">
<h1>My Game</h1>
<div id="status">Initializing...</div>
<button id="startBtn" disabled>Start Game</button>
</div>

<script>
// ============= CONFIG =============
// Contact support@hyve.gg for these values
const HYVE_API_URL = 'YOUR_API_URL_HERE';
const TELEMETRY_TOKEN = 'YOUR_TOKEN_HERE';

// Simple in-memory session (implement your own persistence if needed)
let currentSession = {
sessionId: null,
walletAddress: null
};

// ============= AUTH =============
function parseHyveToken() {
const params = new URLSearchParams(window.location.search);
return params.get('hyve-token');
}

function validateHyveToken(token) {
if (!token) return null;

try {
const [signature, message] = token.split('.');
if (!signature || !message) return null;

const decoded = atob(message);
const messageData = JSON.parse(decoded);

if (messageData.expiration && Date.now() > messageData.expiration) {
return null;
}

return {
walletAddress: messageData.address || messageData.userId,
userId: messageData.userId || messageData.address,
isValid: true
};
} catch (error) {
console.error('Token validation failed:', error);
return null;
}
}

function initHyveAuth() {
const token = parseHyveToken();
const session = validateHyveToken(token);

if (session) {
// Store session however you want - this is just an example
currentSession.sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
currentSession.walletAddress = session.walletAddress;

// Clear token from URL
const url = new URL(window.location);
url.searchParams.delete('hyve-token');
window.history.replaceState({}, document.title, url.pathname + url.search);

return session;
}

return null;
}

// ============= TELEMETRY =============
async function sendHyveEvent({
sessionId,
walletAddress,
eventLocation,
eventCategory,
eventSubCategory,
eventAction,
eventSubAction,
eventDetails = {}
}) {
const payload = {
session_id: sessionId,
hyve_user_id: walletAddress,
event_location: eventLocation,
event_category: eventCategory,
event_sub_category: eventSubCategory,
event_action: eventAction,
...(eventSubAction && { event_sub_action: eventSubAction }),
event_details: {
...eventDetails,
timestamp: new Date().toISOString()
}
};

try {
const response = await fetch(`${HYVE_API_URL}/api/v1/partners/analytics/events`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${TELEMETRY_TOKEN}`
},
body: JSON.stringify(payload)
});

if (!response.ok) throw new Error(`HTTP ${response.status}`);

console.log('📊 Event sent:', eventLocation, '>', eventCategory, '>', eventAction);
return { success: true };
} catch (error) {
console.error('❌ Telemetry failed:', error);
return { success: false, error };
}
}

// ============= GAME =============
async function initGame() {
const statusEl = document.getElementById('status');
const startBtn = document.getElementById('startBtn');

// Initialize auth
statusEl.textContent = 'Authenticating...';
const session = initHyveAuth();

if (!session) {
statusEl.textContent = '❌ Authentication failed';
console.error('Add ?hyve-token=... to URL');
return;
}

statusEl.textContent = `✅ Connected: ${currentSession.walletAddress.substr(0, 6)}...`;
startBtn.disabled = false;

// Track session start
await sendHyveEvent({
sessionId: currentSession.sessionId,
walletAddress: currentSession.walletAddress,
eventLocation: 'game',
eventCategory: 'session',
eventAction: 'start',
eventDetails: {
platform: navigator.platform,
user_agent: navigator.userAgent
}
});

// Start game button
startBtn.onclick = async () => {
await sendHyveEvent({
sessionId: currentSession.sessionId,
walletAddress: currentSession.walletAddress,
eventLocation: 'game',
eventCategory: 'gameplay',
eventAction: 'start'
});

statusEl.textContent = '🎮 Game started!';
// Your game logic here...
};
}

// Initialize when page loads
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initGame);
} else {
initGame();
}
</script>
</body>
</html>

Next Steps

  1. Contact support@hyve.gg for your telemetry API URL and token
  2. Integrate authentication using the examples above
  3. Add telemetry events for key game moments
  4. Test locally with mock tokens
  5. Deploy and test in Hyve platform iframe