Best Practices

Best Practices

Essential guide for building production-ready TELA applications with size constraints, performance optimization, and DERO blockchain integration.

⚠️

Critical Size Constraints TELA has strict size limitations that are absolute requirements. Never exceed these limits or deployment will fail.

πŸ“ Size Constraints (CRITICAL)

File Size Limits

File TypeContent LimitTotal LimitStatus
TELA-DOC-118.00 KB19.20 KB⚠️ Absolute max
TELA-INDEX-19 KB recommended11.64 KB max⚠️ May break updates
Shard Size17,500 bytes-⚠️ Auto-split point
🚫

Actual Error Messages from parse.go:

  • "docCode size is to large, max %.2fKB"
  • "DOC SC size is to large, max %.2fKB"
  • "contract exceeds max INDEX install size by %.2fKB"

Size Planning Guide

File SizeActionStrategyCompression
< 10 KBβœ… DeployDirect deploymentOptional
10-15 KB⚠️ MonitorStandard workflowConsider .gz
15-18 KB⚠️ CriticalOptimize firstRequired
18 KB+❌ Too largeSplit into modulesUse DocShards

🎯 Core Principles

Entry Point: index.html (CRITICAL)

🚨

Your main HTML file MUST be named index.html

TELA browsers (including Hologram) look for index.html as the default entry point. If your DOC1 file has any other name (like myapp.html, main.html, or Snake_Deluxe.html), your app will NOT render - users will see a file listing instead.

# ❌ WRONG - Shows file listing, app doesn't load
DOC1: Snake_Deluxe.html
DOC1: myapp.html
DOC1: main.html
 
# βœ… CORRECT - App loads properly
DOC1: index.html

Always rename your main HTML file to index.html before deployment.

HTML-First Development

TELA Principle: HTML-First, JavaScript-Minimal Write fast, zippy static HTML-based applications using proven patterns from tela_tests/app1.

Proven JavaScript Patterns

// βœ… PROVEN PATTERN - Based on working tela_tests/app1
let socket;
const applicationData = {
    "id": Array.from({length:64},()=>Math.floor(Math.random()*16).toString(16)).join(''),
    "name": "Your TELA Application",
    "url": "http://localhost:" + location.port
};
 
function connectWebSocket() {
    socket = new WebSocket("ws://localhost:44326/xswd");
    socket.addEventListener("open", function(event) {
        socket.send(JSON.stringify(applicationData));
    });
}

⚑ Size Optimization Quick Reference

Optimization Techniques Comparison

TechniqueBeforeAfterSavings
Variable NamescalculateDEROAmount()calcDERO()~40%
String Concatenation4 statements1 statementOverhead reduction
Function Compression127 bytes64 bytes50%
CSS Shorthand4 properties1 property75%
Template CompressionMulti-lineSingle-line~30%

CSS Optimization

What❌ Avoidβœ… Optimize
Propertiesmargin-top: 1rem; margin-right: 0; margin-bottom: 1rem; margin-left: 0;margin: 1rem 0;
Colorsrgba(255, 255, 255, 1)#fff
FormattingMulti-line verboseSingle-line compressed
SelectorsLong descriptive namesShort functional names

JavaScript Optimization

What❌ Avoidβœ… Optimize
VariablescurrentBlockHeight, transactionHashListh, txs
FunctionsSeparate helpersCombined operations
TemplatesMulti-line template literalsSingle concatenation
ObjectsapplicationName, connectionTimeoutname, timeout
StylesRepeated inline stylesShared constants

Quick Examples:

// Variable shortening: 47 bytes β†’ 28 bytes
function calcDERO(a) {
    return a ? (parseFloat(a)/1e12).toFixed(6)+' DERO' : '0.000000 DERO';
}
 
// Template compression: Multi-line β†’ Single-line
var t = '<div class="card"><h2>'+title+'</h2><p>'+content+'</p></div>';
 
// Shared styles: Repeated β†’ Constant
var s = 'background:rgba(0,0,0,0.2);border:1px solid rgba(82,200,219,0.3);';
function renderCard() { return '<div style="'+s+'">Card</div>'; }

HTML Optimization

What❌ Avoidβœ… Optimize
Attributesid="main-container" style="display: block;"id="main"
WhitespaceFormatted with indentationCompressed single-line
StructureVerbose nested divsMinimal semantic HTML

πŸ“¦ Module Organization

ScenarioStrategyFile CountExample
< 18 KB totalSingle file1Simple apps
18-35 KBSplit by feature2-3Core + UI modules
35 KB+Full modular split4+Use DocShards system

Single File Pattern:

({
    name: 'simple-app',
    version: '1.0.0',
    init: function() { /* ... */ },
    render: function() { /* ... */ }
});

Multi-Module Pattern:

// core.js (15KB) - Core logic
// ui.js (12KB) - UI components  
// data.js (10KB) - Data handling

πŸ”— DERO Blockchain Integration

XSWD Protocol Requirements

🚫

MANDATORY: XSWD Protocol Only ALL blockchain data must come from DERO daemon via XSWD WebSocket protocol. External APIs are forbidden.

Data Sourceβœ… Allowed❌ Forbidden
DERO Daemonxswd.call('DERO.GetInfo')-
Wallet via XSWDxswd.call('GetBalance')-
External APIs-fetch('https://api.example.com')
CDN Libraries-<script src="https://cdn...">
// βœ… CORRECT: XSWD data fetching
async function getBlockData(height) {
    const block = await xswd.call('DERO.GetBlock', { height });
    return block;
}
 
// ❌ FORBIDDEN: External API calls
// fetch('https://api.example.com/block/' + height)  // NEVER

Real Data Only Policy

// βœ… CORRECT: Live blockchain data
const balance = await xswd.call('GetBalance');
const deroAmount = balance.balance / 100000;
 
// ❌ FORBIDDEN: Demo or placeholder data
// const demoBalance = 123.45678;  // NEVER USE FAKE DATA

🚫 No External Dependencies

Dependency Type❌ Forbiddenβœ… Solution
CSS FrameworksBootstrap, Tailwind CDNCustom minimal CSS
JavaScript LibrariesjQuery, Chart.js CDNLightweight custom implementations
FontsGoogle Fonts CDNSystem fonts or embedded
IconsFont Awesome CDNSVG icons or emoji
// βœ… GOOD: Custom lightweight implementation
const MiniChart = {
    draw(canvas, data) {
        const ctx = canvas.getContext('2d');
        const max = Math.max(...data);
        // Minimal chart drawing code...
    }
};
 
// ❌ AVOID: Heavy external libraries
// import Chart from 'chart.js';  // Too large for TELA

⚑ Performance Targets

MetricTargetCritical
Load Time< 2 secondsRequired
Animation FPS60 fpsSmooth
Memory FootprintMinimalLong-running apps

Efficient DOM Updates:

// βœ… GOOD: Batch updates
function updateBlockList(blocks) {
    const html = blocks.map(b => 
        `<div class="b" data-h="${b.height}">...</div>`
    ).join('');
    document.getElementById('blocks').innerHTML = html;
}
 
// ❌ AVOID: Individual manipulations
blocks.forEach(block => {
    const div = document.createElement('div'); // Slow
    container.appendChild(div);
});

πŸ” Security & Privacy

Practiceβœ… Good❌ Avoid
Data StorageLocal preferences onlySensitive wallet data
External TrackingNoneAnalytics services
User InputSanitize all inputsDirect injection
Content SecurityCSP compliantInline scripts from user data
// βœ… GOOD: Secure patterns
const SecureTELAApp = {
    savePreference(key, value) {
        localStorage.setItem(`tela-app-${key}`, JSON.stringify(value));
    },
    executeSecurely(userInput) {
        return userInput.replace(/[<>'"&]/g, ''); // Sanitize
    }
};

βœ… What Works in TELA

Proven JavaScript Features

FeatureStatusExample
ES6 let/constβœ… Workslet socket; const data = {};
Arrow Functionsβœ… Worksdocument.addEventListener('mousemove', (e) => {...})
Template Literalsβœ… Works`${title}`
String Concatenationβœ… Works"http://localhost:" + location.port
Traditional Functionsβœ… Worksfunction connect() {...}
Event Listenersβœ… Workssocket.addEventListener('open', fn)

CSS Features That Work

FeatureStatusExample
CSS Variablesβœ… Works:root { --color: #52c8db; }
Animationsβœ… Works@keyframes spin { 0% { ... } }
Grid/Flexboxβœ… Worksdisplay: grid; grid-template-columns: ...
Gradientsβœ… Worksbackground: linear-gradient(...)
Transformsβœ… Workstransform: rotate(360deg)

πŸ“‹ Development Checklist

Quick Development Checklist - Use this for every TELA application

Pre-Development

  • Plan file structure (< 18KB per file)
  • Identify modules needed
  • Design XSWD-only data access
  • Plan caching strategy

During Development

  • Monitor sizes: wc -c *.js *.css *.html
  • Test with real DERO daemon
  • Validate XSWD integration
  • Optimize for < 2s load time

Pre-Deployment

  • All files < 18KB verified
  • Test compression if 15-18KB
  • Validate with tela-cli serve local ./project
  • No external dependencies

Post-Deployment

  • Test deployed functionality
  • Monitor performance
  • Gather user feedback

Related Documentation