From 8d39af951193e268690e0978702a22d96c965988 Mon Sep 17 00:00:00 2001 From: alexander-sei Date: Thu, 8 Jan 2026 15:36:55 +0100 Subject: [PATCH 1/5] First iteration on ai pages --- content/answers/_meta.js | 11 + content/answers/pseocontent.csv | 81 ++++ package.json | 1 + scripts/generate-answers.js | 631 ++++++++++++++++++++++++++++++++ 4 files changed, 724 insertions(+) create mode 100644 content/answers/_meta.js create mode 100644 content/answers/pseocontent.csv create mode 100644 scripts/generate-answers.js diff --git a/content/answers/_meta.js b/content/answers/_meta.js new file mode 100644 index 00000000..5439127a --- /dev/null +++ b/content/answers/_meta.js @@ -0,0 +1,11 @@ +export default { + '*': { + display: 'hidden', + theme: { + sidebar: false, + toc: true, + breadcrumb: false, + pagination: false + } + } +}; diff --git a/content/answers/pseocontent.csv b/content/answers/pseocontent.csv new file mode 100644 index 00000000..854738ff --- /dev/null +++ b/content/answers/pseocontent.csv @@ -0,0 +1,81 @@ +What is [Blockchain Term] and How Does it Work?,Target Keyword,MSV +What is Blockchain and How Does It Work?,what is blockchain,31000 +What is an NFT and How Does It Work?,what is NFT,12000 +What is DeFi and How Does It Work?,what is DeFi,3300 +What is Staking in Blockchain and How Does It Work?,what is staking,1300 +What is Yield Farming in Crypto and How Does It Work?,what is yield farming,1100 +What is a Slippage and How Does It Work?,what is slippage,900 +What is a Stablecoin and How Does It Work?,what is stablecoin,800 +What is an Interoperability and How Does It Work?,what is interoperability,800 +What is a Smart Contract and How Does It Work?,what is smart contract,600 +What is MEV and Why It Matters,what is MEV,500 +What is Sharding in Crypto and How Does It Work?,what is sharding,500 +What is an EVM and How Does It Work?,what is EVM,400 +What is Proof Of Stake and How Does It Secure the Blockchain?,what is proof of stake,350 +What is TVL and Why It Matters,what is TVL,250 +What is a Hash Rate and How Does It Work?,what is hash rate,200 +What is a Wallet and How Does It Work?,what is wallet,200 +What is Minting in Crypto and How Does It Work?,what is minting,200 +What is Proof Of Work and How Does It Secure the Blockchain?,what is proof of work,200 +What is a Tokenomics and How Does It Work?,what is tokenomics,150 +What is a Rug Pull and How Does It Work?,what is rug pull,150 +What is a Mainnet and How Does It Work?,what is mainnet,150 +What is Liquid Staking in Crypto and How Does It Work?,what is liquid staking,150 +What is a Layer 1 Blockchain and How Does It Work?,what is layer 1 blockchain,100 +What is a Whale and How Does It Work?,what is whale,100 +What is a Composability and How Does It Work?,what is composability,100 +What is an Impermanent Loss and How Does It Work?,what is impermanent loss,80 +What is a Liquidity Pool and How Does It Work?,what is liquidity pool,70 +What is a Sidechain and How Does It Work?,what is sidechain,70 +What is Slashing in Crypto and How Does It Work?,what is slashing,60 +What is a Cold Wallet and How Does It Work?,what is cold wallet,50 +What is a DAOs and How Does It Work?,what is DAOs,50 +What is a Testnet and How Does It Work?,what is testnet,50 +What is a Zero-knowledge Proof and How Does It Work?,what is zero-knowledge proof,40 +What is a Block Time and How Does It Work?,what is block time,40 +What is a Hot Wallet and How Does It Work?,what is hot wallet,40 +What is a Block Explorer and How Does It Work?,what is block explorer,40 +What is an Oracles and How Does It Work?,what is oracles,40 +What is a Rollup and How Does It Work?,what is rollup,30 +What is Proof Of History and How Does It Secure the Blockchain?,what is proof of history,30 +What is a Governance Token and How Does It Work?,what is governance token,20 +What is a Custodial Wallet and How Does It Work?,what is custodial wallet,20 +What Are Airdrops and How Do They Work?,what is airdrops,20 +What Are Staking Rewards and How Do They Work?,what is staking rewards,20 +What is a Hard Fork and How Does It Work?,what is hard fork,20 +What is Front-running in Crypto and How Does It Work?,what is front-running,20 +What Are Gas Fees and How Do They Work?,what is gas fees,10 +What is a Consensus Mechanism and How Does It Work?,what is consensus mechanism,10 +What is a Validator and How Does It Work?,what is validator,10 +What is a Non-custodial Wallet and How Does It Work?,what is non-custodial wallet,10 +What is a Flash Loan and How Does It Work?,what is flash loan,10 +What is an Atomic Swap and How Does It Work?,what is atomic swap,10 +What is a Block Height and How Does It Work?,what is block height,10 +What is a Genesis Block and How Does It Work?,what is genesis block,10 +What is a Block Reward and How Does It Work?,what is block reward,10 +What is a Token Burn and How Does It Work?,what is token burn,10 +What is a Smart Contract Audit and How Does It Work?,what is smart contract audit,10 +What Are Event Logs and How Do They Work?,what is event logs,10 +What is the IBC Protocol and How Does It Work?,what is IBC protocol,10 +What is a Layer 2 Solution and How Does It Work?,what is layer 2 solution,n/a +What Are zk-SNARKs and How Do They Work?,what is zk-SNARKs,n/a +What is a Cross-chain Bridge and How Does It Work?,what is cross-chain bridge,n/a +What is a Governance Proposal and How Does It Work?,what is governance proposal,n/a +What is a Soft Fork and How Does It Work?,what is soft fork,n/a +What is a Gas War and How Does It Work?,what is gas war,n/a +What is a Chain Reorg and How Does It Work?,what is chain reorg,n/a +What is a Rebase Token and How Does It Work?,what is rebase token,n/a +What is a Wrapped Token and How Does It Work?,what is wrapped token,n/a +What is a Burn Mechanism and How Does It Work?,what is burn mechanism,n/a +Rollup Vs Sidechain: Key Differences Explained,what is rollup vs sidechain,n/a +What is Delegated Staking in Crypto and How Does It Work?,what is delegated staking,n/a +What is a Validator Set and How Does It Work?,what is validator set,n/a +What is a Light Client and How Does It Work?,what is light client,n/a +What is a Trustless Bridge and How Does It Work?,what is trustless bridge,n/a +What is a Multi-sig Wallet and How Does It Work?,what is multi-sig wallet,n/a +What is a Crypto Oracle and How Does It Work?,what is crypto oracle,n/a +What is a Smart Contract Upgradeability and How Does It Work?,what is smart contract upgradeability,n/a +What is a Gas Optimization and How Does It Work?,what is gas optimization,n/a +What is an Interchain Security and How Does It Work?,what is interchain security,n/a +What is a Validator Commission and How Does It Work?,what is validator commission,n/a +What is a LSDfi and How Does It Work?,what is LSDfi,n/a \ No newline at end of file diff --git a/package.json b/package.json index f7317470..01383da1 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "scrape-docs": "node scripts/scrape-docs-html.js", "upload-to-trieve": "node scripts/upload-to-trieve.js", "seo:audit": "node scripts/audit-content-seo.mjs", + "generate:answers": "node scripts/generate-answers.js", "test": "jest", "test:watch": "jest --watch", "prepare": "husky" diff --git a/scripts/generate-answers.js b/scripts/generate-answers.js new file mode 100644 index 00000000..d8f802ce --- /dev/null +++ b/scripts/generate-answers.js @@ -0,0 +1,631 @@ +#!/usr/bin/env node +/** + * Generate SEO-friendly answer pages from seed questions. + * + * Usage: + * node scripts/generate-answers.js # Generate all missing answers + * node scripts/generate-answers.js --dry-run # Preview what would be generated + * node scripts/generate-answers.js --force # Regenerate all answers + * node scripts/generate-answers.js --id=deploy-smart-contract-sei # Generate specific answer + * node scripts/generate-answers.js --csv=path/to/file.csv # Generate from CSV + * node scripts/generate-answers.js --import-csv=path/to/file.csv # Import CSV to seed-questions.json + * node scripts/generate-answers.js --priority=high # Only high priority (MSV >= 1000) + * node scripts/generate-answers.js --priority=medium # Medium+ priority (MSV >= 100) + * node scripts/generate-answers.js --category=evm # Only specific category + * node scripts/generate-answers.js --min-msv=500 # Custom MSV threshold + * node scripts/generate-answers.js --limit=10 # Limit number of questions + * + * Configuration: + * Set AI_PROVIDER env var to 'claude', 'gemini', 'groq', or 'manual' (default: manual) + * Set ANTHROPIC_API_KEY, GEMINI_API_KEY, or GROQ_API_KEY for AI generation + * + * The script reads questions from src/data/seed-questions.json and generates + * MDX files in content/answers/ that are: + * - Hidden from navigation (via _meta.js) + * - Accessible via direct URL + * - Included in sitemap for SEO + */ + +const fs = require('fs'); +const path = require('path'); + +const SEED_QUESTIONS_PATH = path.join(__dirname, '../src/data/seed-questions.json'); +const ANSWERS_DIR = path.join(__dirname, '../content/answers'); +const CONTENT_DIR = path.join(__dirname, '../content'); + +// Category to related docs mapping for "Learn more" links +const CATEGORY_DOCS = { + evm: [ + { title: 'EVM Overview', href: '/evm' }, + { title: 'Networks & RPC', href: '/evm/networks' }, + { title: 'Deploy with Hardhat', href: '/evm/evm-hardhat' }, + { title: 'Deploy with Foundry', href: '/evm/evm-foundry' } + ], + learn: [ + { title: 'Getting Started', href: '/learn' }, + { title: 'Accounts', href: '/learn/accounts' }, + { title: 'Faucet', href: '/learn/faucet' } + ], + node: [ + { title: 'Node Operations', href: '/node' }, + { title: 'Validators', href: '/node/validators' } + ], + 'cosmos-sdk': [ + { title: 'Cosmos SDK', href: '/cosmos-sdk' }, + { title: 'Transactions', href: '/cosmos-sdk/transactions' } + ], + glossary: [ + { title: 'Getting Started', href: '/learn' }, + { title: 'Token Standards', href: '/learn/dev-token-standards' }, + { title: 'Staking', href: '/learn/general-staking' }, + { title: 'Oracles', href: '/learn/oracles' } + ] +}; + +// Keyword to category mapping for auto-categorization +const KEYWORD_CATEGORIES = { + // EVM-specific + evm: 'evm', + solidity: 'evm', + 'smart contract': 'evm', + hardhat: 'evm', + foundry: 'evm', + remix: 'evm', + // Node/validator + validator: 'node', + node: 'node', + 'validator set': 'node', + 'validator commission': 'node', + // Cosmos + ibc: 'cosmos-sdk', + cosmos: 'cosmos-sdk', + 'interchain security': 'cosmos-sdk', + // Default to glossary for general blockchain terms + default: 'glossary' +}; + +/** + * Parse a simple CSV (handles basic quoting) + */ +function parseCSV(content) { + const lines = content.trim().split('\n'); + const headers = parseCSVLine(lines[0]); + const rows = []; + + for (let i = 1; i < lines.length; i++) { + const values = parseCSVLine(lines[i]); + if (values.length >= headers.length) { + const row = {}; + headers.forEach((header, idx) => { + row[header.trim()] = values[idx]?.trim() || ''; + }); + rows.push(row); + } + } + + return rows; +} + +/** + * Parse a single CSV line (handles quoted fields) + */ +function parseCSVLine(line) { + const result = []; + let current = ''; + let inQuotes = false; + + for (let i = 0; i < line.length; i++) { + const char = line[i]; + + if (char === '"') { + inQuotes = !inQuotes; + } else if (char === ',' && !inQuotes) { + result.push(current); + current = ''; + } else { + current += char; + } + } + result.push(current); + + return result; +} + +/** + * Slugify a question into a URL-friendly filename + */ +function slugify(text) { + return text + .toLowerCase() + .replace(/[?'":\[\]]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +/** + * Auto-detect category from keywords + */ +function detectCategory(question, keyword) { + const lowerQ = (question + ' ' + keyword).toLowerCase(); + + for (const [key, category] of Object.entries(KEYWORD_CATEGORIES)) { + if (key !== 'default' && lowerQ.includes(key)) { + return category; + } + } + + return KEYWORD_CATEGORIES.default; +} + +/** + * Calculate priority from MSV (Monthly Search Volume) + */ +function calculatePriority(msv) { + const num = parseInt(msv, 10); + if (isNaN(num) || msv === 'n/a') return 'low'; + if (num >= 1000) return 'high'; + if (num >= 100) return 'medium'; + return 'low'; +} + +/** + * Convert CSV rows to question format + */ +function csvToQuestions(rows) { + return rows.map((row) => { + // Handle different possible column names + const question = row['What is [Blockchain Term] and How Does it Work?'] || row['Question'] || row['question'] || Object.values(row)[0]; + + const keyword = row['Target Keyword'] || row['Keyword'] || row['keyword'] || ''; + + const msv = row['MSV'] || row['Volume'] || row['volume'] || ''; + + const id = slugify(question); + const category = detectCategory(question, keyword); + const priority = calculatePriority(msv); + + return { + id, + question, + category, + priority, + keyword: keyword || undefined, + msv: msv !== 'n/a' ? parseInt(msv, 10) || undefined : undefined + }; + }); +} + +/** + * Generate MDX content for a question (manual/placeholder mode) + */ +function generateManualMDX(question) { + const { id, question: q, category, keyword } = question; + const relatedDocs = CATEGORY_DOCS[category] || CATEGORY_DOCS.glossary; + const slug = id || slugify(q); + + // Build keywords array + const keywordParts = keyword ? keyword.split(' ').filter((k) => k.length > 2) : []; + const slugParts = slug.split('-').filter((k) => k.length > 2); + const allKeywords = ['sei', 'blockchain', category, ...new Set([...keywordParts, ...slugParts])]; + + const relatedLinks = relatedDocs.map((doc) => `- [${doc.title}](${doc.href})`).join('\n'); + + return `--- +title: '${q.replace(/'/g, "\\'")}' +description: 'Learn about ${keyword || q.replace(/'/g, "\\'")} and how it works in blockchain and on Sei Network.' +keywords: [${allKeywords.map((k) => `'${k}'`).join(', ')}] +--- + +import { Callout } from 'nextra/components'; + +# ${q} + + +This guide explains ${keyword || 'this concept'} in the context of blockchain technology and Sei Network. + + +{/* TODO: Add comprehensive answer here */} + +## Overview + +_This content is being prepared. Please check the related documentation below._ + +## How It Works on Sei + +Sei is a high-performance Layer 1 blockchain with EVM compatibility. Here's how ${keyword || 'this concept'} applies to Sei: + +_Content coming soon._ + +## Related Documentation + +${relatedLinks} + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ +`; +} + +/** + * Generate answer using Gemini API (free tier) + */ +async function generateWithGemini(question, apiKey) { + const { question: q, category, keyword } = question; + + const prompt = `You are a technical documentation assistant for Sei Network, a high-performance Layer 1 blockchain with EVM compatibility. + +Generate a comprehensive, SEO-friendly answer for this question: "${q}" + +Target keyword: ${keyword || 'N/A'} +Category: ${category} + +Guidelines: +- Start with a clear, concise definition (2-3 sentences) +- Explain how this concept works in general blockchain context +- Then explain how it specifically applies to Sei Network (mention Sei's parallelization, ~400ms finality, or EVM compatibility where relevant) +- Include code examples where relevant (use \`\`\`solidity, \`\`\`typescript, or \`\`\`bash) +- Use clear headings like "## Overview", "## How It Works", "## On Sei Network" +- Keep the answer focused and scannable +- Do NOT include the question as a heading (it will be added separately) +- Format the response as markdown content (not full MDX) + +Respond with ONLY the markdown content for the answer body.`; + + const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + contents: [{ parts: [{ text: prompt }] }], + generationConfig: { + temperature: 0.7, + maxOutputTokens: 2048 + } + }) + }); + + if (!response.ok) { + throw new Error(`Gemini API error: ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + return data.candidates?.[0]?.content?.parts?.[0]?.text || ''; +} + +/** + * Generate answer using Groq API (free tier) + */ +async function generateWithGroq(question, apiKey) { + const { question: q, category, keyword } = question; + + const prompt = `You are a technical documentation assistant for Sei Network, a high-performance Layer 1 blockchain with EVM compatibility. + +Generate a comprehensive, SEO-friendly answer for this question: "${q}" + +Target keyword: ${keyword || 'N/A'} +Category: ${category} + +Guidelines: +- Start with a clear, concise definition (2-3 sentences) +- Explain how this concept works in general blockchain context +- Then explain how it specifically applies to Sei Network (mention Sei's parallelization, ~400ms finality, or EVM compatibility where relevant) +- Include code examples where relevant (use \`\`\`solidity, \`\`\`typescript, or \`\`\`bash) +- Use clear headings like "## Overview", "## How It Works", "## On Sei Network" +- Keep the answer focused and scannable +- Do NOT include the question as a heading (it will be added separately) +- Format the response as markdown content (not full MDX) + +Respond with ONLY the markdown content for the answer body.`; + + const response = await fetch('https://api.groq.com/openai/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${apiKey}` + }, + body: JSON.stringify({ + model: 'llama-3.1-70b-versatile', + messages: [{ role: 'user', content: prompt }], + temperature: 0.7, + max_tokens: 2048 + }) + }); + + if (!response.ok) { + throw new Error(`Groq API error: ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + return data.choices?.[0]?.message?.content || ''; +} + +/** + * Generate answer using Claude API (Anthropic) + */ +async function generateWithClaude(question, apiKey) { + const { question: q, category, keyword } = question; + + const prompt = `You are a technical documentation assistant for Sei Network, a high-performance Layer 1 blockchain with EVM compatibility. + +Generate a comprehensive, SEO-friendly answer for this question: "${q}" + +Target keyword: ${keyword || 'N/A'} +Category: ${category} + +Guidelines: +- Start with a clear, concise definition (2-3 sentences) +- Explain how this concept works in general blockchain context +- Then explain how it specifically applies to Sei Network (mention Sei's parallelization, ~400ms finality, or EVM compatibility where relevant) +- Include code examples where relevant (use \`\`\`solidity, \`\`\`typescript, or \`\`\`bash) +- Use clear headings like "## Overview", "## How It Works", "## On Sei Network" +- Keep the answer focused and scannable +- Do NOT include the question as a heading (it will be added separately) +- Format the response as markdown content (not full MDX) + +Respond with ONLY the markdown content for the answer body.`; + + const response = await fetch('https://api.anthropic.com/v1/messages', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-api-key': apiKey, + 'anthropic-version': '2023-06-01' + }, + body: JSON.stringify({ + model: 'claude-sonnet-4-20250514', + max_tokens: 2048, + messages: [{ role: 'user', content: prompt }] + }) + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`Claude API error: ${response.status} ${response.statusText} - ${errorText}`); + } + + const data = await response.json(); + return data.content?.[0]?.text || ''; +} + +/** + * Wrap AI-generated content in MDX template + */ +function wrapInMDX(question, content) { + const { id, question: q, category, keyword } = question; + const relatedDocs = CATEGORY_DOCS[category] || CATEGORY_DOCS.glossary; + const slug = id || slugify(q); + + // Build keywords array + const keywordParts = keyword ? keyword.split(' ').filter((k) => k.length > 2) : []; + const slugParts = slug.split('-').filter((k) => k.length > 2); + const allKeywords = ['sei', 'blockchain', category, ...new Set([...keywordParts, ...slugParts])]; + + const relatedLinks = relatedDocs.map((doc) => `- [${doc.title}](${doc.href})`).join('\n'); + + return `--- +title: '${q.replace(/'/g, "\\'")}' +description: 'Learn about ${keyword || q.replace(/'/g, "\\'")} and how it works in blockchain and on Sei Network.' +keywords: [${allKeywords.map((k) => `'${k}'`).join(', ')}] +--- + +import { Callout } from 'nextra/components'; + +# ${q} + +${content} + +## Related Documentation + +${relatedLinks} + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ +`; +} + +/** + * Import CSV to seed-questions.json + */ +function importCSVToJSON(csvPath, dryRun) { + const content = fs.readFileSync(csvPath, 'utf8'); + const rows = parseCSV(content); + const newQuestions = csvToQuestions(rows); + + // Load existing questions + let existingQuestions = []; + if (fs.existsSync(SEED_QUESTIONS_PATH)) { + const seedData = JSON.parse(fs.readFileSync(SEED_QUESTIONS_PATH, 'utf8')); + existingQuestions = seedData.questions || []; + } + + // Merge (avoid duplicates by id) + const existingIds = new Set(existingQuestions.map((q) => q.id)); + const toAdd = newQuestions.filter((q) => !existingIds.has(q.id)); + + const merged = [...existingQuestions, ...toAdd]; + + console.log(`\n📥 CSV Import`); + console.log(` CSV rows: ${rows.length}`); + console.log(` New questions: ${toAdd.length}`); + console.log(` Duplicates skipped: ${rows.length - toAdd.length}`); + console.log(` Total after merge: ${merged.length}`); + + if (dryRun) { + console.log(`\n💡 Dry run - no changes made.`); + console.log(`\nSample of new questions:`); + toAdd.slice(0, 5).forEach((q) => { + console.log(` - [${q.category}] ${q.question}`); + }); + } else { + fs.writeFileSync(SEED_QUESTIONS_PATH, JSON.stringify({ questions: merged }, null, '\t')); + console.log(`\n✅ Saved to ${SEED_QUESTIONS_PATH}`); + } + + return toAdd; +} + +/** + * Main generation logic + */ +async function main() { + const args = process.argv.slice(2); + const dryRun = args.includes('--dry-run'); + const force = args.includes('--force'); + const specificId = args.find((a) => a.startsWith('--id='))?.split('=')[1]; + const csvPath = args.find((a) => a.startsWith('--csv='))?.split('=')[1]; + const importCsvPath = args.find((a) => a.startsWith('--import-csv='))?.split('=')[1]; + const priorityFilter = args.find((a) => a.startsWith('--priority='))?.split('=')[1]; + const categoryFilter = args.find((a) => a.startsWith('--category='))?.split('=')[1]; + const minMsv = parseInt(args.find((a) => a.startsWith('--min-msv='))?.split('=')[1] || '0', 10); + const limit = parseInt(args.find((a) => a.startsWith('--limit='))?.split('=')[1] || '0', 10); + + const provider = process.env.AI_PROVIDER || 'manual'; + const claudeKey = process.env.ANTHROPIC_API_KEY; + const geminiKey = process.env.GEMINI_API_KEY; + const groqKey = process.env.GROQ_API_KEY; + + // Handle import-only mode + if (importCsvPath) { + importCSVToJSON(importCsvPath, dryRun); + return; + } + + console.log(`\n📝 Answer Generator for Sei Docs`); + console.log(` Provider: ${provider}`); + console.log(` Dry run: ${dryRun}`); + console.log(` Force regenerate: ${force}`); + if (specificId) console.log(` Specific ID: ${specificId}`); + if (csvPath) console.log(` CSV source: ${csvPath}`); + if (priorityFilter) console.log(` Priority filter: ${priorityFilter}`); + if (categoryFilter) console.log(` Category filter: ${categoryFilter}`); + if (minMsv) console.log(` Min MSV: ${minMsv}`); + if (limit) console.log(` Limit: ${limit}`); + console.log(''); + + // Ensure answers directory exists + if (!fs.existsSync(ANSWERS_DIR)) { + if (dryRun) { + console.log(`Would create directory: ${ANSWERS_DIR}`); + } else { + fs.mkdirSync(ANSWERS_DIR, { recursive: true }); + console.log(`✅ Created ${ANSWERS_DIR}`); + } + } + + // Load questions from CSV or JSON + let questions; + if (csvPath) { + const content = fs.readFileSync(csvPath, 'utf8'); + const rows = parseCSV(content); + questions = csvToQuestions(rows); + console.log(`📄 Loaded ${questions.length} questions from CSV\n`); + } else { + const seedData = JSON.parse(fs.readFileSync(SEED_QUESTIONS_PATH, 'utf8')); + questions = seedData.questions; + } + + // Apply filters + const originalCount = questions.length; + + if (specificId) { + questions = questions.filter((q) => q.id === specificId); + if (questions.length === 0) { + console.error(`❌ No question found with id: ${specificId}`); + process.exit(1); + } + } + + if (priorityFilter) { + if (priorityFilter === 'high') { + questions = questions.filter((q) => q.priority === 'high' || (q.msv && q.msv >= 1000)); + } else if (priorityFilter === 'medium') { + questions = questions.filter((q) => q.priority === 'high' || q.priority === 'medium' || (q.msv && q.msv >= 100)); + } + } + + if (categoryFilter) { + questions = questions.filter((q) => q.category === categoryFilter); + } + + if (minMsv > 0) { + questions = questions.filter((q) => q.msv && q.msv >= minMsv); + } + + // Sort by MSV descending (highest value first) + questions.sort((a, b) => (b.msv || 0) - (a.msv || 0)); + + if (limit > 0) { + questions = questions.slice(0, limit); + } + + if (questions.length !== originalCount) { + console.log(`📋 Filtered: ${originalCount} → ${questions.length} questions\n`); + } + + let generated = 0; + let skipped = 0; + let failed = 0; + + for (const question of questions) { + const slug = question.id || slugify(question.question); + const filePath = path.join(ANSWERS_DIR, `${slug}.mdx`); + const exists = fs.existsSync(filePath); + + if (exists && !force) { + console.log(`⏭️ Skipping (exists): ${slug}`); + skipped++; + continue; + } + + console.log(`📄 Generating: ${slug}`); + + try { + let content; + + if (provider === 'claude' && claudeKey) { + const aiContent = await generateWithClaude(question, claudeKey); + content = wrapInMDX(question, aiContent); + } else if (provider === 'gemini' && geminiKey) { + const aiContent = await generateWithGemini(question, geminiKey); + content = wrapInMDX(question, aiContent); + } else if (provider === 'groq' && groqKey) { + const aiContent = await generateWithGroq(question, groqKey); + content = wrapInMDX(question, aiContent); + } else { + content = generateManualMDX(question); + } + + if (dryRun) { + console.log(` Would write to: ${filePath}`); + console.log(` Content length: ${content.length} chars`); + } else { + fs.writeFileSync(filePath, content); + console.log(` ✅ Written: ${filePath}`); + } + + generated++; + + // Rate limiting for API calls + if (provider !== 'manual') { + await new Promise((r) => setTimeout(r, 1000)); + } + } catch (error) { + console.error(` ❌ Failed: ${error.message}`); + failed++; + } + } + + console.log(`\n📊 Summary:`); + console.log(` Generated: ${generated}`); + console.log(` Skipped: ${skipped}`); + console.log(` Failed: ${failed}`); + + if (dryRun) { + console.log(`\n💡 Run without --dry-run to actually generate files.`); + } +} + +main().catch((err) => { + console.error('Fatal error:', err); + process.exit(1); +}); From 9c48780ec0a57f8b94e28827624ecc6c793286cb Mon Sep 17 00:00:00 2001 From: alexander-sei Date: Fri, 9 Jan 2026 22:20:38 +0100 Subject: [PATCH 2/5] Update script and add first example batch --- ...vs-sidechain-key-differences-explained.mdx | 162 ++++++++++ ...what-are-airdrops-and-how-do-they-work.mdx | 180 ++++++++++++ ...at-are-event-logs-and-how-do-they-work.mdx | 169 +++++++++++ ...what-are-gas-fees-and-how-do-they-work.mdx | 146 +++++++++ ...e-staking-rewards-and-how-do-they-work.mdx | 110 +++++++ ...hat-are-zk-snarks-and-how-do-they-work.mdx | 174 +++++++++++ ...-a-block-explorer-and-how-does-it-work.mdx | 177 +++++++++++ ...is-a-block-height-and-how-does-it-work.mdx | 127 ++++++++ ...is-a-block-reward-and-how-does-it-work.mdx | 133 +++++++++ ...t-is-a-block-time-and-how-does-it-work.mdx | 124 ++++++++ ...-a-burn-mechanism-and-how-does-it-work.mdx | 144 +++++++++ ...-is-a-chain-reorg-and-how-does-it-work.mdx | 166 +++++++++++ ...-is-a-cold-wallet-and-how-does-it-work.mdx | 146 +++++++++ ...s-a-composability-and-how-does-it-work.mdx | 187 ++++++++++++ ...nsensus-mechanism-and-how-does-it-work.mdx | 102 +++++++ ...ross-chain-bridge-and-how-does-it-work.mdx | 180 ++++++++++++ ...s-a-crypto-oracle-and-how-does-it-work.mdx | 168 +++++++++++ ...-custodial-wallet-and-how-does-it-work.mdx | 125 ++++++++ .../what-is-a-daos-and-how-does-it-work.mdx | 197 +++++++++++++ ...t-is-a-flash-loan-and-how-does-it-work.mdx | 147 ++++++++++ ...-gas-optimization-and-how-does-it-work.mdx | 198 +++++++++++++ ...what-is-a-gas-war-and-how-does-it-work.mdx | 131 +++++++++ ...s-a-genesis-block-and-how-does-it-work.mdx | 119 ++++++++ ...vernance-proposal-and-how-does-it-work.mdx | 133 +++++++++ ...-governance-token-and-how-does-it-work.mdx | 164 +++++++++++ ...at-is-a-hard-fork-and-how-does-it-work.mdx | 109 +++++++ ...at-is-a-hash-rate-and-how-does-it-work.mdx | 101 +++++++ ...t-is-a-hot-wallet-and-how-does-it-work.mdx | 99 +++++++ ...ayer-1-blockchain-and-how-does-it-work.mdx | 151 ++++++++++ ...-layer-2-solution-and-how-does-it-work.mdx | 141 +++++++++ ...is-a-light-client-and-how-does-it-work.mdx | 169 +++++++++++ ...-a-liquidity-pool-and-how-does-it-work.mdx | 135 +++++++++ .../what-is-a-lsdfi-and-how-does-it-work.mdx | 144 +++++++++ ...what-is-a-mainnet-and-how-does-it-work.mdx | 146 +++++++++ ...-multi-sig-wallet-and-how-does-it-work.mdx | 188 ++++++++++++ ...-custodial-wallet-and-how-does-it-work.mdx | 154 ++++++++++ ...is-a-rebase-token-and-how-does-it-work.mdx | 202 +++++++++++++ .../what-is-a-rollup-and-how-does-it-work.mdx | 160 ++++++++++ ...hat-is-a-rug-pull-and-how-does-it-work.mdx | 157 ++++++++++ ...at-is-a-sidechain-and-how-does-it-work.mdx | 145 +++++++++ ...hat-is-a-slippage-and-how-does-it-work.mdx | 140 +++++++++ ...-a-smart-contract-and-how-does-it-work.mdx | 145 +++++++++ ...rt-contract-audit-and-how-does-it-work.mdx | 223 ++++++++++++++ ...ct-upgradeability-and-how-does-it-work.mdx | 162 ++++++++++ ...at-is-a-soft-fork-and-how-does-it-work.mdx | 132 +++++++++ ...t-is-a-stablecoin-and-how-does-it-work.mdx | 176 +++++++++++ ...what-is-a-testnet-and-how-does-it-work.mdx | 131 +++++++++ ...t-is-a-token-burn-and-how-does-it-work.mdx | 162 ++++++++++ ...t-is-a-tokenomics-and-how-does-it-work.mdx | 197 +++++++++++++ ...-trustless-bridge-and-how-does-it-work.mdx | 161 ++++++++++ ...at-is-a-validator-and-how-does-it-work.mdx | 149 ++++++++++ ...idator-commission-and-how-does-it-work.mdx | 139 +++++++++ ...s-a-validator-set-and-how-does-it-work.mdx | 135 +++++++++ .../what-is-a-wallet-and-how-does-it-work.mdx | 136 +++++++++ .../what-is-a-whale-and-how-does-it-work.mdx | 156 ++++++++++ ...s-a-wrapped-token-and-how-does-it-work.mdx | 141 +++++++++ ...o-knowledge-proof-and-how-does-it-work.mdx | 162 ++++++++++ ...is-an-atomic-swap-and-how-does-it-work.mdx | 176 +++++++++++ .../what-is-an-evm-and-how-does-it-work.mdx | 160 ++++++++++ ...-impermanent-loss-and-how-does-it-work.mdx | 144 +++++++++ ...terchain-security-and-how-does-it-work.mdx | 112 +++++++ ...-interoperability-and-how-does-it-work.mdx | 185 ++++++++++++ .../what-is-an-nft-and-how-does-it-work.mdx | 146 +++++++++ ...hat-is-an-oracles-and-how-does-it-work.mdx | 157 ++++++++++ ...hat-is-blockchain-and-how-does-it-work.mdx | 118 ++++++++ .../what-is-defi-and-how-does-it-work.mdx | 134 +++++++++ ...staking-in-crypto-and-how-does-it-work.mdx | 156 ++++++++++ ...running-in-crypto-and-how-does-it-work.mdx | 171 +++++++++++ ...staking-in-crypto-and-how-does-it-work.mdx | 135 +++++++++ .../what-is-mev-and-why-it-matters.mdx | 139 +++++++++ ...minting-in-crypto-and-how-does-it-work.mdx | 218 ++++++++++++++ ...-and-how-does-it-secure-the-blockchain.mdx | 111 +++++++ ...-and-how-does-it-secure-the-blockchain.mdx | 128 ++++++++ ...-and-how-does-it-secure-the-blockchain.mdx | 132 +++++++++ ...harding-in-crypto-and-how-does-it-work.mdx | 120 ++++++++ ...lashing-in-crypto-and-how-does-it-work.mdx | 121 ++++++++ ...ing-in-blockchain-and-how-does-it-work.mdx | 147 ++++++++++ ...-the-ibc-protocol-and-how-does-it-work.mdx | 154 ++++++++++ .../what-is-tvl-and-why-it-matters.mdx | 158 ++++++++++ ...farming-in-crypto-and-how-does-it-work.mdx | 248 ++++++++++++++++ package.json | 1 + scripts/generate-answers.js | 276 +++++++++--------- yarn.lock | 5 + 83 files changed, 12279 insertions(+), 130 deletions(-) create mode 100644 content/answers/rollup-vs-sidechain-key-differences-explained.mdx create mode 100644 content/answers/what-are-airdrops-and-how-do-they-work.mdx create mode 100644 content/answers/what-are-event-logs-and-how-do-they-work.mdx create mode 100644 content/answers/what-are-gas-fees-and-how-do-they-work.mdx create mode 100644 content/answers/what-are-staking-rewards-and-how-do-they-work.mdx create mode 100644 content/answers/what-are-zk-snarks-and-how-do-they-work.mdx create mode 100644 content/answers/what-is-a-block-explorer-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-block-height-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-block-reward-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-block-time-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-chain-reorg-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-cold-wallet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-composability-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-daos-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-flash-loan-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-gas-optimization-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-gas-war-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-genesis-block-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-governance-proposal-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-governance-token-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-hard-fork-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-hash-rate-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-hot-wallet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-light-client-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-lsdfi-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-mainnet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-rebase-token-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-rollup-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-rug-pull-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-sidechain-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-slippage-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-smart-contract-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-soft-fork-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-stablecoin-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-testnet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-token-burn-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-tokenomics-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-validator-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-validator-commission-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-validator-set-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-wallet-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-whale-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-wrapped-token-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-atomic-swap-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-evm-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-interchain-security-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-interoperability-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-nft-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-an-oracles-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-blockchain-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-defi-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-mev-and-why-it-matters.mdx create mode 100644 content/answers/what-is-minting-in-crypto-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx create mode 100644 content/answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx create mode 100644 content/answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx create mode 100644 content/answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx create mode 100644 content/answers/what-is-tvl-and-why-it-matters.mdx create mode 100644 content/answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/rollup-vs-sidechain-key-differences-explained.mdx b/content/answers/rollup-vs-sidechain-key-differences-explained.mdx new file mode 100644 index 00000000..8b73644a --- /dev/null +++ b/content/answers/rollup-vs-sidechain-key-differences-explained.mdx @@ -0,0 +1,162 @@ +--- +title: 'Rollup Vs Sidechain: Key Differences Explained' +description: 'Learn about what is rollup vs sidechain and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'rollup', 'sidechain', 'key', 'differences', 'explained'] +--- + +import { Callout } from 'nextra/components'; + +# Rollup Vs Sidechain: Key Differences Explained + +## Overview + +A **rollup** is a Layer 2 scaling solution that executes transactions off-chain and posts compressed data (and proof/commitments) back to a Layer 1, inheriting much of the L1’s security. A **sidechain** is a separate blockchain that runs in parallel to a main chain and uses its own consensus/security, typically connected via a bridge. + +In other words, **what is rollup vs sidechain** comes down to **security and settlement**: rollups generally **settle to** and **inherit security from** an L1, while sidechains are **independent chains** that **bridge to** an L1. + +--- + +## How It Works + +### Rollups (general blockchain context) + +Rollups bundle (“roll up”) many transactions into a smaller representation that is posted to an L1. Users get cheaper fees and higher throughput while relying on the L1 for settlement. + +Key properties: + +- **Execution off-chain, settlement on-chain**: Transactions are executed by the rollup, but final settlement is tied to the L1. +- **Data availability & verification**: The rollup posts transaction data (or enough data to reconstruct state) and commitments/proofs to the L1. +- **Security inheritance**: Because the L1 stores rollup data/commitments and enforces rules for state updates, rollups typically inherit strong security from the L1. + +Common types: + +- **Optimistic rollups**: Assume batches are correct by default; allow a _challenge window_ where fraud proofs can be submitted. +- **ZK rollups**: Publish validity proofs (e.g., zk-SNARKs/zk-STARKs) that prove correctness; typically faster finality at the cost of heavier proving infrastructure. + +Implications: + +- **Finality and withdrawals** depend on the rollup design (e.g., optimistic challenge periods can delay withdrawals). +- **Bridging** between rollup and L1 is usually more trust-minimized than typical sidechain bridges (though details vary by implementation). + +--- + +### Sidechains (general blockchain context) + +A sidechain is its own blockchain with its own validator set/consensus. It connects to a main chain through a bridge that transfers assets/messages between chains. + +Key properties: + +- **Independent security model**: Sidechain safety depends on its own validators, staking, and consensus rules—not the main chain’s validator set. +- **Bridged assets**: Assets are often represented as wrapped tokens on the sidechain; bridge security becomes critical. +- **Different parameters**: Sidechains can tune block times, fees, VM, and throughput independent of the main chain. + +Implications: + +- **Higher performance is possible**, but **security is not automatically inherited** from the main chain. +- **Bridge risk** is central: if the bridge or sidechain consensus is compromised, users’ bridged funds may be at risk. + +--- + +## Key Differences (Rollup vs Sidechain) + +| Dimension | Rollup | Sidechain | +| ------------------------ | ------------------------------------------------------------ | --------------------------------------------------------- | +| Relationship to L1 | Settles to L1; posts data/commitments/proofs | Independent chain; connects via bridge | +| Security | Typically inherits much of L1 security | Secured by its own validator set | +| Data availability | Usually anchored to L1 (design-dependent) | Typically maintained by sidechain nodes | +| Finality | Tied to L1 settlement rules (plus any challenge/proof model) | Determined by sidechain consensus | +| Bridge trust assumptions | Often more trust-minimized (varies) | Often higher trust in bridge + sidechain validators | +| Upgrades/governance | Often constrained by L1 anchoring requirements | More freedom; can be more centralized | +| Best for | Scaling while leveraging L1 security | Custom environments, high throughput, app-specific chains | + +--- + +## When to Choose Which + +Choose a **rollup** if you want: + +- Strong alignment with an L1’s security and settlement guarantees +- A more trust-minimized path for posting state updates +- L2 scaling while retaining L1 compatibility (especially for ecosystems like Ethereum) + +Choose a **sidechain** if you want: + +- A fully independent chain with custom parameters and governance +- Very high throughput and flexibility, and you accept separate security assumptions +- Appchain-style deployments where sovereignty matters more than inheriting L1 security + +--- + +## On Sei Network + +Sei is a high-performance Layer 1 designed for fast execution and strong user experience, featuring **parallelization** and **~400ms finality**, plus **EVM compatibility** (via Sei’s EVM). This shifts the “rollup vs sidechain” discussion because many teams can get “L2-like” performance **directly on an L1**. + +### How rollups relate to Sei + +- **Rollups can still exist** in a multi-chain world, but if your primary goal is faster finality and higher throughput, deploying directly on Sei may reduce the need for rollup complexity (sequencers, batch posting, challenge windows, etc.). +- **EVM compatibility** means many Ethereum-oriented applications can deploy to Sei with familiar tooling and smart contract patterns, while benefiting from Sei’s fast finality and parallel execution. + +### How sidechains relate to Sei + +- A sidechain is generally used to gain independence or customization. On Sei, teams often find they can achieve high performance and low latency **without** creating a separate chain and bridge trust assumptions. +- If you do create or connect a sidechain to Sei, you should treat it as a **separate security domain**: the sidechain’s consensus and any bridges determine the risk profile. + +### Practical takeaway for builders on Sei + +If your objective is speed, throughput, and EVM-based application deployment, **Sei’s L1 architecture (parallelization + ~400ms finality)** can provide a simpler path than operating an L2 rollup or maintaining a sidechain’s independent validator and bridge security. + +--- + +## Example: Deploying an EVM Contract on Sei (instead of using an L2/sidechain) + +Below is a minimal Solidity contract and a typical Foundry-style deployment flow to Sei’s EVM endpoint. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public number; + + function setNumber(uint256 newNumber) external { + number = newNumber; + } + + function increment() external { + number += 1; + } +} +``` + +```bash +# Example (Foundry) — set your Sei EVM RPC URL and private key +export RPC_URL="https://" +export PRIVATE_KEY="0x..." + +# Deploy +forge create --rpc-url $RPC_URL --private-key $PRIVATE_KEY src/Counter.sol:Counter +``` + +This illustrates a common alternative to “rollup vs sidechain” decisions: if the main requirement is performance and EVM support, deploying directly to Sei can simplify architecture while still delivering fast finality. + +--- + +## Summary + +The core answer to **what is rollup vs sidechain** is: + +- **Rollups** scale by executing off-chain but **settling to and leveraging L1 security** through posted data/commitments and proof mechanisms. +- **Sidechains** are **independent blockchains** with their own security and consensus, connected via bridges that introduce separate trust assumptions. + +On **Sei Network**, many applications can achieve high-performance execution directly on an L1—leveraging **parallelization**, **~400ms finality**, and **EVM compatibility**—often reducing the need to introduce additional layers like rollups or sidechains unless specific sovereignty or architectural constraints require them. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-are-airdrops-and-how-do-they-work.mdx b/content/answers/what-are-airdrops-and-how-do-they-work.mdx new file mode 100644 index 00000000..30067656 --- /dev/null +++ b/content/answers/what-are-airdrops-and-how-do-they-work.mdx @@ -0,0 +1,180 @@ +--- +title: 'What Are Airdrops and How Do They Work?' +description: 'Learn about what is airdrops and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'airdrops', 'are', 'and', 'how', 'they', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What Are Airdrops and How Do They Work? + +## Overview + +Airdrops are a method of distributing crypto tokens to users’ wallets, typically for free or in exchange for completing simple actions. Projects use airdrops to bootstrap adoption, reward early supporters, decentralize token ownership, or incentivize specific behaviors. If you’re searching for **what is airdrops**, the simplest definition is: token distributions designed to create awareness and participation in a network. + +## How It Works + +Airdrops generally follow a predictable lifecycle: + +### 1) Eligibility rules (“who gets tokens”) + +Projects define criteria that determine which wallets qualify, such as: + +- **Snapshot-based**: Holding a token, NFT, or meeting an on-chain condition at a specific block/time. +- **Activity-based**: Using a product (swaps, staking, bridging, lending), voting, or providing liquidity. +- **Allowlist-based**: Joining a community, registering interest, KYC (rare for decentralized launches), or being a known contributor. +- **Tiered allocation**: Higher usage or longer participation earns more tokens. + +### 2) Snapshot and allocation (“how much each wallet gets”) + +A project takes an on-chain **snapshot** (a record of wallet balances/activities at a point in time) and computes allocations using formulas such as: + +- Flat amounts per eligible wallet +- Proportional to balances (e.g., token holdings or LP shares) +- Points systems (e.g., volume, days active, number of transactions) + +### 3) Distribution mechanism (“how tokens are delivered”) + +Common distribution patterns include: + +- **Automatic distribution**: Tokens are sent directly to eligible wallets (no action required). +- **Claim-based distribution**: Users must call a **claim** function (paying gas) to receive tokens. This reduces unwanted spam and lets users opt in. +- **Vesting/streaming**: Tokens unlock over time to reduce immediate sell pressure and align long-term incentives. + +### 4) Claiming and verification (“prove you’re eligible”) + +For claim-based airdrops, projects typically use: + +- **Merkle trees**: Off-chain eligibility lists compressed into a Merkle root stored on-chain. Users submit a Merkle proof to claim. +- **Signature-based claims**: A trusted signer (or set of signers) authorizes claims via EIP-712 signatures. + +### 5) Anti-abuse protections + +Because airdrops can be targeted by bots and “Sybil” attackers (many wallets controlled by one actor), projects often add: + +- Minimum activity thresholds (e.g., number of days used, unique interactions) +- Exclusion rules (e.g., obvious farming patterns) +- Caps or diminishing returns +- Optional identity checks (trade-offs with decentralization) + +## Common Types of Airdrops + +- **Standard promotional airdrops**: Small distributions to drive awareness. +- **Reward airdrops**: For users who provided liquidity, traded, staked, or tested products. +- **Retroactive airdrops**: Reward past users based on historical behavior (popular for DeFi). +- **Holder airdrops**: Reward wallets holding a particular token or NFT. +- **Ecosystem airdrops**: Incentivize usage across multiple apps within an ecosystem. + +## Benefits and Risks + +### Benefits + +- **User acquisition**: Attracts attention and new users quickly. +- **Decentralization**: Spreads ownership to more participants. +- **Incentives**: Rewards early adoption and meaningful usage. +- **Liquidity & network effects**: Can increase activity and ecosystem growth. + +### Risks + +- **Scams and phishing**: Fake claim sites, malicious approvals, impersonation on social channels. +- **High gas costs (on some chains)**: Claiming can be expensive during congestion. +- **Tax implications**: Many jurisdictions treat airdropped tokens as taxable income upon receipt (consult a tax professional). +- **Market volatility**: Tokens may drop sharply after distribution. + +## How to Safely Participate in Airdrops + +- Verify links through official project sources (website, verified social accounts, docs). +- Never share seed phrases; avoid signing unknown messages. +- Be cautious with token approvals; review and revoke allowances when needed. +- Prefer a separate wallet for experimental activity. +- Check contract addresses against official announcements. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, designed for fast execution and great UX. Airdrops on Sei typically benefit from: + +- **Fast finality (~400ms)**, meaning eligibility actions (swaps, staking, interactions) and claim transactions can confirm quickly. +- **Parallelized execution**, enabling higher throughput and smoother claim periods—especially useful when many users claim at once. +- **EVM tooling compatibility**, allowing projects to run familiar airdrop patterns (Merkle claims, vesting contracts) using Solidity and standard Ethereum libraries. + +In practice, this means a Sei airdrop can feel closer to a Web2 experience: quick confirmations, reduced congestion issues, and easy integration with EVM wallets and developer tooling. + +## Example: Merkle Claim Airdrop Contract (Solidity) + +Below is a simplified EVM-style claim contract commonly used for airdrops. It verifies eligibility using a Merkle proof and prevents double-claims. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; + +contract MerkleAirdrop { + IERC20 public immutable token; + bytes32 public immutable merkleRoot; + + mapping(address => bool) public hasClaimed; + + event Claimed(address indexed account, uint256 amount); + + constructor(IERC20 _token, bytes32 _merkleRoot) { + token = _token; + merkleRoot = _merkleRoot; + } + + function claim(uint256 amount, bytes32[] calldata proof) external { + require(!hasClaimed[msg.sender], "Already claimed"); + + // leaf = keccak256(abi.encodePacked(account, amount)) + bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(msg.sender, amount)))); + require(MerkleProof.verify(proof, merkleRoot, leaf), "Invalid proof"); + + hasClaimed[msg.sender] = true; + require(token.transfer(msg.sender, amount), "Transfer failed"); + + emit Claimed(msg.sender, amount); + } +} +``` + +## Example: Claim Script (TypeScript) + +A typical client flow is: fetch the user’s allocation + Merkle proof from an API, then submit a `claim(amount, proof)` transaction. + +```typescript +import { ethers } from 'ethers'; + +const AIRDROP_ADDRESS = '0xYourAirdropContract'; +const ABI = ['function claim(uint256 amount, bytes32[] proof) external', 'function hasClaimed(address) view returns (bool)']; + +async function claimAirdrop(rpcUrl: string, privateKey: string, amount: string, proof: string[]) { + const provider = new ethers.JsonRpcProvider(rpcUrl); + const wallet = new ethers.Wallet(privateKey, provider); + const airdrop = new ethers.Contract(AIRDROP_ADDRESS, ABI, wallet); + + const claimed = await airdrop.hasClaimed(wallet.address); + if (claimed) throw new Error('Already claimed'); + + const tx = await airdrop.claim(amount, proof); + await tx.wait(); + return tx.hash; +} +``` + +## Key Takeaways + +- If you’re asking **what is airdrops**, it’s a token distribution strategy used to reward users and grow networks. +- Airdrops usually rely on snapshots, eligibility rules, and either automatic transfers or on-chain claim contracts. +- On **Sei Network**, airdrops can be smoother due to **parallelization**, **~400ms finality**, and **EVM compatibility** for standard Solidity-based claim mechanisms. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-are-event-logs-and-how-do-they-work.mdx b/content/answers/what-are-event-logs-and-how-do-they-work.mdx new file mode 100644 index 00000000..69447622 --- /dev/null +++ b/content/answers/what-are-event-logs-and-how-do-they-work.mdx @@ -0,0 +1,169 @@ +--- +title: 'What Are Event Logs and How Do They Work?' +description: 'Learn about what is event logs and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'event', 'logs', 'are', 'and', 'how', 'they', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What Are Event Logs and How Do They Work? + +## Overview + +Event logs (often called _logs_ or _events_) are append-only records emitted by smart contracts during transaction execution to describe something that happened (e.g., a transfer, swap, or state change). If you’re asking **“what is event logs”**, the simplest answer is: event logs are structured transaction metadata designed for efficient indexing, querying, and off-chain consumption—without requiring expensive on-chain storage reads. + +Unlike contract storage, logs are primarily intended for off-chain systems (indexers, analytics, UIs) and are not directly accessible to other contracts during execution. + +## How It Works + +### 1) Events are emitted during a transaction + +In EVM-based chains, a contract uses `emit EventName(...)` to write log entries to the transaction receipt. Each log includes: + +- **Address**: the contract that emitted the log +- **Topics**: up to 4 indexed fields (including the event signature hash as topic0) +- **Data**: ABI-encoded non-indexed fields +- **Block/tx metadata**: block number, tx hash, log index, etc. + +### 2) Indexed vs non-indexed parameters + +Event parameters can be marked as `indexed`: + +- **Indexed** parameters go into **topics**, enabling efficient filtering (e.g., all transfers involving an address). +- **Non-indexed** parameters are stored in the **data** section and are not directly filterable by node-level topic filters. + +Example: ERC-20 `Transfer(address indexed from, address indexed to, uint256 value)` is designed so apps can efficiently query transfers for `from` or `to`. + +### 3) Logs are not contract-readable state + +Logs are part of execution output, but **contracts cannot read past logs on-chain**. This is a key design choice: + +- Logs are cheaper than writing equivalent data into contract storage. +- They are ideal for off-chain consumption (frontends, bridges, data pipelines). +- They are not suitable as the only source of truth for on-chain logic. + +### 4) Clients query logs via RPC + +Applications typically retrieve logs using JSON-RPC methods such as: + +- `eth_getLogs` (filter by block range, address, topics) +- `eth_getTransactionReceipt` (logs for a specific transaction) + +Logs can be reorged if finality isn’t reached; therefore production systems often wait for finality/confirmations before acting. + +## On Sei Network + +Sei Network supports **EVM compatibility**, so event logs follow the same semantics and tooling as Ethereum-style logs (topics, data, receipts, `eth_getLogs`, etc.). This means existing EVM indexers, analytics tools, and dApp frontends can listen to Sei contract events with minimal changes. + +Sei’s architecture also makes event-driven systems more responsive: + +- **~400ms finality** (typical) helps event consumers (UIs, bots, indexers) react quickly with lower “waiting time” and reduced reorg concern compared to slower-finality networks. +- **Parallelization** improves throughput, meaning more transactions (and therefore more logs) can be produced efficiently—important for high-frequency apps that rely heavily on events (DEXs, games, order-book style apps). + +### Practical implications on Sei + +- You can use standard EVM event patterns (e.g., ERC-20 `Transfer`, custom app events) and rely on common tooling. +- Indexers can keep up with higher transaction volumes; event logs remain the preferred method for emitting application activity for off-chain consumption. +- Faster finality enables near-real-time UX based on emitted events. + +## Example: Emitting Event Logs (Solidity) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract OrderBook { + event OrderPlaced( + bytes32 indexed orderId, + address indexed trader, + uint256 price, + uint256 amount + ); + + function placeOrder(bytes32 orderId, uint256 price, uint256 amount) external { + // ... update state, validate inputs, etc. + emit OrderPlaced(orderId, msg.sender, price, amount); + } +} +``` + +**Notes:** + +- `orderId` and `trader` are `indexed`, so consumers can filter quickly by those fields. +- `price` and `amount` are in the data section—still available, but not topic-filterable. + +## Example: Reading Logs with ethers (TypeScript) + +```typescript +import { ethers } from 'ethers'; + +const rpcUrl = 'https://YOUR_SEI_EVM_RPC'; // Sei EVM RPC endpoint +const provider = new ethers.JsonRpcProvider(rpcUrl); + +const contractAddress = '0xYourContractAddress'; +const abi = ['event OrderPlaced(bytes32 indexed orderId, address indexed trader, uint256 price, uint256 amount)']; + +const iface = new ethers.Interface(abi); + +// Build a filter by contract + event topic +const eventTopic = iface.getEvent('OrderPlaced').topicHash; + +const logs = await provider.getLogs({ + address: contractAddress, + topics: [eventTopic], // you can add additional topic filters for indexed params + fromBlock: 'latest' +}); + +for (const log of logs) { + const parsed = iface.parseLog(log); + console.log({ + orderId: parsed.args.orderId, + trader: parsed.args.trader, + price: parsed.args.price.toString(), + amount: parsed.args.amount.toString() + }); +} +``` + +## Example: Querying Logs via JSON-RPC (bash) + +```bash +curl -s https://YOUR_SEI_EVM_RPC \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc":"2.0", + "id":1, + "method":"eth_getLogs", + "params":[{ + "address":"0xYourContractAddress", + "fromBlock":"0x0", + "toBlock":"latest", + "topics":["0xYourEventSignatureTopic0"] + }] + }' +``` + +## Common Use Cases + +- **Indexing and analytics:** build dashboards, leaderboards, and historical views. +- **UI updates:** show “transaction succeeded” and render resulting actions based on logs. +- **Automation:** trading bots, liquidation bots, keepers, and alerting systems triggered by events. +- **Auditing and monitoring:** detect anomalous behavior and track contract activity. + +## Key Takeaways + +- Event logs are **append-only, structured records** emitted during transactions for efficient off-chain querying. +- **Topics (indexed fields)** enable fast filtering; **data** holds the remaining parameters. +- Logs are **not on-chain readable state**, so don’t rely on them for contract-critical logic. +- On **Sei Network**, EVM event logs work the same as Ethereum’s, while Sei’s **parallelization** and **~400ms finality** help event-driven apps feel faster and scale better. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-are-gas-fees-and-how-do-they-work.mdx b/content/answers/what-are-gas-fees-and-how-do-they-work.mdx new file mode 100644 index 00000000..4ee98d61 --- /dev/null +++ b/content/answers/what-are-gas-fees-and-how-do-they-work.mdx @@ -0,0 +1,146 @@ +--- +title: 'What Are Gas Fees and How Do They Work?' +description: 'Learn about what is gas fees and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'gas', 'fees', 'are', 'and', 'how', 'they', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What Are Gas Fees and How Do They Work? + +## Overview + +Gas fees are transaction costs paid to validators to process and finalize activity on a blockchain, such as sending tokens or calling a smart contract. In practice, “gas” measures the computational work needed, and the “gas fee” is the amount you pay (in the network’s native token) to cover that work. + +If you’re searching **what is gas fees**, the simplest answer is: gas fees are the payments that keep a blockchain secure and functional by compensating those who execute transactions and preventing spam. + +## How It Works + +### Gas vs. Gas Fee (Key Terms) + +- **Gas**: A unit that represents how much computation or resource usage a transaction requires (CPU, storage access, contract execution). +- **Gas limit**: The maximum gas units you’re willing to spend for a transaction. +- **Gas price**: The price per unit of gas (typically denominated in the chain’s native token). +- **Gas fee**: The total cost you pay, usually computed as: + **gas fee = gas used × gas price** + +Some networks also include: + +- **Base fee**: A minimum fee level that can adjust based on demand (popularized by EIP-1559-style mechanics on Ethereum-like chains). +- **Priority fee / tip**: An additional amount paid to incentivize validators to include your transaction sooner. + +### Why Gas Fees Exist + +Gas fees serve two main purposes: + +1. **Compensate validators** + Validators spend resources to execute transactions, maintain the network, and provide security. Fees reward them for this work. + +2. **Prevent network spam and congestion** + Without a cost to transact, attackers could flood the network with meaningless transactions. Fees create an economic disincentive and help allocate block space. + +### What Affects Gas Fees? + +- **Network demand**: More users competing for limited block space typically raises the effective price of inclusion. +- **Transaction complexity**: Interacting with smart contracts (DEX swaps, NFT mints, multi-call transactions) generally consumes more gas than a simple token transfer. +- **State/storage usage**: Writing to storage costs more than reading, because it increases long-term state size. +- **Your settings**: Choosing a higher gas price (or higher priority fee) can increase confirmation speed during congestion. + +### What Happens If You Set Gas Too Low? + +- **Gas limit too low**: The transaction may run out of gas and revert. You’ll usually still pay for the computation that happened before it reverted. +- **Gas price too low**: Your transaction may sit pending longer or fail to be included promptly, depending on network conditions and mempool policies. + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, designed for fast and efficient transaction execution. Gas fees on Sei follow the same general principles—users pay fees to execute transactions and smart contracts—but Sei’s architecture is optimized to reduce congestion and improve user experience. + +Key Sei-specific benefits: + +- **Parallelization**: Sei can execute many transactions in parallel when they don’t conflict, improving throughput and helping keep fees more predictable under load. +- **~400ms finality**: Fast finality means transactions settle quickly once included, reducing uncertainty and the need to overpay for speed. +- **EVM compatibility**: If you’re building Solidity contracts or using Ethereum tooling (wallets, libraries, dev frameworks), you’ll interact with gas concepts in familiar ways, while benefiting from Sei’s performance. + +### Estimating Gas on Sei (EVM) + +From a developer perspective, you typically: + +1. Estimate gas usage for the call. +2. Fetch current fee data (gas price and/or EIP-1559 style fields if supported by your provider). +3. Submit the transaction with appropriate limits. + +#### TypeScript (ethers.js) example + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const PRIVATE_KEY = process.env.PRIVATE_KEY!; + +async function main() { + const provider = new ethers.JsonRpcProvider(RPC_URL); + const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + + // Example: send a simple value transfer + const to = '0x000000000000000000000000000000000000dEaD'; + const value = ethers.parseEther('0.01'); + + // Estimate gas + const gasLimit = await provider.estimateGas({ + from: wallet.address, + to, + value + }); + + // Get fee data (gasPrice or EIP-1559 style fields depending on provider/network) + const feeData = await provider.getFeeData(); + + const tx = await wallet.sendTransaction({ + to, + value, + gasLimit, + // Use either gasPrice or EIP-1559 fields based on what's available + gasPrice: feeData.gasPrice ?? undefined, + maxFeePerGas: feeData.maxFeePerGas ?? undefined, + maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? undefined + }); + + console.log('tx hash:', tx.hash); + console.log('waiting for confirmation...'); + const receipt = await tx.wait(); + console.log('confirmed in block:', receipt?.blockNumber); +} + +main().catch(console.error); +``` + +### Checking Gas / Fees via CLI (JSON-RPC) + +```bash +# Get current gas price (legacy style) +curl -s -X POST "$SEI_EVM_RPC" \ + -H "Content-Type: application/json" \ + --data '{"jsonrpc":"2.0","id":1,"method":"eth_gasPrice","params":[]}' | jq +``` + +## Practical Tips + +- **Estimate first**: Use `estimateGas` to avoid setting gas limits too low. +- **Avoid overpaying**: During low activity, moderate gas settings are usually sufficient—especially on high-throughput networks like Sei. +- **Optimize contracts**: Reducing storage writes and unnecessary loops can lower gas usage for users. +- **Monitor congestion**: If an app is time-sensitive, raise the fee parameters modestly rather than drastically. + +## Summary + +Gas fees are the mechanism blockchains use to price computation and allocate limited block space: you pay for the resources your transaction consumes. On Sei Network, the same gas model applies in an EVM-compatible way, while Sei’s **parallel execution** and **~400ms finality** help deliver fast confirmations and a smoother fee experience at scale. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-are-staking-rewards-and-how-do-they-work.mdx b/content/answers/what-are-staking-rewards-and-how-do-they-work.mdx new file mode 100644 index 00000000..65618135 --- /dev/null +++ b/content/answers/what-are-staking-rewards-and-how-do-they-work.mdx @@ -0,0 +1,110 @@ +--- +title: 'What Are Staking Rewards and How Do They Work?' +description: 'Learn about what is staking rewards and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'staking', 'rewards', 'are', 'and', 'how', 'they', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What Are Staking Rewards and How Do They Work? + +## Overview + +Staking rewards are incentives paid to users who lock (stake) their tokens to help secure and operate a proof-of-stake (PoS) blockchain. In practice, **what is staking rewards** refers to the yield (often paid in the network’s native token) earned for participating in consensus—either by running a validator or delegating stake to one. + +These rewards typically come from newly issued tokens (inflation), transaction fees, or a combination of both, and they can vary based on network conditions, validator performance, and staking participation rates. + +## How It Works + +### 1) Staking secures PoS networks + +In PoS, validators are chosen to propose and attest to blocks based on the amount of stake they control (their own tokens plus tokens delegated to them). By staking, participants create “skin in the game,” aligning incentives to behave honestly. + +### 2) Validators and delegators + +- **Validators** run infrastructure (nodes) that participate in consensus. They are responsible for uptime, correct signing, and producing/validating blocks. +- **Delegators** stake by delegating tokens to a validator without running validator hardware themselves. Delegators share in the validator’s rewards, minus a validator commission. + +### 3) Where staking rewards come from + +Common sources include: + +- **Block rewards / inflation:** New tokens minted and distributed to stakers. +- **Transaction fees:** A portion of gas/fees paid by users is distributed to validators/delegators. + +The exact formula differs per chain, but most systems distribute rewards proportional to stake and validator participation. + +### 4) Distribution and compounding + +Rewards may be: + +- Credited automatically to staking balances, +- Claimable via a transaction (then optionally restaked), +- Or periodically distributed depending on chain design. + +Many stakers **compound** by claiming rewards and staking them again to increase future rewards. + +### 5) Key variables that affect rewards + +- **Network staking ratio:** If a larger share of total supply is staked, per-token rewards may decrease (depending on issuance design). +- **Validator commission:** A percentage taken by the validator before delegators receive rewards. +- **Validator performance:** Downtime or missed signatures can reduce rewards. +- **Slashing risk:** Misbehavior (double-signing, prolonged downtime, or protocol-defined faults) can cause a portion of stake to be penalized. + +### 6) Unstaking and lockups + +Many PoS networks impose an **unbonding period** (a delay between requesting unstake and receiving funds) to protect security and discourage short-term attacks. + +## On Sei Network + +Sei is a high-performance Layer 1 with **fast finality (~400ms)** and an **EVM-compatible** execution environment, designed for parallelized throughput. Staking on Sei follows the typical PoS model: validators secure the chain and delegators can stake to validators to earn rewards. + +### How staking rewards apply on Sei + +- **Delegation model:** Users can delegate SEI to validators and receive staking rewards proportional to their delegated stake (net of validator commission). +- **Validator set performance:** Because Sei targets high throughput and quick finality, validator uptime and correct participation are especially important—poor performance can reduce effective rewards and may incur penalties per protocol rules. +- **Fast settlement context:** Sei’s low-latency finality helps applications (including EVM apps) settle quickly, while staking provides the security guarantees behind that rapid confirmation experience. +- **EVM compatibility:** Staking is a core protocol function (consensus/security), while EVM compatibility enables smart contracts and tooling. Users often interact with staking via wallets, explorers, or native staking modules rather than directly through Solidity contracts. + +### Typical workflow (delegator) + +1. Choose a validator (consider commission, uptime, reputation). +2. Delegate tokens (stake). +3. Rewards accrue as the validator participates in consensus. +4. Claim rewards (and optionally redelegate/compound). +5. Unstake (subject to any network unbonding rules). + +## Example Commands (Conceptual) + +Exact commands depend on your wallet/provider and Sei’s CLI tooling, but the flow typically looks like this with Cosmos-SDK-style transactions: + +```bash +# Delegate (stake) tokens to a validator +seid tx staking delegate 1000000usei \ + --from --chain-id --gas auto --fees + +# Withdraw staking rewards +seid tx distribution withdraw-rewards \ + --from --chain-id --gas auto --fees + +# Unbond (unstake) tokens +seid tx staking unbond 1000000usei \ + --from --chain-id --gas auto --fees +``` + +## Key Takeaways + +- **What is staking rewards?** It’s the token-denominated yield earned for helping secure a PoS network by staking directly as a validator or delegating to one. +- Rewards are typically funded by **inflation and/or transaction fees**, and distributed based on stake and validator participation. +- On **Sei Network**, staking rewards support a validator-secured chain designed for **parallelized performance** and **~400ms finality**, with **EVM compatibility** enabling a broad smart contract ecosystem on top of that secure base. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-are-zk-snarks-and-how-do-they-work.mdx b/content/answers/what-are-zk-snarks-and-how-do-they-work.mdx new file mode 100644 index 00000000..a889c1af --- /dev/null +++ b/content/answers/what-are-zk-snarks-and-how-do-they-work.mdx @@ -0,0 +1,174 @@ +--- +title: 'What Are zk-SNARKs and How Do They Work?' +description: 'Learn about what is zk-SNARKs and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'zk-SNARKs', 'are', 'snarks', 'and', 'how', 'they', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What Are zk-SNARKs and How Do They Work? + +## Overview + +zk-SNARKs (Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge) are cryptographic proofs that let someone prove a statement is true without revealing the underlying data (zero-knowledge), with proofs that are small (succinct) and can be verified quickly, typically without back-and-forth communication (non-interactive). If you’re searching **“what is zk-SNARKs”**, the simplest definition is: a way to prove correctness privately and efficiently. + +They’re widely used in blockchains for privacy-preserving transactions and for scalability via verifiable computation (proving that off-chain work was done correctly). + +## How It Works + +### Zero-knowledge proof basics + +A zero-knowledge proof involves: + +- **Prover**: generates a proof that a statement is true (e.g., “I know valid inputs that satisfy this program/constraint system”). +- **Verifier**: checks the proof’s validity without learning the secret inputs. + +In a blockchain setting, the statement is often: “This transaction/state transition follows the rules,” while keeping sensitive data hidden. + +### The “SNARK” properties + +zk-SNARKs add specific properties that make them practical for blockchains: + +- **Succinct**: proofs are small (often a few hundred bytes) and verification is fast. +- **Non-interactive**: the prover sends a single proof; the verifier checks it once. +- **Argument of knowledge**: a valid proof implies the prover “knows” a valid witness (the secret inputs) under standard cryptographic assumptions. + +### High-level pipeline + +1. **Define a computation** + Express the rule you want to prove as a circuit/constraint system (e.g., arithmetic constraints). + Examples: “balances don’t go negative,” “signature is valid,” “hash preimage exists.” + +2. **Generate keys (setup phase in many SNARKs)** + Many zk-SNARK systems require a **trusted setup** to produce: + + - **Proving key (PK)**: used to generate proofs. + - **Verification key (VK)**: used to verify proofs. + (Some modern proof systems reduce or remove trusted setup requirements, but “zk-SNARK” commonly refers to setup-based SNARKs.) + +3. **Prove** + The prover takes: + + - **Public inputs**: values the verifier can see (e.g., commitment, Merkle root, output hash). + - **Private inputs (“witness”)**: secret values (e.g., sender’s key, amounts, preimage). + Then generates a proof `π` that the constraints are satisfied. + +4. **Verify** + The verifier checks `π` using the VK and the public inputs. If verification succeeds, the blockchain can accept the transaction or state update without seeing the private data. + +### What zk-SNARKs are used for in blockchains + +- **Privacy**: hide amounts, addresses, or other transaction details while still enforcing validity. +- **Scalability / verifiable compute**: prove that complex computation happened off-chain and post only a proof on-chain (common in rollups and other L2 designs). + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, **parallelization**, and ~**400ms finality**. zk-SNARK-based applications on Sei benefit from: + +- **Fast settlement**: once a zk-proof is verified in a block, Sei’s low-latency finality helps zk-based apps reach finality quickly. +- **EVM compatibility**: zk verification can be implemented in Solidity using pairings/elliptic-curve precompiles where available (depending on the curve and scheme), enabling Ethereum-style zk-verifier contracts to be deployed on Sei. +- **Parallel execution**: Sei’s parallelization can improve throughput for workloads around proof submission, state updates, and associated transactions—especially when many users submit proofs concurrently—while verification itself remains a deterministic on-chain computation. + +Typical Sei zk-SNARK integration patterns include: + +- **On-chain verifier contract**: users post a proof; the contract verifies it and updates state (e.g., mint, withdraw, or register). +- **ZK-enabled apps**: privacy-preserving credentials, attestations, or compliance checks (prove “I’m eligible” without revealing identity). +- **ZK rollup-style bridges/appchains**: post proofs of off-chain state transitions for secure settlement on Sei (architecture-dependent). + +## Example: Verifying a zk-SNARK Proof in Solidity (Conceptual) + +Most zk-SNARK deployments on EVM chains use an autogenerated verifier contract (e.g., for Groth16) produced by tooling like circom/snarkjs or other ecosystems. The verifier typically exposes a function like `verifyProof`. + +```solidity +// Conceptual interface; actual verifier code is usually autogenerated. +interface IVerifier { + function verifyProof( + uint256[2] calldata a, + uint256[2][2] calldata b, + uint256[2] calldata c, + uint256[] calldata publicInputs + ) external view returns (bool); +} + +contract ZkGate { + IVerifier public verifier; + + constructor(address _verifier) { + verifier = IVerifier(_verifier); + } + + function submitProof( + uint256[2] calldata a, + uint256[2][2] calldata b, + uint256[2] calldata c, + uint256[] calldata publicInputs + ) external { + require(verifier.verifyProof(a, b, c, publicInputs), "Invalid proof"); + + // If proof is valid, perform state change (mint, unlock, register, etc.) + // ... + } +} +``` + +> Note: The exact proof format depends on the proving system (e.g., Groth16, PLONK variants), curve choice, and the verifier implementation used on Sei’s EVM. + +## Developer Workflow (Typical) + +A common zk-SNARK workflow looks like: + +1. Write a circuit (constraints). +2. Generate proving/verifying keys (setup). +3. Generate proofs off-chain. +4. Deploy verifier on-chain. +5. Submit proofs to update on-chain state. + +Tooling varies, but a “proof generation then on-chain verification” flow often resembles: + +```bash +# 1) Compile circuit (example tooling) +circom circuit.circom --r1cs --wasm --sym + +# 2) Setup (scheme-dependent; often generates proving/verification keys) +snarkjs groth16 setup circuit.r1cs pot.ptau circuit_0000.zkey +snarkjs zkey export verificationkey circuit_0000.zkey verification_key.json + +# 3) Create witness + proof +node circuit_js/generate_witness.js circuit_js/circuit.wasm input.json witness.wtns +snarkjs groth16 prove circuit_0000.zkey witness.wtns proof.json public.json + +# 4) Export Solidity verifier (if supported by tooling) +snarkjs zkey export solidityverifier circuit_0000.zkey Verifier.sol +``` + +## Key Benefits and Tradeoffs + +### Benefits + +- **Strong privacy guarantees**: prove correctness without revealing secrets. +- **Efficient verification**: small proofs and quick checks enable on-chain practicality. +- **Composable logic**: can enforce complex constraints with minimal on-chain data. + +### Tradeoffs + +- **Circuit complexity**: translating programs into constraints can be difficult and performance-sensitive. +- **Setup requirements**: many zk-SNARKs require trusted setup; mismanagement can undermine security (depending on the scheme). +- **Prover cost**: generating proofs can be computationally heavy, often done off-chain with specialized optimization. + +## Related Terms + +- **Zero-knowledge proofs (ZKPs)**: the broader category. +- **zk-STARKs**: often transparent setup and different performance tradeoffs (usually larger proofs). +- **Commitments / Merkle trees**: commonly used as public inputs to prove membership or correctness without revealing data. +- **Rollups / Validity proofs**: L2 patterns that use ZK proofs to scale throughput while retaining L1 security. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-block-explorer-and-how-does-it-work.mdx b/content/answers/what-is-a-block-explorer-and-how-does-it-work.mdx new file mode 100644 index 00000000..4696193a --- /dev/null +++ b/content/answers/what-is-a-block-explorer-and-how-does-it-work.mdx @@ -0,0 +1,177 @@ +--- +title: 'What is a Block Explorer and How Does It Work?' +description: 'Learn about what is block explorer and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'block', 'explorer', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Block Explorer and How Does It Work? + +## Overview + +A **block explorer** is a web-based tool that lets anyone search, view, and verify blockchain data such as blocks, transactions, wallet addresses, and smart contract activity. In simple terms, it’s a “search engine” for a blockchain that provides transparency by turning raw on-chain data into readable pages. + +If you’re asking **what is block explorer**, the key idea is this: it helps users independently confirm what happened on-chain—without trusting a third party. + +## How It Works + +Block explorers typically work by connecting to one or more blockchain nodes and indexing the data those nodes produce. The explorer then serves that indexed data through a user interface (and often an API) so people can quickly search and filter information. + +### 1) Data Source: Blockchain Nodes + +A block explorer reads data from the blockchain via: + +- **RPC (Remote Procedure Call)** endpoints (e.g., JSON-RPC for EVM chains) +- Node APIs (e.g., Tendermint/CometBFT RPC on Cosmos-based chains) +- Event subscriptions (for real-time updates) + +Nodes provide canonical chain data such as: + +- Block headers and block contents +- Transactions and receipts/logs +- State changes (balances, contract storage updates) +- Validator and consensus information (chain-dependent) + +### 2) Indexing and Storage + +Because searching directly through full node data can be slow, explorers usually: + +- Continuously ingest new blocks +- Parse transactions, internal calls, logs/events, and metadata +- Store the parsed results in a database optimized for queries (e.g., Postgres, Elasticsearch) + +This indexing layer enables common explorer features like: + +- Full-text search by **tx hash**, **block height**, or **address** +- Filtering token transfers by **contract** and **event signature** +- Tracking historical balances and activity + +### 3) Decoding Transactions and Smart Contract Events + +On smart contract chains, explorers decode: + +- **Transaction input data** to identify which contract function was called +- **Event logs** (e.g., ERC-20 `Transfer`) to show token movements +- **Contract ABIs** (when verified) to present human-readable function names and parameters + +When a contract is “verified,” the explorer can match on-chain bytecode to source code and ABI, making contract interactions easier to understand. + +### 4) Confirmations and Finality + +Explorers show whether a transaction is: + +- **Pending** (broadcast but not yet included in a block) +- **Included** (in a block) +- **Finalized** (high confidence it won’t be reverted, depending on the chain’s finality model) + +Some chains use probabilistic finality (confidence increases with more blocks), while others provide fast deterministic finality through consensus. + +### 5) Common Explorer Pages and Fields + +A typical explorer surfaces: + +- **Transaction page:** hash, status, block/height, gas/fees, sender/receiver, logs, token transfers +- **Block page:** height, timestamp, proposer, tx count, gas used, block hash +- **Address page:** balance, tx history, token holdings, contract interactions +- **Contract page:** bytecode, ABI, verified source, read/write methods + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, designed for throughput and speed, including **~400ms finality**. A block explorer on Sei serves the same core purpose—transparent verification of on-chain activity—but it becomes especially useful for observing Sei’s fast block production and parallel execution behavior at scale. + +### What You’ll See on a Sei Block Explorer + +On Sei, an explorer typically exposes: + +- **Rapid block confirmations** reflecting Sei’s ~400ms finality +- **EVM transaction details** (hash, from/to, gas, calldata, logs) similar to Ethereum explorers +- **Smart contract events** for ERC-20/721-style contracts deployed via Sei’s EVM +- Network and consensus-related metadata (chain-dependent), including block timing and throughput indicators + +### Parallelization and Explorer Indexing + +Sei’s performance characteristics (including parallelization) mean explorers and indexers often need to: + +- Keep up with higher transaction throughput +- Efficiently process large volumes of EVM logs/events +- Provide near real-time updates for dApps and traders + +From a user perspective, this translates into faster visibility of transaction inclusion and finality, and more responsive search and filtering when tracking activity. + +## Practical Usage Examples + +### Find a Transaction (by Hash) + +Use an RPC call to retrieve transaction details (EVM-compatible JSON-RPC): + +```bash +curl -s -X POST https://YOUR_SEI_EVM_RPC_ENDPOINT \ + -H "Content-Type: application/json" \ + --data '{ + "jsonrpc":"2.0", + "id":1, + "method":"eth_getTransactionByHash", + "params":["0xYOUR_TX_HASH"] + }' +``` + +To fetch the receipt (status, logs, gas used): + +```bash +curl -s -X POST https://YOUR_SEI_EVM_RPC_ENDPOINT \ + -H "Content-Type: application/json" \ + --data '{ + "jsonrpc":"2.0", + "id":1, + "method":"eth_getTransactionReceipt", + "params":["0xYOUR_TX_HASH"] + }' +``` + +### Look Up an Address Balance + +```bash +curl -s -X POST https://YOUR_SEI_EVM_RPC_ENDPOINT \ + -H "Content-Type: application/json" \ + --data '{ + "jsonrpc":"2.0", + "id":1, + "method":"eth_getBalance", + "params":["0xYOUR_ADDRESS","latest"] + }' +``` + +### Decode Token Transfers (ERC-20 `Transfer` Event) + +Explorers detect common events like `Transfer(address,address,uint256)` via log topics. The event signature hash is: + +```solidity +// keccak256("Transfer(address,address,uint256)") +bytes32 constant TRANSFER_TOPIC = + 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; +``` + +Indexers/explorers query logs and decode them to show token transfers on transaction and address pages. + +## Why Block Explorers Matter + +A block explorer is essential for: + +- **Verifying payments and transfers** (who sent what, and when) +- **Debugging smart contract interactions** (function calls, logs, reverts) +- **Auditing and transparency** (independent on-chain verification) +- **Operational monitoring** (tracking confirmations/finality, fees, throughput) + +On Sei, these benefits are amplified by fast finality and EVM compatibility—users can confirm outcomes quickly, while developers can inspect contract behavior using familiar Ethereum-style transaction and event data. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-block-height-and-how-does-it-work.mdx b/content/answers/what-is-a-block-height-and-how-does-it-work.mdx new file mode 100644 index 00000000..2ea86281 --- /dev/null +++ b/content/answers/what-is-a-block-height-and-how-does-it-work.mdx @@ -0,0 +1,127 @@ +--- +title: 'What is a Block Height and How Does It Work?' +description: 'Learn about what is block height and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'block', 'height', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Block Height and How Does It Work? + +## Overview + +Block height is the sequential number assigned to a block in a blockchain, indicating its position in the chain starting from the genesis block. In simple terms, **what is block height** refers to “how many blocks have been added” up to a specific point, which helps users and applications reference a precise moment in the chain’s history. + +## How It Works + +### Block height as an ordering mechanism + +- **Genesis block**: The first block in the chain (commonly height `0`, though some explorers label it `1` depending on convention). +- **Incremental growth**: Each new block adds `+1` to the height (e.g., after height `100`, the next block is `101`). +- **Uniqueness by chain**: A block height refers to a position in _a specific blockchain_. Height `500,000` on one network is not comparable to the same height on another. + +### Block height vs. block hash + +- **Block height** is a simple index (e.g., `123456`). +- **Block hash** is a unique cryptographic identifier for a specific block. +- Because forks can create multiple competing blocks at the same height (temporarily), applications that need strict certainty often use: + - the **block hash**, and/or + - a **confirmation depth** (e.g., “6 blocks after height X”). + +### Why block height matters + +Block height is used throughout blockchain systems for: + +- **Finality/confirmations**: “Wait until height is N blocks ahead” to reduce reorg risk. +- **State queries at a point in time**: Query balances, contract state, or logs “as of block height X.” +- **Protocol rules**: Network upgrades, parameter changes, and governance execution can be scheduled at specific heights. +- **Indexing and analytics**: Explorers, indexers, and data pipelines batch data by block ranges. + +### Handling forks and reorgs + +In most blockchains, there may be short-lived forks where: + +- Two blocks exist at the same height on different branches. +- The network later converges on a canonical chain. +- A **reorg** replaces one branch’s blocks with another’s, meaning “the block at height X” can change briefly. + +## On Sei Network + +On Sei, block height plays the same core role—ordering blocks and enabling deterministic references to chain history—but is especially useful given Sei’s performance characteristics and EVM compatibility. + +### Fast finality and high-throughput execution + +- Sei is designed for high performance with **~400ms finality**, so block height advances quickly and is frequently used by apps for near-real-time UX. +- Sei’s parallelization and optimized execution mean many transactions can be processed efficiently per block; block height becomes a convenient “clock” for indexing and synchronization. + +### EVM compatibility: using block height in smart contracts + +In EVM contexts, block height corresponds to the EVM notion of the current block number (`block.number`). Solidity contracts can use block height for time/sequence-based logic (with the usual caveat: block height is not wall-clock time). + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract HeightGated { + uint256 public immutable startHeight; + + constructor(uint256 _startHeight) { + startHeight = _startHeight; + } + + function isActive() public view returns (bool) { + // On Sei EVM, block.number reflects the current block height. + return block.number >= startHeight; + } +} +``` + +### Querying block height from Sei nodes (RPC) + +You can retrieve the latest block height via Tendermint/CometBFT RPC: + +```bash +curl -s http://localhost:26657/status | jq -r .result.sync_info.latest_block_height +``` + +If you’re interacting via EVM-compatible JSON-RPC, you can read the current block number: + +```bash +curl -s -X POST http://localhost:8545 \ + -H "Content-Type: application/json" \ + --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' +``` + +### Reading block height in application code + +Example in TypeScript using an EVM provider: + +```typescript +import { JsonRpcProvider } from 'ethers'; + +const provider = new JsonRpcProvider('http://localhost:8545'); + +async function main() { + const blockNumber = await provider.getBlockNumber(); + console.log('Current block height:', blockNumber); +} + +main().catch(console.error); +``` + +## Key Takeaways + +- **Block height** is the sequential position of a block in a blockchain, used to reference and organize chain history. +- It supports confirmations, historical state queries, indexing, and protocol scheduling. +- On **Sei Network**, block height advances quickly due to **~400ms finality** and benefits high-throughput apps; it’s also directly accessible in **Sei’s EVM** as `block.number` and through standard RPC endpoints. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-block-reward-and-how-does-it-work.mdx b/content/answers/what-is-a-block-reward-and-how-does-it-work.mdx new file mode 100644 index 00000000..e9f2356e --- /dev/null +++ b/content/answers/what-is-a-block-reward-and-how-does-it-work.mdx @@ -0,0 +1,133 @@ +--- +title: 'What is a Block Reward and How Does It Work?' +description: 'Learn about what is block reward and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'block', 'reward', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Block Reward and How Does It Work? + +## Overview + +A **block reward** is the incentive paid to a blockchain participant (typically a validator or miner) for producing and finalizing a new block. It usually consists of **newly minted tokens (issuance)** and may also include **transaction fees** collected from transactions in that block. In short, if you’re asking **what is block reward**, it’s the protocol’s built-in mechanism to fund security and encourage honest participation. + +## How It Works + +### 1) Why block rewards exist + +Blockchains need a way to: + +- **Secure the network** by compensating those who expend resources to propose/validate blocks. +- **Distribute new tokens** (when the chain has inflation/issuance). +- **Incentivize liveness and correctness**, discouraging censorship or invalid blocks. + +### 2) What the reward is made of + +A block reward commonly includes: + +- **Block subsidy (issuance):** Newly created tokens paid out per block (or per time period). +- **Transaction fees:** User-paid fees attached to transactions. Depending on the chain, fees may be: + - Paid to the block producer/validator + - Shared among validators/delegators + - Partially burned or redirected to a treasury + +### 3) Who receives it (PoW vs PoS) + +- **Proof of Work (PoW):** Miners compete to solve a computational puzzle; the winner proposes the next block and receives the reward. +- **Proof of Stake (PoS):** Validators are selected according to stake (and other protocol rules) to propose/attest blocks; rewards are distributed based on participation and stake, often shared with delegators. + +### 4) When rewards are paid + +In many networks, rewards are calculated and distributed: + +- **Per block** (e.g., block-by-block accounting), or +- **Per epoch** (batched distribution over a time window) + +### 5) Trade-offs and design choices + +Block reward design impacts: + +- **Inflation rate:** Higher issuance can increase security incentives but dilutes supply. +- **Network security:** Stronger incentives generally increase participation and reduce attack viability. +- **Fee markets:** Whether fees go to validators, are burned, or both affects user costs and token economics. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **fast finality (~400ms)** and **EVM compatibility**, built to support high-throughput applications. Like other PoS networks, Sei uses validator incentives (including rewards derived from protocol economics) to keep the chain secure while maintaining rapid block production and quick finality. + +### 1) Rewards in a fast-finality PoS environment + +Because Sei reaches finality quickly, validator operations are optimized for: + +- **Frequent block production and confirmation** in a tight latency budget +- **Consistent uptime and correct behavior**, since high-performance chains amplify the importance of reliability + +In general, validators earn rewards for participating in consensus and helping finalize blocks. Delegators who stake to validators can receive a share of those rewards, net of validator commission, depending on staking and distribution rules. + +### 2) Interaction with Sei’s parallelization + +Sei’s architecture emphasizes **parallelization** to improve throughput. While parallel execution increases transaction capacity, **block rewards still primarily incentivize consensus participation**—i.e., proposing/validating blocks and maintaining security—rather than rewarding each transaction execution individually. + +### 3) EVM compatibility and fee-driven incentives + +With Sei’s **EVM compatibility**, smart contracts and users interact in familiar Ethereum-style patterns (e.g., gas). In many EVM-based systems, **transaction fees** are a major part of validator revenue. On Sei, transaction fees (and any protocol-defined issuance) contribute to incentives that keep validators aligned with network performance and security. + +> Note: Exact reward formulas (issuance schedules, fee routing, commission behavior, and distribution timing) are protocol- and governance-defined and can evolve over time. + +## Example: Observing block producer and fees (general EVM workflow) + +If you’re building on Sei’s EVM and want to inspect blocks and fee-related fields, you can use standard EVM JSON-RPC calls (via any Sei EVM RPC endpoint). + +### TypeScript (ethers): read block metadata + +```typescript +import { ethers } from 'ethers'; + +const rpcUrl = process.env.SEI_EVM_RPC!; +const provider = new ethers.JsonRpcProvider(rpcUrl); + +async function main() { + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); + + console.log('Block number:', blockNumber); + console.log('Block producer (miner/beneficiary field):', block?.miner); + console.log('Base fee (if supported):', block?.baseFeePerGas?.toString()); + console.log('Tx count:', block?.transactions?.length); +} + +main().catch(console.error); +``` + +### Bash: query a block by number (hex) via JSON-RPC + +```bash +curl -s -X POST "$SEI_EVM_RPC" \ + -H "Content-Type: application/json" \ + --data '{ + "jsonrpc":"2.0", + "id":1, + "method":"eth_getBlockByNumber", + "params":["latest", false] + }' | jq +``` + +These calls help you understand _who produced a block_ and what fee-related parameters were in effect, which is often part of analyzing validator economics and (indirectly) block reward outcomes. + +## Key Takeaways + +- **What is block reward?** It’s the protocol incentive for producing/finalizing blocks—typically **issuance + fees**. +- Block rewards secure the chain by paying validators/miners for honest work and participation. +- On **Sei Network**, rewards support a PoS security model optimized for **parallelization**, **high throughput**, and **~400ms finality**, with incentives compatible with an **EVM-style** fee environment. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-block-time-and-how-does-it-work.mdx b/content/answers/what-is-a-block-time-and-how-does-it-work.mdx new file mode 100644 index 00000000..5afd1368 --- /dev/null +++ b/content/answers/what-is-a-block-time-and-how-does-it-work.mdx @@ -0,0 +1,124 @@ +--- +title: 'What is a Block Time and How Does It Work?' +description: 'Learn about what is block time and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'block', 'time', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Block Time and How Does It Work? + +## Overview + +Block time is the average time it takes a blockchain network to produce a new block of transactions and add it to the chain. In simple terms, it’s the cadence of the network: how frequently transactions are bundled, proposed, and confirmed on-chain. When people ask **“what is block time”**, they’re usually trying to understand how quickly a network can include transactions and how responsive it feels for users. + +## How It Works + +### What “block time” measures + +- **Time between blocks:** Typically measured as an average over many blocks (because block production can vary). +- **Transaction inclusion speed:** Shorter block times often mean transactions can be _included_ sooner, though “final confirmation” depends on the consensus model. +- **Network throughput and UX:** Faster block times can improve user experience (faster updates), but may increase network overhead if blocks are too frequent. + +### What determines block time + +Block time is an emergent result of protocol design and network conditions, including: + +- **Consensus mechanism:** Proof-of-Work (PoW), Proof-of-Stake (PoS), and BFT-style consensus each have different timing and finality characteristics. +- **Block proposal/validation steps:** The time for proposing a block, propagating it through the network, and validating it. +- **Network latency and bandwidth:** Higher latency can force longer target block times to reduce fork/reorg risk. +- **Validator/miner behavior:** Availability, performance, and configuration can influence stability around the target. + +### Block time vs. finality (important distinction) + +Block time is **not always the same as finality**. + +- **Block time**: how often new blocks are produced. +- **Finality**: when a transaction is considered irreversible (or extremely unlikely to be reverted). + +Some networks have _probabilistic finality_ (often requiring multiple confirmations), while others have _fast deterministic finality_ where a block becomes final quickly after it’s produced. + +### Why block time matters + +- **User experience:** Shorter block times usually mean faster feedback (e.g., balances updating sooner). +- **Trading and DeFi:** Lower latency can improve execution and reduce stale pricing windows. +- **Security and reorg risk:** Very short block times can increase the chance of competing blocks if propagation can’t keep up. +- **Infrastructure load:** More blocks per hour increases indexing, storage, and networking work. + +## On Sei Network + +Sei is designed for high performance and low-latency transaction confirmation. While “block time” is often used as a general term, Sei’s user-facing experience is better captured by its **fast finality (~400ms)** and its ability to process many transactions concurrently. + +### Sei’s fast finality and responsiveness + +- **~400ms finality:** Transactions can reach finality in around 400 milliseconds, enabling near real-time experiences for trading, gaming, and consumer apps. +- **Practical impact:** Users see confirmations quickly, and developers can build apps that rely on rapid, deterministic outcomes. + +### Parallelization: scaling without waiting for a single sequential pipeline + +Sei’s architecture emphasizes **parallelization**, allowing the network to execute many independent transactions concurrently (when they don’t conflict on state). This improves throughput and helps maintain low latency under load—meaning the network can stay responsive even when activity spikes. + +### EVM compatibility: familiar tooling with fast confirmation + +Sei supports **EVM compatibility**, so smart contract developers can use common Ethereum tools (Solidity, Hardhat/Foundry-style flows, Ethers.js/Web3.js patterns) while benefiting from Sei’s performance characteristics. + +### Developer example: measuring “block time” via block timestamps (EVM) + +On EVM chains, a common way to _approximate_ block time is to sample timestamps from consecutive blocks. This measures “time between blocks” from the perspective of the node you query. + +```typescript +import { JsonRpcProvider } from 'ethers'; + +async function estimateBlockTime(rpcUrl: string, sample: number = 200) { + const provider = new JsonRpcProvider(rpcUrl); + + const latest = await provider.getBlock('latest'); + const past = await provider.getBlock(latest.number - sample); + + const seconds = latest.timestamp - past.timestamp; + return seconds / sample; +} + +(async () => { + const rpcUrl = process.env.RPC_URL!; + const avg = await estimateBlockTime(rpcUrl, 200); + console.log(`Estimated average block time: ~${avg.toFixed(2)}s`); +})(); +``` + +**Notes:** + +- Block timestamps can vary based on protocol rules and validator behavior, so this is an estimate. +- For user experience on Sei, **finality (~400ms)** is often the more meaningful metric than average time-between-blocks. + +### Contract example: reading the current block timestamp + +Smart contracts can’t directly read “block time,” but they can use block metadata such as `block.timestamp` and `block.number`. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract BlockMetadata { + function getBlockInfo() external view returns (uint256 number, uint256 timestamp) { + return (block.number, block.timestamp); + } +} +``` + +## Key Takeaways + +- **What is block time?** It’s the average interval between newly produced blocks on a blockchain. +- Block time influences **transaction inclusion speed**, but **finality** determines when a transaction is truly irreversible. +- On **Sei Network**, developers and users benefit from **~400ms finality**, **parallelized execution**, and **EVM compatibility**, enabling fast, scalable on-chain applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx b/content/answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx new file mode 100644 index 00000000..cfe4365f --- /dev/null +++ b/content/answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx @@ -0,0 +1,144 @@ +--- +title: 'What is a Burn Mechanism and How Does It Work?' +description: 'Learn about what is burn mechanism and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'burn', 'mechanism', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Burn Mechanism and How Does It Work? + +## Overview + +A **burn mechanism** is a protocol rule that permanently removes tokens from circulation by sending them to an irrecoverable address or destroying them at the contract level. The goal is typically to reduce circulating supply, adjust token economics, or align incentives (e.g., by making supply more scarce over time). + +In SEO terms, **what is burn mechanism**: it’s a systematic way for a blockchain or token project to “retire” tokens so they can no longer be spent, effectively decreasing supply. + +## How It Works + +Burning is implemented in a few common ways across blockchains and token standards: + +### 1) Send to a “burn” or irrecoverable address + +Tokens are transferred to an address with no known private key (e.g., `0x000...dEaD` on EVM chains). The tokens still exist in the ledger but are economically unusable, so they are effectively removed from circulation. + +- **Pros:** Simple, transparent, easy to verify on-chain. +- **Cons:** Tokens still technically “exist” in state; relies on the assumption no one can access the address. + +### 2) Contract-level destruction (token supply reduction) + +Many token contracts include a `burn()` function that decreases both the holder’s balance and the token’s `totalSupply`. This is a canonical “true burn” at the token standard level. + +- **Pros:** Explicit reduction in `totalSupply`, commonly supported in token standards. +- **Cons:** Requires correct implementation; mistakes can break token accounting. + +### 3) Fee burns (burn-on-transfer or protocol fee burning) + +A portion of each transaction fee or transfer amount is burned automatically. This can create a deflationary pressure tied to network usage. + +- **Pros:** Usage-based burn aligns supply changes with demand/activity. +- **Cons:** Can make transfers more expensive and complicate integrations if not standard. + +### 4) Scheduled or governance-controlled burns + +Projects may burn tokens on a set schedule (e.g., quarterly) or via governance proposals. + +- **Pros:** Predictable or community-controlled. +- **Cons:** Requires trust in process (unless fully automated) and can be sensitive to governance risks. + +### Verifying a burn + +Burn events are generally verifiable by: + +- On-chain transaction logs (e.g., `Transfer` events to a burn address). +- Observing `totalSupply` decreasing (for contract-level burns). +- Block explorer views of balances held at burn addresses. + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, enabling standard Solidity token patterns (including burn functions and burn addresses) to work as they do on other EVM chains—while benefiting from Sei’s **parallelized execution** and **~400ms finality**. This means burn transactions can be confirmed quickly and reliably, and high-throughput burn-on-transfer or fee-burning designs can scale with network activity. + +Common ways burn mechanisms are implemented on Sei include: + +- **EVM token burns (Solidity):** ERC-20 style tokens can expose `burn()` methods or burn via transfers to a dead address. +- **Application-level burns:** dApps can burn tokens as part of their business logic (e.g., burning a portion of fees, mint/burn cycles for synthetic assets, or burning NFTs for upgrades). +- **High-throughput patterns:** Sei’s parallelization can help applications process many burn-related transactions efficiently, useful for mechanisms tied to frequent transfers or automated market activity. + +## Example: ERC-20 Burn Function (Solidity) + +Below is a minimal pattern showing a contract-level burn that reduces both balances and `totalSupply`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +contract BurnableToken is ERC20 { + constructor() ERC20("BurnableToken", "BURN") { + _mint(msg.sender, 1_000_000e18); + } + + function burn(uint256 amount) external { + _burn(msg.sender, amount); + } +} +``` + +**What this does:** + +- `_burn(msg.sender, amount)` reduces the caller’s balance and the token’s `totalSupply`. +- On Sei’s EVM, this is executed and finalized quickly, making supply changes visible almost immediately in explorers and indexers. + +## Example: Burn by Sending to a Dead Address (Solidity) + +Some projects use a well-known burn address: + +```solidity +pragma solidity ^0.8.20; + +interface IERC20 { + function transfer(address to, uint256 value) external returns (bool); +} + +contract BurnByTransfer { + address public constant DEAD = 0x000000000000000000000000000000000000dEaD; + + function burnToken(IERC20 token, uint256 amount) external { + // Caller must have approved this contract beforehand if using transferFrom (not shown). + // This example assumes the contract already holds tokens and sends them to DEAD. + token.transfer(DEAD, amount); + } +} +``` + +**Note:** This method doesn’t necessarily reduce `totalSupply`; it just moves tokens to an unusable address. Whether this is considered “burning” depends on the project’s definition and accounting. + +## Why Projects Use Burn Mechanisms + +- **Supply reduction:** Lower circulating supply can increase scarcity (though price impact is never guaranteed). +- **Value capture:** Burning a portion of fees can align token holders with network or dApp usage. +- **Incentive design:** Can discourage spam (burned fees) or encourage long-term holding. +- **Economic stability:** Used in mechanisms that balance minting (issuance) and burning (redemption). + +## Key Considerations and Risks + +- **Transparency:** Burns should be provable on-chain (events, supply changes). +- **Irreversibility:** A burn is usually permanent; mistakes cannot be undone. +- **Tokenomics realism:** Burning doesn’t create value by itself—demand, utility, and distribution still matter. +- **Implementation correctness:** Poorly written burn logic can break accounting or introduce vulnerabilities. + +## Summary + +A burn mechanism permanently removes tokens from circulation—either by reducing `totalSupply` via contract logic or by sending tokens to an irrecoverable address. On Sei Network, burn mechanisms are commonly implemented through EVM-compatible Solidity contracts and can take advantage of Sei’s **parallelization** and **~400ms finality** for fast, scalable, and verifiable supply adjustments. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-chain-reorg-and-how-does-it-work.mdx b/content/answers/what-is-a-chain-reorg-and-how-does-it-work.mdx new file mode 100644 index 00000000..e66d61a7 --- /dev/null +++ b/content/answers/what-is-a-chain-reorg-and-how-does-it-work.mdx @@ -0,0 +1,166 @@ +--- +title: 'What is a Chain Reorg and How Does It Work?' +description: 'Learn about what is chain reorg and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'chain', 'reorg', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Chain Reorg and How Does It Work? + +## Overview + +A **chain reorg** (chain reorganization) is a change in a blockchain’s canonical (accepted) history where one set of recent blocks is replaced by a different set. This happens when the network temporarily disagrees about the “best” chain, and later converges on a single version, causing some transactions to be **reordered** or **dropped** until they are re-included. + +In other words, if you’re asking **what is chain reorg**, it’s the network’s mechanism for resolving competing block histories so that all nodes end up with the same ledger. + +## How It Works + +### Why reorgs happen + +Reorgs typically occur due to **network latency** and **simultaneous block production**: + +- Two validators/miners produce different valid blocks at roughly the same time. +- Different parts of the network see different blocks first, creating a **temporary fork**. +- As more blocks are built, one fork becomes “heavier”/more preferred by the consensus rules. +- Nodes switch to that fork, and blocks on the losing fork become **orphaned** (removed from the canonical chain). + +### Canonical chain selection (generalized) + +Most blockchains have rules that determine which chain is considered canonical: + +- **Nakamoto-style (PoW / longest/heaviest chain)**: the chain with the most cumulative work (often the “longest”) wins. +- **BFT-style finality (many PoS chains)**: once a block is finalized by consensus, it cannot be reverted except under extreme conditions (e.g., catastrophic faults). + +### What happens to transactions + +When a reorg replaces blocks: + +- Transactions in the removed blocks may: + - Return to the **mempool** (pending pool) and be re-mined later, or + - Become invalid (e.g., due to nonce changes or conflicts), or + - Be replaced by different transactions included on the winning fork. +- Applications may observe: + - A transaction that was “confirmed” becoming **unconfirmed** + - Temporary balance/state changes that later revert + +This is why many systems wait for multiple confirmations or explicit finality before considering a transaction irreversible. + +### Reorg depth + +Reorgs are often described by **depth** (how many blocks are replaced): + +- **1-block reorg**: only the latest block changes; common on some networks. +- **Deep reorg**: multiple blocks replaced; rarer and more disruptive. + +## On Sei Network + +Sei is a high-performance Layer 1 with fast time-to-finality (often cited around **~400ms finality** under normal conditions) and EVM compatibility. Practically, this means: + +- **Shorter “uncertainty window”**: Because blocks reach finality quickly, the time during which a chain reorg could affect your transaction is typically much smaller than on chains where probabilistic confirmation is used. +- **Improved UX for apps**: Fast finality reduces the need to wait for many blocks before treating results as stable, benefiting exchanges, trading apps, and other latency-sensitive experiences. +- **Parallelization + throughput**: Sei’s execution and throughput optimizations (including parallelization techniques) help process high transaction volumes efficiently, while finality properties help reduce reorg-related edge cases for downstream systems. + +Even with fast finality, developers should still build with the assumption that **pre-finalized** blocks can be reorganized in rare situations (e.g., network partitions or competing proposals), and only treat **finalized** state as irreversible. + +## Developer Implications & Best Practices + +### 1) Distinguish “included” vs “finalized” + +For user-facing flows, label states clearly: + +- **Pending**: transaction broadcast but not in a block +- **Included/Confirmed**: transaction in a block but not finalized +- **Finalized**: irreversible under normal assumptions + +### 2) Wait for finality for critical actions + +Use finality (or an equivalent strong confirmation signal) for: + +- Deposits/withdrawals +- Large trades/settlements +- Cross-chain bridging steps + +### 3) Design idempotent backends + +If a transaction is reorged out and later re-included, your system should not double-count actions. Common techniques: + +- Use a unique business key (order ID, payment ID) +- Track processed transaction hashes **and** the block height/finality status +- Reconcile on block updates + +### 4) Monitor reorg signals + +Indexers and apps should detect reorgs by tracking: + +- Block hashes per height +- Parent hash continuity +- Finalization events (where available) + +## Example: Handling Reorgs in an Indexer (TypeScript) + +Below is a simplified pattern for detecting a reorg by verifying parent-child continuity while ingesting blocks: + +```typescript +type BlockHeader = { + number: number; // block height + hash: string; + parentHash: string; +}; + +const seenByHeight = new Map(); + +async function ingestBlock(header: BlockHeader) { + const prev = seenByHeight.get(header.number - 1); + + // If we have the previous height and it doesn't match parentHash, a reorg happened. + if (prev && header.parentHash !== prev.hash) { + // Reorg detected: rollback recent blocks and reprocess. + // Depth depends on how far back hashes diverge. + await handleReorg(header.number - 1); + } + + seenByHeight.set(header.number, header); +} + +async function handleReorg(fromHeight: number) { + // In practice: + // 1) walk backward until you find a common ancestor + // 2) delete derived data for orphaned blocks + // 3) re-ingest blocks from the ancestor forward + console.log(`Reorg detected starting at height ${fromHeight}`); +} +``` + +## Example: User-Facing Confirmation Strategy (EVM / Solidity) + +Smart contracts generally can’t “detect” reorgs directly (they only see the chain they’re executing on), but app logic can reduce risk by delaying critical operations until a transaction is finalized. For example, a backend might only mark an on-chain payment as complete after a finality/confirmation policy is met. + +Solidity-side, you can still implement patterns that help off-chain systems remain robust: + +```solidity +// A simple payment event; off-chain systems should consider finality before acting. +event Payment(address indexed from, uint256 amount, bytes32 indexed paymentId); + +function pay(bytes32 paymentId) external payable { + require(msg.value > 0, "no value"); + emit Payment(msg.sender, msg.value, paymentId); +} +``` + +Off-chain, you would index `Payment` events and only treat them as irreversible once the transaction is finalized per Sei’s finality guarantees and your risk model. + +## Summary + +A chain reorg is the process where a blockchain replaces part of its recent history with a different set of blocks to resolve temporary forks and converge on a single canonical chain. Reorgs can cause transactions to be reordered or temporarily disappear until re-included, so applications should distinguish between “included” and “finalized” states. On Sei Network, fast finality (often ~400ms) and performance-oriented design reduce the practical impact window for reorg-related uncertainty, improving reliability for EVM-compatible applications and high-throughput use cases. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-cold-wallet-and-how-does-it-work.mdx b/content/answers/what-is-a-cold-wallet-and-how-does-it-work.mdx new file mode 100644 index 00000000..f54ce4f1 --- /dev/null +++ b/content/answers/what-is-a-cold-wallet-and-how-does-it-work.mdx @@ -0,0 +1,146 @@ +--- +title: 'What is a Cold Wallet and How Does It Work?' +description: 'Learn about what is cold wallet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'cold', 'wallet', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Cold Wallet and How Does It Work? + +## Overview + +A **cold wallet** is a cryptocurrency wallet that keeps your private keys **offline**, reducing exposure to online attacks like malware, phishing, and remote exploits. If you’re searching **“what is cold wallet”**, the simplest answer is: it’s a storage method designed for **maximum security**, typically used for long-term holding rather than frequent trading. + +Cold wallets are commonly implemented as **hardware wallets**, **paper wallets**, or **air-gapped** devices that never connect to the internet. + +## How It Works + +At a high level, all crypto wallets manage **private keys**—the secret credentials that authorize spending funds from an address. + +### Key concepts + +- **Private key (secret):** Used to create signatures that approve transactions. +- **Public key / address (shareable):** Where you receive funds. +- **Signing:** A transaction is signed with the private key to prove authorization. +- **Broadcasting:** The signed transaction is sent to the blockchain network for inclusion in a block. + +### Cold wallet transaction flow + +1. **Create an unsigned transaction** on an online device (computer/phone). +2. **Transfer the unsigned transaction** to the offline device (USB, QR code, SD card). +3. **Sign the transaction offline** using the cold wallet (private key never touches the internet). +4. **Move the signed transaction back** to the online device. +5. **Broadcast the signed transaction** to the blockchain network. + +Because the private key stays offline, attackers generally can’t steal it through typical internet-based methods. + +### Pros and cons + +**Pros** + +- Strong protection against online threats +- Ideal for long-term storage and treasury management + +**Cons** + +- Less convenient for frequent transactions +- Requires careful backup (seed phrase) and physical security + +## Types of Cold Wallets + +### Hardware wallets + +Dedicated devices (e.g., Ledger, Trezor) that store keys in secure hardware and sign transactions internally. + +### Air-gapped wallets + +Devices that never connect to the internet (no Wi‑Fi/Bluetooth), often using QR codes or removable media to move unsigned/signed transactions. + +### Paper wallets (legacy) + +Printed private keys/seed phrases. Generally discouraged today due to risk of loss, damage, and user error—hardware wallets and secure offline backups are safer. + +## On Sei Network + +On **Sei Network**, a cold wallet works the same fundamental way: your wallet signs transactions with an offline private key, then the signed transaction is broadcast to Sei. Since Sei is an **EVM-compatible Layer 1**, most cold wallet tooling and operational patterns used for Ethereum-like chains also apply. + +Where Sei differs is in the network experience once a signed transaction is submitted: + +- **Fast finality (~400ms):** Signed transactions—once broadcast—can reach finality quickly, improving user experience for secure, deliberate cold-wallet spending workflows. +- **Parallelization:** Sei is designed to process transactions efficiently in parallel, helping maintain performance even under high activity. +- **EVM compatibility:** You can use familiar Ethereum-style accounts and tooling, including hardware wallets that support EVM chains and EIP-155 signing. + +### Example: Broadcast a signed transaction to Sei (EVM) with Foundry + +If you sign a transaction offline (or use a hardware wallet), you can broadcast via standard EVM tools by pointing them to Sei’s RPC endpoint. + +```bash +# Example structure (replace RPC URL, contract, and parameters as needed) +export SEI_EVM_RPC_URL="https://" +export PRIVATE_KEY="" + +cast send \ + --rpc-url "$SEI_EVM_RPC_URL" \ + --private-key "$PRIVATE_KEY" \ + 0xYourContractAddress \ + "transfer(address,uint256)" \ + 0xRecipientAddress \ + 1000000000000000000 +``` + +> For real cold wallet usage, avoid exporting private keys on an internet-connected machine. Prefer hardware wallet integrations or fully offline signing workflows. + +### Example: Using a hardware wallet with ethers (TypeScript) + +This pattern is commonly used with EVM chains. Point your provider at Sei’s EVM RPC. + +```typescript +import { ethers } from 'ethers'; + +// Sei EVM RPC endpoint (replace with the one you use) +const provider = new ethers.JsonRpcProvider('https://'); + +// Hardware wallets are typically integrated via specific signer libraries/connectors. +// Conceptually, you'd obtain a signer that can sign without exposing the private key: +async function main() { + // Example placeholder: replace with your hardware wallet signer integration + const signer = new ethers.Wallet(process.env.DEMO_PRIVATE_KEY!, provider); + + const tx = await signer.sendTransaction({ + to: '0xRecipientAddress', + value: ethers.parseEther('0.01') + }); + + console.log('Tx hash:', tx.hash); + console.log('Waiting for confirmation...'); + const receipt = await tx.wait(); + console.log('Confirmed in block:', receipt?.blockNumber); +} + +main().catch(console.error); +``` + +## Best Practices for Cold Wallet Security + +- **Back up your seed phrase** offline (preferably multiple copies in secure locations). +- **Never share or photograph seed phrases**; avoid cloud storage and messaging apps. +- **Verify addresses on-device** (hardware wallet screen) before signing. +- **Use multisig for treasuries** to reduce single-point-of-failure risk. +- **Test with small amounts first**, especially when moving funds to/from cold storage. +- **Keep firmware and wallet software updated**, but verify sources and release authenticity. + +## Summary + +If you’re asking **what is cold wallet**, it’s an offline key storage approach that significantly reduces online attack risk by keeping private keys disconnected from the internet. It works by signing transactions offline and broadcasting only signed data online. On **Sei Network**, cold wallets follow standard EVM-style workflows while benefiting from Sei’s **EVM compatibility**, **parallelized execution**, and **~400ms finality** once transactions are broadcast. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-composability-and-how-does-it-work.mdx b/content/answers/what-is-a-composability-and-how-does-it-work.mdx new file mode 100644 index 00000000..f416056c --- /dev/null +++ b/content/answers/what-is-a-composability-and-how-does-it-work.mdx @@ -0,0 +1,187 @@ +--- +title: 'What is a Composability and How Does It Work?' +description: 'Learn about what is composability and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'composability', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Composability and How Does It Work? + +## Overview + +Composability is the ability for blockchain applications (smart contracts, protocols, and tokens) to seamlessly connect and build on top of each other like “money legos.” In practice, it means one app can call into another app’s contracts, reuse its liquidity or logic, and combine multiple actions into a single user flow or transaction. + +When people ask **what is composability**, they’re usually referring to how easily on-chain components can be combined to create new products (e.g., swapping, lending, and staking in one sequence) without needing permission from the original builders. + +## How It Works + +### Smart contracts as reusable building blocks + +On programmable blockchains, core functionality is deployed as smart contracts. Any other contract can interact with them by calling public functions, passing parameters, and receiving return values. This enables: + +- **Protocol-to-protocol integration** (e.g., a yield aggregator calling a lending market) +- **Atomic multi-step actions** (e.g., swap → deposit → borrow in a single transaction) +- **Shared liquidity and standards** (e.g., ERC-20 tokens and AMM pools reused across many apps) + +### Atomicity: the key property + +A major enabler of composability is **atomic execution**: a transaction containing multiple calls either fully succeeds or fully fails. This reduces partial-state risk and allows complex workflows: + +1. Contract A calls Contract B (e.g., swap) +2. Then calls Contract C (e.g., deposit collateral) +3. Then calls Contract D (e.g., borrow) +4. If any step fails, everything reverts + +### Synchronous vs. asynchronous composability + +- **Synchronous composability**: cross-contract calls happen within the same transaction (common within a single chain). This is the “classic DeFi lego” model. +- **Asynchronous composability**: interactions occur across messages/blocks (often cross-chain), introducing latency and additional failure modes (bridges, relayers, finality delays). + +### Benefits and trade-offs + +**Benefits** + +- Faster innovation: developers reuse existing, audited components +- Better UX: fewer steps and lower coordination overhead +- More capital efficiency: shared liquidity across apps + +**Trade-offs** + +- Dependency risk: upstream changes or exploits can cascade +- MEV and ordering sensitivity: complex transactions may be front-run +- Shared-state contention: high demand can increase latency or fees on some chains + +## On Sei Network + +Sei is designed to enhance composability for both DeFi and general-purpose apps by combining **EVM compatibility**, **parallelization**, and **~400ms finality**. + +### EVM composability (Solidity + existing tooling) + +Sei’s EVM compatibility means developers can deploy Solidity contracts and integrate with familiar patterns (ERC-20, routers, vaults, etc.). This makes it straightforward to compose Sei-native protocols and EVM-based contracts using standard ABI calls and tooling (Hardhat, Foundry, ethers). + +### Parallelization improves composability at scale + +As ecosystems grow, many users try to compose the same popular contracts (DEX pools, lending markets) at once. Sei’s **parallelized execution** aims to increase throughput by executing non-conflicting transactions concurrently—helping composable apps remain responsive during high demand. + +What this means for composability: + +- More complex multi-contract flows can be processed with less congestion +- High-volume primitives (DEXes, perps, liquid staking) are more usable as “lego blocks” +- Apps that depend on multiple protocols can deliver more consistent UX under load + +### ~400ms finality improves UX for multi-step workflows + +Composability often involves multi-step sequences (even when not fully atomic, e.g., follow-up actions after a swap). Sei’s **~400ms finality** helps reduce perceived latency for confirmations and state updates, improving: + +- Real-time trading experiences +- Rapid collateral adjustments +- Higher-frequency interactions between apps and protocols + +## Example: Composing Contracts with a Router (Solidity) + +Below is a simplified example of a “router” contract that composes two protocols: it swaps tokens on a DEX, then deposits the output into a vault—atomically. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function approve(address spender, uint256 amount) external returns (bool); + function balanceOf(address owner) external view returns (uint256); +} + +interface IDex { + function swapExactInput( + address tokenIn, + address tokenOut, + uint256 amountIn, + uint256 minAmountOut, + address to + ) external returns (uint256 amountOut); +} + +interface IVault { + function deposit(address token, uint256 amount, address recipient) external returns (uint256 shares); +} + +contract ComposableRouter { + IDex public immutable dex; + IVault public immutable vault; + + constructor(IDex _dex, IVault _vault) { + dex = _dex; + vault = _vault; + } + + /// @notice Swap tokenIn -> tokenOut, then deposit tokenOut into vault, atomically. + function swapThenDeposit( + address tokenIn, + address tokenOut, + uint256 amountIn, + uint256 minAmountOut, + address recipient + ) external returns (uint256 amountOut, uint256 shares) { + // In a real implementation you would transferFrom(tokenIn) from msg.sender first. + + // Swap via DEX + IERC20(tokenIn).approve(address(dex), amountIn); + amountOut = dex.swapExactInput(tokenIn, tokenOut, amountIn, minAmountOut, address(this)); + + // Deposit swapped tokens into vault + IERC20(tokenOut).approve(address(vault), amountOut); + shares = vault.deposit(tokenOut, amountOut, recipient); + + // If swap or deposit fails, the entire transaction reverts (atomic composability). + } +} +``` + +## Example: Calling Composed Flows (TypeScript) + +Using ethers to call the router on Sei EVM: + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const PRIVATE_KEY = process.env.PRIVATE_KEY!; + +const provider = new ethers.JsonRpcProvider(RPC_URL); +const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + +const routerAddress = '0xRouter...'; +const routerAbi = ['function swapThenDeposit(address tokenIn,address tokenOut,uint256 amountIn,uint256 minAmountOut,address recipient) returns (uint256,uint256)']; + +const router = new ethers.Contract(routerAddress, routerAbi, wallet); + +async function main() { + const tokenIn = '0xTokenIn...'; + const tokenOut = '0xTokenOut...'; + const amountIn = ethers.parseUnits('10', 6); + const minAmountOut = ethers.parseUnits('9.9', 6); + + const tx = await router.swapThenDeposit(tokenIn, tokenOut, amountIn, minAmountOut, wallet.address); + const receipt = await tx.wait(); + console.log('Included in tx:', receipt?.hash); +} + +main().catch(console.error); +``` + +## Key Takeaways + +- **Composability** is the ability to combine on-chain apps and smart contracts into new, richer workflows. +- It relies on **standard interfaces**, **cross-contract calls**, and often **atomic transactions** to ensure multi-step actions succeed together. +- On **Sei Network**, composability benefits from **EVM compatibility** (easy integration), **parallelization** (better throughput for shared primitives), and **~400ms finality** (faster confirmations and smoother UX). + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx b/content/answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx new file mode 100644 index 00000000..afa204a0 --- /dev/null +++ b/content/answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx @@ -0,0 +1,102 @@ +--- +title: 'What is a Consensus Mechanism and How Does It Work?' +description: 'Learn about what is consensus mechanism and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'consensus', 'mechanism', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Consensus Mechanism and How Does It Work? + +## Overview + +A **consensus mechanism** is the set of rules and processes a blockchain uses to ensure all nodes agree on the same ledger state (i.e., which transactions are valid and in what order). In other words, it’s how a decentralized network reaches agreement without relying on a central authority—answering the question, **“what is consensus mechanism”** in practical terms: it’s the protocol that prevents double-spends and keeps the chain consistent. + +## How It Works + +At a high level, consensus mechanisms solve three core problems: + +1. **Transaction validity**: deciding which transactions follow the protocol rules (signatures, balances, nonce, etc.). +2. **Transaction ordering**: agreeing on a single, canonical order of valid transactions. +3. **Finality**: determining when a transaction is considered irreversible (or how hard it is to revert). + +While implementations vary, most consensus mechanisms follow this general flow: + +1. **Nodes receive transactions** and verify them locally. +2. **A block proposer/leader** is selected (randomly, weighted by stake, or via other rules). +3. The proposer **bundles transactions into a block** and broadcasts it. +4. Other nodes **validate the proposed block**. +5. Nodes run a **voting/commit process** (typical in Proof of Stake and BFT-style consensus) or **compete via computation** (Proof of Work) to finalize the block. +6. Once finalized, nodes **append the block** to the chain and move on to the next height. + +### Common Types of Consensus Mechanisms + +- **Proof of Work (PoW)**: Miners compete to solve a computational puzzle. Security comes from the cost of computation. Finality is typically probabilistic (more confirmations = more confidence). +- **Proof of Stake (PoS)**: Validators stake tokens and are selected to propose/attest to blocks. Misbehavior can be penalized (slashing). Finality can be faster and more deterministic with BFT-style voting. +- **BFT (Byzantine Fault Tolerant) consensus**: A family of protocols where validators vote in rounds to agree on blocks even if some validators are faulty/malicious (up to a threshold). Often used alongside PoS. + +### Key Properties to Know + +- **Liveness**: the network continues producing blocks. +- **Safety**: the network doesn’t finalize conflicting histories. +- **Finality model**: + - _Probabilistic finality_: reversions become less likely over time. + - _Deterministic (instant) finality_: once finalized, the block is not expected to be reverted unless extreme conditions occur. + +## On Sei Network + +Sei Network uses a **Proof of Stake + BFT-style consensus** model designed for high throughput and fast confirmation. This enables **~400ms finality**, meaning transactions can become final very quickly compared to many L1s, improving UX for trading, gaming, and other latency-sensitive applications. + +### Why Consensus Matters for Sei + +- **Fast finality (~400ms)**: Applications can treat transactions as final quickly, reducing waiting time and improving responsiveness. +- **High-performance execution with parallelization**: Sei’s execution layer is optimized for throughput via parallelization, which complements fast consensus by ensuring the chain can process many transactions efficiently once agreement is reached. +- **EVM compatibility**: Developers can deploy Solidity smart contracts and use familiar Ethereum tooling, while benefiting from Sei’s fast finality and performance characteristics. + +### Practical Implications for Developers + +- **Lower confirmation latency**: Frontends can update state faster after a transaction. +- **Better UX under load**: Fast consensus plus performant execution helps maintain responsiveness even when activity spikes. +- **EVM workflows still apply**: You interact with Sei similarly to Ethereum from an app perspective (RPC calls, transaction receipts), but finality can be achieved significantly faster. + +## Example: Waiting for Transaction Confirmation (EVM) + +Below is a simple TypeScript example using `ethers` to submit a transaction and wait for confirmation on Sei’s EVM. With fast finality, the wait time to a confirmed receipt is typically short. + +```typescript +import { ethers } from 'ethers'; + +async function sendTx() { + // Replace with a Sei EVM RPC endpoint + const provider = new ethers.JsonRpcProvider('https://YOUR_SEI_EVM_RPC'); + const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + + const tx = await wallet.sendTransaction({ + to: '0xRecipientAddress...', + value: ethers.parseEther('0.01') + }); + + console.log('Submitted tx:', tx.hash); + + // Wait for 1 confirmation; on fast-finality chains this is typically quick + const receipt = await tx.wait(1); + console.log('Confirmed in block:', receipt?.blockNumber); +} + +sendTx().catch(console.error); +``` + +## Summary + +A consensus mechanism is the protocol that lets a decentralized blockchain network agree on valid transactions, block ordering, and finality. In general, it coordinates proposer selection, validation, and agreement so the chain stays consistent and resistant to attacks. On Sei Network, PoS + BFT-style consensus with **~400ms finality**, combined with **parallelized execution** and **EVM compatibility**, provides fast, scalable confirmations for modern onchain applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx b/content/answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx new file mode 100644 index 00000000..246b5a2a --- /dev/null +++ b/content/answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx @@ -0,0 +1,180 @@ +--- +title: 'What is a Cross-chain Bridge and How Does It Work?' +description: 'Learn about what is cross-chain bridge and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'cross-chain', 'bridge', 'cross', 'chain', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Cross-chain Bridge and How Does It Work? + +## Overview + +A cross-chain bridge is a protocol that lets users move tokens and data between separate blockchain networks that don’t natively interoperate. In practical terms, it “translates” value from one chain to another by locking, escrowing, or verifying assets on the source chain and issuing a corresponding representation on the destination chain. If you’re asking **what is cross-chain bridge**, it’s best understood as the infrastructure that enables asset portability and cross-ecosystem apps. + +## How It Works + +Most bridges follow one of a few common models. The key idea is that because chains have independent consensus, the destination chain needs a trustworthy way to know that something happened on the source chain. + +### 1) Lock-and-Mint (Wrapped Assets) + +This is the classic “wrapped token” pattern: + +1. **Deposit on source chain:** You send tokens to a bridge contract on Chain A. +2. **Lock/escrow:** The bridge contract locks the tokens so they can’t be spent on Chain A. +3. **Message/verification:** Relayers/validators (or a light client) prove to Chain B that the deposit happened. +4. **Mint on destination chain:** A wrapped representation (e.g., `wTOKEN`) is minted to you on Chain B. +5. **Redeem/burn to return:** To go back, you **burn** wrapped tokens on Chain B, and the bridge **unlocks** the original tokens on Chain A. + +**Pros:** Simple mental model; widely used. +**Cons:** Wrapped assets add trust and risk: if bridge custody or verification fails, the wrapped token can lose backing. + +### 2) Burn-and-Mint (Canonical Bridged Supply) + +Some ecosystems treat the bridged version as canonical on multiple chains: + +1. Tokens are **burned** (or locked) on Chain A. +2. Tokens are **minted** on Chain B, often by the same issuer/bridge. + +This is common for tokens that are explicitly designed to exist across multiple chains under a single supply control system. + +### 3) Liquidity Network (Swap-Based Bridges) + +Instead of wrapping, some bridges use liquidity pools or market makers: + +1. You deposit on Chain A. +2. A liquidity provider pays you out on Chain B. +3. Providers later rebalance inventory across chains. + +**Pros:** Often fast; can avoid wrapped assets in some designs. +**Cons:** Depends on available liquidity and pricing; can introduce slippage/fees. + +### 4) Verification Models (Who “Proves” the Source Chain?) + +Bridge security largely depends on how the destination chain verifies source-chain events: + +- **Trusted multisig/committee:** A set of signers attests to events. Simple, but trust-heavy. +- **External validator set:** A dedicated bridge validator network signs messages. Stronger than a small multisig, but still not the full security of the source chain. +- **Light-client / consensus verification:** The destination chain verifies the source chain’s consensus proofs (most trust-minimized, usually more complex and costly). +- **Optimistic verification:** Messages are accepted unless challenged within a window; security depends on watchers and dispute mechanisms. + +### 5) Fees, Finality, and Reorg Safety + +Bridging typically includes: + +- **Source chain confirmations/finality wait** to avoid reorgs. +- **Relayer fees** (paying entities that deliver proofs/messages). +- **Destination chain gas fees** to execute mint/unlock actions. + +The stronger the finality and the faster the block confirmation, the faster and safer bridging can be. + +## Security Considerations (Why Bridges Are Hard) + +Cross-chain bridges are a frequent target because they often custody large amounts of value and sit between different security domains. + +Key risks include: + +- **Custody compromise:** If locked funds are controlled by a contract or committee that can be exploited, funds can be stolen. +- **Verification bugs:** Incorrect proof verification can allow attackers to mint assets without valid deposits. +- **Replay/message ordering issues:** Messages must be uniquely identified and consumed once. +- **Admin key risk:** Upgradable contracts and privileged roles can introduce centralization and key compromise risk. +- **Liquidity risk:** Swap-based bridges can fail if liquidity dries up or markets move sharply. + +Best practices: + +- Prefer **audited, battle-tested** bridges. +- Verify **bridge TVL, architecture, and trust assumptions** (multisig vs light-client). +- Use **rate limits**, **circuit breakers**, and **monitoring** for large transfers. +- Start with small transfers when using a bridge for the first time. + +## On Sei Network + +Sei is a high-performance Layer 1 designed for low-latency execution and high throughput, with **EVM compatibility** and a fast user experience enabled by parallelization and ~**400ms finality**. In a bridging context, that means: + +- **Faster destination settlement:** Once a bridge message is verified and executed on Sei, the resulting state (mint/unlock) can finalize quickly, improving end-user UX. +- **High-throughput execution:** Sei’s parallelized execution can help handle high volumes of bridge-related transactions (mints, burns, message processing) efficiently, especially during peak demand. +- **EVM tooling compatibility:** If a bridge deploys EVM contracts on Sei, developers can use standard Solidity patterns and Ethereum tooling for integration. + +### Typical Flow Bridging Into Sei (Conceptual) + +1. User deposits tokens on an origin chain bridge contract. +2. Bridge relayers/verification mechanism generates a message/proof. +3. The destination bridge contract on **Sei** receives the message. +4. The contract mints wrapped assets (or releases liquidity) to the user’s Sei address. +5. With **fast finality**, the user can typically start using bridged assets on Sei shortly after execution. + +### Example: ERC-20 Bridge Receiver Pattern (Solidity) + +Below is a simplified example of a destination-side bridge contract pattern you may see in EVM environments (including Sei’s EVM). Real bridges add robust proof verification, replay protection, access controls, and often separate messaging layers. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IMintableERC20 { + function mint(address to, uint256 amount) external; +} + +contract SimpleBridgeReceiver { + IMintableERC20 public immutable wrappedToken; + + // Tracks processed messages to prevent replay + mapping(bytes32 => bool) public processed; + + // In practice, this would be a verified messaging endpoint or bridge verifier. + address public immutable verifier; + + constructor(address _wrappedToken, address _verifier) { + wrappedToken = IMintableERC20(_wrappedToken); + verifier = _verifier; + } + + modifier onlyVerifier() { + require(msg.sender == verifier, "not verifier"); + _; + } + + // Called after a source-chain deposit is proven/attested. + function receiveBridgedTokens( + bytes32 messageId, + address recipient, + uint256 amount + ) external onlyVerifier { + require(!processed[messageId], "message already processed"); + processed[messageId] = true; + + wrappedToken.mint(recipient, amount); + } +} +``` + +### Example: Reading a Transaction Receipt (TypeScript) + +If you’re integrating a bridge UX, you’ll typically wait for the destination-chain transaction to be confirmed/finalized before updating UI state. + +```typescript +import { ethers } from 'ethers'; + +async function waitForDestinationExecution(provider: ethers.Provider, txHash: string) { + const receipt = await provider.waitForTransaction(txHash, 1); + if (!receipt || receipt.status !== 1) { + throw new Error('Bridge execution failed on destination chain'); + } + return receipt; +} +``` + +## Summary + +A cross-chain bridge is the infrastructure that enables assets and messages to move between blockchains by locking/burning on one chain and minting/releasing on another, backed by some verification mechanism. Bridge designs vary (wrapped assets, liquidity-based transfers, light-client verification), and security depends on trust assumptions and correct message validation. On Sei Network, bridging benefits from **fast (~400ms) finality**, **parallelized execution**, and **EVM compatibility**, which together can improve settlement speed and developer integration for cross-chain applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx b/content/answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx new file mode 100644 index 00000000..d6bc5538 --- /dev/null +++ b/content/answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx @@ -0,0 +1,168 @@ +--- +title: 'What is a Crypto Oracle and How Does It Work?' +description: 'Learn about what is crypto oracle and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'crypto', 'oracle', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Crypto Oracle and How Does It Work? + +## Overview + +A **crypto oracle** is a service that delivers **off-chain data** (data from outside the blockchain) to **on-chain smart contracts** in a way contracts can reliably consume. Put simply, it answers the question **“what is crypto oracle”** by acting as the bridge between blockchains and real-world information like asset prices, event outcomes, randomness, and API responses. + +Because blockchains can’t directly fetch external data without breaking determinism, oracles provide a standardized, verifiable method to import that data so decentralized applications (dApps) can make decisions based on real-world conditions. + +## How It Works + +### Why smart contracts need oracles + +Smart contracts execute deterministically: every node must be able to reproduce the same result from the same inputs. If a contract tried to call a normal web API directly, different nodes could get different responses (or no response), causing consensus failure. Oracles solve this by **bringing external data on-chain** through a process nodes can validate. + +### Common oracle types + +- **Price oracles**: Provide token/asset prices (e.g., ETH/USD) for lending, derivatives, stablecoins. +- **Data feed oracles**: Supply non-price data (weather, sports results, interest rates). +- **Randomness oracles (VRF)**: Provide verifiable randomness for games, NFT mints, lotteries. +- **Cross-chain/messaging oracles**: Relay information between chains (sometimes paired with bridges). +- **Compute oracles**: Provide results of off-chain computation (e.g., ML scoring, aggregation). + +### Oracle delivery models + +- **Push model**: Oracle periodically publishes data to an on-chain contract (e.g., a price feed updated every N seconds). +- **Pull model**: A contract (or user) requests data; an oracle responds later with the result (request/response pattern). + +### Trust and security models + +Oracles introduce an important dependency: the contract is only as trustworthy as its data source and delivery mechanism. + +Typical security approaches include: + +- **Decentralized oracle networks (DONs)**: Multiple independent nodes fetch/aggregate the same data. +- **Aggregation & medianization**: Combine many sources; use median to reduce outliers. +- **Signed data**: Oracles sign the payload; on-chain verifies signature(s). +- **Staleness checks**: Contracts reject data older than a threshold. +- **Circuit breakers**: Pause sensitive actions if data deviates too sharply. +- **Economic incentives/slashing**: Misbehavior can be penalized. + +### High-level flow + +1. **Smart contract needs external data** (e.g., BTC/USD price). +2. **Oracle nodes fetch data** from multiple APIs/exchanges. +3. **Oracle network aggregates** and finalizes a value. +4. **Oracle publishes on-chain** (push) or returns result (pull). +5. **Contract reads oracle value** and proceeds (liquidations, swaps, payouts, etc.). + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, enabling Solidity-based dApps to integrate oracle data similarly to other EVM chains. For oracle-driven applications (DeFi, perps, lending), Sei’s **parallelized execution** and **~400ms finality** can significantly improve the user experience: price updates and state transitions confirm quickly, reducing latency between “data update” and “action taken.” + +Key implications on Sei: + +- **Faster reaction to market moves**: With low finality time, oracle updates can be acted on quickly (e.g., liquidations, margin checks). +- **Higher throughput for oracle consumers**: Parallelization helps when many contracts/users read feeds and execute trades simultaneously. +- **EVM tooling compatibility**: Standard Solidity patterns (interfaces, feed readers, staleness checks) apply, making it straightforward to port existing oracle-integrated contracts. + +> Note: The exact oracle provider integration (addresses, interfaces, update cadence) depends on the specific oracle network deployed on Sei. Always use the official provider documentation and deployed contract addresses for Sei. + +## Example: Reading an Oracle Price Feed (Solidity) + +Below is a **generic EVM-style** example of consuming a price feed and enforcing basic safety checks (staleness and nonzero price). Replace the interface and function signatures with those from your chosen oracle provider on Sei. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IPriceFeed { + // Example interface (varies by provider) + function latestAnswer() external view returns (int256); + function latestTimestamp() external view returns (uint256); +} + +contract OracleConsumer { + IPriceFeed public immutable feed; + + // Example: reject data older than 60 seconds + uint256 public constant MAX_STALENESS = 60; + + constructor(address feedAddress) { + require(feedAddress != address(0), "invalid feed"); + feed = IPriceFeed(feedAddress); + } + + function getPrice() external view returns (uint256 price) { + int256 answer = feed.latestAnswer(); + uint256 updatedAt = feed.latestTimestamp(); + + require(answer > 0, "bad price"); + require(block.timestamp - updatedAt <= MAX_STALENESS, "stale price"); + + // Cast safe after checking answer > 0 + price = uint256(answer); + } +} +``` + +## Example: Deploying to Sei EVM (Hardhat) + +This is a typical EVM deployment flow. Use Sei’s EVM RPC endpoint and chain ID for your target network (testnet/mainnet). + +```bash +npm init -y +npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox +npx hardhat init +``` + +```typescript +// hardhat.config.ts +import { HardhatUserConfig } from 'hardhat/config'; +import '@nomicfoundation/hardhat-toolbox'; + +const config: HardhatUserConfig = { + solidity: '0.8.20', + networks: { + sei: { + url: process.env.SEI_EVM_RPC_URL!, // e.g., https://... + accounts: [process.env.DEPLOYER_PRIVATE_KEY!], + chainId: Number(process.env.SEI_CHAIN_ID!) // set for Sei network + } + } +}; + +export default config; +``` + +```bash +# Compile +npx hardhat compile + +# Deploy +SEI_EVM_RPC_URL="https://" \ +SEI_CHAIN_ID="XXXX" \ +DEPLOYER_PRIVATE_KEY="0x..." \ +npx hardhat run scripts/deploy.ts --network sei +``` + +## Best Practices for Using Crypto Oracles + +- **Validate freshness**: Enforce staleness thresholds appropriate for your app’s risk (especially for perps/lending). +- **Handle decimals correctly**: Many feeds return scaled integers (e.g., 1e8). Normalize before using. +- **Use fallbacks when possible**: Multiple feeds/providers can reduce downtime risk. +- **Add sanity bounds**: Reject extreme deviations or require multiple confirmations during volatility. +- **Design for Sei performance**: With ~400ms finality, consider tighter update intervals and risk checks that benefit from fast confirmation. + +## Summary + +A crypto oracle is the critical infrastructure that lets smart contracts use off-chain data safely and consistently. In general, oracles fetch, aggregate, and publish external information on-chain; on **Sei Network**, the combination of **EVM compatibility**, **parallel execution**, and **~400ms finality** enables oracle-powered dApps to respond quickly and scale under heavy usage. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx b/content/answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx new file mode 100644 index 00000000..7cb556c6 --- /dev/null +++ b/content/answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx @@ -0,0 +1,125 @@ +--- +title: 'What is a Custodial Wallet and How Does It Work?' +description: 'Learn about what is custodial wallet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'custodial', 'wallet', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Custodial Wallet and How Does It Work? + +## Overview + +A **custodial wallet** is a crypto wallet where a third party (such as an exchange or wallet provider) holds and manages your private keys on your behalf. In practice, this means the custodian can sign transactions for you, and you access your funds through an account, password, and often additional security controls like 2FA. + +If you’re searching **“what is custodial wallet”**, the simplest answer is: it’s a wallet where you don’t directly control the private keys—another entity does. + +## How It Works + +In blockchain systems, ownership of assets is controlled by **private keys**, which are used to sign transactions. A custodial wallet changes the typical “self-custody” model by shifting key management and transaction signing to a service provider. + +### Key components + +- **Private key custody**: The provider stores private keys (often in HSMs, cold storage, or multi-signature setups). +- **User account access**: You log into an app or exchange to view balances and request transfers. +- **Transaction signing**: When you initiate a send, the custodian signs and broadcasts the transaction to the network. +- **Internal ledgers** (common): Many custodians keep an internal database of user balances and only settle on-chain when needed (e.g., withdrawals). + +### Typical transaction flow + +1. **Deposit**: You send tokens to a deposit address managed by the custodian (or assigned to your account). +2. **Balance update**: Your account balance is credited (sometimes after on-chain confirmations). +3. **Transfer within platform**: Moves may occur off-chain inside the custodian’s internal ledger. +4. **Withdraw**: You request a withdrawal to an external address; the custodian signs an on-chain transaction and broadcasts it. + +### Custodial vs. non-custodial (quick comparison) + +- **Custodial wallet**: Provider controls keys; easier UX; relies on provider security and policies. +- **Non-custodial wallet**: You control keys/seed phrase; more responsibility; typically more censorship-resistant. + +### Pros and cons + +**Pros** + +- Easier onboarding and recovery (password reset, account recovery) +- Often includes integrated fiat on-ramps/off-ramps +- Provider may offer additional security tooling and monitoring + +**Cons** + +- Counterparty risk (provider hacks, insolvency, withdrawal freezes) +- Less privacy (KYC/AML is common) +- Potential censorship or transaction limits +- “Not your keys, not your coins” tradeoff + +## On Sei Network + +On **Sei Network** (a high-performance Layer 1 with **EVM compatibility**), custodial wallets work the same fundamental way: the custodian controls the private keys used to sign transactions that move assets on Sei. What changes is the **user experience and operational performance** due to Sei’s design: + +- **Fast settlement and UX**: Sei’s ~**400ms finality** can make deposits, withdrawals, and on-chain confirmations feel near-instant compared to slower networks, improving custodial exchange workflows. +- **High throughput via parallelization**: Sei’s **parallelized execution** enables many transactions to be processed efficiently, which can help custodians handle bursts of withdrawals, hot-wallet operations, and user activity at scale. +- **EVM compatibility**: Custodians can support Sei using familiar Ethereum-style tooling—addresses, signing, and smart contract interactions—while benefiting from Sei’s performance characteristics. + +### What custodians typically do on Sei + +- Maintain **hot wallets** (for frequent withdrawals) and **cold wallets** (for long-term storage) +- Monitor Sei blocks/events to detect deposits and credit user accounts +- Aggregate withdrawals to optimize operational overhead +- Integrate with EVM tooling (RPC, transaction signing libraries) to support Sei-based assets and dApps + +## Example: Sending a Transaction (Custodian-Style) on Sei EVM + +Below is a simplified example of how a custodian (or any backend service) might sign and broadcast a transaction on Sei’s EVM using `ethers`. In a real custodial wallet, the private key would typically be protected by an HSM/KMS and strict policy controls. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = 'https://evm-rpc.sei-apis.com'; // Example RPC endpoint (use your preferred provider) +const provider = new ethers.JsonRpcProvider(RPC_URL); + +// In production, do NOT hardcode keys. Use KMS/HSM and access controls. +const privateKey = process.env.CUSTODIAN_HOT_WALLET_KEY!; +const wallet = new ethers.Wallet(privateKey, provider); + +async function sendSeiEvmTx() { + const to = '0xRecipientAddressHere000000000000000000000000'; + const value = ethers.parseEther('0.01'); // Native token amount on Sei EVM + + const tx = await wallet.sendTransaction({ + to, + value + }); + + console.log('Broadcasted tx hash:', tx.hash); + + const receipt = await tx.wait(); + console.log('Confirmed in block:', receipt?.blockNumber); +} + +sendSeiEvmTx().catch(console.error); +``` + +## Security Notes (Best Practices) + +Custodial wallets are security-critical because a compromise of the custodian’s keys can impact many users. + +- Use **segregated hot/cold storage**, withdrawal limits, and rate controls +- Use **multi-sig** or policy-based signing for large withdrawals +- Store keys in **HSM/KMS** where possible; enforce least-privilege access +- Implement **on-chain monitoring** and anomaly detection +- Maintain clear procedures for incident response and proof-of-reserves where applicable + +## Summary + +A custodial wallet is a wallet where a third party holds your private keys and processes transactions on your behalf. It simplifies onboarding and recovery but introduces counterparty risk and reduces direct control. On **Sei Network**, custodial wallets operate the same way while benefiting from Sei’s **parallelization**, **~400ms finality**, and **EVM compatibility** for fast, scalable transaction processing. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-daos-and-how-does-it-work.mdx b/content/answers/what-is-a-daos-and-how-does-it-work.mdx new file mode 100644 index 00000000..44d16aaa --- /dev/null +++ b/content/answers/what-is-a-daos-and-how-does-it-work.mdx @@ -0,0 +1,197 @@ +--- +title: 'What is a DAOs and How Does It Work?' +description: 'Learn about what is DAOs and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'DAOs', 'daos', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a DAOs and How Does It Work? + +## Overview + +A **DAO (Decentralized Autonomous Organization)** is an internet-native organization governed by code (smart contracts) and community voting rather than a centralized leadership team. In practice, a DAO coordinates people, treasury funds, and decision-making using transparent rules enforced on-chain. If you’re searching **what is DAOs**, it refers to DAOs as a category: multiple decentralized organizations that operate through blockchain-based governance. + +## How It Works + +### 1) Smart contracts define the rules + +Most DAOs are built on smart contracts that encode: + +- **Membership logic** (who can participate) +- **Voting mechanisms** (how proposals pass) +- **Treasury controls** (how funds can be spent) +- **Execution** (what happens when a proposal passes) + +Once deployed, these contracts can automatically enforce outcomes (e.g., transferring funds) when governance conditions are met. + +### 2) Membership and voting power + +DAOs typically grant governance rights via: + +- **Fungible governance tokens** (1 token = 1 vote, or weighted variants) +- **NFT-based membership** (membership represented by NFTs) +- **Reputation / points systems** (off-chain or on-chain attestations) + +Voting power can be subject to rules like quorum, supermajority thresholds, proposal deposits, or delegation. + +### 3) Proposals: create → discuss → vote → execute + +A common DAO flow looks like this: + +1. **Proposal creation**: A member proposes an action (e.g., fund a project, change parameters). +2. **Discussion period**: Forum/Discord debate and refinement. +3. **Voting**: Token holders/members vote during a fixed window. +4. **Execution**: + - **On-chain execution**: Passing a proposal triggers a smart contract action automatically. + - **Off-chain execution**: The DAO decides, but a team/multisig carries out actions manually (often used early-stage). + +### 4) Treasury management (multisig vs. fully autonomous) + +Many DAOs start with **multisig wallets** for safety and later move to more autonomous systems (e.g., timelocks + governance execution). A typical setup includes: + +- **Treasury wallet** holding assets (native tokens, ERC-20s, NFTs) +- **Timelock** to delay execution, giving members time to react to malicious proposals +- **Guardrails** such as spending limits, whitelists, or emergency pause mechanisms + +### 5) Security and governance risks + +DAOs are powerful but introduce risks: + +- **Smart contract bugs**: can lead to treasury loss or governance takeover +- **Governance attacks**: buying/borrowing tokens to pass harmful proposals +- **Low participation**: small groups can dominate decisions +- **Operational risk**: off-chain execution relies on trusted parties + +Best practices include audits, timelocks, proposal thresholds, and transparent governance processes. + +## On Sei Network + +Sei Network is a high-performance Layer 1 blockchain with **EVM compatibility**, designed for fast finality and scalable execution—properties that benefit DAOs that require frequent proposals, voting, and treasury actions. + +### Why DAOs fit well on Sei + +- **Fast finality (~400ms)**: Governance actions (like casting votes or executing a passed proposal) can confirm quickly, improving user experience for time-sensitive decisions. +- **Parallelization**: Sei’s parallel execution architecture helps the network handle high throughput, which can be useful when a DAO has many members voting or when multiple DAO-related contracts are active simultaneously. +- **EVM compatibility**: Solidity-based governance and treasury contracts (common in Ethereum ecosystems) can be deployed on Sei, enabling familiar tooling and patterns for DAO development. + +### Typical DAO patterns on Sei + +A Sei-based DAO often combines: + +- **EVM governance contracts** (proposals + voting) +- **Treasury contracts** (assets management, spending execution) +- **Timelock mechanisms** (delayed execution for safety) +- **Delegation** (members delegate votes to trusted representatives) + +## Example: Minimal governance-style contract (Solidity) + +Below is a simplified example showing core DAO concepts: proposals, voting, and execution. This is **not production-ready** (no quorum, no delegation, no timelock), but it illustrates how DAO logic is commonly expressed on EVM chains like Sei. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract SimpleDAO { + struct Proposal { + address target; + uint256 value; + bytes data; + string description; + uint256 votesFor; + uint256 votesAgainst; + uint64 endTime; + bool executed; + } + + mapping(address => uint256) public votingPower; // simplified: set by admin in real systems + Proposal[] public proposals; + mapping(uint256 => mapping(address => bool)) public hasVoted; + + constructor(address[] memory members, uint256[] memory power) { + require(members.length == power.length, "len mismatch"); + for (uint256 i = 0; i < members.length; i++) { + votingPower[members[i]] = power[i]; + } + } + + function propose( + address target, + uint256 value, + bytes calldata data, + string calldata description, + uint64 votingPeriodSeconds + ) external returns (uint256 id) { + require(votingPower[msg.sender] > 0, "not a member"); + proposals.push(Proposal({ + target: target, + value: value, + data: data, + description: description, + votesFor: 0, + votesAgainst: 0, + endTime: uint64(block.timestamp) + votingPeriodSeconds, + executed: false + })); + return proposals.length - 1; + } + + function vote(uint256 id, bool support) external { + Proposal storage p = proposals[id]; + require(block.timestamp < p.endTime, "voting ended"); + require(!hasVoted[id][msg.sender], "already voted"); + uint256 power = votingPower[msg.sender]; + require(power > 0, "no voting power"); + + hasVoted[id][msg.sender] = true; + if (support) p.votesFor += power; + else p.votesAgainst += power; + } + + function execute(uint256 id) external { + Proposal storage p = proposals[id]; + require(block.timestamp >= p.endTime, "voting active"); + require(!p.executed, "already executed"); + require(p.votesFor > p.votesAgainst, "did not pass"); + + p.executed = true; + (bool ok,) = p.target.call{value: p.value}(p.data); + require(ok, "call failed"); + } + + receive() external payable {} +} +``` + +## Example: Deploying to Sei (EVM) with Foundry + +Use the Sei EVM RPC endpoint for your environment (testnet/mainnet) and a funded private key. + +```bash +# Set environment variables +export RPC_URL="https://" +export PRIVATE_KEY="" + +# Deploy (example) +forge create --rpc-url "$RPC_URL" \ + --private-key "$PRIVATE_KEY" \ + src/SimpleDAO.sol:SimpleDAO \ + --constructor-args "[]" "[]" +``` + +## Key Takeaways + +- **What is DAOs**: DAOs are decentralized organizations that use smart contracts and community voting to manage decisions and assets transparently. +- DAOs work through **proposals, voting, and execution**, often backed by a treasury and safety mechanisms like timelocks. +- On **Sei Network**, DAOs can leverage **EVM compatibility**, **parallelized execution**, and **~400ms finality** to deliver fast, scalable governance experiences. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-flash-loan-and-how-does-it-work.mdx b/content/answers/what-is-a-flash-loan-and-how-does-it-work.mdx new file mode 100644 index 00000000..20f85e38 --- /dev/null +++ b/content/answers/what-is-a-flash-loan-and-how-does-it-work.mdx @@ -0,0 +1,147 @@ +--- +title: 'What is a Flash Loan and How Does It Work?' +description: 'Learn about what is flash loan and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'flash', 'loan', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Flash Loan and How Does It Work? + +## Overview + +A **flash loan** is a type of **uncollateralized loan** in DeFi that must be **borrowed and repaid within the same blockchain transaction**. If repayment (plus any fee) doesn’t happen by the end of that transaction, the entire transaction **reverts**, as if it never occurred. + +In simple terms, flash loans let users temporarily access large amounts of liquidity for a single atomic operation, enabling strategies like arbitrage, refinancing, or collateral swaps—without needing upfront capital. + +## How It Works + +Flash loans rely on a core blockchain property: **atomicity**. A transaction either completes fully or fails fully. Flash loan providers (typically lending protocols) enforce repayment with a rule like: “After your actions, the protocol must end this transaction with at least the amount it started with (plus fee).” + +### Key Components + +- **Liquidity Pool / Lender Contract**: Holds funds that can be borrowed. +- **Borrower Contract**: Receives the loan and executes logic (arbitrage, swaps, repayments, etc.). +- **Callback / Execution Hook**: The lender calls the borrower back to run logic with the borrowed funds. +- **Repayment Check**: At the end of the transaction, the lender verifies funds were returned. + +### Typical Flow + +1. **Request loan** from a flash loan provider for an amount of token X. +2. Provider **transfers tokens** to your contract. +3. Provider invokes a **callback function** (e.g., `executeOperation`) where you run your logic: + - Arbitrage across DEXes + - Swap collateral types + - Repay and re-borrow to refinance +4. Your contract **repays** the principal + fee back to the lender. +5. If repayment conditions aren’t met, the transaction **reverts**. + +### Common Use Cases + +- **Arbitrage**: Exploit price differences across DEXes within one transaction. +- **Collateral swap / debt refinance**: Repay a position in one protocol and open a new one elsewhere. +- **Liquidations**: Borrow funds to liquidate an undercollateralized position and repay within the same transaction. + +### Risks and Considerations + +- **Not “free money”**: Profits must exceed fees + gas costs, and execution must succeed. +- **MEV and front-running**: Other actors can reorder or copy profitable trades. +- **Smart contract risk**: Bugs in borrower or integrations can cause reverts or losses (e.g., if funds are not repaid). +- **Market slippage**: Price impact can erase expected profit. + +## On Sei Network + +On **Sei Network**, flash loan-style strategies benefit from Sei’s performance characteristics, especially: + +- **Fast finality (~400ms)**, which can reduce execution uncertainty for time-sensitive arbitrage and refinancing flows. +- **Parallelization**, enabling higher throughput and more concurrent activity—important for active DeFi markets and rapid price discovery. +- **EVM compatibility**, allowing Solidity-based flash loan patterns and tooling familiar from Ethereum to be used on Sei. + +While the _concept_ of “what is flash loan” is the same across chains, Sei’s fast finality and high-performance design can make certain transaction-bound strategies (like arbitrage across AMMs or rapid refinancing) more practical—provided liquidity protocols on Sei expose flash loan interfaces. + +### Solidity: Minimal Flash Loan Pattern (Conceptual) + +Below is a simplified example showing the common structure: a borrower requests a flash loan, receives funds, executes logic, and repays before the transaction ends. (Exact interfaces vary by protocol.) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function balanceOf(address) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function transfer(address to, uint256 amount) external returns (bool); +} + +interface IFlashLender { + function flashLoan( + address receiver, + address token, + uint256 amount, + bytes calldata data + ) external; +} + +contract FlashBorrower { + address public lender; + + constructor(address _lender) { + lender = _lender; + } + + /// @notice Initiates the flash loan. + function startFlashLoan(address token, uint256 amount, bytes calldata data) external { + IFlashLender(lender).flashLoan(address(this), token, amount, data); + } + + /// @notice Callback invoked by the lender within the same transaction. + /// The lender expects `amount + fee` to be returned by the end of this call/tx. + function onFlashLoan( + address token, + uint256 amount, + uint256 fee, + bytes calldata data + ) external returns (bytes32) { + require(msg.sender == lender, "unauthorized"); + + // 1) Use the borrowed funds (arbitrage, collateral swap, liquidation, etc.) + _executeStrategy(token, amount, data); + + // 2) Repay principal + fee before transaction ends + uint256 repayment = amount + fee; + IERC20(token).transfer(lender, repayment); + + // Return value depends on the lender standard; shown as a placeholder + return keccak256("FLASH_LOAN_SUCCESS"); + } + + function _executeStrategy(address token, uint256 amount, bytes calldata data) internal { + // Implement your strategy: + // - swap token on DEX A + // - swap back on DEX B + // - ensure final balance covers repayment + profit + } +} +``` + +### Tips for Deploying Flash Loan Strategies on Sei (EVM) + +- Use standard **EVM tooling** (Foundry/Hardhat) and Sei’s EVM RPC endpoints. +- Model **gas and slippage** carefully; profitability depends on execution costs and pool depth. +- Add protections against **reentrancy**, unexpected callbacks, and unfavorable price movement. +- Consider MEV-aware execution (private relays/bundling, where available) for competitive arbitrage. + +## Summary + +A flash loan is an uncollateralized DeFi loan that must be borrowed and repaid within a single atomic transaction, reverting if repayment fails. In general blockchain contexts, flash loans are enabled by transaction atomicity and are used for arbitrage, refinancing, collateral swaps, and liquidations. On Sei Network, the same pattern applies with added advantages from **EVM compatibility**, **parallelization**, and **~400ms finality**, which can make transaction-bound DeFi strategies more responsive and efficient. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-gas-optimization-and-how-does-it-work.mdx b/content/answers/what-is-a-gas-optimization-and-how-does-it-work.mdx new file mode 100644 index 00000000..cfaaf0d6 --- /dev/null +++ b/content/answers/what-is-a-gas-optimization-and-how-does-it-work.mdx @@ -0,0 +1,198 @@ +--- +title: 'What is a Gas Optimization and How Does It Work?' +description: 'Learn about what is gas optimization and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'gas', 'optimization', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Gas Optimization and How Does It Work? + +## Overview + +Gas optimization is the practice of reducing the amount of **gas** (transaction execution cost) required to run operations on a blockchain, typically by making smart contracts and transactions more efficient. In practical terms, it lowers fees for users, increases throughput, and can reduce the likelihood of transactions failing due to running out of gas. If you’re asking **what is gas optimization**, it’s essentially “writing and executing blockchain code in a way that does the same work with fewer computational steps and less storage usage.” + +## How It Works + +### Gas basics (why costs exist) + +Most smart contract platforms meter computation to prevent spam and allocate scarce resources fairly. Each operation (e.g., arithmetic, memory expansion, storage reads/writes, logs) consumes gas. The sender sets a gas limit and (depending on the network) pays fees based on gas used and prevailing pricing rules. + +Key drivers of gas cost on EVM-style chains: + +- **Storage writes are expensive**: Writing to contract storage (`SSTORE`) costs far more than memory ops because it changes the persistent state that every full node must keep. +- **Storage reads are also significant**: `SLOAD` has a notable cost, especially compared to stack/memory operations. +- **Calldata and logs cost gas**: Larger inputs and many events increase gas usage. +- **Complex control flow and loops**: More executed opcodes means more gas. + +### Common gas optimization techniques + +Below are widely used approaches in Solidity/EVM development: + +#### 1) Minimize storage writes and reads + +- Cache storage values in memory for repeated use within a function. +- Batch updates instead of writing repeatedly. +- Prefer emitting events for “history” over storing large arrays when feasible. + +```solidity +// Before: repeated SLOADs +function incrementMany(uint256 n) external { + for (uint256 i = 0; i < n; i++) { + counter += 1; + } +} + +// After: cache in memory, write once +function incrementMany(uint256 n) external { + uint256 c = counter; + for (uint256 i = 0; i < n; i++) { + unchecked { c += 1; } + } + counter = c; // single SSTORE +} +``` + +#### 2) Use appropriate data types and packing + +- Pack multiple smaller variables into a single 32-byte storage slot when possible (e.g., `uint128`, `uint64`, `bool`), and order them to pack efficiently. + +```solidity +// Efficient packing (fits in one slot if ordered correctly) +struct Position { + uint128 size; + uint64 entryPrice; + bool isLong; + // 7 bytes padding (still within a single 32-byte slot overall) +} +``` + +#### 3) Prefer `calldata` for external read-only inputs + +For external functions, `calldata` avoids copying into memory. + +```solidity +function setList(address[] calldata addrs) external { + // iterate over calldata without copying to memory +} +``` + +#### 4) Avoid unnecessary work in loops + +- Reduce loop iterations. +- Use mappings instead of arrays for membership tests. +- Precompute constants and reuse computed values. + +#### 5) Use `unchecked` for safe arithmetic in controlled cases + +Solidity 0.8+ adds overflow checks. If you can prove safety (e.g., loop counters), `unchecked` saves gas. + +```solidity +for (uint256 i = 0; i < n; ) { + // ... + unchecked { ++i; } +} +``` + +#### 6) Custom errors instead of revert strings + +Custom errors reduce deployment and revert costs. + +```solidity +error NotAuthorized(); + +function adminOnly() external { + if (msg.sender != owner) revert NotAuthorized(); +} +``` + +#### 7) Be mindful of events and revert data + +Events are cheaper than storage for logging, but still cost gas. Large revert strings and excessive event data increase costs. + +### Measuring gas usage + +Gas optimization should be evidence-based. Typical workflows: + +- Use a local test runner to compare gas before/after changes. +- Benchmark hot paths (functions called frequently). +- Ensure changes do not sacrifice correctness or security. + +Example with Foundry: + +```bash +forge test --gas-report +``` + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, enabling Solidity developers to apply the same gas optimization principles used on Ethereum-like environments. Gas optimization on Sei matters because: + +- **Lower gas usage reduces fees** for users and improves UX for high-frequency applications (e.g., trading, games, consumer apps). +- Sei’s **parallelization** can execute many transactions concurrently when they don’t contend for the same state, improving throughput; optimized contracts that reduce unnecessary state contention can benefit more from parallel execution. +- Sei’s fast time-to-finality (often cited around **~400ms finality**) means well-optimized transactions can contribute to smoother real-time interactions—especially for apps that submit transactions frequently. + +### Practical considerations for Sei EVM developers + +1. **Reduce shared-state contention** + Parallel execution is most effective when transactions touch different parts of state. Design patterns that help: + +- Favor per-user storage (e.g., `mapping(address => ...)`) over globally updated counters or arrays. +- Batch operations in ways that avoid repeatedly writing to the same global variables. +- Use events for analytics rather than updating global aggregates on-chain. + +2. **Optimize the “hot path”** + On high-throughput chains, small savings per call can compound. Focus on: + +- Core trading/order functions +- Token transfers/settlements +- Repeated actions in games and social apps + +3. **Keep deployment size in check** + Contract size impacts deployment cost and sometimes call overhead. Use libraries carefully, remove unused code, and prefer simpler patterns where possible. + +### Example: Cache storage and reduce contention + +Instead of incrementing a single global value (high contention), consider per-user stats: + +```solidity +mapping(address => uint256) public userPoints; + +function addPoints(uint256 points) external { + // Mostly isolated per user, improving parallelizability + userPoints[msg.sender] += points; +} +``` + +### Tooling example: estimating gas with ethers.js + +You can estimate gas for a transaction on Sei EVM similarly to other EVM chains: + +```typescript +import { ethers } from 'ethers'; + +const provider = new ethers.JsonRpcProvider(process.env.SEI_EVM_RPC_URL); +const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + +const contract = new ethers.Contract('0xYourContract', ['function addPoints(uint256 points)'], wallet); + +const gas = await contract.addPoints.estimateGas(123n); +console.log('Estimated gas:', gas.toString()); +``` + +## Key Takeaways + +- **What is gas optimization?** It’s reducing the computational and storage cost of transactions and smart contract execution while preserving correct behavior. +- The biggest wins usually come from **minimizing storage writes**, **reducing redundant reads**, **efficient data packing**, and **simplifying hot paths**. +- On **Sei Network**, gas optimization complements Sei’s **EVM compatibility** and can pair well with Sei’s **parallel execution** and fast finality to deliver lower fees and more responsive applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-gas-war-and-how-does-it-work.mdx b/content/answers/what-is-a-gas-war-and-how-does-it-work.mdx new file mode 100644 index 00000000..31bb17c3 --- /dev/null +++ b/content/answers/what-is-a-gas-war-and-how-does-it-work.mdx @@ -0,0 +1,131 @@ +--- +title: 'What is a Gas War and How Does It Work?' +description: 'Learn about what is gas war and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'gas', 'war', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Gas War and How Does It Work? + +## Overview + +A **gas war** is a situation where multiple blockchain users compete to get their transactions included first by **bidding up the gas price** (the fee offered to validators/miners). In practice, this causes transaction fees to spike rapidly, and many participants overpay or fail while trying to “outbid” each other. + +In other words, if you’re searching **what is gas war**, it’s the fee-based competition for limited blockspace—often triggered by highly sought-after events like NFT mints, liquidations, arbitrage, or token launches. + +## How It Works + +### 1) Transactions compete for limited blockspace + +Most blockchains have a limited amount of computation and data they can include per block. When demand exceeds capacity, validators prioritize transactions that pay higher fees. + +### 2) Users “bid” via gas price / fee parameters + +Depending on the network’s fee model, users set: + +- **Gas limit**: maximum units of gas the transaction can consume +- **Gas price** or **fee cap / priority tip**: how much they’re willing to pay per unit of gas + +Validators generally choose transactions that maximize fee revenue (or meet other local policies), which creates an incentive to increase the offered fee during congestion. + +### 3) Feedback loop: the “war” + +As users observe delayed or failed transactions, they submit replacements with higher fees (or use wallet “speed up” features). Bots do this automatically. The result is a rapid escalation in fees. + +### 4) Common triggers + +Gas wars often occur around: + +- **NFT mints** with limited supply +- **DEX arbitrage** opportunities +- **Liquidations** on lending protocols +- **Airdrop claims** or “first come, first served” launches +- **MEV (Maximal Extractable Value)** opportunities (sandwiching, backrunning, etc.) + +### 5) Typical outcomes + +- **Fee spikes**: Users pay far more than normal. +- **Failed or reverted transactions**: If a contract reverts (e.g., mint sold out), the user still pays for gas spent on execution up to the revert point. +- **Network congestion**: Large mempools and slower inclusion for regular users. +- **MEV dominance**: Sophisticated bots often win due to better infrastructure and strategies. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, designed to reduce the user pain that commonly accompanies congestion events. + +### Parallelization reduces contention + +On traditional single-threaded execution paths, many transactions must be processed sequentially, increasing contention during high-demand events. **Sei’s parallelization** enables higher throughput by executing non-conflicting transactions concurrently, which helps absorb spikes in activity and can reduce the intensity of fee bidding. + +### Fast finality changes the “race” dynamics + +Sei targets **~400ms finality**, meaning transactions confirm quickly once included. Faster confirmation reduces the uncertainty window where users repeatedly resubmit higher-fee transactions “just in case,” which can help dampen the escalation pattern that fuels a gas war. + +### EVM compatibility and familiar fee mechanics + +Because Sei supports EVM execution, developers and users can interact with Sei using familiar Ethereum tooling and patterns (wallets, RPC methods, Solidity contracts). While any chain can experience fee competition during extreme demand, Sei’s performance characteristics are intended to make high-traffic events smoother for end users. + +## Example: How “Bidding Up” Fees Happens (EVM-style) + +Below is a simplified example using `ethers` where a user increases fee parameters to get included sooner (a common behavior during a gas war). Exact fields depend on the chain’s transaction type and fee model, but the pattern is the same: **raise the fee cap and/or tip**. + +```typescript +import { ethers } from 'ethers'; + +const provider = new ethers.JsonRpcProvider(process.env.RPC_URL); +const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + +async function sendWithHigherFees(to: string, data: string) { + // Base estimate + const feeData = await provider.getFeeData(); + + // "Bid up" by increasing maxFeePerGas and maxPriorityFeePerGas + const maxFeePerGas = ((feeData.maxFeePerGas ?? 0n) * 12n) / 10n; // +20% + const maxPriorityFeePerGas = ((feeData.maxPriorityFeePerGas ?? 0n) * 15n) / 10n; // +50% + + const tx = await wallet.sendTransaction({ + to, + data, + // Gas limit should be estimated; simplified here: + gasLimit: 300000n, + maxFeePerGas, + maxPriorityFeePerGas + }); + + console.log('tx hash:', tx.hash); + await tx.wait(); + console.log('confirmed'); +} +``` + +## Why Gas Wars Matter (User and Developer Impact) + +- **Users**: risk overpaying fees, getting stuck pending, or paying gas on reverted transactions. +- **Developers**: launches can become inaccessible to normal users; bots dominate; user experience suffers. +- **Protocols**: higher MEV extraction and volatility around critical events. + +## Common Mitigations + +While not always avoidable, gas wars can be reduced with design choices such as: + +- **Allowlists / presales** to spread demand over time +- **Commit-reveal schemes** to reduce last-second bidding +- **Auctions** (price discovery) instead of first-come-first-served mints +- **Rate limits / per-wallet caps** to reduce bot-driven spam +- **MEV-aware designs** (e.g., batch auctions, fair ordering policies) + +## Summary + +A gas war is a competitive fee-bidding event where users raise gas prices to get priority inclusion during congestion. It emerges from limited blockspace, high-demand moments, and automated strategies like MEV. On Sei Network, **parallel execution**, **~400ms finality**, and **EVM compatibility** help make high-traffic periods more efficient and reduce the conditions that commonly intensify gas wars. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-genesis-block-and-how-does-it-work.mdx b/content/answers/what-is-a-genesis-block-and-how-does-it-work.mdx new file mode 100644 index 00000000..a3e424eb --- /dev/null +++ b/content/answers/what-is-a-genesis-block-and-how-does-it-work.mdx @@ -0,0 +1,119 @@ +--- +title: 'What is a Genesis Block and How Does It Work?' +description: 'Learn about what is genesis block and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'genesis', 'block', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Genesis Block and How Does It Work? + +## Overview + +A **genesis block** is the **first block** in a blockchain and serves as the starting point for the network’s entire transaction history. It is typically **hardcoded or created at chain launch** and establishes the initial state (such as initial balances, parameters, and validator set) that every node agrees on. + +In other words, when someone asks **“what is genesis block”**, the answer is: it’s the foundational block that anchors the chain’s identity and defines the initial conditions from which all subsequent blocks are built. + +## How It Works + +### 1) The genesis block defines the initial state + +Before a blockchain can produce blocks, nodes must agree on a shared “starting snapshot.” The genesis block (or genesis configuration that produces it) sets: + +- **Chain identity** (e.g., chain ID / network ID) +- **Consensus parameters** (block times, validator rules, slashing settings, etc.) +- **Initial accounts and balances** (pre-mined allocations, foundation/community funds) +- **Initial validator set** (for Proof-of-Stake networks) +- **System modules / protocol settings** (staking, governance, fee parameters) + +This ensures that independent nodes starting from scratch can reproduce the same initial state deterministically. + +### 2) It’s typically not “mined” like later blocks + +Many networks treat the genesis block as a **special case**: + +- It may not contain normal transactions. +- It may have a fixed height (usually **height 0** or **height 1**, depending on the implementation). +- Its hash and contents are often **known in advance** and shipped as part of node software or configuration. + +### 3) It anchors chain security and verification + +A node syncing a blockchain relies on: + +- The **genesis state** to initialize its local database. +- Subsequent blocks being validated against consensus rules that the genesis block established. + +If two nodes use different genesis configurations (even slightly), they will compute different state roots and effectively be on **different networks** (a “different chain”). + +### 4) Genesis vs. forks and restarts + +- A **hard fork** usually updates protocol rules while preserving history (same genesis). +- A **new chain / restart** often creates a **new genesis** (new chain ID and initial state), even if it shares code or community. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **parallelized execution**, **fast finality (~400ms)**, and **EVM compatibility**. On Sei, the genesis block plays the same foundational role—defining the initial state and parameters—but it also matters specifically for: + +- **Chain identity for EVM and Cosmos layers**: Sei runs a Cosmos SDK-based chain with EVM compatibility, and the genesis configuration sets the chain ID and module parameters that clients and tooling (including EVM tooling) rely on. +- **Validator set and staking parameters**: As a Proof-of-Stake network, Sei’s genesis establishes the initial validator set and staking/governance configuration that enables secure block production from the first moment. +- **Deterministic startup for high-throughput execution**: Sei’s parallelization and rapid finality depend on nodes starting from an identical genesis state so that transaction execution and state transitions remain consistent across all participants. + +Practically, if you deploy infrastructure or build on Sei, you must ensure your node and tooling reference the **correct genesis file** for the intended network (e.g., mainnet vs testnet), because the genesis determines the chain you are connecting to. + +## Common Properties of a Genesis Block + +- **No parent block**: It has no previous hash to reference. +- **Fixed height**: The first height in the chain’s history. +- **Network-defining**: Changing genesis parameters produces a different network. +- **Often includes initial allocations**: Establishes initial token distribution and module state. + +## How to Inspect a Chain’s Genesis (Examples) + +### Using a Cosmos SDK-style node CLI (common for Sei-based networks) + +If you run a node locally, you can typically view the genesis file like this: + +```bash +# Path may vary by installation; commonly under a node's home directory +cat ~/.seid/config/genesis.json | head +``` + +To search for key sections: + +```bash +cat ~/.seid/config/genesis.json | jq '.chain_id' +cat ~/.seid/config/genesis.json | jq '.app_state.staking.params' +cat ~/.seid/config/genesis.json | jq '.app_state.bank.balances[:5]' +``` + +### Verifying you’re on the expected chain + +Chain ID is a quick sanity check that you’re using the correct genesis/network: + +```bash +seid status 2>/dev/null | jq '.NodeInfo.network' +``` + +> Note: Command names/paths can vary depending on your Sei node setup and version. The key concept is that the **genesis.json** defines the starting configuration the node uses to join a specific Sei network. + +## Why the Genesis Block Matters + +- **Consensus alignment**: All validators and full nodes must share the same genesis to agree on state and produce blocks. +- **Network separation**: Different genesis files separate mainnets, testnets, and private networks. +- **Protocol initialization**: Governance, staking, and system modules can only operate correctly if their initial parameters are set at genesis. +- **Trust and transparency**: Public networks often publish the genesis so anyone can independently verify the network’s initial conditions. + +## Summary + +A genesis block is the first block (or initial state configuration) that bootstraps a blockchain, defining critical parameters like chain identity, consensus rules, and starting balances. In Sei Network, the genesis is especially important because it underpins a fast-finality (~400ms), parallelized Layer 1 with EVM compatibility—ensuring every node starts from the same state and can validate and execute blocks consistently. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-governance-proposal-and-how-does-it-work.mdx b/content/answers/what-is-a-governance-proposal-and-how-does-it-work.mdx new file mode 100644 index 00000000..e6e6c8e7 --- /dev/null +++ b/content/answers/what-is-a-governance-proposal-and-how-does-it-work.mdx @@ -0,0 +1,133 @@ +--- +title: 'What is a Governance Proposal and How Does It Work?' +description: 'Learn about what is governance proposal and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'governance', 'proposal', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Governance Proposal and How Does It Work? + +## Overview + +A **governance proposal** is a formal on-chain request to change how a blockchain network operates—such as upgrading software, adjusting parameters, spending community funds, or managing access/permissions. In short, **what is governance proposal** usually refers to the mechanism token holders (or their delegates) use to coordinate changes transparently, with rules enforced by the blockchain itself. + +## How It Works + +Most blockchain governance systems follow a common lifecycle: + +### 1) Proposal Creation + +A proposer drafts a proposal with: + +- A **title/summary** and detailed description +- The **type** of change (e.g., parameter change, software upgrade, community spend) +- Any required **payload** (e.g., new parameter values, upgrade height, recipient addresses) +- A **deposit** (in many PoS systems) to prevent spam and ensure seriousness + +If the proposal meets minimum requirements (including deposit thresholds), it enters an official voting period. + +### 2) Voting Period + +Eligible voters (often token holders) can vote directly or via **delegation** to validators or representatives. Common vote options include: + +- **Yes** +- **No** +- **NoWithVeto** (signals the proposal is harmful/spam; may slash deposit depending on chain rules) +- **Abstain** + +Governance rules typically define: + +- **Quorum**: minimum participation required +- **Threshold**: minimum “Yes” ratio to pass +- **Veto**: maximum allowed “NoWithVeto” before automatically failing + +### 3) Tallying & Outcome + +At the end of voting, the chain tallies votes according to its rules. If the proposal passes, it moves to execution. + +### 4) Execution / Enactment + +Execution depends on proposal type: + +- **Parameter changes** may be applied automatically. +- **Community spend** may transfer funds from a community pool. +- **Software upgrades** may schedule an upgrade height/time (validators coordinate to run the new binary). +- Some systems require off-chain steps (e.g., validators upgrading nodes) even if the decision is on-chain. + +## Common Types of Governance Proposals + +- **Protocol upgrades**: adopt new consensus or application logic +- **Parameter changes**: adjust fees, staking params, gas settings, limits +- **Treasury/community spend**: fund development, grants, ecosystem initiatives +- **Text proposals** (in some ecosystems): signaling/community coordination without automatic execution +- **Permissioning/whitelisting** (chain-dependent): manage access to specific modules or features + +## Why Governance Proposals Matter + +Governance proposals provide a structured way to: + +- Evolve protocol rules without centralized control +- Increase transparency (all votes and outcomes are auditable) +- Align incentives between validators, token holders, builders, and users +- Reduce forks by giving stakeholders a standard decision process + +## On Sei Network + +Sei Network uses on-chain governance to coordinate upgrades and parameter changes in a way that matches Sei’s design goals: **high throughput, parallelized execution, and fast finality (~400ms)**. Once a governance proposal is submitted and enters voting, stakeholders can vote on-chain; when it passes, the network can enact changes in a predictable, transparent manner. + +Key ways governance proposals relate to Sei: + +- **Fast finality improves governance UX**: transactions for voting and proposal interactions confirm quickly, making participation more responsive during active voting windows. +- **Parallelization supports scale**: as network usage grows, Sei’s parallelized execution helps governance interactions (proposal submissions, vote transactions) remain efficient alongside normal app traffic. +- **EVM compatibility**: Sei’s EVM support enables governance-related tooling and integrations familiar to Ethereum developers (e.g., indexers, analytics, wallets), while core chain governance remains on-chain and auditable. + +> Note: The exact governance parameters (deposit amount, quorum, thresholds, voting period) are chain-configurable and may change over time via governance itself. + +## Practical Examples + +### Check proposals and vote via CLI (Cosmos SDK-style) + +If you’re using Sei’s CLI tooling, governance flows typically look like: + +```bash +# List proposals +seid query gov proposals + +# Get details for a specific proposal +seid query gov proposal + +# Vote on a proposal (example: "yes") +seid tx gov vote yes \ + --from \ + --chain-id \ + --fees +``` + +### Query governance state from an app (TypeScript example) + +Many apps query governance via RPC/REST endpoints exposed by full nodes (exact endpoints depend on your stack and provider). Conceptually: + +```typescript +// Pseudocode: fetch proposal details from a REST endpoint +const proposalId = 42; +const res = await fetch(`https:///cosmos/gov/v1/proposals/${proposalId}`); +const proposal = await res.json(); + +console.log(proposal); +``` + +## Summary + +A governance proposal is the on-chain process for proposing, voting on, and enacting changes to a blockchain network. In general, it moves through creation, voting, tallying, and execution under predefined rules like quorum and thresholds. On Sei Network, governance proposals benefit from Sei’s fast finality and scalable, parallelized design—supporting efficient participation and reliable network evolution as the ecosystem grows. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-governance-token-and-how-does-it-work.mdx b/content/answers/what-is-a-governance-token-and-how-does-it-work.mdx new file mode 100644 index 00000000..f8005ef4 --- /dev/null +++ b/content/answers/what-is-a-governance-token-and-how-does-it-work.mdx @@ -0,0 +1,164 @@ +--- +title: 'What is a Governance Token and How Does It Work?' +description: 'Learn about what is governance token and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'governance', 'token', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Governance Token and How Does It Work? + +## Overview + +A **governance token** is a cryptocurrency that gives holders the ability to participate in the decision-making process of a blockchain protocol, dApp, or DAO (Decentralized Autonomous Organization). In practice, it’s used to **vote on proposals** that can change parameters, allocate treasury funds, upgrade smart contracts, or shape long-term strategy. + +If you’re searching **what is governance token**, the key idea is: it’s a token that represents **governance power**—often proportional to how many tokens you hold or lock—rather than just a medium of exchange. + +## How It Works + +### Governance rights and voting power + +Governance tokens typically confer: + +- **Voting rights** on proposals (e.g., parameter changes, upgrades, grants) +- **Proposal creation rights** (often requiring a minimum threshold of tokens) +- **Delegation** (holders can delegate voting power to representatives) + +Voting power is commonly determined by: + +- **Token balance** (1 token = 1 vote), or +- **Locked/staked tokens** (time-locked tokens can have higher influence), or +- **Quadratic or reputation-based systems** (less common, but used to reduce whale dominance) + +### Proposal lifecycle (typical flow) + +1. **Discussion**: Idea is debated in forums/Discord/governance platforms. +2. **Proposal submission**: A proposal is formally created, sometimes requiring a deposit. +3. **Voting period**: Token holders vote _For/Against/Abstain_ (or more granular options). +4. **Quorum + threshold**: Proposal passes only if enough votes participate (quorum) and meets pass criteria (threshold). +5. **Execution**: + - **On-chain execution**: Smart contracts automatically execute the approved changes. + - **Off-chain execution**: The result guides humans/multisigs (less trust-minimized). + +### On-chain vs. off-chain governance + +- **On-chain governance**: Voting and execution happen on-chain via smart contracts; transparent and enforceable. +- **Off-chain governance**: Voting might happen on Snapshot or forums; execution is manual or controlled by a multisig. + +### Common uses of governance tokens + +- **Protocol upgrades** (new features, bug fixes, contract migrations) +- **Treasury management** (funding grants, liquidity incentives) +- **Economic parameters** (fees, collateral factors, staking rewards) +- **Validator / network settings** (in PoS systems, governance can adjust consensus parameters) + +### Benefits and risks + +**Benefits** + +- Aligns protocol direction with stakeholders +- Decentralizes control over upgrades and funds +- Encourages community participation and long-term ownership + +**Risks** + +- **Whale capture**: Large holders can dominate outcomes +- **Low voter turnout**: A small minority may decide critical changes +- **Governance attacks**: Borrowed tokens (if not mitigated) can influence votes +- **Coordination overhead**: Complex proposals can be slow to finalize + +## On Sei Network + +Sei Network is a high-performance Layer 1 designed for fast, scalable applications and supports **EVM compatibility**, enabling Ethereum-style governance contracts to run in a familiar environment. Governance activity benefits from Sei’s performance characteristics, including **parallelized execution** and **~400ms finality**, which can make proposal interactions (creating proposals, casting votes, executing decisions) feel significantly more responsive than on slower chains. + +### Governance token patterns you’ll see on Sei + +Projects on Sei commonly implement governance using EVM-native patterns such as: + +- **Token-based voting** (ERC-20 governance tokens) +- **Delegation** (delegate votes without transferring tokens) +- **Timelocks** for execution (delays between passing and executing proposals to increase safety) +- **Governor contracts** (OpenZeppelin Governor framework) + +Because Sei is EVM compatible, teams can deploy widely used governance stacks with minimal changes, while users benefit from faster confirmations and improved UX during voting windows and execution steps. + +### Example: EVM governance token interface (Solidity) + +Below is a simplified interface-style example of a governance token with delegation. Many projects use OpenZeppelin’s `ERC20Votes` under the hood. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IGovernanceToken { + function delegate(address delegatee) external; + function getVotes(address account) external view returns (uint256); + function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); +} +``` + +### Example: Creating and voting on proposals (Solidity, Governor pattern) + +Many DAOs use an on-chain Governor contract (e.g., OpenZeppelin). The exact implementation varies, but the core methods look like this: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IGovernor { + function propose( + address[] memory targets, + uint256[] memory values, + bytes[] memory calldatas, + string memory description + ) external returns (uint256 proposalId); + + function castVote(uint256 proposalId, uint8 support) external returns (uint256); + // support: 0 = Against, 1 = For, 2 = Abstain +} +``` + +### Example: Interacting from TypeScript (ethers.js) + +Using Sei’s EVM RPC endpoint, you can interact with governance contracts like on any EVM chain. + +```typescript +import { ethers } from 'ethers'; + +const rpcUrl = process.env.SEI_EVM_RPC!; +const provider = new ethers.JsonRpcProvider(rpcUrl); + +const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + +// Example: governance token delegation +const tokenAddress = '0xYourGovernanceToken'; +const tokenAbi = ['function delegate(address delegatee) external', 'function getVotes(address account) view returns (uint256)']; + +const token = new ethers.Contract(tokenAddress, tokenAbi, wallet); + +async function delegateVotes(delegatee: string) { + const tx = await token.delegate(delegatee); + await tx.wait(); + const votes = await token.getVotes(await wallet.getAddress()); + console.log('Current votes:', votes.toString()); +} + +delegateVotes('0xDelegateeAddress'); +``` + +## Key Takeaways + +- A governance token is a token that grants **voting and proposal influence** over a protocol or DAO. +- Governance typically involves **proposal submission → voting → quorum/threshold checks → execution**, ideally on-chain. +- On Sei Network, governance token systems can leverage **EVM compatibility** and benefit from **parallelization** and **~400ms finality**, improving the speed and user experience of governance interactions. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-hard-fork-and-how-does-it-work.mdx b/content/answers/what-is-a-hard-fork-and-how-does-it-work.mdx new file mode 100644 index 00000000..62fc57dd --- /dev/null +++ b/content/answers/what-is-a-hard-fork-and-how-does-it-work.mdx @@ -0,0 +1,109 @@ +--- +title: 'What is a Hard Fork and How Does It Work?' +description: 'Learn about what is hard fork and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'hard', 'fork', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Hard Fork and How Does It Work? + +## Overview + +A **hard fork** is a backward-incompatible change to a blockchain’s protocol rules that causes nodes running the old software to reject blocks produced under the new rules. In practice, this can **split the network into two chains** if some participants upgrade and others do not. If everyone upgrades, the chain continues as one with the new rules. + +## How It Works + +In a blockchain, nodes validate blocks using a shared set of consensus rules (e.g., transaction formats, gas rules, signature schemes, block limits). A hard fork changes those rules in a way that **older clients cannot validate**. + +### 1) Rule change and activation + +A hard fork is typically implemented as a protocol upgrade with an agreed activation mechanism, such as: + +- **Block height activation:** new rules start at a specific block number. +- **Time-based activation:** new rules start after a specific timestamp. +- **Governance-triggered activation:** validators vote and the upgrade is enabled when conditions are met. + +### 2) Network upgrade (coordination) + +Validators, full nodes, exchanges, indexers, and wallet providers must upgrade their software to follow the new rules. If a meaningful portion does not upgrade, the network can diverge. + +### 3) Chain split (optional but possible) + +After activation: + +- **Upgraded nodes** accept blocks that follow the new rules. +- **Non-upgraded nodes** reject those blocks and continue building on the old rules. + +This results in two networks with shared history up to the fork point, but different futures. Users may end up with assets on both chains depending on how the split is handled. + +### 4) Outcomes + +Hard forks commonly happen for: + +- **Protocol improvements:** performance, scalability, fee market changes. +- **Security fixes:** patching vulnerabilities quickly. +- **Feature additions:** new opcodes, new transaction types, new cryptography. +- **Governance disagreements:** differing visions for the protocol can lead to persistent chain splits. + +### Hard Fork vs Soft Fork + +- **Hard fork:** backward-incompatible; old nodes cannot follow without upgrading. +- **Soft fork:** backward-compatible tightening of rules; old nodes can still accept new blocks (though they may not understand all details). + +## On Sei Network + +On **Sei Network**, a hard fork corresponds to a **protocol upgrade** that changes consensus or execution rules such that nodes must update to remain compatible. Because Sei is designed for high performance—leveraging **parallelization** in execution and offering **~400ms finality**—upgrades can be especially important for improving throughput, latency, and developer experience while preserving deterministic and secure state transitions. + +Key implications on Sei: + +- **Validator-led upgrades:** As a Proof-of-Stake network, validators coordinate upgrades to ensure continuity of consensus and block production. +- **Fast finality considerations:** With ~400ms finality, network coordination around the activation point is important to avoid temporary divergence and to keep applications operating smoothly. +- **EVM compatibility:** When Sei introduces EVM-related enhancements (e.g., execution changes, gas accounting adjustments, precompile updates), these may be delivered via hard forks/protocol upgrades. EVM tooling (contracts, RPC clients, indexers) may need updates alongside the chain upgrade. +- **Parallelized execution:** Upgrades may include changes that affect how transactions are scheduled or executed in parallel. This can improve performance but must remain deterministic so all nodes reach the same state. + +### What developers and operators should do + +If Sei announces a protocol upgrade (hard fork), typical best practices include: + +- Upgrade node binaries by the recommended version before the activation height. +- Monitor release notes for any EVM/RPC behavior changes that could affect dApps, indexers, and off-chain services. +- Test smart contracts and infrastructure against the upgraded network (testnet/devnet) if behavior changes are expected. + +## Example: Node Upgrade Workflow (Operator) + +Below is a typical workflow pattern for upgrading a node ahead of a hard fork (exact commands and versions depend on the release): + +```bash +# 1) Stop the node service +sudo systemctl stop seid + +# 2) Install/replace the binary with the upgraded version (example) +# (Use the official Sei release instructions for the correct artifact/version) +curl -L https://example.com/sei-release/seid -o /usr/local/bin/seid +chmod +x /usr/local/bin/seid + +# 3) Confirm version +seid version + +# 4) Restart the node service +sudo systemctl start seid + +# 5) Verify logs for successful sync and readiness before the upgrade height +journalctl -u seid -f +``` + +## Why Hard Forks Matter + +For anyone searching **“what is hard fork”**, the key takeaway is that a hard fork is how blockchains introduce major changes that require participants to upgrade. Done smoothly, it’s a coordinated protocol evolution; done with disagreement or poor coordination, it can split the chain and create two competing networks. On Sei, hard forks (protocol upgrades) are a mechanism to safely evolve a fast-finality, parallelized, EVM-compatible Layer 1 while maintaining network security and state consistency. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-hash-rate-and-how-does-it-work.mdx b/content/answers/what-is-a-hash-rate-and-how-does-it-work.mdx new file mode 100644 index 00000000..3e84b88a --- /dev/null +++ b/content/answers/what-is-a-hash-rate-and-how-does-it-work.mdx @@ -0,0 +1,101 @@ +--- +title: 'What is a Hash Rate and How Does It Work?' +description: 'Learn about what is hash rate and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'hash', 'rate', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Hash Rate and How Does It Work? + +## Overview + +Hash rate is a measure of how much computational work a blockchain network (or a single miner/validator) can perform per second to compute cryptographic hashes. In simple terms, it describes how quickly machines can attempt to solve the hashing “puzzle” required by Proof-of-Work (PoW) systems. If you’re searching **what is hash rate**, think of it as the network’s hashing “speed” and a key indicator of PoW security and competition. + +## How It Works + +### Hashing and “Attempts per Second” + +A **hash** is the output of a cryptographic hash function (e.g., SHA-256) that deterministically maps any input into a fixed-length string. In PoW mining, participants repeatedly vary an input value (often called a _nonce_) and hash the block header until they find an output that meets the network’s difficulty target (e.g., the hash must be below a certain number). + +- Each hash computation is effectively one “attempt.” +- **Hash rate** is the number of attempts per second. + +Common units: + +- **H/s**: hashes per second +- **kH/s, MH/s, GH/s, TH/s, PH/s, EH/s**: thousand → million → billion → trillion → quadrillion → quintillion → exahashes per second + +### Network Hash Rate vs. Miner Hash Rate + +- **Miner hash rate**: the hashing power contributed by one device, miner, or pool. +- **Network hash rate**: the combined hash rate of all miners participating in the PoW network. + +### Difficulty and Block Production + +PoW networks adjust **difficulty** so that blocks are produced at a stable average interval (e.g., ~10 minutes on Bitcoin). When total hash rate increases, blocks would be found faster _unless_ the network increases difficulty; when hash rate drops, difficulty may decrease so blocks don’t become too slow. + +Conceptually: + +- Higher hash rate (with constant difficulty) → blocks found faster +- Higher difficulty (with constant hash rate) → blocks found slower + +### Why Hash Rate Matters + +In PoW, hash rate is closely tied to: + +- **Security**: More total hash rate generally makes it harder to attack the chain (e.g., a “51% attack” requires enormous compute). +- **Decentralization/Competition**: Hash rate distribution across miners/pools affects how concentrated mining power is. +- **Energy/Cost**: Mining resources scale with hash rate (hardware and electricity). + +### Simple Mining Pseudocode (Conceptual) + +```typescript +// Conceptual PoW mining loop (not production code) +while (true) { + const nonce = randomNonce(); + const hash = sha256(blockHeader + nonce); + + if (hash < targetDifficulty) { + // Found a valid block + submitBlock(blockHeader, nonce); + break; + } +} +// Hash rate ≈ how many iterations (hash attempts) you can do per second +``` + +## On Sei Network + +Sei Network is a high-performance Layer 1 blockchain with **~400ms finality**, **parallelization**, and **EVM compatibility**, but it is **not a Proof-of-Work chain**. That means the classic notion of “hash rate” (as used to measure PoW mining power) does **not** directly apply to Sei’s consensus security model. + +### What’s the Equivalent Concept on Sei? + +On Sei (as on other Proof-of-Stake-style systems), network security and block production depend on factors like: + +- **Staked capital** securing consensus (rather than mining hash power) +- **Validator set** participation and performance +- **Consensus finality** (Sei targets ~400ms finality), which affects how quickly transactions become irreversible + +So, if you’re evaluating Sei, you typically look at metrics such as: + +- Total stake / bonded stake (economic security) +- Validator uptime, voting power distribution, and performance +- Throughput and latency enabled by Sei’s **parallel execution** and optimized architecture +- EVM compatibility for deploying Solidity smart contracts without PoW mining + +### Takeaway + +- **Hash rate** is a PoW-specific measure of computational power used to find valid blocks. +- **Sei Network** achieves security and fast finality without PoW mining, so **hash rate is not a core network metric**; instead, stake and validator consensus drive security, while Sei’s parallelization and fast finality drive performance. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-hot-wallet-and-how-does-it-work.mdx b/content/answers/what-is-a-hot-wallet-and-how-does-it-work.mdx new file mode 100644 index 00000000..84a930e3 --- /dev/null +++ b/content/answers/what-is-a-hot-wallet-and-how-does-it-work.mdx @@ -0,0 +1,99 @@ +--- +title: 'What is a Hot Wallet and How Does It Work?' +description: 'Learn about what is hot wallet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'hot', 'wallet', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Hot Wallet and How Does It Work? + +## Overview + +A **hot wallet** is a cryptocurrency wallet that is **connected to the internet**, making it easy to send, receive, and manage digital assets quickly. In simple terms, when people ask **“what is hot wallet”**, they’re referring to a wallet designed for **convenience and frequent transactions**, typically at the cost of increased exposure to online threats compared to offline (“cold”) storage. + +Hot wallets are commonly used for day-to-day activity like swapping tokens, interacting with dApps, minting NFTs, and staking—especially on fast networks where users benefit from quick confirmations. + +## How It Works + +Hot wallets manage **private keys** (or a seed phrase that derives them) that authorize transactions on a blockchain: + +- **Key generation & storage:** When you create a hot wallet, it generates a seed phrase/private keys and stores them on an internet-connected device (phone, browser, or server). +- **Signing transactions:** To move funds, the wallet creates and **cryptographically signs** a transaction using the private key. The signed transaction is then broadcast to the network. +- **Address & balances:** The wallet shows your public address and reads balances by querying blockchain nodes or RPC endpoints—funds remain on-chain, not “inside” the wallet. +- **Security model:** Because it’s online, a hot wallet can be exposed to phishing, malware, compromised devices, malicious browser extensions, or leaked seed phrases. + +### Common Types of Hot Wallets + +- **Mobile wallets:** Apps that store keys on a smartphone. +- **Browser extension wallets:** Wallets integrated into the browser for dApp access. +- **Web wallets / hosted wallets:** Keys may be held by a service provider (custodial) or encrypted client-side (non-custodial). +- **Server wallets:** Programmatic wallets used by exchanges or apps—highly sensitive and must be secured with strong operational controls. + +### Hot Wallet vs. Cold Wallet (Quick Comparison) + +- **Hot wallet:** Best for speed and frequent use; higher online risk. +- **Cold wallet (hardware/air-gapped):** Best for long-term storage; slower but much more resistant to remote attacks. + +## On Sei Network + +Hot wallets are especially useful on **Sei Network**, a high-performance Layer 1 designed for low latency and high throughput. Sei’s features make interactive usage (trading, DeFi, gaming) smoother for hot-wallet users: + +- **Fast user experience:** Sei offers **~400ms finality**, so transactions initiated from a hot wallet can confirm quickly—ideal for active DeFi and real-time apps. +- **Parallelization:** Sei’s architecture supports **parallel execution**, improving throughput and reducing congestion—helpful when many users are signing and broadcasting transactions at the same time. +- **EVM compatibility:** Sei supports **EVM-compatible smart contracts**, so popular Ethereum-style wallets and tooling patterns can apply, and Solidity contracts behave in familiar ways. + +### Using a Hot Wallet with Sei (EVM) via JSON-RPC + +Below is an example using `ethers` to connect a hot wallet (private key) to Sei’s EVM and send a transaction. Replace the RPC URL and chain parameters with Sei’s current EVM network details from official docs. + +```typescript +import { ethers } from 'ethers'; + +// 1) Connect to Sei EVM RPC +const RPC_URL = process.env.SEI_EVM_RPC_URL!; +const provider = new ethers.JsonRpcProvider(RPC_URL); + +// 2) Load hot wallet from private key (store securely in env vars) +const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + +async function main() { + // 3) Build and send a simple native token transfer + const tx = await wallet.sendTransaction({ + to: '0xRecipientAddressHere...', + value: ethers.parseEther('0.01') + }); + + console.log('tx hash:', tx.hash); + + // 4) Wait for confirmation (Sei finality is fast) + const receipt = await tx.wait(); + console.log('confirmed in block:', receipt?.blockNumber); +} + +main().catch(console.error); +``` + +## Security Best Practices (Hot Wallet) + +- **Never share your seed phrase**; no legitimate app or support agent will ask for it. +- Use a **hardware wallet** for large balances; keep a hot wallet for “spending money.” +- Enable **device security** (OS updates, screen lock, malware protection). +- Watch for **phishing**: verify URLs, avoid unknown links, and double-check dApp permissions. +- Use **separate wallets**: one for daily dApp usage, one for savings. +- Store keys in **secure environments** (avoid copying into notes/screenshots); for apps, prefer secure enclaves where available. + +## Summary + +A hot wallet is an internet-connected crypto wallet that makes it easy to sign transactions and interact with blockchains, trading convenience for greater online exposure. On **Sei Network**, hot wallets pair well with **~400ms finality**, **parallelization**, and **EVM compatibility**, enabling fast, responsive on-chain activity for everyday users and dApp interactions. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx b/content/answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx new file mode 100644 index 00000000..3995e550 --- /dev/null +++ b/content/answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx @@ -0,0 +1,151 @@ +--- +title: 'What is a Layer 1 Blockchain and How Does It Work?' +description: 'Learn about what is layer 1 blockchain and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'layer', 'blockchain', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Layer 1 Blockchain and How Does It Work? + +## Overview + +A **Layer 1 (L1) blockchain** is a base, independent blockchain network that processes transactions, secures data, and reaches consensus **directly on its own chain**—without relying on another blockchain for security or settlement. In other words, when people ask **“what is layer 1 blockchain”**, they mean the foundational network layer where blocks are produced, transactions are finalized, and the chain’s security model lives. + +Layer 1s typically provide the core features of a blockchain: a ledger, a consensus mechanism, a native asset for fees, and the ability to run applications (directly or via smart contracts). + +## How It Works + +### 1) Core Components of a Layer 1 + +A Layer 1 blockchain generally includes: + +- **Consensus**: The method nodes use to agree on the next block (e.g., Proof of Stake, Proof of Work). +- **Networking**: Peer-to-peer communication for propagating transactions and blocks. +- **Execution**: The rules for validating and applying transactions (and smart contracts, if supported). +- **Data availability & storage**: The chain stores block data so anyone can verify state transitions. +- **Finality**: The point at which transactions are considered irreversible (economic or deterministic finality depending on the design). + +### 2) Transaction Lifecycle on an L1 (High Level) + +1. **User signs and broadcasts** a transaction to the network. +2. **Validators/nodes verify** basic correctness (signature, nonce, fee, etc.). +3. **Transactions enter a mempool** (pending pool), awaiting inclusion. +4. A **block producer** proposes a block containing a set of transactions. +5. The network reaches **consensus** on the block. +6. The chain **executes** the transactions to update state. +7. After enough confirmations or once finality is reached, the transaction is **considered final**. + +### 3) What Makes an L1 Different from Layer 2? + +- **Layer 1**: Provides the base security and settlement; consensus and data live on the chain itself. +- **Layer 2**: Builds on top of an L1 to improve scalability/costs (e.g., rollups), usually inheriting security from the L1. + +### 4) Common L1 Scaling Approaches + +Layer 1 networks improve throughput and latency using techniques such as: + +- **Faster block times / quicker finality** +- **Parallel execution** (running independent transactions concurrently) +- **Optimized consensus and networking** +- **State and storage optimizations** + +## On Sei Network + +Sei is a **high-performance Layer 1 blockchain** designed for low-latency execution and modern app requirements, while also supporting **EVM compatibility** for Ethereum-style smart contracts. + +### Parallelization and Performance + +On Sei, Layer 1 scaling is achieved with strong performance characteristics and **parallelization**—allowing many non-conflicting transactions to be processed concurrently—helping increase throughput and reduce contention. Sei is also known for **~400ms finality**, enabling near-instant user experiences for trading, gaming, and other real-time applications. + +### EVM Compatibility + +Sei’s EVM compatibility means developers can deploy and run Solidity smart contracts and integrate with familiar Ethereum tooling (wallets, libraries, and developer workflows). This makes it easier to build on a high-performance L1 without abandoning the Ethereum ecosystem. + +### Example: Deploying a Simple Solidity Contract (EVM) + +Below is a minimal Solidity contract you can deploy to Sei’s EVM environment. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public count; + + function inc() external { + count += 1; + } + + function dec() external { + require(count > 0, "count underflow"); + count -= 1; + } +} +``` + +### Example: Sending a Transaction with ethers.js (TypeScript) + +This example connects to an RPC endpoint and calls `inc()`. + +```typescript +import { ethers } from 'ethers'; + +async function main() { + // Replace with Sei EVM RPC endpoint + const rpcUrl = process.env.RPC_URL as string; + const provider = new ethers.JsonRpcProvider(rpcUrl); + + // Use a funded private key for Sei EVM + const pk = process.env.PRIVATE_KEY as string; + const wallet = new ethers.Wallet(pk, provider); + + // Deployed contract address on Sei EVM + const counterAddress = '0xYourContractAddress'; + + const abi = ['function count() view returns (uint256)', 'function inc()']; + + const counter = new ethers.Contract(counterAddress, abi, wallet); + + const before = await counter.count(); + console.log('count before:', before.toString()); + + const tx = await counter.inc(); + console.log('tx hash:', tx.hash); + + await tx.wait(); // waits for inclusion/finality per provider semantics + const after = await counter.count(); + console.log('count after:', after.toString()); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); +``` + +### Why “Layer 1” Matters for Builders and Users on Sei + +Because Sei is an L1, it provides: + +- **Native settlement and security** directly on-chain (no external settlement layer required) +- **Fast finality (~400ms)** for responsive applications +- **Parallelized execution** to scale throughput efficiently +- **EVM compatibility** to reuse Ethereum contracts and tooling + +## Key Takeaways + +- A **Layer 1 blockchain** is the foundational network that runs consensus, executes transactions, and finalizes state on its own chain. +- L1s are responsible for **security, settlement, and data availability**, and can scale via performance-focused designs like **parallel execution**. +- **Sei Network** is a high-performance L1 with **parallelization**, **~400ms finality**, and **EVM compatibility**, making it well-suited for low-latency, high-throughput applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx b/content/answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx new file mode 100644 index 00000000..cc07b96d --- /dev/null +++ b/content/answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx @@ -0,0 +1,141 @@ +--- +title: 'What is a Layer 2 Solution and How Does It Work?' +description: 'Learn about what is layer 2 solution and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'layer', 'solution', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Layer 2 Solution and How Does It Work? + +## Overview + +A **Layer 2 (L2) solution** is a scaling system built **on top of a Layer 1 (L1) blockchain** to increase transaction throughput and reduce fees while inheriting the L1’s security. In short, **what is layer 2 solution**: it’s a network or protocol that processes transactions off the main chain (or more efficiently) and then posts proof or compressed data back to the main chain. + +## How It Works + +Layer 2 solutions generally work by **moving execution and state updates away from the L1’s base layer**, then periodically “settling” the results on L1. The core idea is to reduce how much work the L1 must do per transaction while maintaining security guarantees. + +### Key Concepts + +- **Execution off-chain / off-L1:** Transactions are processed in an L2 environment (separate network, smart contract system, or side execution layer). +- **Data availability & settlement:** L2 results are submitted to L1 so the L1 can act as the final arbiter (depending on the model). +- **Security model:** Some L2s inherit L1 security closely (rollups), while others rely more on external validators (validiums/sidechains). + +### Common Types of Layer 2 Solutions + +#### 1) Rollups (Most common L2 model) + +Rollups bundle many L2 transactions into a small amount of L1 data. + +- **Optimistic Rollups** + + - Assume batches are valid by default. + - Use a **challenge window** (fraud proofs) where invalid batches can be disputed. + - Tradeoff: **withdrawals to L1 can be slower** due to challenge periods. + +- **ZK Rollups** + - Submit **validity proofs** (zero-knowledge proofs) to L1 showing the batch is correct. + - Tradeoff: typically more complex proving infrastructure, but **faster finality for withdrawals** (design-dependent). + +#### 2) State Channels + +Participants lock funds on L1, then exchange signed updates off-chain. Only the opening and closing (or disputes) touch L1. + +- Great for repeated interactions between a small set of users. +- Less general-purpose for open smart contract environments. + +#### 3) Sidechains / Appchains (Related but distinct) + +These are separate chains that may bridge to an L1, but they typically **do not inherit L1 security in the same way rollups do**. + +- Can be fast and cheap. +- Security depends on the sidechain’s validator set and consensus. + +### Typical L2 Transaction Lifecycle (Rollup Example) + +1. **User submits transaction** to the L2 sequencer (or validator set). +2. **L2 executes** the transaction and updates L2 state. +3. **Batching:** Many transactions are compressed into a batch. +4. **Posting to L1:** The L2 posts calldata/state commitments (and sometimes proofs) to L1. +5. **Finalization / dispute:** + - Optimistic: final after challenge window. + - ZK: final after proof verification. + +## Benefits and Tradeoffs + +### Benefits + +- **Lower fees:** Less L1 computation and storage per transaction. +- **Higher throughput:** L2 can process more transactions per second than L1. +- **Better UX:** Faster confirmations, cheaper interactions for DeFi, games, and consumer apps. + +### Tradeoffs + +- **Bridging complexity:** Deposits/withdrawals and cross-chain messaging add moving parts. +- **Finality differences:** L2 “soft finality” may be fast, but L1-settled finality depends on the L2 design. +- **Liquidity fragmentation:** Assets and users spread across multiple L2s. + +## On Sei Network + +Sei Network is a **high-performance Layer 1** with **parallelized execution**, **~400ms finality**, and **EVM compatibility**, which changes the scaling calculus compared to L1s that rely heavily on L2s for throughput. + +### How Layer 2 Fits with Sei + +- **Many applications may not need an L2** to achieve low latency and high throughput because Sei’s L1 is built to scale at the base layer using parallelization and fast finality. +- **L2s can still exist on Sei** for specialized needs: + - Application-specific execution environments (custom rules, privacy, specialized data availability). + - Very high-volume, domain-specific workloads (e.g., gaming or microtransactions) that benefit from additional batching. + - Cross-ecosystem strategies where an L2 acts as an aggregation layer interacting with multiple chains. + +### EVM Compatibility Considerations + +Because Sei supports EVM-compatible smart contracts, many scaling patterns (bridges, rollup-like systems, batching contracts) can be implemented using familiar Ethereum tooling and Solidity-based contracts, with the advantage of Sei’s fast finality and parallelization at the base layer. + +## Simple Example: Batching Transactions (Conceptual) + +Below is a simplified illustration of the **batching idea** (not a full rollup) where an operator submits a commitment representing many user actions, reducing on-chain writes. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// @notice Conceptual batch-commit contract (illustrative only). +/// Real rollups require data availability, fraud/validity proofs, and withdrawals logic. +contract BatchCommit { + event BatchSubmitted(uint256 indexed batchId, bytes32 stateRoot, bytes32 txsHash); + + uint256 public nextBatchId; + + function submitBatch(bytes32 stateRoot, bytes32 txsHash) external { + emit BatchSubmitted(nextBatchId, stateRoot, txsHash); + nextBatchId++; + } +} +``` + +### Submitting a Batch (Example CLI Flow) + +```bash +# Example: call submitBatch using a CLI like cast (Foundry) +cast send \ + "submitBatch(bytes32,bytes32)" \ + 0x 0x \ + --rpc-url \ + --private-key +``` + +## Summary + +A Layer 2 solution is a scaling approach that **processes transactions outside the base chain** and then **settles results back on Layer 1**, typically lowering fees and increasing throughput. Common L2 designs include **optimistic rollups**, **ZK rollups**, and **state channels**, each with different security and finality tradeoffs. On Sei Network, the need for L2 can be reduced for many use cases thanks to **parallelization**, **~400ms finality**, and **EVM compatibility**, though L2s may still be useful for specialized application requirements. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-light-client-and-how-does-it-work.mdx b/content/answers/what-is-a-light-client-and-how-does-it-work.mdx new file mode 100644 index 00000000..22cffe36 --- /dev/null +++ b/content/answers/what-is-a-light-client-and-how-does-it-work.mdx @@ -0,0 +1,169 @@ +--- +title: 'What is a Light Client and How Does It Work?' +description: 'Learn about what is light client and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'light', 'client', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Light Client and How Does It Work? + +## Overview + +A **light client** is a blockchain node that verifies key parts of a network’s state (like block headers and consensus proofs) without downloading or executing the entire chain. In other words, when people ask **“what is light client”**, the answer is: a lightweight verifier that trades full data storage and computation for efficiency while still preserving strong security guarantees. + +Light clients are commonly used in wallets, mobile apps, embedded devices, and cross-chain systems where running a full node is too expensive. + +## How It Works + +### What a light client downloads + +Unlike a full node (which downloads and validates every block and transaction), a light client typically downloads: + +- **Block headers** (small metadata about blocks) +- **Consensus proofs / validator signatures** (to confirm headers are legitimate) +- **Occasional state proofs** (e.g., Merkle proofs) for specific queries like account balances or contract storage + +### How it verifies data securely + +A light client relies on cryptographic commitments to verify information: + +1. **Header verification** + + - The client checks that a new block header is valid under the chain’s consensus rules. + - In Proof-of-Stake (PoS) systems, this often means verifying that a sufficient portion of the validator set signed the header. + +2. **Proof-based queries** + + - When it needs to verify a specific value (e.g., “what is the balance of address X?”), it requests: + - The value, plus + - A **Merkle proof** (or equivalent) that the value is included in the committed state root inside a verified header. + - The client verifies the proof locally without needing the full state. + +3. **Security model** + - Light clients are secure as long as: + - They can obtain honest headers (or can detect invalid ones via signatures/consensus proofs), and + - They are not isolated by an attacker (e.g., eclipse attack) into seeing only malicious peers. + +### Light client vs full node (quick comparison) + +- **Full node**: verifies everything, stores full state/history, highest resource cost. +- **Light client**: verifies headers + proofs as needed, minimal storage and bandwidth, depends on full nodes for data availability. + +## Common Use Cases + +- **Wallets and mobile clients** that need strong verification without heavy resource usage +- **Cross-chain bridges / IBC-style interoperability**, where one chain verifies another chain’s consensus headers +- **DApps and RPC consumers** that want trust-minimized reads (e.g., verifying balances without trusting an RPC provider) +- **Hardware/IoT environments** where running a full node is impractical + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, designed for fast and efficient execution using parallelization and delivering **~400ms finality**. Light clients are particularly valuable on Sei because they let applications and users verify chain state quickly with minimal overhead while benefiting from Sei’s rapid finality. + +### What light clients verify on Sei + +A Sei light client generally focuses on: + +- **Sei block headers** and their consensus validity (validator signatures / consensus proofs) +- **State commitments** (e.g., a state root or equivalent commitment contained in a verified header) +- **Merkle proofs** (or chain-specific proofs) for specific application queries + +Because Sei finalizes quickly (~400ms), a light client can reach high confidence in recent state updates faster than on many other networks—improving UX for wallets, exchanges, and cross-chain verification. + +### EVM compatibility considerations + +With Sei’s EVM support, many developers interact using Ethereum-style tooling (JSON-RPC, Solidity contracts, ethers.js). A typical pattern is: + +- Use standard RPC for convenience, but +- Add a **verification layer** (light-client style) when you need trust minimization: + - Verify block headers and signatures (consensus-level), + - Verify specific state via proofs (where available in your stack). + +> Note: The exact proof formats and available endpoints depend on the client stack and interfaces you’re using (Cosmos SDK/CometBFT-style proofs vs EVM JSON-RPC conventions). In trust-minimized designs, your system should be explicit about which parts are verified and which are assumed from the RPC provider. + +## Example: Conceptual Light Client Header Verification (Pseudo-Flow) + +Below is a simplified, conceptual outline (not chain-specific code) showing how a light client processes new headers: + +```typescript +type Header = { + height: number; + blockHash: string; + stateRoot: string; + validatorSetHash: string; + signatures: Uint8Array[]; +}; + +function verifyHeader(header: Header, trustedValidatorSet: Uint8Array): boolean { + // 1) Check basic header fields (height monotonicity, hashes, etc.) + // 2) Verify signatures meet the consensus threshold for the validator set + // 3) Ensure validatorSetHash matches expected/tracked validator set updates + return verifyConsensusSignatures(header, trustedValidatorSet); +} + +function verifyStateProof(stateRoot: string, key: Uint8Array, value: Uint8Array, proof: Uint8Array): boolean { + // Verify the Merkle proof that (key => value) is included under stateRoot + return verifyMerkleProof(stateRoot, key, value, proof); +} +``` + +## Example: Solidity Contract Pattern (On-Chain Light Client Consumer) + +In cross-chain or trust-minimized designs, a smart contract can consume results from a verified light client (often maintained by an on-chain light client contract). Here’s a minimal pattern where a contract relies on a verified header/state root: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface ILightClient { + function latestHeight() external view returns (uint256); + function stateRoot(uint256 height) external view returns (bytes32); +} + +contract ProofConsumer { + ILightClient public lightClient; + + constructor(address lightClientAddress) { + lightClient = ILightClient(lightClientAddress); + } + + function getLatestVerifiedRoot() external view returns (uint256 height, bytes32 root) { + height = lightClient.latestHeight(); + root = lightClient.stateRoot(height); + } +} +``` + +This pattern is commonly used in bridges and interoperability systems: the light client verifies headers, and application contracts rely on those verified commitments. + +## Key Benefits and Limitations + +### Benefits + +- **Low resource usage**: minimal storage, bandwidth, and CPU +- **Faster startup**: no need to sync full chain history +- **Stronger trust model than plain RPC**: can verify headers and proofs locally +- **Great fit for Sei’s speed**: ~400ms finality enables rapid, responsive verification + +### Limitations + +- **Data availability dependence**: must request data/proofs from full nodes +- **More complex engineering** than trusting an RPC endpoint +- **Peer isolation risks** (e.g., eclipse attacks) if networking is not robust +- **Proof support varies by interface**: some environments expose proofs more naturally than others + +## Summary + +A light client is a lightweight blockchain verifier that validates block headers and cryptographic proofs instead of executing the full chain. In general, it provides a strong security/efficiency tradeoff for wallets, mobile apps, and cross-chain systems. On Sei Network, light clients pair well with Sei’s **parallelized execution**, **EVM compatibility**, and **~400ms finality**, enabling fast, trust-minimized verification for modern applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx b/content/answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx new file mode 100644 index 00000000..e7732f37 --- /dev/null +++ b/content/answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx @@ -0,0 +1,135 @@ +--- +title: 'What is a Liquidity Pool and How Does It Work?' +description: 'Learn about what is liquidity pool and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'liquidity', 'pool', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Liquidity Pool and How Does It Work? + +## Overview + +A **liquidity pool** is a smart contract (or on-chain account/module) that holds reserves of two or more assets so users can trade, lend, or provide liquidity without needing a traditional order book or a direct counterparty. In most DeFi markets, liquidity pools power automated swaps and enable continuous trading, with prices determined algorithmically. + +In other words, when people ask **“what is liquidity pool”**, the answer is: it’s an on-chain vault of tokens governed by rules (an AMM formula or similar) that lets anyone swap assets and lets liquidity providers earn fees for supplying those tokens. + +## How It Works + +### 1) Liquidity Providers (LPs) deposit assets + +A pool typically holds a pair like `TOKENA/TOKENB`. Liquidity providers deposit both tokens in a required proportion (often based on the pool’s current price). In return, they receive **LP tokens** (or a position NFT) representing their share of the pool. + +- If you own 10% of the LP tokens, you generally own 10% of the pool reserves. +- LP tokens can often be used elsewhere in DeFi (e.g., farming, collateral), depending on the protocol. + +### 2) Traders swap against the pool (AMM pricing) + +Instead of matching buyers and sellers, the pool uses an **Automated Market Maker (AMM)** to quote prices. A common AMM model is the constant product formula: + +- **Constant product AMM:** `x * y = k` + Where `x` and `y` are the reserves of each token, and `k` is a constant. + +When a trader buys `TOKENA`, they add `TOKENB` to the pool and remove `TOKENA`. This changes the reserve ratio, which changes the price—creating **slippage** (worse execution for larger trades relative to pool size). + +Other pool designs exist (stable swap curves, concentrated liquidity, weighted pools), but the key idea remains: **the pool’s reserves and rules determine the swap price**. + +### 3) Fees reward liquidity providers + +Most pools charge a swap fee (e.g., 0.05%–0.30%). Fees are distributed to LPs, usually by: + +- Increasing pool reserves (fees stay in the pool), which increases the value of LP shares, or +- Directly distributing fees according to the protocol rules. + +### 4) LP returns and key risks + +Liquidity pools can generate yield, but LPs take on risks: + +- **Impermanent Loss (IL):** If the relative price of pooled assets changes, LPs may end up with a different asset mix than if they simply held the tokens. This can reduce value versus holding, though fees can offset it. +- **Smart contract risk:** Bugs, exploits, or oracle issues can lead to losses. +- **Liquidity risk:** Shallow pools can cause high slippage, reducing trader demand and fee potential. +- **Depegs/stablecoin risk:** Pools involving stable assets can be exposed to depeg events. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, optimized for trading and DeFi. Liquidity pools on Sei behave like pools on other blockchains—LPs deposit assets, traders swap using AMM logic, and fees accrue to LPs—but they benefit from Sei’s design goals: + +- **Fast finality (~400ms):** Swaps, liquidity adds/removes, and arbitrage updates can confirm quickly, improving UX and reducing the time users are exposed to price movement while a transaction is pending. +- **Parallelization:** Sei’s execution model is built to handle high throughput by processing many non-conflicting transactions in parallel, which can help DeFi apps scale during periods of high demand. +- **EVM compatibility:** Existing Solidity-based AMM and DEX architectures can be deployed on Sei, allowing teams to port or build familiar liquidity pool designs while leveraging Sei’s performance. + +### Example: Minimal AMM-style swap interface (Solidity) + +Many liquidity pool contracts expose methods similar to the following (exact interfaces vary by DEX): + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface ILiquidityPool { + function token0() external view returns (address); + function token1() external view returns (address); + + /// @notice Swap exact input amount of tokenIn for tokenOut. + /// @dev Real implementations include slippage controls, fees, and callbacks. + function swapExactIn( + address tokenIn, + uint256 amountIn, + address to, + uint256 minAmountOut, + uint256 deadline + ) external returns (uint256 amountOut); +} +``` + +### Example: Adding liquidity via an EVM router (TypeScript) + +On Sei’s EVM, you interact with pool/router contracts using standard Ethereum tooling (ethers.js-style). This is a simplified pattern: + +```typescript +import { ethers } from 'ethers'; + +const provider = new ethers.JsonRpcProvider(process.env.SEI_EVM_RPC_URL!); +const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + +// Router ABI fragment (example only) +const routerAbi = ['function addLiquidity(address tokenA,address tokenB,uint amountADesired,uint amountBDesired,uint amountAMin,uint amountBMin,address to,uint deadline) returns (uint amountA,uint amountB,uint liquidity)']; + +const router = new ethers.Contract('0xRouterAddress', routerAbi, wallet); + +const tokenA = '0xTokenA'; +const tokenB = '0xTokenB'; + +const amountADesired = ethers.parseUnits('10', 18); +const amountBDesired = ethers.parseUnits('1000', 6); + +const tx = await router.addLiquidity( + tokenA, + tokenB, + amountADesired, + amountBDesired, + 0, // amountAMin (set appropriately to protect against slippage) + 0, // amountBMin + await wallet.getAddress(), + Math.floor(Date.now() / 1000) + 60 // deadline +); + +await tx.wait(); +``` + +## Key Takeaways + +- A liquidity pool is an on-chain reserve of tokens that enables trading without order-book counterparties. +- LPs deposit assets and earn swap fees, but face impermanent loss and smart contract risk. +- On Sei Network, liquidity pools can deliver a smoother trading experience thanks to **~400ms finality**, **parallelized execution**, and **EVM compatibility** for Solidity-based DeFi applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-lsdfi-and-how-does-it-work.mdx b/content/answers/what-is-a-lsdfi-and-how-does-it-work.mdx new file mode 100644 index 00000000..1dea50fe --- /dev/null +++ b/content/answers/what-is-a-lsdfi-and-how-does-it-work.mdx @@ -0,0 +1,144 @@ +--- +title: 'What is a LSDfi and How Does It Work?' +description: 'Learn about what is LSDfi and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'LSDfi', 'lsdfi', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a LSDfi and How Does It Work? + +## Overview + +LSDfi (Liquid Staking Derivatives DeFi) is a category of DeFi that uses **liquid staking derivatives (LSDs)**—tokens representing staked assets—to unlock additional yield and capital efficiency across lending, trading, vaults, and structured strategies. In simple terms, LSDfi lets users **stake** to earn staking rewards while still being able to **use a liquid token** in DeFi. + +If you’re searching **what is LSDfi**, the core idea is: _turn staked positions into composable assets that can be used across DeFi without giving up staking rewards._ + +## How It Works + +### 1) Liquid staking creates an LSD + +In many Proof-of-Stake (PoS) networks, staking typically locks tokens, reducing liquidity. Liquid staking protocols solve this by issuing an LSD token (e.g., staked-ETH receipt token) to represent your staked position. + +- You deposit/stake the base asset (e.g., ETH, ATOM, SEI—depending on chain) +- The protocol stakes it with validators +- You receive an LSD token that tracks your position and rewards + +LSDs generally accrue value in one of two ways: + +- **Rebasing**: your LSD balance increases over time +- **Exchange-rate**: the LSD’s redemption value vs. the base asset increases + +### 2) LSDfi uses LSDs as DeFi collateral and building blocks + +Once you hold an LSD, LSDfi strategies can route it through DeFi primitives: + +- **Lending/Borrowing**: Use LSD as collateral to borrow stablecoins or other assets, increasing capital efficiency. +- **DEX Liquidity**: Pair LSD with another asset to earn swap fees + potentially incentives (but with price/risk considerations). +- **Yield Aggregation / Vaults**: Automated strategies that rebalance across lending pools, DEX LP positions, or leverage loops. +- **Structured Products**: Split principal and yield, create fixed/variable yield products, or manage risk via hedging. + +### 3) Common LSDfi “looping” pattern (higher yield, higher risk) + +A typical LSDfi strategy is a leveraged loop: + +1. Stake asset → receive LSD +2. Deposit LSD as collateral +3. Borrow more of the base asset (or a correlated asset) +4. Stake again → receive more LSD +5. Repeat (within safe collateral limits) + +This can amplify staking yield plus any DeFi incentives, but it also amplifies liquidation and depeg risks. + +### 4) Key risks in LSDfi + +LSDfi can introduce multiple layers of risk: + +- **Smart contract risk**: liquid staking + DeFi protocols + integrations +- **Validator/slashing risk**: staking penalties can reduce backing value +- **LSD depeg risk**: LSD market price may diverge from redemption value +- **Liquidation risk**: if LSD collateral value drops, positions can be liquidated +- **Liquidity risk**: exiting large positions can move markets or incur high slippage + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, designed for scalable trading and DeFi execution. LSDfi on Sei follows the same core pattern—turning staked positions into liquid, composable assets—but benefits from Sei’s chain characteristics: + +- **Fast time-to-finality (~400ms)**: reduces confirmation latency for trading, rebalancing, and liquidation-sensitive workflows. +- **Parallelization**: enables higher throughput by executing compatible transactions concurrently, supporting busy DeFi markets and strategies at scale. +- **EVM compatibility**: Solidity-based LSDfi apps and integrations can be deployed and used by Ethereum-style tooling (wallets, indexers, dev frameworks), while leveraging Sei’s performance. + +### Typical LSDfi flow on Sei + +1. **Stake SEI (or another supported PoS asset)** via a liquid staking provider → receive an LSD token. +2. **Use the LSD across Sei DeFi**: + - Deposit as collateral in money markets + - Provide liquidity on AMMs/DEXs + - Enter vault strategies that compound staking + DeFi yield +3. **Manage positions faster** due to Sei’s low-latency finality—helpful for collateral updates, refinancing, or risk management. + +### Example: interacting with an LSD token (ERC-20) on Sei EVM + +Below is a minimal Solidity example showing how a vault could accept an LSD token and track deposits (illustrative only—no rewards logic): + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function transfer(address to, uint256 amount) external returns (bool); + function balanceOf(address a) external view returns (uint256); +} + +contract SimpleLSDVault { + IERC20 public immutable lsd; + mapping(address => uint256) public shares; + + constructor(address _lsd) { + lsd = IERC20(_lsd); + } + + function deposit(uint256 amount) external { + require(amount > 0, "amount=0"); + require(lsd.transferFrom(msg.sender, address(this), amount), "transferFrom failed"); + shares[msg.sender] += amount; // 1:1 shares for simplicity + } + + function withdraw(uint256 amount) external { + require(shares[msg.sender] >= amount, "insufficient shares"); + shares[msg.sender] -= amount; + require(lsd.transfer(msg.sender, amount), "transfer failed"); + } +} +``` + +### Example: configuring Sei EVM in a dev workflow + +Using Foundry to point to a Sei EVM RPC (replace placeholders with your endpoint and key management): + +```bash +export SEI_EVM_RPC_URL="https://" +export PRIVATE_KEY="" + +forge create \ + --rpc-url $SEI_EVM_RPC_URL \ + --private-key $PRIVATE_KEY \ + src/SimpleLSDVault.sol:SimpleLSDVault \ + --constructor-args +``` + +## Summary + +LSDfi is “liquid staking meets DeFi”: it transforms staked assets into liquid tokens (LSDs) that can be used as collateral, LP assets, or inputs to automated strategies—often earning staking yield plus additional DeFi yield. On Sei Network, LSDfi can be implemented with familiar EVM tooling while benefiting from **parallel execution** and **~400ms finality**, which can improve responsiveness for active DeFi strategies and risk management. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-mainnet-and-how-does-it-work.mdx b/content/answers/what-is-a-mainnet-and-how-does-it-work.mdx new file mode 100644 index 00000000..d6e26fa1 --- /dev/null +++ b/content/answers/what-is-a-mainnet-and-how-does-it-work.mdx @@ -0,0 +1,146 @@ +--- +title: 'What is a Mainnet and How Does It Work?' +description: 'Learn about what is mainnet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'mainnet', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Mainnet and How Does It Work? + +## Overview + +A **mainnet** (main network) is the production blockchain network where real transactions occur using assets with real economic value. When people ask **“what is mainnet”**, they’re referring to the live, fully operational version of a blockchain that users and applications rely on for permanent, immutable records. + +Mainnets contrast with **testnets** (used for testing with valueless tokens) and **devnets/localnets** (private environments for development). + +## How It Works + +### Mainnet vs. Testnet (and why it matters) + +- **Mainnet:** Real users, real tokens, real stakes. Transactions are intended to be final and economically meaningful. +- **Testnet:** Used to test wallets, smart contracts, and infrastructure without risking real funds. Tokens are typically free via faucets and have no market value. +- **Devnet/Localnet:** Small, controlled networks (often run locally) for rapid iteration and debugging. + +### Core components of a mainnet + +A mainnet functions through several core building blocks: + +1. **Nodes** + + - **Full nodes** download and verify the chain’s data. + - **Validator nodes** participate in consensus (depending on the chain design) to propose/confirm blocks. + +2. **Consensus** + + - A consensus protocol (often Proof of Stake) ensures participants agree on the order and validity of transactions. + - Consensus provides **finality**, meaning transactions become extremely difficult (or impossible) to reverse after confirmation. + +3. **Transactions and blocks** + + - Users sign transactions with private keys and broadcast them to the network. + - Validators/orderers include transactions in blocks. + - Blocks are finalized according to the chain’s consensus rules, making history tamper-resistant. + +4. **Fees (gas)** + + - Users pay fees to compensate validators and prevent spam. + - Smart contract execution usually costs more than simple transfers due to computation. + +5. **Smart contracts and dApps (if supported)** + - On smart-contract platforms, mainnet is where contracts are deployed for real usage. + - Contract upgrades (if possible) and operational security become critical because bugs impact real funds. + +### Typical workflow: from testnet to mainnet + +1. Develop and test smart contracts on local environments. +2. Deploy to a testnet and run integration tests (wallets, indexers, frontends). +3. Audit and harden security assumptions. +4. Deploy to mainnet, initialize configuration, and monitor. + +## On Sei Network + +Sei Network’s mainnet is the live Sei blockchain where transactions and smart contracts execute with real economic value, benefiting from Sei’s performance-oriented design. Sei is **EVM-compatible**, enabling Ethereum-style smart contracts and tooling while operating as a high-performance Layer 1. + +### What “mainnet” means on Sei + +- **Real assets and real users:** Tokens and application states on Sei mainnet carry real value. +- **Fast user experience:** Sei targets **~400ms finality**, so transactions can reach finality quickly compared to many traditional L1s. +- **High throughput via parallelization:** Sei is designed to process many operations efficiently, leveraging **parallelization** to increase capacity and reduce bottlenecks—particularly important for high-volume apps. + +### EVM compatibility on Sei mainnet + +Because Sei supports EVM workflows, developers can: + +- Write and deploy **Solidity** contracts. +- Use familiar tooling like `ethers`, Hardhat, Foundry, and standard wallet flows. +- Treat Sei mainnet like an EVM chain for deployment and integration, while benefiting from Sei’s performance characteristics. + +### Example: Deploying to Sei mainnet (conceptual) + +Below is a minimal example of how teams typically switch from testnet to mainnet by changing the RPC endpoint and chain configuration. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_MAINNET_RPC!; // e.g. https:// +const PRIVATE_KEY = process.env.DEPLOYER_KEY!; + +async function main() { + const provider = new ethers.JsonRpcProvider(RPC_URL); + const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + + // Example: send a simple transaction (native token transfer) + const tx = await wallet.sendTransaction({ + to: '0xYourRecipientAddressHere', + value: ethers.parseEther('0.01') + }); + + console.log('Submitted tx:', tx.hash); + const receipt = await tx.wait(); + console.log('Finalized in block:', receipt?.blockNumber); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); +``` + +### Example: Simple Solidity contract for mainnet deployment + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public number; + + function increment() external { + number += 1; + } + + function setNumber(uint256 newNumber) external { + number = newNumber; + } +} +``` + +Deploying this contract to Sei mainnet makes its state and interactions real and permanent, so audits, access control, and monitoring are essential. + +## Key Takeaways + +- **What is mainnet?** The live, production blockchain network where transactions and smart contract execution have real economic value. +- Mainnets rely on nodes, consensus, fees, and finalized blocks to provide security and permanence. +- **On Sei Network**, mainnet combines **EVM compatibility** with high-performance design, including **parallelization** and **~400ms finality**, enabling fast and scalable real-world applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx b/content/answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx new file mode 100644 index 00000000..856983eb --- /dev/null +++ b/content/answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx @@ -0,0 +1,188 @@ +--- +title: 'What is a Multi-sig Wallet and How Does It Work?' +description: 'Learn about what is multi-sig wallet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'multi-sig', 'wallet', 'multi', 'sig', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Multi-sig Wallet and How Does It Work? + +## Overview + +A multi-sig wallet (multi-signature wallet) is a cryptocurrency wallet that requires **two or more approvals (signatures)** to authorize a transaction instead of a single private key. In other words, control of funds is shared across multiple keys, reducing the risk that one compromised device or person can move assets unilaterally. + +If you’re searching **what is multi-sig wallet**, it’s best understood as a wallet governed by an **M-of-N rule** (e.g., 2-of-3), commonly used by teams, treasuries, and security-conscious individuals. + +## How It Works + +### Multi-sig basics (M-of-N) + +Multi-sig policies are usually expressed as: + +- **N** = total number of authorized signers (keys) +- **M** = minimum number of signatures required to execute a transaction + +Examples: + +- **2-of-3**: any 2 of the 3 signers can approve a transaction (common for small teams) +- **3-of-5**: 3 out of 5 signers must approve (common for DAOs/treasuries) +- **1-of-2**: either signer can approve (less common; more for redundancy than security) + +### What happens during a transaction + +1. **Transaction is proposed** (recipient, amount, calldata, etc.). +2. **Signers review** the transaction details. +3. **Each signer signs** the transaction (or signs an approval message). +4. Once **M signatures are collected**, the wallet **executes** the transaction on-chain. + +### Key benefits + +- **Reduced single point of failure**: one compromised key doesn’t automatically mean stolen funds. +- **Shared custody / governance**: decisions can require multiple stakeholders. +- **Operational controls**: can implement approvals, spending limits, and role-based access (depending on the wallet design). + +### Common implementations in blockchain systems + +Multi-sig can be implemented in two main ways: + +- **Protocol-level (UTXO-style scripts)**: Some blockchains support multi-sig directly in transaction scripts. +- **Smart contract-based (account model)**: On EVM chains, multi-sig is typically a **smart contract wallet** that validates multiple signatures and then performs calls/transfers. + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, enabling standard smart contract multi-sig patterns used across Ethereum tooling—while benefiting from Sei’s **parallelized execution** and **~400ms finality** for fast confirmation of approvals and executions. + +### What multi-sig looks like on Sei + +Because Sei supports the EVM, a multi-sig wallet is usually: + +- A **smart contract** deployed on Sei EVM +- Controlled by a set of signer addresses +- Enforcing an **M-of-N** threshold for approvals +- Executing transactions as contract calls once enough signatures are collected + +Parallelization can help high-throughput applications (like exchanges, games, and on-chain treasuries with many operations) by allowing independent transactions to be processed efficiently, while fast finality makes the “collect signatures → execute” loop feel responsive. + +### Developer workflow (EVM multi-sig pattern) + +A typical pattern is: + +- Off-chain: collect signatures from owners over a transaction hash (EIP-712 typed data is common) +- On-chain: the multi-sig contract verifies signatures and executes the requested call + +Below is an illustrative (simplified) Solidity example showing the core idea. Production wallets add nonce management, replay protection, module systems, and richer access control. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; + +contract SimpleMultisig { + using ECDSA for bytes32; + + mapping(address => bool) public isOwner; + uint256 public threshold; + uint256 public nonce; + + event Executed(address indexed to, uint256 value, bytes data); + + constructor(address[] memory owners, uint256 _threshold) { + require(owners.length > 0, "no owners"); + require(_threshold > 0 && _threshold <= owners.length, "bad threshold"); + + for (uint256 i = 0; i < owners.length; i++) { + require(owners[i] != address(0), "zero owner"); + require(!isOwner[owners[i]], "duplicate owner"); + isOwner[owners[i]] = true; + } + threshold = _threshold; + } + + function getTxHash(address to, uint256 value, bytes calldata data, uint256 _nonce) + public + view + returns (bytes32) + { + return keccak256(abi.encode(block.chainid, address(this), to, value, keccak256(data), _nonce)); + } + + function execute( + address to, + uint256 value, + bytes calldata data, + bytes[] calldata signatures + ) external returns (bytes memory result) { + bytes32 txHash = getTxHash(to, value, data, nonce).toEthSignedMessageHash(); + + require(signatures.length >= threshold, "not enough sigs"); + + // Verify signatures are from distinct owners (naive O(n^2) approach for demo) + address[] memory seen = new address[](signatures.length); + for (uint256 i = 0; i < signatures.length; i++) { + address signer = txHash.recover(signatures[i]); + require(isOwner[signer], "not owner"); + + for (uint256 j = 0; j < i; j++) require(seen[j] != signer, "duplicate sig"); + seen[i] = signer; + } + + nonce++; + + (bool ok, bytes memory res) = to.call{value: value}(data); + require(ok, "call failed"); + + emit Executed(to, value, data); + return res; + } + + receive() external payable {} +} +``` + +### Deploying and interacting on Sei (example) + +Using Foundry against Sei EVM (replace RPC with your target network endpoint): + +```bash +# Set your Sei EVM RPC endpoint +export SEI_EVM_RPC="https://" + +# Deploy (example) +forge create \ + --rpc-url "$SEI_EVM_RPC" \ + --private-key "$DEPLOYER_PRIVATE_KEY" \ + src/SimpleMultisig.sol:SimpleMultisig \ + --constructor-args '["0xOwner1...","0xOwner2...","0xOwner3..."]' 2 +``` + +## Common Use Cases + +- **DAO or protocol treasury management**: require multiple core contributors to approve spending. +- **Team funds and operations**: avoid reliance on one person/device. +- **Custody hardening**: distribute keys across hardware wallets, locations, or trusted parties. +- **Cross-functional approvals**: finance + security + engineering all sign off for critical actions. + +## Security Considerations & Best Practices + +- Use a **reputable, audited multi-sig implementation** (especially for large treasuries). +- Ensure **nonce/replay protection** and **chainId/domain separation** for signatures. +- Choose an appropriate threshold (e.g., **2-of-3** balances resilience and availability). +- Plan for **key loss and signer rotation** (add/remove owners securely). +- Keep signers on **hardware wallets** and use operational procedures (transaction reviews, allowlists, spending limits). + +## Summary + +A multi-sig wallet is a wallet that requires **multiple signatures** to move funds, typically defined by an **M-of-N** approval threshold. In EVM systems, it is most often implemented as a **smart contract wallet** that verifies multiple signatures before executing transactions. On **Sei Network**, multi-sig wallets work like other EVM chains but benefit from Sei’s **parallelization** and **~400ms finality**, making multi-party approvals and execution fast and practical for high-throughput applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx b/content/answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx new file mode 100644 index 00000000..7dbb4bb8 --- /dev/null +++ b/content/answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx @@ -0,0 +1,154 @@ +--- +title: 'What is a Non-custodial Wallet and How Does It Work?' +description: 'Learn about what is non-custodial wallet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'non-custodial', 'wallet', 'non', 'custodial', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Non-custodial Wallet and How Does It Work? + +## Overview + +A **non-custodial wallet** is a crypto wallet where **you control the private keys (or seed phrase)** that authorize transactions and access funds. In other words, **you—not an exchange or third party—are the custodian** of your assets. When people ask **“what is non-custodial wallet”**, the core idea is self-sovereign ownership: you hold the credentials needed to sign transactions on-chain. + +## How It Works + +### Keys, seed phrases, and ownership + +Non-custodial wallets are built around public-key cryptography: + +- **Seed phrase (mnemonic):** A human-readable backup (typically 12–24 words) that can deterministically generate many private keys. +- **Private key:** A secret used to **sign transactions**. Whoever has it can move funds. +- **Public key / address:** Derived from the private key; used to **receive funds** and identify accounts on-chain. + +If you lose the seed phrase/private key, there is usually **no account recovery**—that’s the tradeoff for full control. + +### Signing vs. broadcasting + +A non-custodial wallet typically does two things: + +1. **Creates and signs a transaction locally** (often on your device). +2. **Broadcasts the signed transaction** to the blockchain network via an RPC provider or node. + +Because the signature is created with your private key, the network can verify you authorized the action **without ever seeing your private key**. + +### Interaction with dApps + +When connecting to decentralized applications (dApps), the wallet acts like a permissions layer: + +- The dApp requests an action (e.g., “sign this message” or “send this transaction”). +- The wallet prompts you to approve. +- If approved, the wallet signs and returns the signature/transaction for broadcast. + +### Token approvals (important for EVM chains) + +On EVM-compatible networks, interacting with ERC-20 tokens often requires **an approval** before a contract can spend your tokens: + +- `approve(spender, amount)` grants allowance. +- Then the contract can call `transferFrom(...)` up to the allowed amount. + +This is a common source of risk if users approve unlimited amounts to untrusted contracts. + +```solidity +// Example: ERC-20 allowance pattern (conceptual) +IERC20 token = IERC20(0xToken); +token.approve(0xSpender, 1_000e18); // allow spender to move up to 1000 tokens +``` + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility** and fast finality (often cited around **~400ms**). A non-custodial wallet on Sei works the same foundational way—**you hold the keys and sign transactions**—but the user experience benefits from Sei’s performance and parallelization. + +### EVM compatibility + +Because Sei supports EVM, non-custodial wallets that work across EVM ecosystems can also support Sei’s EVM environment. Practically, this means: + +- You can use familiar Ethereum-style accounts (0x addresses). +- You sign EVM transactions and interact with smart contracts (DEXs, NFT markets, lending protocols) similarly to other EVM networks. + +### Fast confirmations and parallel execution + +With Sei’s design goals around throughput and fast finality: + +- Transactions you sign in a non-custodial wallet can reach finality quickly (often around **~400ms**). +- Sei’s **parallelization** can help networks remain responsive under load, improving dApp interactions like swaps, mints, and contract calls. + +### Example: Sending an EVM transaction on Sei (ethers.js) + +Below is a minimal TypeScript example of a non-custodial flow: you load a private key locally, sign, and send a transaction to Sei’s EVM via an RPC endpoint. + +```typescript +import { ethers } from 'ethers'; + +// 1) Connect to a Sei EVM RPC endpoint +const rpcUrl = 'https://YOUR_SEI_EVM_RPC'; +const provider = new ethers.JsonRpcProvider(rpcUrl); + +// 2) Load your non-custodial wallet (private key stored locally/securely) +const privateKey = process.env.PRIVATE_KEY as string; +const wallet = new ethers.Wallet(privateKey, provider); + +async function main() { + // 3) Create + sign + broadcast a transaction + const tx = await wallet.sendTransaction({ + to: '0xRecipientAddress...', + value: ethers.parseEther('0.01') + }); + + console.log('Tx hash:', tx.hash); + + // 4) Wait for confirmation/finality + const receipt = await tx.wait(); + console.log('Confirmed in block:', receipt?.blockNumber); +} + +main().catch(console.error); +``` + +## Benefits of a Non-Custodial Wallet + +- **Full control of funds:** No intermediary can freeze or restrict withdrawals. +- **Permissionless access:** Use dApps directly from your wallet. +- **Portability:** Restore the wallet on another device using the seed phrase. +- **Transparency:** Actions are verified by on-chain signatures rather than platform promises. + +## Risks and Best Practices + +### Key risks + +- **Key/seed loss:** Funds may be unrecoverable. +- **Phishing and malicious approvals:** Signing the wrong message or approving a malicious contract can lead to loss. +- **Device compromise:** Malware can exfiltrate keys if not properly secured. + +### Best practices + +- Back up your **seed phrase offline** (never in cloud notes/screenshots). +- Use a **hardware wallet** for significant funds. +- Review transaction details and **limit token approvals** when possible. +- Verify dApp URLs and contract addresses before connecting. + +## Non-Custodial vs. Custodial Wallet (Quick Comparison) + +| Feature | Non-custodial wallet | Custodial wallet | +| -------------------------- | -------------------- | ------------------------------- | +| Who controls private keys? | You | Third party (exchange/provider) | +| Account recovery | Usually none | Often available (email/KYC) | +| Censorship resistance | Higher | Lower (platform rules) | +| Ease of use | More responsibility | More convenience | +| dApp access | Direct | Sometimes limited | + +## Summary + +A non-custodial wallet is a wallet where **you control the private keys**, meaning you directly authorize and sign blockchain transactions without relying on a custodian. In general, it works by generating keys from a seed phrase, signing transactions locally, and broadcasting them to the network. On Sei Network, non-custodial wallets benefit from **EVM compatibility**, **parallelization**, and fast finality (around **~400ms**), making on-chain interactions feel notably faster while preserving self-custody. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-rebase-token-and-how-does-it-work.mdx b/content/answers/what-is-a-rebase-token-and-how-does-it-work.mdx new file mode 100644 index 00000000..771facb4 --- /dev/null +++ b/content/answers/what-is-a-rebase-token-and-how-does-it-work.mdx @@ -0,0 +1,202 @@ +--- +title: 'What is a Rebase Token and How Does It Work?' +description: 'Learn about what is rebase token and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'rebase', 'token', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Rebase Token and How Does It Work? + +## Overview + +A **rebase token** is a cryptocurrency whose **total supply automatically adjusts up or down** at predefined times or in response to certain conditions, while each holder’s wallet balance changes **proportionally**. In other words, instead of the token price moving to reflect demand, the protocol changes the number of tokens in circulation to influence the price (or track an external target). + +If you’re searching for **what is rebase token**, the key idea is: **your number of tokens can change without you transferring anything**, because the protocol “rebases” (resizes) balances. + +## How It Works + +### Supply adjustment (“rebase”) mechanics + +Rebase tokens implement a periodic supply update, typically called a **rebase event**. During a rebase: + +- The protocol computes a **rebase factor** (e.g., +2% or −1% supply change). +- **All holders’ balances are scaled by the same factor**. +- The token’s **total supply changes**, but each holder’s **ownership percentage** of the network remains roughly the same (excluding rounding and special accounts). + +Example: + +- You hold 100 tokens. +- A +10% rebase occurs. +- Your balance becomes 110 tokens. +- Everyone else’s balance also increases by 10%, so your share of the total stays similar. + +### Positive vs. negative rebase + +- **Positive rebase**: total supply increases; balances increase proportionally. +- **Negative rebase**: total supply decreases; balances decrease proportionally. + +### Why rebase tokens exist + +Rebase designs are commonly used to: + +- Attempt to **stabilize** around a target (e.g., $1, CPI index, or another reference). +- Express “elastic supply” monetary policies. +- Implement certain algorithmic or index-like token behaviors. + +### Key implications for users and apps + +- **Wallet balances are not constant**: a user’s “amount of tokens” changes after each rebase. +- **Price and market cap interpretation**: price may adjust after rebase; market cap can remain similar even as supply changes. +- **Integrations can be tricky**: + - DEX pools, lending protocols, vaults, and accounting systems must handle **changing balances**. + - Some rebasing tokens use “shares” internally and show “balance” as a derived value. +- **Not the same as staking rewards**: staking increases balances for stakers only; rebasing usually affects all holders proportionally (or all holders in a defined set). + +## Common Implementation Patterns + +### 1) Global scaling factor (“gons” / “shares” model) + +Many rebasing ERC-20 tokens avoid updating every address on rebase (which would be too expensive) by: + +- Tracking balances in **internal units** (shares). +- Maintaining a global **scaling factor** that converts shares to user-facing balances. + +This allows O(1) rebase updates (update one global variable), rather than iterating through all holders. + +### 2) Explicit balance updates (rare on-chain) + +Directly updating every holder’s balance during a rebase is typically impractical on-chain due to gas and state access costs. + +## Solidity Example (Simplified “Shares + Index” Rebase Token) + +Below is a conceptual, simplified pattern showing how rebasing can be implemented via a global index. (This is not production-ready—real implementations must address rounding, permissions, integrations, and security concerns.) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +contract SimpleRebaseToken { + string public name = "Simple Rebase Token"; + string public symbol = "SRT"; + uint8 public decimals = 18; + + // "Shares" are internal units that don't change during rebase + mapping(address => uint256) private _shares; + uint256 private _totalShares; + + // Index scales shares -> token balance: balance = shares * index / 1e18 + uint256 public index = 1e18; // starts at 1.0 + + event Transfer(address indexed from, address indexed to, uint256 value); + event Rebase(uint256 oldIndex, uint256 newIndex); + + function totalSupply() public view returns (uint256) { + // supply changes as index changes + return (_totalShares * index) / 1e18; + } + + function balanceOf(address account) public view returns (uint256) { + return (_shares[account] * index) / 1e18; + } + + function sharesOf(address account) external view returns (uint256) { + return _shares[account]; + } + + function transfer(address to, uint256 amount) external returns (bool) { + // Convert amount -> shares at current index + uint256 shareAmount = (amount * 1e18) / index; + + _shares[msg.sender] -= shareAmount; + _shares[to] += shareAmount; + + emit Transfer(msg.sender, to, amount); + return true; + } + + function mint(address to, uint256 amount) external { + uint256 shareAmount = (amount * 1e18) / index; + _shares[to] += shareAmount; + _totalShares += shareAmount; + emit Transfer(address(0), to, amount); + } + + // Rebase by updating the global index (e.g., +5% => index *= 1.05) + function rebase(int256 bps) external { + // bps in basis points, e.g., +500 = +5%, -200 = -2% + uint256 old = index; + + if (bps >= 0) { + index = (index * (10_000 + uint256(bps))) / 10_000; + } else { + index = (index * (10_000 - uint256(-bps))) / 10_000; + } + + emit Rebase(old, index); + } +} +``` + +### Notes for integrators + +- If a protocol records a user’s “token amount” over time, it must handle that balances can change after a rebase. +- Some systems prefer to account in **shares** (fixed) rather than rebasing balances (variable). + +## On Sei Network + +On **Sei Network**, a rebase token typically uses the **same ERC-20 patterns** as on other EVM chains, because Sei is **EVM compatible**. That means you can deploy rebasing token contracts using Solidity and standard tooling, while benefiting from Sei’s performance characteristics. + +Key considerations specific to Sei: + +- **Fast finality (~400ms)**: Rebase events (index updates) can be confirmed quickly, which can improve UX for apps that synchronize after a rebase (e.g., dashboards, vaults, or DEX adapters). +- **High throughput and parallelization**: Sei’s architecture is designed for **parallel execution**, which helps high-activity ecosystems (DEXs, perps, aggregators) remain responsive even when many users interact with rebasing assets around rebase boundaries. +- **Ecosystem integrations**: When integrating a rebasing token into Sei-based DeFi: + - Ensure AMMs, lending markets, and vault strategies correctly handle rebasing balance semantics. + - Prefer internal accounting in **shares** or use wrapper tokens (non-rebasing representations) if a protocol expects static balances. + +### Deploying a Rebase Token to Sei (Example) + +Using standard EVM workflows (e.g., Foundry), deployment looks like any other EVM chain—just target Sei’s RPC. + +```bash +# Example (replace RPC URL, private key, and contract path as needed) +export SEI_EVM_RPC="https://YOUR_SEI_RPC_ENDPOINT" +export PRIVATE_KEY="0xYOUR_PRIVATE_KEY" + +forge create \ + --rpc-url "$SEI_EVM_RPC" \ + --private-key "$PRIVATE_KEY" \ + src/SimpleRebaseToken.sol:SimpleRebaseToken +``` + +## Benefits and Risks + +### Potential benefits + +- Can implement **elastic-supply** tokenomics or algorithmic stabilization. +- Efficient rebases using a global index (low per-rebase gas). + +### Key risks / gotchas + +- **User confusion**: “I didn’t transact, why did my balance change?” +- **Protocol compatibility**: Some DeFi systems break if they assume fixed balances. +- **Rounding effects**: Small holders may see tiny rounding discrepancies over time. +- **Market dynamics**: Rebasing does not guarantee price stability; it changes supply mechanics and can introduce volatility. + +## Summary + +A rebase token is an elastic-supply asset where wallet balances are periodically adjusted via a protocol-driven rebase, changing total supply without requiring transfers. In general blockchain terms, rebases are typically implemented using a global scaling factor over internal “shares” to avoid per-holder updates. On **Sei Network**, rebasing tokens are implemented like standard ERC-20 contracts thanks to **EVM compatibility**, and can benefit from Sei’s **~400ms finality** and **parallelized, high-throughput** execution for smoother integration in high-activity DeFi environments. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-rollup-and-how-does-it-work.mdx b/content/answers/what-is-a-rollup-and-how-does-it-work.mdx new file mode 100644 index 00000000..25228435 --- /dev/null +++ b/content/answers/what-is-a-rollup-and-how-does-it-work.mdx @@ -0,0 +1,160 @@ +--- +title: 'What is a Rollup and How Does It Work?' +description: 'Learn about what is rollup and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'rollup', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Rollup and How Does It Work? + +## Overview + +A **rollup** is a Layer 2 (L2) scaling solution that processes transactions off-chain (or off the base layer) and then posts a compressed summary of those transactions to a Layer 1 (L1) blockchain for security. In other words, **what is rollup** technology? It’s a method to increase throughput and reduce fees while still inheriting the L1’s security guarantees. + +Rollups are widely used to scale smart contract platforms by moving execution and data handling to an L2 and using the L1 as the source of truth for settlement and dispute resolution. + +## How It Works + +At a high level, rollups work by separating **execution** (compute) from **settlement** (final recording on L1): + +1. **Users send transactions to the rollup** + + - Transactions are submitted to an L2 network operated by one or more entities (often called a **sequencer**). + - The sequencer orders transactions and produces L2 blocks. + +2. **Transactions are executed off the L1** + + - The rollup executes transactions and updates its state (account balances, contract storage, etc.) on the L2. + - This reduces load on the L1 since the L1 no longer executes every transaction directly. + +3. **Compressed data/state commitments are posted to the L1** + + - The rollup periodically submits a batch of transactions (or their calldata) plus a **state root** commitment to the L1. + - Posting enough data to the L1 is critical so anyone can reconstruct and verify the rollup state (“data availability”). + +4. **The L1 enforces correctness via proofs or challenges** + Rollups typically fall into two main categories: + + **Optimistic Rollups** + + - Assume batches are valid by default (“optimistically”). + - Include a **challenge window** during which anyone can submit a fraud proof to show the batch is invalid. + - Pros: simpler proving; often EVM-compatible. + - Tradeoff: withdrawals to L1 may require waiting until the challenge period ends. + + **ZK Rollups (Zero-Knowledge Rollups)** + + - Submit a **validity proof** (e.g., SNARK/STARK) to the L1 proving the state transition is correct. + - Pros: fast finality for withdrawals (once proof is verified); strong correctness guarantees. + - Tradeoff: more complex infrastructure; proving can be compute-intensive. + +### Key components + +- **Sequencer**: Orders transactions and produces L2 blocks. Some systems are centralized initially; decentralization is a common roadmap goal. +- **Prover (ZK rollups)**: Generates validity proofs for batches. +- **Verifier contract (on L1)**: Verifies fraud proofs (optimistic) or validity proofs (ZK) and stores rollup commitments. +- **Bridges**: Smart contracts that lock assets on L1 and mint/credit corresponding assets on L2, and vice versa. + +### Conceptual flow (simplified) + +```text +User tx -> Rollup sequencer -> L2 execution -> Batch + state root -> L1 settlement + |-> (optional) proof -> L1 verification +``` + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **~400ms finality**, **parallelized execution**, and **EVM compatibility** (via Sei’s EVM). While rollups are typically discussed as L2s built on top of an L1, understanding rollups is still important for Sei builders because: + +- **Sei’s fast finality reduces settlement latency**: If a rollup (or rollup-like system) settles to Sei, frequent batching and quicker confirmations on the settlement layer can improve end-user responsiveness. +- **Parallelization improves throughput for settlement workloads**: Rollups often post batches, verify proofs, and process bridge operations—Sei’s parallel execution can help handle these settlement transactions efficiently. +- **EVM compatibility simplifies integration**: Many rollup ecosystems and tooling are Ethereum-oriented. Sei’s EVM compatibility can make it easier to port smart contracts or bridge/settlement logic that assumes EVM semantics. + +### Example: Posting a batch commitment (conceptual) + +A rollup settlement contract on an EVM-compatible chain (including Sei EVM) often stores a batch commitment such as a state root and metadata: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract RollupSettlement { + struct Batch { + bytes32 stateRoot; + bytes32 txDataHash; // hash of compressed tx data / calldata + uint256 timestamp; + } + + Batch[] public batches; + + event BatchSubmitted(uint256 indexed batchIndex, bytes32 stateRoot, bytes32 txDataHash); + + function submitBatch(bytes32 stateRoot, bytes32 txDataHash) external { + batches.push(Batch({ + stateRoot: stateRoot, + txDataHash: txDataHash, + timestamp: block.timestamp + })); + + emit BatchSubmitted(batches.length - 1, stateRoot, txDataHash); + } +} +``` + +In production systems, this contract would typically also include: + +- Access control / sequencer rotation rules +- Fraud-proof or validity-proof verification logic +- Bridge hooks for deposits and withdrawals + +### Example: Interacting with a settlement contract on Sei EVM + +Using `ethers` to submit a batch: + +```typescript +import { ethers } from 'ethers'; + +const rpcUrl = process.env.SEI_EVM_RPC!; +const privateKey = process.env.PRIVATE_KEY!; +const contractAddress = '0xYourRollupSettlementContract'; + +const abi = ['function submitBatch(bytes32 stateRoot, bytes32 txDataHash) external', 'event BatchSubmitted(uint256 indexed batchIndex, bytes32 stateRoot, bytes32 txDataHash)']; + +async function main() { + const provider = new ethers.JsonRpcProvider(rpcUrl); + const wallet = new ethers.Wallet(privateKey, provider); + const contract = new ethers.Contract(contractAddress, abi, wallet); + + const stateRoot = '0x' + '11'.repeat(32); + const txDataHash = '0x' + '22'.repeat(32); + + const tx = await contract.submitBatch(stateRoot, txDataHash); + await tx.wait(); + + console.log('Batch submitted:', tx.hash); +} + +main().catch(console.error); +``` + +## Why Rollups Matter + +Rollups matter because they can: + +- **Increase transaction throughput** by moving execution off the base chain +- **Lower fees** by amortizing L1 costs across many L2 transactions +- **Preserve strong security guarantees** by settling to an L1 and enabling on-chain verification (via proofs or challenges) + +On high-performance L1s like Sei—designed with fast finality, parallel execution, and EVM compatibility—rollup settlement and rollup-adjacent designs can benefit from efficient, low-latency confirmation and familiar Ethereum tooling. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-rug-pull-and-how-does-it-work.mdx b/content/answers/what-is-a-rug-pull-and-how-does-it-work.mdx new file mode 100644 index 00000000..7dc4e33e --- /dev/null +++ b/content/answers/what-is-a-rug-pull-and-how-does-it-work.mdx @@ -0,0 +1,157 @@ +--- +title: 'What is a Rug Pull and How Does It Work?' +description: 'Learn about what is rug pull and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'rug', 'pull', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Rug Pull and How Does It Work? + +## Overview + +A **rug pull** is a type of crypto scam where project creators or insiders suddenly drain funds or abandon a project, leaving investors with tokens that rapidly lose value or become impossible to sell. In short, it’s when liquidity, assets, or trust is “pulled out from under” the community—often after aggressive marketing and hype. + +When people ask **“what is rug pull”**, they’re usually referring to these scams in DeFi and token launches, especially on decentralized exchanges (DEXs) where anyone can create a token and liquidity pool. + +## How It Works + +Rug pulls generally exploit the open, permissionless nature of blockchains: anyone can deploy a token contract, create a market, and attract buyers without centralized gatekeepers. Common patterns include: + +### 1) Liquidity Removal (Classic DEX Rug Pull) + +**Mechanism:** The team creates a token and seeds a DEX liquidity pool (e.g., TOKEN/USDC). Buyers swap into the token, increasing the pool value. The team then **withdraws the liquidity** (often by removing LP tokens), causing the token price to collapse and leaving holders unable to sell without extreme slippage. + +**Typical indicators** + +- Liquidity is not locked or is lockable only for a short period +- LP tokens are held by the deployer wallet (single point of control) +- Sudden, large liquidity withdrawals + +### 2) Mint / Supply Inflation Rugs + +**Mechanism:** The token contract allows the owner to **mint unlimited tokens** or adjust supply parameters. After buyers purchase, the owner mints a massive amount and sells into the pool, crashing the price. + +**Indicators** + +- Owner-controlled `mint()` or supply-changing functions +- No hard cap or unclear tokenomics +- Owner retains special privileges without time locks or governance + +### 3) Trading Restriction (Honeypot-Style Rugs) + +**Mechanism:** The contract is coded so that users can buy but **cannot sell**, or selling is subject to extreme taxes/fees that effectively prevent exiting. This is often disguised via complex transfer logic. + +**Indicators** + +- Transfer logic includes blacklists/whitelists controlled by owner +- Sell tax can be changed to 50–100% +- Only certain addresses can sell or interact with the pair + +### 4) Treasury / Protocol Drain + +**Mechanism:** In protocols (staking, vaults, lending), developers include backdoors or privileged roles that can **move user deposits** or withdraw protocol funds. + +**Indicators** + +- Upgradeable contracts without transparent governance +- Admin keys with broad permissions +- No multisig, no time locks, no audits + +### 5) “Soft Rug” (Abandonment / Slow Exit) + +**Mechanism:** Rather than a single event, the team slowly sells allocations, fails to deliver, disappears from social channels, or stops maintaining liquidity and development. The result is still the same: token value collapses. + +**Indicators** + +- Anonymous team with no accountability +- Unclear roadmap and no commits/releases +- Insider wallets steadily selling + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility** and fast, deterministic block performance (often cited around **~400ms finality**). Rug pulls can still occur on Sei—because they are primarily **smart contract and governance risks**, not “slow chain” problems. + +Where Sei’s design matters: + +- **EVM compatibility:** Many token and DeFi contracts on Sei follow familiar Ethereum patterns (ERC-20–style tokens, DEX pools, LP tokens). This means the _same rug pull vectors_ (liquidity removal, honeypots, admin backdoors) can exist if contracts are unsafe. +- **Fast finality (~400ms):** If a rug pull transaction is submitted (e.g., liquidity removal or admin drain), it can finalize quickly. That’s good for user experience, but it also means victims may have **little time to react** once malicious actions start. +- **Parallelization:** Sei’s parallel execution helps throughput and reduces congestion, but it doesn’t automatically protect against malicious contract logic. Security still depends on contract design, audits, and permission controls. + +In practice, the best defense on Sei is the same as elsewhere: evaluate contract permissions, liquidity controls, and admin key management—especially for newly launched tokens and high-APR farms. + +## Common Rug Pull Techniques (Smart Contract Patterns) + +Below are simplified examples of patterns that are often abused. These snippets are for educational detection purposes. + +### Owner-controlled minting + +```solidity +// Simplified example: unlimited minting controlled by owner +function mint(address to, uint256 amount) external onlyOwner { + _mint(to, amount); +} +``` + +### Owner can change fees to block selling + +```solidity +// Example: owner can set sell fee to near 100% +uint256 public sellFeeBps = 300; // 3% + +function setSellFee(uint256 newFeeBps) external onlyOwner { + require(newFeeBps <= 10000, "bps max"); + sellFeeBps = newFeeBps; +} +``` + +### Blacklist / restricted transfers + +```solidity +mapping(address => bool) public blacklisted; + +function setBlacklisted(address user, bool value) external onlyOwner { + blacklisted[user] = value; +} + +function _beforeTokenTransfer(address from, address to, uint256 amount) internal view { + require(!blacklisted[from] && !blacklisted[to], "blacklisted"); +} +``` + +## How to Reduce Rug Pull Risk (Quick Checklist) + +### Token & contract checks + +- Verify the contract is **verified** and readable on a block explorer. +- Look for **owner privileges**: minting, pausing, blacklisting, fee changes, upgrades. +- Prefer contracts with: + - **Renounced ownership** (when appropriate), or + - Ownership behind a **multisig** and **time lock** + +### Liquidity checks (DEX tokens) + +- Confirm liquidity is **locked** for a meaningful duration or controlled by a reputable mechanism. +- Identify who holds the **LP tokens**. +- Watch for unusually high **sell taxes** or dynamic fee controls. + +### Project due diligence + +- Avoid projects that rely solely on marketing, countdown launches, or unrealistic APR. +- Review audits (if any), but also verify whether the deployed contract matches the audited version. +- Track team wallets and token distribution to spot concentrated insider holdings. + +## Summary + +A rug pull is a scam where project insiders use control over liquidity, token supply, or privileged contract functions to extract value and leave holders with near-worthless tokens. It typically plays out via liquidity removal, mint-and-dump, honeypot sell restrictions, or admin-key drains. On Sei Network—despite fast finality, parallelization, and EVM compatibility—rug pull risk is primarily determined by smart contract permissions and liquidity controls, so careful onchain verification and risk checks remain essential. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-sidechain-and-how-does-it-work.mdx b/content/answers/what-is-a-sidechain-and-how-does-it-work.mdx new file mode 100644 index 00000000..c2c9e5f5 --- /dev/null +++ b/content/answers/what-is-a-sidechain-and-how-does-it-work.mdx @@ -0,0 +1,145 @@ +--- +title: 'What is a Sidechain and How Does It Work?' +description: 'Learn about what is sidechain and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'sidechain', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Sidechain and How Does It Work? + +## Overview + +A **sidechain** is an independent blockchain that runs in parallel to a “main” blockchain (often called the **mainchain** or **Layer 1**) and is connected to it through a bridge, typically enabling assets or data to move between the two networks. In practice, when people ask **“what is sidechain”**, they’re usually referring to a chain that offloads activity from the mainchain to improve scalability, add features, or experiment with different rules while still interoperating with the main ecosystem. + +Sidechains are commonly used to increase throughput, reduce fees, enable custom execution environments (e.g., different virtual machines), or support application-specific requirements without changing the mainchain’s base protocol. + +## How It Works + +### 1) Independent consensus and security model + +A core property of a sidechain is that it typically has its **own validator set and consensus mechanism**. That means: + +- The sidechain can process transactions and finalize blocks independently of the mainchain. +- The sidechain’s security is usually **separate** from the mainchain’s security (unless it uses special “shared security” designs). + +This independence enables flexibility, but also means the sidechain’s trust assumptions may differ from the mainchain’s. + +### 2) Two-way bridging (pegging) + +To move assets between a mainchain and a sidechain, ecosystems rely on a **bridge**. The bridge implements a **two-way peg** conceptually: + +- **Mainchain → Sidechain:** Assets are locked (or escrowed) on the mainchain, and a corresponding representation is minted/released on the sidechain. +- **Sidechain → Mainchain:** The sidechain representation is burned/locked, and the original assets are released back on the mainchain. + +Bridges can be implemented in several ways: + +- **Federated bridges:** A set of entities collectively controls the bridge (common historically; introduces trust in the federation). +- **Light-client / proof-based bridges:** One chain verifies cryptographic proofs of the other chain’s state (more trust-minimized, but complex). +- **Optimistic bridges:** Transfers are assumed valid unless challenged within a dispute window. + +### 3) Cross-chain messaging + +Beyond asset transfers, some sidechains support **general message passing**, enabling contracts on one chain to trigger actions on another. This can power: + +- Cross-chain swaps and routing +- Cross-chain governance or voting +- Interoperable dApps spanning multiple chains + +### 4) Why sidechains exist (benefits and tradeoffs) + +**Benefits** + +- Higher throughput / lower fees due to independent blockspace +- Faster iteration and specialized features (custom gas rules, privacy, app-specific logic) +- Reduced load on the mainchain + +**Tradeoffs** + +- Different (often weaker) security assumptions than the mainchain +- Bridge risk: bridges are frequent attack targets, and can be the weakest link +- Liquidity fragmentation (assets spread across chains) + +### Sidechain vs. Layer 2 (quick distinction) + +A **Layer 2** (e.g., optimistic rollups, zk-rollups) generally derives security from the mainchain by posting proofs or transaction data back to it. A **sidechain** usually does **not** inherit mainchain security by default; it operates with its own consensus and relies on bridging for interoperability. + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, designed for low-latency execution and high throughput. While **Sei itself is not a sidechain** (it’s a standalone L1), it can participate in **sidechain-like architectures** in two common ways: + +1. **Sei as a high-performance execution environment connected to other chains via bridges** + +- Projects may treat Sei as a fast settlement/execution domain for trading, DeFi, and high-frequency applications. +- With Sei’s parallelization and ~**400ms finality**, cross-chain workflows can feel more responsive once messages/bridged transfers arrive on Sei. + +2. **Sei as a “mainchain” that connects to app-specific chains** + +- An application may choose to run an appchain/sidechain for specialized needs and bridge to Sei for liquidity and user access. +- Sei’s EVM compatibility makes it straightforward for teams to reuse Solidity tooling and patterns when building cross-chain integrations. + +### Practical implications for builders on Sei + +- **Bridge integration matters:** If your dApp on Sei accepts assets bridged from another network (or sends assets out), your security model must account for the bridge’s trust assumptions. +- **Fast finality helps UX:** Once a cross-chain transfer is finalized on Sei, users can proceed quickly thanks to rapid block finality and parallel execution. +- **EVM interoperability:** Solidity contracts can implement common bridging and “wrapped asset” patterns familiar from other EVM ecosystems. + +## Example: Basic lock/mint pattern (illustrative) + +Below is a simplified example of a bridge-style contract pattern. Real bridges require rigorous validation of cross-chain proofs, replay protection, rate limits, and robust access controls—this snippet is for conceptual understanding only. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function transfer(address to, uint256 amount) external returns (bool); +} + +contract SimpleLockbox { + IERC20 public immutable token; + + // In real systems this would be a verified bridge module, not a single key. + address public bridgeOperator; + + event Locked(address indexed user, uint256 amount, bytes32 indexed destination); + event Released(address indexed user, uint256 amount); + + constructor(IERC20 _token, address _bridgeOperator) { + token = _token; + bridgeOperator = _bridgeOperator; + } + + // User locks tokens on this chain; bridge mints/releases representation on the sidechain. + function lock(uint256 amount, bytes32 destinationAddressOnOtherChain) external { + require(amount > 0, "amount=0"); + require(token.transferFrom(msg.sender, address(this), amount), "transferFrom failed"); + emit Locked(msg.sender, amount, destinationAddressOnOtherChain); + } + + // Bridge releases tokens back after verifying a burn/lock happened on the other chain. + function release(address to, uint256 amount) external { + require(msg.sender == bridgeOperator, "not authorized"); + require(token.transfer(to, amount), "transfer failed"); + emit Released(to, amount); + } +} +``` + +## Key Takeaways + +- A sidechain is an independent blockchain connected to a mainchain via a bridge; it can move assets/data across chains while operating under its own consensus. +- Sidechains help scale and add flexibility but introduce separate security assumptions and bridge risk. +- On Sei Network, sidechain-style designs commonly show up through **bridged interoperability** and **app-specific chains**, with Sei’s **parallelization**, **~400ms finality**, and **EVM compatibility** supporting fast, familiar developer workflows. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-slippage-and-how-does-it-work.mdx b/content/answers/what-is-a-slippage-and-how-does-it-work.mdx new file mode 100644 index 00000000..4136436c --- /dev/null +++ b/content/answers/what-is-a-slippage-and-how-does-it-work.mdx @@ -0,0 +1,140 @@ +--- +title: 'What is a Slippage and How Does It Work?' +description: 'Learn about what is slippage and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'slippage', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Slippage and How Does It Work? + +## Overview + +Slippage is the difference between the expected price of a trade and the actual execution price. It usually happens when prices move between the time you submit a transaction and the time it is confirmed, or when there isn’t enough liquidity at your desired price. In simple terms, slippage is the “price drift” you experience when buying or selling on-chain. + +## How It Works + +In most crypto trading (especially on AMMs/DEXs), slippage occurs because trades are executed against liquidity pools with prices determined by supply and demand. When you submit a trade, the blockchain must include your transaction in a block; by the time it executes, pool reserves or market prices may have changed. + +### Common Causes of Slippage + +- **Price volatility:** Rapid price movements can change the best available price before your transaction executes. +- **Low liquidity / shallow pools:** Larger trades move the pool price more, causing worse execution. +- **Trade size (price impact):** AMM pricing curves (e.g., constant product) adjust price as your swap consumes liquidity. +- **Network congestion:** Longer confirmation times increase the window for price changes. +- **MEV / frontrunning (on some networks):** Other transactions can reorder or trade around yours, affecting the execution price. + +### Positive vs. Negative Slippage + +- **Negative slippage:** You receive fewer tokens than expected (worse price). +- **Positive slippage:** You receive more tokens than expected (better price). Some DEXs pass this benefit to the trader; others may route it differently depending on design. + +### Slippage Tolerance + +Most wallets and DEX UIs let you set a **slippage tolerance** (e.g., 0.5%, 1%, 2%). This defines the maximum acceptable deviation from the quoted price. If execution would exceed that limit, the swap reverts to protect you from unexpectedly bad fills. + +In AMM-based swaps, slippage tolerance typically translates into a **minimum output amount** (often `amountOutMin`) or a **maximum input amount** (for exact-output swaps). The transaction will only succeed if the on-chain execution meets that constraint. + +### Example (Conceptual) + +If you expect to receive **1,000 USDC** for selling a token, and you set a **1%** slippage tolerance, then the trade must execute at **≥ 990 USDC**. If the pool price moves such that you would receive **985 USDC**, the transaction reverts. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, built for fast and efficient trading. Slippage mechanics on Sei are the same as in other EVM ecosystems—your execution depends on liquidity, price impact, and the state of the pool at the moment your transaction is included. + +Where Sei makes a practical difference: + +- **~400ms finality reduces time-based slippage risk:** Faster confirmation lowers the time window for adverse price movement between submission and execution compared to slower-finality networks. +- **Parallelization improves throughput:** Sei’s parallelized execution helps the network handle many transactions efficiently, which can reduce congestion-related delays that often amplify slippage. +- **EVM compatibility:** Solidity-based DEX contracts on Sei typically expose the same parameters you’ll recognize from other chains (e.g., `amountOutMin`, `deadline`), so slippage protection patterns carry over directly. + +Even on a fast chain, slippage can still occur due to **low liquidity**, **large trades**, or **rapid market movement**—speed helps, but it doesn’t eliminate AMM price impact. + +## Code Examples + +### Solidity: Enforcing Slippage Protection in a Swap + +Below is a simplified Uniswap V2–style swap example showing how `amountOutMin` protects against slippage. (Router and interface names may vary by DEX deployment on Sei.) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IRouter { + function swapExactTokensForTokens( + uint amountIn, + uint amountOutMin, + address[] calldata path, + address to, + uint deadline + ) external returns (uint[] memory amounts); +} + +contract SlippageProtectedSwap { + IRouter public immutable router; + + constructor(address _router) { + router = IRouter(_router); + } + + function swap( + uint256 amountIn, + uint256 minAmountOut, // slippage-protected minimum received + address[] calldata path + ) external { + // In a real implementation, you'd transfer/approve tokenIn first. + uint256 deadline = block.timestamp + 60; // short deadline reduces execution uncertainty + + router.swapExactTokensForTokens( + amountIn, + minAmountOut, + path, + msg.sender, + deadline + ); + } +} +``` + +**Key idea:** `minAmountOut` is derived from your quote and slippage tolerance. If the pool state changes such that output would be lower, the transaction reverts. + +### TypeScript: Calculating `amountOutMin` from Slippage Tolerance + +```typescript +import { BigNumber } from 'ethers'; + +// expectedOut: quoted amount out from a router quoter or UI quote +// slippageBps: slippage tolerance in basis points (e.g., 50 = 0.50%, 100 = 1%) +export function amountOutMin(expectedOut: BigNumber, slippageBps: number): BigNumber { + const bpsDenominator = BigNumber.from(10_000); + const slippage = bpsDenominator.sub(BigNumber.from(slippageBps)); + return expectedOut.mul(slippage).div(bpsDenominator); +} + +// Example: +// expectedOut = 1000 units, slippageBps = 100 (1%) => amountOutMin = 990 units +``` + +### Best Practices to Reduce Slippage (Especially for On-Chain Swaps) + +- **Use deeper liquidity pools** and consider splitting large trades. +- **Set a reasonable slippage tolerance:** Too low may cause frequent reverts; too high may lead to poor fills. +- **Use short deadlines** to reduce exposure to price movement. +- **Avoid trading during extreme volatility** or when liquidity is thin. +- On Sei, **fast finality** and **high throughput** can help reduce delay-driven slippage, but you still need `amountOutMin`/slippage controls. + +## Summary + +If you’re searching “**what is slippage**,” the core answer is: slippage is the execution-price difference caused by market movement and liquidity conditions between quote and confirmation. In blockchain trading, it’s managed with slippage tolerance settings and on-chain minimum/maximum bounds (like `amountOutMin`). On Sei Network, the same protections apply, with the added benefit that Sei’s fast (~400ms) finality and parallelized execution can reduce delay-related slippage in practice. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-smart-contract-and-how-does-it-work.mdx b/content/answers/what-is-a-smart-contract-and-how-does-it-work.mdx new file mode 100644 index 00000000..9c10d688 --- /dev/null +++ b/content/answers/what-is-a-smart-contract-and-how-does-it-work.mdx @@ -0,0 +1,145 @@ +--- +title: 'What is a Smart Contract and How Does It Work?' +description: 'Learn about what is smart contract and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'evm', 'what', 'smart', 'contract', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Smart Contract and How Does It Work? + +## Overview + +A **smart contract** is a program deployed on a blockchain that automatically executes predefined actions when specific conditions are met. In practical terms, it’s a **tamper-resistant, publicly verifiable** set of rules that can hold and transfer value (tokens) without relying on a centralized intermediary. If you’re asking **what is smart contract**, it’s best understood as “code + state” living on-chain. + +## How It Works + +### 1) Contract code and state + +A smart contract consists of: + +- **Code**: the logic (functions, checks, rules). +- **State**: stored data (balances, ownership, configuration, etc.). + +Once deployed, the code is typically immutable (or only upgradable via explicit patterns), and the state changes only through valid transactions. + +### 2) Transactions trigger execution + +Smart contracts don’t run on their own. They execute when a transaction (or another contract call) invokes them: + +- A user submits a transaction calling a function (e.g., `transfer`, `swap`, `mint`). +- Network validators execute the contract code deterministically. +- If the call succeeds, state updates are committed to the blockchain; if it reverts, state remains unchanged. + +### 3) Deterministic computation and consensus + +Every validator (or node) must compute the **same result** from the same inputs. The blockchain’s consensus ensures: + +- Only valid state transitions are finalized. +- The resulting state is consistent across all nodes. + +### 4) Gas/fees and execution limits (EVM context) + +On EVM-based chains, execution costs **gas**, which: + +- Prices computation and storage. +- Prevents infinite loops / resource abuse. +- Is paid by the transaction sender as a fee. + +### 5) Events and composability + +Contracts can: + +- Emit **events** to create an indexed on-chain log for apps and analytics. +- Call other contracts, enabling **composability** (e.g., DeFi building blocks). + +## Common Smart Contract Use Cases + +- **Token issuance** (ERC-20 / ERC-721 / ERC-1155) +- **DeFi** (DEX swaps, lending, staking, derivatives) +- **NFT minting and marketplaces** +- **DAOs and governance** (voting, timelocks, treasuries) +- **Escrow and payments** (conditional release, subscriptions) + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, meaning developers can deploy and interact with Solidity smart contracts using familiar Ethereum tooling. Sei’s architecture is designed for speed and scalability, leveraging **parallelization** where possible and providing **~400ms finality**, which can significantly improve UX for trading, payments, and other latency-sensitive applications. + +Key implications for smart contracts on Sei: + +- **EVM-compatible development**: Write contracts in Solidity, use standard ABIs, and integrate with common libraries and frameworks. +- **Fast confirmation UX**: With **~400ms finality**, contract interactions (e.g., swaps, mints, game actions) can feel near-instant compared to slower finality chains. +- **Parallelized execution potential**: Sei is built to increase throughput via parallelization, enabling higher performance for workloads with independent state access patterns. + +## Example: A Simple Solidity Smart Contract (EVM) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public number; + + event NumberChanged(uint256 newNumber, address indexed caller); + + function setNumber(uint256 newNumber) external { + number = newNumber; + emit NumberChanged(newNumber, msg.sender); + } + + function increment() external { + number += 1; + emit NumberChanged(number, msg.sender); + } +} +``` + +What’s happening here: + +- `number` is **on-chain state** stored in the contract. +- `setNumber` and `increment` are **transactions** that update state. +- `NumberChanged` is an **event** that frontends/indexers can watch. + +## Deploying to Sei EVM (Example) + +Using Foundry (one common workflow), you can deploy to Sei’s EVM JSON-RPC endpoint. + +```bash +# Set environment variables +export RPC_URL="https://" +export PRIVATE_KEY="" + +# Deploy (example assumes a Foundry script or direct create) +forge create --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" src/Counter.sol:Counter +``` + +Then call a function: + +```bash +cast send "increment()" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" +``` + +## Security Considerations (Best Practices) + +Smart contracts are powerful but unforgiving—bugs can become irreversible once deployed. Common best practices include: + +- Use audited libraries (e.g., OpenZeppelin). +- Add access controls (e.g., `onlyOwner`) where needed. +- Prefer pull over push payments to reduce reentrancy risk. +- Write tests (unit + fuzz + integration) and run static analysis. +- Consider upgradeability carefully (transparent/UUPS proxies, timelocks, governance). + +## Summary + +If you’re looking for a practical answer to **what is smart contract**, it’s an on-chain program that enforces rules and executes transactions automatically, with results verified by network consensus. On **Sei Network**, smart contracts benefit from **EVM compatibility**, **parallelization-focused performance**, and **~400ms finality**, making them well-suited for high-throughput, real-time applications. + +## Related Documentation + +- [EVM Overview](/evm) +- [Networks & RPC](/evm/networks) +- [Deploy with Hardhat](/evm/evm-hardhat) +- [Deploy with Foundry](/evm/evm-foundry) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx b/content/answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx new file mode 100644 index 00000000..edc0123e --- /dev/null +++ b/content/answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx @@ -0,0 +1,223 @@ +--- +title: 'What is a Smart Contract Audit and How Does It Work?' +description: 'Learn about what is smart contract audit and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'evm', 'what', 'smart', 'contract', 'audit', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Smart Contract Audit and How Does It Work? + +## Overview + +A smart contract audit is a structured security review of a blockchain contract’s code, design, and deployment configuration to identify vulnerabilities, logic errors, and economic attack vectors before mainnet release. It typically results in a written report that documents findings by severity and provides remediation guidance and verification of fixes. In short, **what is smart contract audit**: an independent, systematic process to reduce the likelihood of exploits and unexpected behavior in immutable on-chain programs. + +## How It Works + +### 1) Define scope and threat model + +Audits start by clarifying what will be reviewed and what “correct” behavior means: + +- **In-scope repos/contracts** (including proxies, libraries, and scripts) +- **Intended invariants** (e.g., “total supply never decreases,” “only owner can pause,” “no user can withdraw more than deposited”) +- **Trust assumptions** (admins, multisigs, oracles, bridges, off-chain signers) +- **Economic/security goals** (MEV resistance, liquidation safety, replay protection) + +A good threat model determines whether the audit focuses only on code correctness or also includes **economic design** (e.g., incentives, pricing, oracle manipulation). + +### 2) Automated analysis (fast coverage) + +Auditors usually run tooling to quickly detect common issues: + +- **Static analyzers**: Slither, Semgrep, Mythril +- **Dependency and compiler checks**: OpenZeppelin versions, Solidity compiler settings +- **Known vulnerability patterns**: reentrancy, unchecked external calls, incorrect access control, integer/precision issues, signature malleability, unsafe upgrades + +Example (typical Solidity audit tool run): + +```bash +# Static analysis (example) +slither . +``` + +### 3) Manual code review (deep correctness) + +Manual review is where most high-impact issues are found, including: + +- **Access control flaws** (wrong role checks, missing `onlyOwner`, privilege escalation) +- **State machine bugs** (incorrect transitions, pause/unpause bypasses) +- **Upgradeable proxy pitfalls** (storage collisions, initializer misuse) +- **Cross-contract interactions** (reentrancy via callbacks, ERC777 hooks, external integrations) +- **Economic attacks** (sandwiching, oracle manipulation, griefing, insolvent vaults) + +Auditors also validate **business logic** against specs and expected invariants. + +### 4) Testing and formal methods (when appropriate) + +Depending on criticality, audits include: + +- **Unit/integration tests**: edge cases, revert conditions, role restrictions +- **Fuzzing & property testing**: Foundry, Echidna +- **Formal verification** (select contracts): proving invariants and safety properties + +Example (Foundry tests and fuzzing): + +```bash +forge test -vvv +forge test --fuzz-runs 10000 +``` + +### 5) Exploit simulations and PoCs + +Auditors often create proof-of-concept exploits to demonstrate impact and ensure fixes are effective. + +A minimal pattern frequently checked is **reentrancy** in withdrawal logic: + +```solidity +// Vulnerable pattern (illustrative) +function withdraw(uint256 amount) external { + require(balances[msg.sender] >= amount, "insufficient"); + (bool ok,) = msg.sender.call{value: amount}(""); // external call + require(ok, "send failed"); + balances[msg.sender] -= amount; // state update after call (bad) +} +``` + +Typical mitigation uses checks-effects-interactions and/or a reentrancy guard: + +```solidity +function withdraw(uint256 amount) external nonReentrant { + require(balances[msg.sender] >= amount, "insufficient"); + balances[msg.sender] -= amount; // effects first + (bool ok,) = msg.sender.call{value: amount}(""); // interactions last + require(ok, "send failed"); +} +``` + +### 6) Reporting, remediation, and verification + +Audit reports generally include: + +- **Findings by severity** (Critical/High/Medium/Low/Informational) +- **Impact and likelihood** +- **Reproduction steps** +- **Recommended fixes** +- **Diff review / re-audit** after patches + +Many teams also run a **post-fix verification** or a shorter re-review to ensure changes don’t introduce new issues. + +### 7) Continuous security (audits aren’t one-and-done) + +Because contracts evolve, mature teams treat audits as part of an ongoing process: + +- Pre-deploy audits + post-deploy monitoring +- Bug bounty programs +- Incident response playbooks +- Repeat audits for major upgrades + +## What an Audit Typically Covers + +### Security vulnerabilities + +- Reentrancy +- Incorrect access control / authorization +- Price/oracle manipulation +- Signature verification issues (EIP-712, replay protection, domain separator mistakes) +- Flash loan and MEV-driven attacks +- Denial of service (gas griefing, unexpected reverts) +- Upgradeability mistakes (initializers, admin roles, proxy storage layout) + +### Correctness and reliability + +- Invariants and accounting correctness +- Precision/rounding and decimal conversions +- Boundary checks and overflow/underflow (still relevant around casting) +- Pausability and emergency controls behavior +- Event correctness (important for indexers and off-chain systems) + +### Deployment and operational safety + +- Constructor/initializer configuration +- Admin key management (multisig, timelocks) +- Upgrade procedures and safeguards +- Integration risks (DEXs, bridges, external protocols) + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, **parallelization**, and **~400ms finality**, which can change how risk is evaluated and tested—especially for high-throughput DeFi applications. + +### EVM compatibility: audit skills and tooling carry over + +If you deploy Solidity contracts on Sei’s EVM environment, the core audit methodology remains the same: + +- Solidity patterns, OpenZeppelin libraries, and EVM security best practices still apply +- Standard tooling (Foundry/Hardhat/Slither) remains highly relevant +- Auditors should verify chain-specific configuration (RPC, chain ID, gas and fee assumptions, deployment scripts) + +Example (Hardhat deploy-style workflow): + +```bash +npx hardhat test +npx hardhat run scripts/deploy.ts --network sei +``` + +### Parallelization: focus on correct state assumptions and composability + +Sei’s parallel execution model enables high throughput, but smart contracts must still be written as if transactions can be interleaved with other users’ actions. Audits on Sei should pay extra attention to: + +- **State-dependent assumptions** (e.g., “this price stays stable during a sequence of actions”) +- **Composability and callbacks** (external calls still introduce complex control flow) +- **MEV and ordering-sensitive logic** (even with fast blocks, price moves and sandwiching are still possible) + +Practically, auditors often recommend: + +- Using explicit **slippage checks** and deadlines for swaps +- Minimizing reliance on “current state” without guardrails +- Designing functions to be **atomic** and resistant to partial execution assumptions + +### ~400ms finality: operational benefits, not a substitute for security + +Fast finality improves UX and reduces the time window for certain operational races (e.g., waiting for confirmations), but it does **not** remove common smart contract risks: + +- Logic bugs and access control flaws remain exploitable +- Economic vulnerabilities can still be triggered in a single block/transaction +- Bridge/oracle dependencies remain critical attack surfaces + +Audits should still validate: + +- Emergency actions (pause, rescue) and their permissions +- Timelock and governance flows (if used) +- Price/oracle robustness and circuit breakers + +## When You Need a Smart Contract Audit + +You should strongly consider an audit when: + +- Deploying to mainnet for the first time (especially with TVL risk) +- Handling custody of user funds or minting/burning assets +- Introducing upgradeability or governance +- Integrating with external protocols (DEXs, lending markets, bridges) +- Making any major refactor or new feature release + +## Best Practices to Prepare for an Audit (and get better results) + +- Provide a clear **spec** (expected behaviors + invariants) +- Ship a strong **test suite** (unit + integration + fuzz tests) +- Freeze scope (minimize code changes during review) +- Document admin roles, upgrade paths, and operational procedures +- Run static analysis and linting before auditors start + +## Summary + +A smart contract audit is a professional security and correctness assessment that combines automated tooling, manual review, and adversarial testing to uncover vulnerabilities before deployment. In general blockchain environments, it focuses on preventing exploits in immutable programs and validating economic and governance assumptions. On Sei Network, audits follow standard EVM security practices while paying particular attention to high-throughput behaviors enabled by parallelization and leveraging Sei’s fast (~400ms) finality for better UX—without treating it as a replacement for robust contract security. + +## Related Documentation + +- [EVM Overview](/evm) +- [Networks & RPC](/evm/networks) +- [Deploy with Hardhat](/evm/evm-hardhat) +- [Deploy with Foundry](/evm/evm-foundry) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx b/content/answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx new file mode 100644 index 00000000..86105c03 --- /dev/null +++ b/content/answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx @@ -0,0 +1,162 @@ +--- +title: 'What is a Smart Contract Upgradeability and How Does It Work?' +description: 'Learn about what is smart contract upgradeability and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'evm', 'what', 'smart', 'contract', 'upgradeability', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Smart Contract Upgradeability and How Does It Work? + +## Overview + +Smart contract upgradeability is a pattern that lets a deployed smart contract change its logic over time without changing the contract address users interact with. It solves the problem that on most blockchains, deployed bytecode is immutable—so bug fixes, feature additions, and performance improvements typically require a new deployment and user migration. + +In short, **what is smart contract upgradeability**? It’s the ability to evolve a contract’s behavior after deployment, usually by separating persistent state (storage) from executable logic (implementation code) and adding controlled mechanisms to switch the logic safely. + +## How It Works + +### Why upgradeability exists + +In a standard (non-upgradeable) contract: + +- The **address** is tied to a fixed bytecode. +- The **storage layout** is fixed by the compiled contract. +- Any change requires deploying a **new contract address** and migrating state/users. + +Upgradeability introduces a stable “entry point” address that delegates execution to a replaceable implementation. + +### The proxy pattern (most common in EVM) + +The most widely used mechanism is a **proxy contract**: + +- Users call the **proxy address** (stable). +- The proxy uses `delegatecall` to run code from an **implementation contract** (replaceable). +- With `delegatecall`, the implementation’s logic executes **in the proxy’s storage context**, so state remains in the proxy while logic can change. + +Core components: + +- **Proxy**: holds state and forwards calls. +- **Implementation (Logic) contract**: contains functions/logic; can be swapped. +- **Admin/Upgrade authority**: controls who can upgrade. +- **Initializer**: replaces constructors (since constructors run only on implementation deployment, not via proxy). + +### Common upgradeability standards + +- **Transparent Proxy (OpenZeppelin)**: separates admin behavior from user calls to avoid selector clashes. +- **UUPS (EIP-1822)**: upgrade function lives in the implementation; proxy is minimal. Often cheaper and common in modern deployments. +- **Beacon Proxy**: multiple proxies share a beacon that points to the current implementation (useful for many instances). + +### Storage layout compatibility (critical) + +Because the proxy keeps the storage, upgrades must preserve storage meaning: + +- Never reorder existing state variables. +- Only append new variables at the end. +- Use reserved “storage gaps” or explicit storage slots. +- Avoid changing types/sizes that would shift slot packing. + +If storage layout is broken, you can corrupt balances, roles, or critical configuration. + +### Upgrade governance and safety + +Upgrades are powerful and risky. Best practices include: + +- **Role-based access control** (only authorized accounts can upgrade). +- **Timelocks** to delay upgrades and allow review. +- **On-chain governance** (DAO votes) for protocol-level contracts. +- **Audits and tests** for new implementations. +- **Emergency pause** / circuit breakers (when appropriate). + +### Minimal UUPS example (Solidity) + +Below is an illustrative UUPS-style upgradeable contract using OpenZeppelin. In practice, use audited libraries and follow their initialization and access-control patterns. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; + +contract CounterV1 is Initializable, UUPSUpgradeable, OwnableUpgradeable { + uint256 public value; + + function initialize(uint256 initialValue) public initializer { + __Ownable_init(msg.sender); + __UUPSUpgradeable_init(); + value = initialValue; + } + + function increment() external { + value += 1; + } + + // Only the owner can upgrade the implementation + function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} +} +``` + +### Upgrading using Hardhat (TypeScript) + +A typical flow uses `@openzeppelin/hardhat-upgrades`: + +```typescript +import { ethers, upgrades } from 'hardhat'; + +async function main() { + const CounterV1 = await ethers.getContractFactory('CounterV1'); + const proxy = await upgrades.deployProxy(CounterV1, [1], { kind: 'uups' }); + await proxy.waitForDeployment(); + + console.log('Proxy address:', await proxy.getAddress()); + + // Later: upgrade to CounterV2 + const CounterV2 = await ethers.getContractFactory('CounterV2'); + const upgraded = await upgrades.upgradeProxy(await proxy.getAddress(), CounterV2); + console.log('Upgraded proxy still at:', await upgraded.getAddress()); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); +``` + +## On Sei Network + +Sei is an **EVM-compatible Layer 1**, so the same upgradeability patterns (Transparent, UUPS, Beacon) and tooling (Hardhat, Foundry, OpenZeppelin Upgrades) apply directly. Contracts on Sei can be upgraded through proxies exactly as they would be on other EVM chains—users keep interacting with the same proxy address while the implementation changes. + +Where Sei’s architecture matters: + +- **Fast finality (~400ms)**: Upgrade transactions (e.g., `upgradeTo`) reach finality quickly, reducing the window of uncertainty between submitting an upgrade and having it confirmed on-chain. This can be beneficial for operational safety, incident response, and coordinated releases. +- **Parallelization**: Sei’s parallel execution model can improve throughput for contract interactions, and upgradeable systems that serve many users can benefit from higher performance. The upgrade itself is still a normal on-chain transaction, but overall app responsiveness and scaling can improve. +- **EVM compatibility**: Existing Ethereum upgradeability best practices transfer—use OpenZeppelin’s proxy standards, maintain storage layout discipline, and secure upgrade authority. + +### Deploying on Sei (example CLI flow) + +Using Hardhat, you’d configure Sei’s EVM RPC endpoint and deploy normally: + +```bash +npm install --save-dev hardhat @openzeppelin/hardhat-upgrades +npx hardhat compile +npx hardhat run scripts/deploy.ts --network sei +``` + +## Key Takeaways + +- Smart contract upgradeability keeps a stable address while allowing logic changes, most commonly via **proxy + delegatecall**. +- The hardest part is **storage layout safety** and **upgrade authorization security**. +- On Sei Network, upgradeability works the same as on other EVM chains, with the added operational benefit of **~400ms finality** and performance advantages from **parallelization**. + +## Related Documentation + +- [EVM Overview](/evm) +- [Networks & RPC](/evm/networks) +- [Deploy with Hardhat](/evm/evm-hardhat) +- [Deploy with Foundry](/evm/evm-foundry) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-soft-fork-and-how-does-it-work.mdx b/content/answers/what-is-a-soft-fork-and-how-does-it-work.mdx new file mode 100644 index 00000000..1de4205e --- /dev/null +++ b/content/answers/what-is-a-soft-fork-and-how-does-it-work.mdx @@ -0,0 +1,132 @@ +--- +title: 'What is a Soft Fork and How Does It Work?' +description: 'Learn about what is soft fork and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'soft', 'fork', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Soft Fork and How Does It Work? + +## Overview + +A **soft fork** is a backward-compatible blockchain protocol upgrade that **tightens** the rules for what blocks and transactions are considered valid. Nodes that upgrade will enforce the new stricter rules, while nodes that do not upgrade can typically continue operating—though they may not fully understand or enforce the new constraints. In short, **what is soft fork**: a network change where new rules are a subset of the old rules, so old software can still accept the upgraded chain. + +## How It Works + +### Backward compatibility and “stricter rules” + +In a soft fork, the network introduces rules that **reduce** the set of valid blocks/transactions compared to the previous protocol. Because the old protocol’s rules are looser, a non-upgraded node will usually still see upgraded blocks as valid (they still fit within the old, broader definition of validity). + +Common examples of “stricter” changes include: + +- Disallowing certain transaction patterns that were previously valid +- Adding additional conditions that must be met for a transaction to be accepted +- Constraining block contents or script behavior to enable new features safely + +### Activation: how a soft fork gets adopted + +Soft forks are typically activated via a coordination mechanism that ensures the network converges on the new rules, such as: + +- **Miner/validator signaling**: block producers indicate readiness; after a threshold is reached, the new rules activate. +- **Time/height-based activation**: the fork activates at a specific block height/time if software is sufficiently deployed. +- **User-activated mechanisms** (in some ecosystems): economic actors enforce new rules via node policy. + +Once activated, upgraded nodes reject blocks that violate the new rules. Non-upgraded nodes may still accept those blocks if they appear valid under the old rules—but if a majority of block production follows the new rules, the canonical chain will comply with the stricter validation, keeping the network unified. + +### Soft fork vs. hard fork (quick comparison) + +- **Soft fork**: backward-compatible; old nodes can usually follow the chain (but won’t enforce new rules). +- **Hard fork**: not backward-compatible; old nodes will reject new blocks, causing a chain split unless everyone upgrades. + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, designed for fast execution and rapid chain convergence (with **~400ms finality**). Protocol upgrades on Sei can introduce rule changes that are conceptually similar to soft forks in other ecosystems—i.e., changes that remain compatible for participants who update promptly—while still leveraging Sei’s architecture to coordinate upgrades efficiently. + +Key points for soft-fork-like behavior in a Sei context: + +- **Fast finality reduces uncertainty during upgrades**: With ~400ms finality, once an upgrade activates and validators produce blocks under the new rules, the chain converges quickly, minimizing prolonged ambiguity around which blocks are canonical. +- **Parallelization and high throughput**: Sei’s parallelized execution model helps maintain performance during network transitions, making it easier to roll out rule-tightening changes without congesting the chain. +- **EVM compatibility considerations**: Changes that affect EVM transaction processing, gas accounting, precompiles, or mempool policies must be carefully coordinated. Even when changes are backward-compatible in principle, clients, indexers, and tooling in the EVM ecosystem may still require updates to reflect new semantics. + +### What soft forks might look like for developers + +On EVM chains, many developer-visible “soft fork” style changes are introduced as **new constraints** or **new optional behaviors** that don’t invalidate existing, already-valid historical data. Examples can include: + +- Enforcing stricter validation for certain transaction fields +- Updating opcode or precompile behavior behind a feature gate or activation height (must be handled carefully to avoid breaking assumptions) +- Tightening mempool acceptance rules (policy) without changing consensus rules (note: mempool policy changes are not always consensus changes) + +Because Sei is a Cosmos SDK–based chain with an EVM runtime, network upgrades are generally delivered through chain upgrade mechanisms coordinated by validators and node operators. Even when an upgrade is “soft” in spirit, **operators and infrastructure providers should still upgrade on time** to ensure they enforce the latest consensus rules and remain compatible with the network. + +## Example: Detecting an Upgrade Height in an EVM dApp + +While Solidity contracts can’t directly read “the fork version,” many apps handle network upgrades by checking the **block number** (or timestamp) at which new behavior is expected, then gating logic accordingly. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract UpgradeGatedLogic { + uint256 public constant UPGRADE_BLOCK = 12_345_678; + + function featureFlag() public view returns (bool) { + // Example: enable a path only after an upgrade activates + return block.number >= UPGRADE_BLOCK; + } + + function doThing() external view returns (string memory) { + if (featureFlag()) { + return "Post-upgrade behavior"; + } else { + return "Pre-upgrade behavior"; + } + } +} +``` + +## Example: Monitoring Network Upgrade Status (TypeScript) + +Apps and indexers commonly monitor chain parameters (block height, client version, or governance events depending on the ecosystem) and adjust behavior when an upgrade activates. + +```typescript +import { ethers } from 'ethers'; + +async function main() { + const rpcUrl = process.env.RPC_URL!; + const provider = new ethers.JsonRpcProvider(rpcUrl); + + const blockNumber = await provider.getBlockNumber(); + console.log('Current block:', blockNumber); + + const UPGRADE_BLOCK = 12_345_678; + if (blockNumber >= UPGRADE_BLOCK) { + console.log('Upgrade is active: use new rules/paths'); + } else { + console.log('Upgrade not active yet: use legacy rules/paths'); + } +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); +``` + +## Key Takeaways + +- **What is soft fork**: a backward-compatible protocol upgrade that makes validation rules stricter so old nodes can still generally follow the chain. +- Soft forks require **coordination for activation**, typically via validator/miner signaling or scheduled activation. +- On **Sei Network**, upgrades benefit from **parallelization** and **~400ms finality**, helping the chain converge quickly and maintain performance during transitions, including those that resemble soft forks in practice. +- Developers should still plan for upgrades by **monitoring activation points** and keeping node/indexer/tooling versions current, especially in the **EVM-compatible** environment. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-stablecoin-and-how-does-it-work.mdx b/content/answers/what-is-a-stablecoin-and-how-does-it-work.mdx new file mode 100644 index 00000000..148b8ce5 --- /dev/null +++ b/content/answers/what-is-a-stablecoin-and-how-does-it-work.mdx @@ -0,0 +1,176 @@ +--- +title: 'What is a Stablecoin and How Does It Work?' +description: 'Learn about what is stablecoin and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'stablecoin', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Stablecoin and How Does It Work? + +## Overview + +A **stablecoin** is a cryptocurrency designed to keep its price **stable** relative to a reference asset, most commonly a fiat currency like the **US dollar (USD)**. If you’re searching **“what is stablecoin”**, the simplest answer is: it’s a digital token that aims to combine crypto’s speed and programmability with the predictable value of traditional money. + +Stablecoins are widely used for payments, trading, remittances, on-chain savings, and as a “base currency” in DeFi because they reduce exposure to the volatility typical of many crypto assets. + +## How It Works + +Stablecoins maintain price stability through one (or a combination) of these mechanisms: + +### 1) Fiat-Collateralized Stablecoins (Off-Chain Reserves) + +These stablecoins are backed by **cash and cash-equivalents** (e.g., bank deposits, short-term government bills) held by a custodian. In many models, users can **mint** new stablecoins by depositing fiat and **redeem** stablecoins for fiat, which helps keep the token near its peg (e.g., $1). + +**How the peg holds (conceptually):** + +- If the stablecoin trades above $1, arbitrageurs mint at $1 and sell higher, pushing price down. +- If it trades below $1, arbitrageurs buy below $1 and redeem for $1, pushing price up. + +**Trade-offs:** + +- Pros: typically strong price stability. +- Cons: relies on custodians, banking rails, audits/attestations, and regulatory compliance. + +### 2) Crypto-Collateralized Stablecoins (On-Chain Reserves) + +These stablecoins are backed by **cryptocurrency collateral** locked in smart contracts, usually **overcollateralized** (e.g., $150 of collateral to mint $100 stablecoin) to handle crypto price swings. If collateral value falls too far, positions can be **liquidated** to protect solvency. + +**Core components:** + +- Collateral vaults / positions +- Overcollateralization ratio +- Oracles to track market prices +- Liquidation mechanisms and incentives + +**Trade-offs:** + +- Pros: transparent, on-chain, less reliance on traditional banks. +- Cons: can be complex; collateral volatility and oracle risk. + +### 3) Algorithmic Stablecoins (Supply/Demand Mechanisms) + +Algorithmic stablecoins attempt to maintain a peg by **adjusting token supply**, incentives, or using secondary tokens—often without full collateral backing. + +**Trade-offs:** + +- Pros: capital efficient in theory. +- Cons: historically higher risk; peg can fail under stress if incentives break. + +### 4) Commodity-Backed Stablecoins + +These are backed by real-world commodities (e.g., gold), aiming to track the commodity price rather than fiat. + +**Trade-offs:** + +- Pros: exposure to commodity value on-chain. +- Cons: depends on custody and redemption guarantees. + +--- + +### Key Concepts You’ll See With Stablecoins + +- **Peg:** the target price (e.g., 1 stablecoin = $1). +- **Mint/Burn:** creating tokens (mint) and destroying them (burn) to manage supply and redemptions. +- **Reserves/Collateral:** assets backing the stablecoin’s value. +- **Oracles:** data feeds used by smart contracts to get market prices. +- **Depegging:** when a stablecoin deviates meaningfully from its target price. + +## On Sei Network + +Stablecoins on **Sei Network** are typically issued and used as **ERC-20 tokens** on Sei’s EVM, making them easy to integrate with existing Ethereum tooling (wallets, indexers, Solidity contracts). Sei’s design—optimized for high throughput with **parallelization** and fast block execution—supports stablecoin use cases like high-frequency trading, on-chain payments, and DeFi collateral management at scale, with **~400ms finality** improving user experience for transfers and swaps. + +Common stablecoin activities on Sei include: + +- **Payments & transfers:** fast settlement and quick confirmation UX due to near-instant finality. +- **DEX trading:** stablecoins serve as quote assets (e.g., stablecoin pairs) and help reduce volatility exposure. +- **Lending/borrowing:** stablecoins are frequently used as borrowed assets or collateral, depending on protocol design. +- **Treasury and accounting:** stable-value units simplify on-chain bookkeeping for DAOs and apps. + +### Example: Interacting With a Stablecoin (ERC-20) in Solidity on Sei + +Below is a minimal example showing how a dApp might accept stablecoin payments using the ERC-20 interface: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function transfer(address to, uint256 amount) external returns (bool); + function balanceOf(address owner) external view returns (uint256); +} + +contract StablecoinCheckout { + IERC20 public immutable stablecoin; + address public immutable merchant; + + constructor(address stablecoinAddress, address merchantAddress) { + stablecoin = IERC20(stablecoinAddress); + merchant = merchantAddress; + } + + function pay(uint256 amount) external { + // User must approve() this contract for `amount` first + require(stablecoin.transferFrom(msg.sender, merchant, amount), "transfer failed"); + } +} +``` + +### Example: Sending a Stablecoin Transfer (EVM) With Ethers.js + +This example shows a basic ERC-20 transfer flow (network RPC and chain ID omitted for brevity—use Sei’s EVM endpoints): + +```typescript +import { ethers } from 'ethers'; + +const ERC20_ABI = ['function transfer(address to, uint256 amount) returns (bool)', 'function decimals() view returns (uint8)']; + +async function sendStablecoin(rpcUrl: string, privateKey: string, stablecoinAddress: string, to: string, amountHuman: string) { + const provider = new ethers.JsonRpcProvider(rpcUrl); + const wallet = new ethers.Wallet(privateKey, provider); + + const token = new ethers.Contract(stablecoinAddress, ERC20_ABI, wallet); + const decimals: number = await token.decimals(); + + const amount = ethers.parseUnits(amountHuman, decimals); + const tx = await token.transfer(to, amount); + await tx.wait(); + return tx.hash; +} +``` + +## Why Stablecoins Matter + +Stablecoins are a foundational building block for crypto because they enable: + +- **Low-volatility on-chain value transfer** +- **More predictable pricing** for goods and services +- **Liquidity** for trading and DeFi +- **Programmable money** for apps (subscriptions, payroll, escrow) + +On Sei, these benefits are amplified by fast settlement (**~400ms finality**) and scalable execution via **parallelization**, making stablecoin-powered applications feel closer to traditional fintech speed while remaining on-chain and composable. + +## Risks and Considerations + +Even though stablecoins aim to be stable, they are not risk-free: + +- **Reserve/custody risk (fiat-backed):** solvency, banking access, transparency of reserves. +- **Smart contract and oracle risk (crypto-backed):** bugs, oracle manipulation, liquidation failures. +- **Liquidity/market risk:** thin liquidity can cause temporary depegs. +- **Regulatory risk:** changes in compliance requirements can affect issuance/redemption. + +## Summary + +If you’re asking **what is stablecoin**, it’s a cryptocurrency that targets a stable price—usually pegged to fiat like USD—using reserves, collateral, and/or algorithmic mechanisms. Stablecoins power much of on-chain commerce and DeFi, and on **Sei Network** they benefit from EVM compatibility and fast, scalable execution—enabling near-instant transfers and efficient trading with **~400ms finality**. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-testnet-and-how-does-it-work.mdx b/content/answers/what-is-a-testnet-and-how-does-it-work.mdx new file mode 100644 index 00000000..f72aac38 --- /dev/null +++ b/content/answers/what-is-a-testnet-and-how-does-it-work.mdx @@ -0,0 +1,131 @@ +--- +title: 'What is a Testnet and How Does It Work?' +description: 'Learn about what is testnet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'testnet', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Testnet and How Does It Work? + +## Overview + +A **testnet** is a separate blockchain network used to test applications, smart contracts, and protocol upgrades without risking real funds. It mirrors the behavior of a mainnet but uses tokens that have no real-world value, making it safe for experimentation. In short, if you’re asking **what is testnet**, it’s the sandbox environment for blockchain development and validation. + +## How It Works + +### Separate Network, Same Rules (Mostly) + +A testnet typically runs the same (or very similar) consensus rules, transaction format, block production, and smart contract execution environment as mainnet. The key difference is that testnet assets are intentionally worthless and are distributed freely (or cheaply) for testing. + +### Testnet Tokens and Faucets + +Because you need tokens to pay gas/fees and simulate real usage, testnets provide tokens via a **faucet**—a service that sends you test tokens after you prove wallet ownership (often by signing in or completing a captcha). + +### What Developers Use Testnets For + +- **Smart contract deployment & verification** (catching bugs before mainnet) +- **Frontend / wallet integration testing** (RPC reliability, event indexing, transaction flows) +- **Load and performance testing** (throughput, latency, concurrency) +- **Protocol upgrades and parameter changes** (validating governance decisions safely) +- **Security testing** (reproducing attack scenarios without financial loss) + +### Typical Testnet Workflow + +1. Create or import a wallet. +2. Connect your wallet or tooling (Hardhat/Foundry) to a testnet RPC endpoint. +3. Request tokens from a faucet. +4. Deploy contracts and run scripts/tests. +5. Monitor results using a testnet explorer and logs. +6. Iterate until stable, then deploy to mainnet. + +## On Sei Network + +Sei testnets provide a realistic environment for building and validating apps before deploying on Sei mainnet. Because Sei is designed for high performance—with **parallelization** and **~400ms finality**—testnet is especially useful for verifying behavior under fast block finality and concurrent transaction execution patterns that may affect app assumptions (e.g., sequencing, state reads/writes, and event timing). + +Sei is also **EVM-compatible**, so Ethereum tooling and Solidity contracts can be tested end-to-end in a Sei environment before mainnet launch. This makes it straightforward to: + +- deploy Solidity contracts, +- test EVM transactions and logs, +- validate indexing and UI flows, +- measure practical latency and confirmation UX under Sei’s rapid finality. + +## Example: Add Sei Testnet to Your Wallet (EVM) + +Below is a typical pattern for adding an EVM network to MetaMask using `wallet_addEthereumChain`. Replace values with the official Sei testnet parameters you intend to use. + +```typescript +// In a browser dApp (e.g., React), adding a Sei EVM testnet to MetaMask +await window.ethereum.request({ + method: 'wallet_addEthereumChain', + params: [ + { + chainId: '0x____', // hex chain ID + chainName: 'Sei Testnet', + nativeCurrency: { name: 'SEI', symbol: 'SEI', decimals: 18 }, + rpcUrls: ['https://'], + blockExplorerUrls: ['https://'] + } + ] +}); +``` + +## Example: Deploy a Solidity Contract to Sei Testnet + +A minimal Solidity contract you can deploy to Sei’s EVM testnet: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public number; + + function setNumber(uint256 newNumber) external { + number = newNumber; + } + + function increment() external { + number += 1; + } +} +``` + +Using Foundry (`cast`) to deploy (illustrative—use your Sei testnet RPC URL and private key): + +```bash +export RPC_URL="https://" +export PRIVATE_KEY="" + +forge create --rpc-url $RPC_URL --private-key $PRIVATE_KEY src/Counter.sol:Counter +``` + +## Key Differences Between Testnet and Mainnet + +- **Economic risk**: Testnet tokens are valueless; mainnet tokens have real value. +- **Stability**: Testnets may reset, halt, or upgrade more frequently. +- **Security assumptions**: Validator sets and attack incentives differ from mainnet. +- **Infrastructure**: Indexers, explorers, and RPC providers may be less consistent on testnets. + +## Best Practices When Using a Testnet + +- Treat testnet like production: use CI tests, linting, and audits where possible. +- Expect resets: never rely on testnet state permanence. +- Test edge cases: high concurrency, rapid confirmations, reverts, and event ordering. +- Validate with explorers/logs: confirm contract addresses, events, and gas usage. +- Use separate keys: never reuse mainnet private keys in testing environments. + +## Summary + +A testnet is a safe, low-stakes blockchain environment that replicates mainnet behavior so developers can test smart contracts, integrations, and upgrades. On Sei Network, testnets are particularly valuable for verifying EVM dApps under Sei’s **parallelized execution** and **~400ms finality**, ensuring production-ready performance and reliability before mainnet deployment. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-token-burn-and-how-does-it-work.mdx b/content/answers/what-is-a-token-burn-and-how-does-it-work.mdx new file mode 100644 index 00000000..714aefd5 --- /dev/null +++ b/content/answers/what-is-a-token-burn-and-how-does-it-work.mdx @@ -0,0 +1,162 @@ +--- +title: 'What is a Token Burn and How Does It Work?' +description: 'Learn about what is token burn and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'token', 'burn', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Token Burn and How Does It Work? + +## Overview + +A **token burn** is the intentional, verifiable destruction of cryptocurrency tokens by sending them to an address that cannot spend them (often called a _burn address_ or _black hole address_). The goal is to reduce the circulating supply, which can affect a token’s economics (tokenomics) by increasing scarcity or aligning incentives. + +In other words, if you’re asking **what is token burn**, it’s a supply-reduction mechanism executed on-chain so anyone can audit the burn transaction. + +## How It Works + +### Common burn mechanisms + +Token burns are typically implemented in one of these ways: + +1. **Send to an irrecoverable address** + + - Tokens are transferred to an address with no known private key (e.g., `0x000000000000000000000000000000000000dEaD` on EVM chains). + - The tokens still “exist” in the ledger but are effectively removed from circulation forever. + +2. **Burn via smart contract function** + + - Many token standards or custom contracts implement a `burn()` function that reduces the caller’s balance and decreases total supply (or moves tokens to a burn address). + - This is often cleaner for accounting because `totalSupply` can be updated directly. + +3. **Protocol-level burns** + - Some networks burn a portion of transaction fees (or other protocol revenues). + - This creates a continuous burn that scales with network usage. + +### Why projects burn tokens + +Projects may burn tokens to: + +- **Reduce circulating supply** and potentially increase scarcity +- **Offset emissions** (e.g., from staking rewards) +- **Stabilize tokenomics** or support a long-term policy +- **Signal commitment** (e.g., burning team allocation, unsold tokens) +- **Tie burns to revenue** (e.g., buyback-and-burn or fee burns) + +### What a burn does—and doesn’t—guarantee + +- A burn **does** reduce circulating supply (and sometimes total supply, depending on implementation). +- A burn **does not** guarantee price increases; price depends on demand, liquidity, market conditions, unlock schedules, and broader token utility. + +### How to verify a token burn + +You can verify burns by checking: + +- The **transaction hash** sending tokens to the burn address +- The **token contract’s `Transfer` events** +- The **burn address balance** (it should only increase) +- Whether **`totalSupply` decreases** (if the contract updates it) + +## On Sei Network + +On **Sei Network** (an EVM-compatible Layer 1), token burns for ERC-20–style tokens work the same way they do on other EVM chains: projects can burn tokens by transferring them to an irrecoverable address or by calling a `burn()` function in a smart contract. + +Sei’s advantages—**high throughput via parallelization** and **~400ms finality**—make burn-related operations (like periodic burns, buyback-and-burn execution, or fee-driven burns) settle quickly and predictably. This can be useful for applications that rely on time-sensitive supply adjustments or transparent, frequent burn events. + +## Example: Burning tokens by sending to a burn address (Solidity) + +A minimal ERC-20 token burn can be implemented by transferring tokens to a known burn address: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function transfer(address to, uint256 amount) external returns (bool); +} + +contract BurnHelper { + // Common EVM burn address + address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; + + function burn(IERC20 token, uint256 amount) external { + // Caller must have approved this contract to spend `amount` + require(token.transfer(BURN_ADDRESS, amount), "Transfer failed"); + } +} +``` + +**Notes** + +- This approach does **not** necessarily reduce `totalSupply` unless the token contract treats transfers to the burn address specially. It does, however, remove tokens from practical circulation. + +## Example: Burning tokens by reducing total supply (Solidity) + +Many projects implement a `burn()` function that reduces both the holder’s balance and `totalSupply`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +contract BurnableToken is ERC20 { + constructor() ERC20("Burnable Token", "BURN") { + _mint(msg.sender, 1_000_000 ether); + } + + function burn(uint256 amount) external { + _burn(msg.sender, amount); // reduces sender balance and totalSupply + } +} +``` + +## Example: Calling burn on Sei EVM (TypeScript) + +Using `ethers` to call a `burn(uint256)` function from a dApp: + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const PRIVATE_KEY = process.env.PRIVATE_KEY!; +const TOKEN_ADDRESS = '0xYourTokenAddress'; + +const ABI = ['function burn(uint256 amount) external', 'function decimals() view returns (uint8)']; + +async function main() { + const provider = new ethers.JsonRpcProvider(RPC_URL); + const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + + const token = new ethers.Contract(TOKEN_ADDRESS, ABI, wallet); + + const decimals: number = await token.decimals(); + const amount = ethers.parseUnits('100', decimals); // burn 100 tokens + + const tx = await token.burn(amount); + console.log('Submitted:', tx.hash); + + const receipt = await tx.wait(); + console.log('Confirmed in block:', receipt.blockNumber); +} + +main().catch(console.error); +``` + +## Key Takeaways + +- **What is token burn?** It’s the deliberate destruction (or permanent removal from circulation) of tokens, executed transparently on-chain. +- Burns are commonly done by **sending tokens to an irrecoverable address** or calling a **contract burn function** that reduces `totalSupply`. +- On **Sei Network**, token burns work like any EVM chain, with the benefit of **parallelized execution** and **~400ms finality** for fast, auditable burn settlement. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-tokenomics-and-how-does-it-work.mdx b/content/answers/what-is-a-tokenomics-and-how-does-it-work.mdx new file mode 100644 index 00000000..b4394d91 --- /dev/null +++ b/content/answers/what-is-a-tokenomics-and-how-does-it-work.mdx @@ -0,0 +1,197 @@ +--- +title: 'What is a Tokenomics and How Does It Work?' +description: 'Learn about what is tokenomics and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'tokenomics', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Tokenomics and How Does It Work? + +## Overview + +Tokenomics (short for “token economics”) is the design and analysis of how a crypto token is created, distributed, used, and governed within a blockchain ecosystem. In practical terms, it defines the rules that drive a token’s supply, demand, incentives, and long-term sustainability—similar to how monetary policy and market structure shape a traditional economy. + +If you’re asking **what is tokenomics**, it’s the framework that explains _why a token should have value_ and _how that value is maintained or grows_ over time. + +## How It Works + +Tokenomics typically combines on-chain rules (hard-coded in smart contracts and protocol parameters) with off-chain behaviors (user adoption, market dynamics, governance decisions). Strong tokenomics aligns incentives across users, developers, validators, and the broader community. + +### Key Components of Tokenomics + +#### 1) Token Supply (Issuance and Limits) + +Common supply models include: + +- **Fixed supply**: No new tokens after a cap is reached (e.g., a “max supply”). +- **Inflationary supply**: New tokens are minted continuously (often to reward validators/stakers). +- **Deflationary mechanisms**: Tokens are burned (destroyed) via fees or buyback-and-burn mechanics. + +What to analyze: + +- Maximum supply vs. circulating supply +- Inflation schedule (emissions over time) +- Burn rate and fee policy + +#### 2) Distribution (Who Gets Tokens, When, and Why) + +Distribution determines initial ownership and how decentralization evolves. + +- **Genesis allocation**: Team, treasury, ecosystem, investors, airdrops, public sale. +- **Vesting schedules**: Time-locked releases to reduce sudden sell pressure and align long-term incentives. +- **Liquidity provisioning**: Allocations for market liquidity (DEX/CEX), often via treasury or market makers. + +What to analyze: + +- Concentration risk (large holders) +- Cliff + linear vesting details +- Unlock schedule and expected emissions + +#### 3) Utility (What the Token Is Used For) + +A token’s value proposition often depends on real usage: + +- **Gas/fees**: Pay transaction execution costs. +- **Staking**: Secure the network and earn rewards. +- **Governance**: Vote on upgrades and parameters. +- **Collateral**: Used in lending/borrowing or as backing for stable assets. +- **In-app currency**: Used within games, DeFi apps, or marketplaces. + +What to analyze: + +- Is utility essential or optional? +- Are there non-token substitutes for the same function? +- Does usage scale with adoption? + +#### 4) Incentives (Rewards and Penalties) + +Tokenomics relies on incentives to encourage desired behavior: + +- **Staking rewards**: Motivate validators and delegators to secure consensus. +- **Liquidity mining**: Attract liquidity to DEXs and DeFi protocols. +- **User incentives**: Encourage early adoption (rebates, rewards, airdrops). +- **Slashing/penalties**: Discourage malicious behavior or downtime. + +What to analyze: + +- Are rewards sustainable, or do they rely on constant new demand? +- Do incentives create “mercenary capital” (short-term farmers) or sticky users? + +#### 5) Demand Drivers and Value Capture + +Value capture describes how network usage translates into token demand: + +- Fee demand (more transactions → more gas usage) +- Staking demand (more TVL/importance → more security needed) +- Governance premium (valuable decision rights) +- Burn/redistribution mechanics (fees burned or paid to stakers) + +What to analyze: + +- Does increased usage increase token demand directly? +- Are fees paid in the token or abstracted away? + +#### 6) Governance and Policy Changes + +Many protocols can update parameters over time: + +- Emissions rates +- Fee splits +- Treasury spend +- Incentive programs + +What to analyze: + +- Governance attack surface (vote concentration) +- Upgrade process and security assumptions + +### Simple Example: Supply + Fees in a Smart Contract + +Below is a minimal illustration of common tokenomics mechanics: capped supply and fee burn. (This is an educational example, not production-ready.) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +contract ExampleToken is ERC20 { + uint256 public immutable MAX_SUPPLY; + uint256 public burnBps = 50; // 0.50% burn on transfers (example) + + constructor(uint256 maxSupply) ERC20("Example Token", "EXT") { + MAX_SUPPLY = maxSupply; + _mint(msg.sender, maxSupply / 10); // initial distribution example + } + + function mint(address to, uint256 amount) external { + require(totalSupply() + amount <= MAX_SUPPLY, "Cap exceeded"); + _mint(to, amount); + } + + function _update(address from, address to, uint256 value) internal override { + // burn a portion on transfers (not on mint/burn) + if (from != address(0) && to != address(0) && burnBps > 0) { + uint256 burnAmount = (value * burnBps) / 10_000; + super._burn(from, burnAmount); + value -= burnAmount; + } + super._update(from, to, value); + } +} +``` + +## On Sei Network + +On Sei Network, tokenomics applies both at the **network level** (gas fees, staking, validator incentives) and at the **application level** (DeFi protocols, games, marketplaces, and any EVM smart contracts deployed on Sei). + +### Why Tokenomics Matters More on High-Performance Chains + +Sei’s high throughput and ~**400ms finality** can change how tokenomics plays out: + +- **Faster feedback loops**: Incentives (like trading rebates, liquidity mining, fee discounts) can attract and retain users more quickly because transactions confirm rapidly. +- **Lower friction**: More frequent interactions (trading, rebalancing, liquidation protection) can increase real utility and fee generation—key ingredients for sustainable token demand. +- **Better UX for on-chain markets**: Applications that rely on speed (e.g., DEXs, derivatives, order-book-style designs) can create more consistent fee-driven value capture. + +### EVM Compatibility and Tokenomics Design + +Because Sei is **EVM-compatible**, teams can implement tokenomics using familiar Solidity patterns: + +- ERC-20 tokens with emissions schedules and vesting +- Fee redistribution or burn mechanics +- Staking/locking contracts for governance or rewards +- On-chain incentive gauges and reward distributors + +Deploying tokenomics contracts on Sei typically looks the same as on other EVM chains, but users benefit from Sei’s performance characteristics (parallelization and fast finality) that support high-frequency, real-time on-chain activity. + +### Practical Tokenomics Considerations When Building on Sei + +When designing “what is tokenomics” for a Sei-based token, projects commonly evaluate: + +- **Fee strategy**: How fees are collected (in token vs. in gas token), whether any portion is burned or redirected to a treasury/stakers. +- **Incentive cadence**: Short block times and rapid finality can intensify farming behavior; consider anti-sybil controls, vesting, or time-weighted rewards. +- **Liquidity design**: Fast finality can improve market quality; consider mechanisms that reward deep, durable liquidity rather than temporary deposits. +- **Scalability of utility**: If your dApp expects many user actions (trades, mints, claims), Sei’s parallel execution can support more utility-driven demand. + +## Quick Checklist for Evaluating Tokenomics + +- **Supply**: Is there a cap? What’s the inflation rate and schedule? +- **Distribution**: Who owns what? What are vesting/unlock timelines? +- **Utility**: What must users do with the token? Is it essential? +- **Incentives**: Are rewards sustainable? Are there penalties for bad behavior? +- **Value capture**: Do fees/burns/staking create persistent demand? +- **Governance**: How are parameters updated, and who controls voting power? + +A well-designed tokenomics model ties real network or application usage to measurable token demand—especially on fast, high-throughput environments like Sei where user activity can scale quickly. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx b/content/answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx new file mode 100644 index 00000000..046659b8 --- /dev/null +++ b/content/answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx @@ -0,0 +1,161 @@ +--- +title: 'What is a Trustless Bridge and How Does It Work?' +description: 'Learn about what is trustless bridge and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'trustless', 'bridge', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Trustless Bridge and How Does It Work? + +## Overview + +A **trustless bridge** is a cross-chain protocol that lets users move assets or messages between blockchains **without relying on a centralized custodian or trusted operator**. Instead, it uses cryptographic verification and on-chain logic so that correctness is enforced by the chains’ consensus rules. + +In other words, when asking **what is trustless bridge**, the core idea is: the bridge’s security comes from verifiable proofs and smart contracts—not from trusting a company to hold or release funds. + +## How It Works + +### 1) Lock/Mint or Burn/Release (Asset Bridging) + +Most token bridges follow one of these patterns: + +- **Lock → Mint (wrapped assets)** + + 1. You lock Token A on Chain 1 into a bridge contract. + 2. The bridge proves (or verifies) that lock event on Chain 1. + 3. A corresponding wrapped token (e.g., wTokenA) is minted on Chain 2. + +- **Burn → Release (return path)** + 1. You burn the wrapped token on Chain 2. + 2. The burn is proven/verified to Chain 1. + 3. The original Token A is released from the lock contract on Chain 1. + +A trustless bridge aims to ensure that the mint/release step can only happen if the lock/burn truly occurred, as proven by cryptographic evidence. + +### 2) Message Passing (Generalized Bridging) + +Beyond tokens, bridges can relay **arbitrary messages**, enabling: + +- cross-chain contract calls, +- cross-chain governance, +- cross-chain account/state synchronization. + +In this model, a message is emitted on the source chain and proven/verified on the destination chain, where it is executed by a target contract. + +### 3) Verification Models (What Makes It “Trustless”) + +There are several common trust-minimized/trustless approaches: + +- **Light client / on-chain verification** + The destination chain runs (or references) a light client of the source chain and verifies headers, consensus, and inclusion proofs (e.g., Merkle proofs). This is closest to “trustless” because it depends primarily on each chain’s consensus security. + +- **Validity proofs (ZK bridges)** + A proof attests that a source-chain event happened according to that chain’s rules. The destination chain verifies the proof on-chain. + +- **Optimistic verification** + Messages are assumed valid unless challenged within a dispute window. This reduces verification costs but introduces latency and relies on watchers/challengers being active. + +> Note: Some “bridges” are actually **multisig or custodian-based** (trusted bridges). They can be fast and simple but are not trustless, because a small group can potentially move funds. + +### 4) Key Security Properties + +A robust trustless bridge typically includes: + +- **Cryptographic finality awareness**: only accepting messages after sufficient confirmations/finality. +- **Replay protection**: preventing the same proof/message from being used more than once. +- **Domain separation**: preventing proofs from one chain/environment being accepted on another. +- **Rate limits / circuit breakers (optional)**: limiting blast radius during unforeseen issues. +- **Audited contracts and minimal privileged roles**: reducing governance/upgrade risk. + +## On Sei Network + +Sei is a high-performance Layer 1 with **~400ms finality**, **parallelized execution**, and **EVM compatibility**, which impacts how trustless bridges are designed and used: + +- **Faster bridging UX**: With rapid finality, bridge protocols can often confirm source-chain events quickly, reducing the time users wait before minting/releasing assets on the destination chain (subject to the bridge’s own security parameters and the other chain’s finality). +- **Parallelization at scale**: Sei’s parallel execution can improve throughput for bridge-related transactions (locking, minting, message execution), helping bridges handle higher volume with less congestion. +- **EVM compatibility**: Bridges can deploy Solidity-based contracts on Sei (Sei EVM), reusing familiar patterns for token vaults, wrapped assets, and message relayers—while still benefiting from Sei’s performance characteristics. + +### Example: Minimal ERC-20 “Mint/Burn” Wrapped Token (Solidity) + +Below is a simplified wrapped token pattern often used on the destination side of a bridge. In practice, mint/burn is restricted to a bridge contract that has verified a proof from the source chain. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract WrappedToken is ERC20, AccessControl { + bytes32 public constant BRIDGE_ROLE = keccak256("BRIDGE_ROLE"); + + constructor(string memory name_, string memory symbol_, address bridge) + ERC20(name_, symbol_) + { + _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); + _grantRole(BRIDGE_ROLE, bridge); + } + + function mint(address to, uint256 amount) external onlyRole(BRIDGE_ROLE) { + _mint(to, amount); + } + + function burn(address from, uint256 amount) external onlyRole(BRIDGE_ROLE) { + _burn(from, amount); + } +} +``` + +### Example: Basic “Message Received” Handler (Solidity) + +A generalized message bridge typically calls into a destination contract after verifying a message. The destination contract should authenticate the caller (the bridge) and include replay protection. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract MessageReceiver { + address public immutable bridge; + mapping(bytes32 => bool) public processed; + + event MessageProcessed(bytes32 indexed messageId, address indexed sender, bytes data); + + constructor(address bridge_) { + bridge = bridge_; + } + + modifier onlyBridge() { + require(msg.sender == bridge, "Not bridge"); + _; + } + + function onMessage(bytes32 messageId, address sender, bytes calldata data) external onlyBridge { + require(!processed[messageId], "Replay"); + processed[messageId] = true; + + // Execute app-specific logic based on `data` + emit MessageProcessed(messageId, sender, data); + } +} +``` + +## Trustless Bridge vs. Trusted Bridge (Quick Comparison) + +- **Trustless bridge**: Security derives from cryptographic verification and chain consensus; minimal reliance on operators. +- **Trusted bridge**: Security depends on a custodian, multisig, or federation; typically simpler but introduces counterparty risk. + +## Why It Matters + +Understanding **what is trustless bridge** is important because bridges are often one of the largest sources of cross-chain risk. A trustless design reduces reliance on intermediaries and can provide stronger guarantees that funds and messages move only when valid, especially when combined with high-performance chains like Sei that offer fast finality, parallel execution, and EVM compatibility. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-validator-and-how-does-it-work.mdx b/content/answers/what-is-a-validator-and-how-does-it-work.mdx new file mode 100644 index 00000000..3eabf542 --- /dev/null +++ b/content/answers/what-is-a-validator-and-how-does-it-work.mdx @@ -0,0 +1,149 @@ +--- +title: 'What is a Validator and How Does It Work?' +description: 'Learn about what is validator and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'node', 'what', 'validator', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Validator and How Does It Work? + +## Overview + +A **validator** is a node operator that participates in a blockchain’s consensus process by proposing blocks, validating transactions, and helping finalize the canonical chain. In Proof-of-Stake (PoS) networks, validators typically secure the network by **staking** tokens and can earn rewards for correct behavior or face **slashing** penalties for misbehavior. + +In other words, if you’re asking **what is validator**, it’s the role responsible for turning pending transactions into verified, finalized blocks while maintaining the network’s security and liveness. + +## How It Works + +### 1) Validator registration and staking + +Most modern PoS chains require validators to lock (stake) tokens to be eligible for block production and voting. Stake acts as collateral: + +- **More stake** generally increases the likelihood of being selected to propose blocks or participate in consensus. +- **Bad behavior** (e.g., signing conflicting blocks) can result in **slashing** (loss of stake). +- **Downtime** can lead to penalties and missed rewards. + +Validators can also accept **delegations** from token holders. Delegators contribute stake to a validator to share in rewards, while the validator takes a commission. + +### 2) Proposing blocks + +Validators gather transactions from the mempool and propose a new block according to network rules: + +- Check transaction validity (signatures, balances, nonces) +- Ensure state transitions are correct +- Include fees and apply block constraints (gas limits, size, etc.) + +### 3) Voting and finality + +Other validators verify the proposed block and cast votes/attestations. Consensus rules determine: + +- When a block is accepted +- When it becomes **final** (cannot be reverted without extreme conditions) + +Finality depends on the consensus mechanism (e.g., BFT-style finality vs. probabilistic finality). + +### 4) Rewards and penalties + +Validators are typically compensated through: + +- **Block rewards / inflation** (if applicable) +- **Transaction fees** +- **MEV / proposer rewards** (varies by chain) + +Penalties may apply for: + +- **Double-signing** (equivocation) +- **Invalid blocks** +- **Prolonged downtime** +- **Protocol rule violations** + +### 5) Validator responsibilities (operations) + +To run safely and reliably, validators must manage: + +- Key security (signing keys, HSMs, secure enclaves) +- High uptime and stable networking +- Monitoring and alerting +- Software upgrades and incident response + +## On Sei Network + +Sei Network uses a validator set to secure the chain and finalize blocks extremely quickly, with **~400ms finality** as a core design goal. Validators on Sei perform the standard PoS duties—propose blocks, validate transactions, and participate in consensus—while benefiting from Sei’s architecture optimized for high throughput and low latency. + +Key Sei-specific considerations: + +- **Fast finality (~400ms):** Validators must maintain low-latency connectivity and robust infrastructure to keep up with rapid block production and voting. +- **Parallelization:** Sei’s execution and processing optimizations are designed to increase throughput; validators must run performant hardware and networking to handle higher transaction volumes efficiently. +- **EVM compatibility:** Sei supports Ethereum-style smart contracts and tooling, so validators validate both native transactions and EVM transactions/state transitions as part of normal block validation. + +### Validator vs. full node on Sei + +- A **full node** verifies and serves blockchain data, but does not participate in consensus voting. +- A **validator** is a full node **plus** consensus responsibilities and staking, and it signs/votes on blocks. + +## Common Validator Architecture + +A production validator setup typically includes: + +- **Validator node process** (consensus + execution) +- **Sentry nodes** (optional) to protect the validator from direct DDoS exposure +- **Remote signer / key management** to isolate signing keys +- **Monitoring stack** (metrics, logs, alerting) +- **Redundancy** (backups, failover plans—without risking double-signing) + +## Example: What a Validator Operator Does (Typical Workflow) + +### Check node status and logs + +```bash +# Example commands vary by deployment and tooling. +# Use your process manager/journal to inspect node logs: +journalctl -u seid -f +``` + +### Monitor key metrics + +You generally monitor: + +- Block height progression +- Peer count / networking health +- Missed blocks / signing performance +- CPU/RAM/disk I/O +- Disk space and state growth + +### Perform safe upgrades + +Validators regularly upgrade binaries and apply chain upgrades: + +```bash +# Stop the service +sudo systemctl stop seid + +# Replace binary (path depends on your installation) +sudo cp ./seid /usr/local/bin/seid + +# Start the service +sudo systemctl start seid +``` + +## Security and Best Practices + +- **Protect signing keys:** Use a remote signer or hardened key storage; minimize access and rotate credentials. +- **Avoid double-signing:** Never run the same validator keys on two active nodes simultaneously. +- **Use sentry nodes:** Reduce attack surface by keeping the validator behind private networking. +- **Automate monitoring:** Alert on missed blocks, halted height, peer drops, and disk thresholds. +- **Plan for upgrades:** Test on staging, follow release notes, and coordinate during scheduled upgrades. + +## Summary + +A validator is the core security and consensus participant in a PoS blockchain—staking tokens, proposing and validating blocks, and voting to finalize the chain. On Sei Network, validators perform these same duties while supporting **parallelized high-throughput execution**, **EVM-compatible workloads**, and **~400ms finality**, making performance, uptime, and secure operations especially important. + +## Related Documentation + +- [Node Operations](/node) +- [Validators](/node/validators) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-validator-commission-and-how-does-it-work.mdx b/content/answers/what-is-a-validator-commission-and-how-does-it-work.mdx new file mode 100644 index 00000000..4ab2b3f5 --- /dev/null +++ b/content/answers/what-is-a-validator-commission-and-how-does-it-work.mdx @@ -0,0 +1,139 @@ +--- +title: 'What is a Validator Commission and How Does It Work?' +description: 'Learn about what is validator commission and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'node', 'what', 'validator', 'commission', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Validator Commission and How Does It Work? + +## Overview + +Validator commission is the percentage of staking rewards a validator keeps as a fee for operating the validator infrastructure and providing staking services to delegators. In other words, it’s how validators get paid for running reliable nodes, managing uptime, and handling operational costs. If you’re searching **what is validator commission**, it’s essentially the validator’s “service fee” taken from rewards before the remaining rewards are distributed to delegators. + +## How It Works + +### Commission in Proof-of-Stake (PoS) + +In PoS networks, token holders can either: + +- **Run a validator** themselves, or +- **Delegate** their stake to an existing validator to participate in consensus and earn rewards. + +Validators earn rewards (and may incur penalties) based on their participation in block production/validation. **Commission** defines how those earned rewards are split: + +- **Validator commission rate**: the % of rewards the validator keeps. +- **Delegator rewards**: the remaining rewards after commission is deducted. + +**Example** + +- Network staking rewards generated: **100 tokens** +- Validator commission: **10%** +- Validator keeps: **10 tokens** +- Delegators share: **90 tokens** (distributed proportionally to their delegated stake) + +### Common Commission Parameters + +Most PoS staking systems track multiple commission fields: + +- **Commission rate (current)**: the validator’s current fee percentage. +- **Max commission**: an upper bound the validator can never exceed. +- **Max change rate**: the maximum amount the validator can increase/decrease the commission by within a time window (often per day). + +These constraints protect delegators from sudden or extreme commission hikes. + +### Why Commission Exists + +Validator operations come with real costs and risks: + +- Hardware, hosting, and bandwidth +- Monitoring, upgrades, and security +- Key management and incident response +- Engineering/support for tooling and integrations + +Commission compensates validators so they can sustainably provide reliable service. + +### Commission vs. Slashing (Important Distinction) + +- **Commission**: a normal fee taken from rewards. +- **Slashing / penalties**: punishment for misbehavior or downtime; can reduce stake and future rewards. + +A low commission doesn’t guarantee higher net returns if the validator has poor uptime or is frequently penalized. + +## On Sei Network + +Sei is a high-performance Layer 1 with **fast (~400ms) finality**, **parallelized execution**, and **EVM compatibility**. Validator commission on Sei follows the familiar Cosmos-SDK-style staking model: delegators earn staking rewards, and validators take a commission from those rewards according to the validator’s commission settings. + +### How Commission Affects Delegators on Sei + +When you delegate SEI to a validator: + +1. The validator participates in consensus and earns block rewards (and possibly other staking-related rewards). +2. The protocol calculates rewards attributable to the validator’s delegations. +3. The validator’s **commission rate** is applied to the rewards. +4. Remaining rewards are distributed to delegators based on their share of the total delegated stake. + +Because Sei aims for high throughput and rapid finality, validators must maintain robust infrastructure to keep pace with the network—commission is the mechanism that funds those operational requirements. + +### What to Evaluate Beyond Commission + +When choosing a validator on Sei, commission is only one variable. Consider: + +- **Uptime / signing performance** (missed signatures can reduce rewards and increase risk) +- **Infrastructure and operational maturity** +- **Governance participation** +- **Security posture** +- **Commission stability** (max commission and max change rate can matter as much as today’s rate) + +## How to Check Validator Commission (CLI) + +If you use the Sei CLI, you can query a validator and view its commission settings. Replace `` with the validator operator address. + +```bash +seid query staking validator -o json +``` + +In the JSON output, look for fields similar to: + +- `commission.commission_rates.rate` +- `commission.commission_rates.max_rate` +- `commission.commission_rates.max_change_rate` + +You can also list validators and inspect commission values: + +```bash +seid query staking validators -o json +``` + +## Practical Example (Understanding Net Rewards) + +Assume: + +- You delegate: **1,000 SEI** +- The validator earns rewards equivalent to: **12% APR** +- Validator commission: **5%** + +Approximate net APR to delegator (ignoring compounding and other factors): + +- Gross rewards: 12% +- Commission deducted from rewards: 5% of 12% = 0.6% +- **Estimated net**: ~11.4% APR + +This is a simplification; real returns can vary with network conditions, validator performance, and reward dynamics. + +## Key Takeaways + +- **Validator commission** is the fee validators take from staking rewards to cover costs and earn revenue. +- Delegators receive rewards **after** commission is applied. +- On **Sei Network**, commission works within a Cosmos-style staking model while validators support Sei’s high-performance design (parallelization and ~400ms finality). +- Choosing a validator should balance **commission rate** with **reliability, security, and long-term behavior**. + +## Related Documentation + +- [Node Operations](/node) +- [Validators](/node/validators) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-validator-set-and-how-does-it-work.mdx b/content/answers/what-is-a-validator-set-and-how-does-it-work.mdx new file mode 100644 index 00000000..b707a587 --- /dev/null +++ b/content/answers/what-is-a-validator-set-and-how-does-it-work.mdx @@ -0,0 +1,135 @@ +--- +title: 'What is a Validator Set and How Does It Work?' +description: 'Learn about what is validator set and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'node', 'what', 'validator', 'set', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Validator Set and How Does It Work? + +## Overview + +A **validator set** is the active group of validator nodes currently authorized to propose and vote on new blocks in a proof‑of‑stake (PoS) blockchain. In other words, when people ask **what is validator set**, the answer is: it’s the subset of network participants that collectively secures consensus at a given time, typically chosen based on staked tokens and protocol rules. + +Validator sets can change over time as stake moves, validators join/leave, or performance and slashing events occur—making them a core mechanism for decentralization and security. + +## How It Works + +### 1) Validators, staking, and selection + +In PoS networks, validators lock (stake) tokens to become eligible to participate in consensus. Many chains select the **top N validators** by stake (including delegated stake) as the **active validator set**, while others use different selection rules. + +Key concepts: + +- **Stake / Voting power:** The amount of stake backing a validator determines its influence in consensus (e.g., vote weight). +- **Delegation:** Token holders can delegate stake to validators, increasing those validators’ voting power. +- **Active vs. inactive validators:** Only the active set participates in block production and voting; others may be queued/standby. + +### 2) Block proposal and voting + +Most modern PoS chains use a BFT-style consensus (or a variant) where: + +1. A validator is selected (often weighted by voting power) to **propose** the next block. +2. Validators in the set **vote/attest** to the proposed block. +3. Once a threshold (commonly **>2/3** of total voting power) is reached, the block becomes **finalized** (i.e., cannot be reverted without violating safety assumptions). + +### 3) Rewards, penalties, and slashing + +Validator sets are kept honest through incentives: + +- **Rewards:** Validators earn block rewards and transaction fees, often shared with delegators after commission. +- **Penalties:** Validators can be penalized for downtime or equivocation (e.g., double-signing). Severe misbehavior can trigger **slashing**, reducing staked tokens. + +### 4) Validator set updates (epoch/periodic changes) + +Networks typically update the validator set on a fixed schedule (e.g., per epoch) or at particular consensus boundaries. Updates may include: + +- Changes in voting power due to delegation/unbonding +- Jailing/un-jailing of validators +- New validators entering the active set, others leaving it + +## On Sei Network + +Sei Network is a high-performance Layer 1 blockchain with **EVM compatibility** (via Sei’s EVM) and fast consensus characteristics (notably **~400ms finality** under normal conditions). On Sei, the **validator set** plays the same fundamental role—securing the chain and finalizing blocks—but it does so in an environment optimized for throughput and low latency. + +### What the validator set does on Sei + +- **Finalizes blocks quickly:** Sei’s consensus aims for very fast finality (around **~400ms**), which depends on validators rapidly proposing and voting. +- **Secures both native and EVM activity:** Transactions from CosmWasm/native modules and EVM transactions ultimately rely on the same underlying validator set for ordering and finality. +- **Supports high throughput via parallelization:** Sei’s execution architecture emphasizes parallelization, and a healthy validator set ensures that consensus and state progression keep pace with high transaction volume. + +### Validator set health matters more at high speed + +With low-latency finality targets, validator performance and uptime are especially important: + +- **Network latency and uptime** directly influence consensus round times. +- **Reliable signing behavior** reduces stalls and helps maintain steady block production. +- **Accurate operations** (key management, monitoring, upgrades) reduce the risk of jailing/slashing events that can disrupt set stability. + +## How to View the Validator Set (Typical Operator/User Workflows) + +### Using a CLI (Cosmos SDK-style) + +Sei is built on Cosmos SDK foundations, so common patterns include querying validators and staking state via a chain CLI. The exact binary name may differ by environment, but the queries generally look like: + +```bash +# List active validators (often filtered by bonded status) +seid query staking validators --status bonded + +# Get a single validator by operator address +seid query staking validator + +# Check staking pool / bonded tokens overview +seid query staking pool +``` + +### Practical interpretation + +When reviewing output, focus on: + +- **Status** (bonded/unbonding/unbonded/jailed) +- **Tokens / voting power** +- **Commission rate** +- **Uptime / signing info** (often available via slashing queries or explorer metrics) + +Example (slashing/signing info query pattern): + +```bash +# Look up signing info by consensus address (varies by chain config) +seid query slashing signing-info +``` + +## Why Validator Sets Matter + +### Security + +A validator set is the backbone of PoS security: + +- Attacks typically require controlling a large fraction of voting power (often >1/3 to break liveness, >2/3 to break safety in many BFT models). +- A diverse validator set reduces concentration risk. + +### Performance and user experience + +- Faster finality and stable block times depend on responsive validators. +- On Sei, where the chain targets **high throughput** and **~400ms finality**, validator responsiveness and infrastructure quality are critical to consistent performance—especially for trading, DeFi, and other latency-sensitive applications. + +### Governance and decentralization + +Validators often participate in governance: + +- Voting power influences on-chain proposals and parameter changes. +- Delegation allows token holders to influence governance indirectly by choosing validators. + +## Summary + +A validator set is the actively participating group of staked nodes that proposes and finalizes blocks, enforces consensus rules, and secures a PoS blockchain through weighted voting, rewards, and slashing. On Sei Network, the validator set underpins Sei’s fast finality (~400ms), high-throughput execution, and EVM-compatible transaction processing—making validator performance and decentralization central to both security and speed. + +## Related Documentation + +- [Node Operations](/node) +- [Validators](/node/validators) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-wallet-and-how-does-it-work.mdx b/content/answers/what-is-a-wallet-and-how-does-it-work.mdx new file mode 100644 index 00000000..4c5def2b --- /dev/null +++ b/content/answers/what-is-a-wallet-and-how-does-it-work.mdx @@ -0,0 +1,136 @@ +--- +title: 'What is a Wallet and How Does It Work?' +description: 'Learn about what is wallet and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'wallet', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Wallet and How Does It Work? + +## Overview + +A **wallet** is a tool (app, device, or software) that lets you **store and manage cryptographic keys** used to control assets on a blockchain. In simple terms, **what is wallet** in crypto? It’s not where coins are “kept”—it’s where the **private keys** (and signing capability) live that prove ownership and authorize transactions. + +Wallets typically provide a user interface to view balances, receive funds, and sign transactions, while the blockchain itself stores the authoritative record of balances and ownership. + +## How It Works + +### Public/Private Keys and Addresses + +Most blockchain wallets are built around asymmetric cryptography: + +- **Private key**: A secret number that grants control over funds. Anyone with the private key can sign transactions and move assets. +- **Public key**: Derived from the private key; used to verify signatures. +- **Address**: A shorter, user-friendly identifier derived from the public key (or from the public key hash). You share this to receive funds. + +When you “send” tokens, your wallet: + +1. Constructs a transaction (recipient, amount, fees, nonce, etc.). +2. **Signs** it with your private key. +3. Broadcasts it to the network. +4. Validators include it in a block; the network updates state to reflect the transfer. + +### Seed Phrases (Recovery Phrases) + +Most modern wallets generate keys from a **seed phrase** (often 12 or 24 words, e.g., BIP-39). This phrase can recreate the same private keys across compatible wallets (via HD derivation such as BIP-32/44). +**Protect the seed phrase**: it is effectively a master key. + +### Custodial vs. Non-Custodial + +- **Non-custodial wallets**: You control the private keys (e.g., MetaMask, hardware wallets). You’re responsible for backup and security. +- **Custodial wallets**: A third party (exchange/app) controls keys on your behalf. Easier UX, but you trust the custodian. + +### Hot vs. Cold Wallets + +- **Hot wallets**: Connected to the internet (browser/mobile). Convenient, higher exposure risk. +- **Cold wallets**: Offline storage (hardware wallet, air-gapped). Stronger protection, slightly less convenient. + +### Signing and Verification (Conceptual Example) + +Signing proves authorization without revealing the private key. Conceptually: + +```typescript +// Pseudocode illustrating signing and verification flow +const txHash = hashTransaction(tx); +const signature = sign(txHash, privateKey); + +// Network/validators verify: +const isValid = verifySignature(txHash, signature, publicKey); +``` + +### EVM Wallet Basics (EOA) + +On EVM chains, most users operate via an **Externally Owned Account (EOA)** controlled by a private key. EOAs sign transactions that can: + +- transfer native tokens +- call smart contracts (e.g., ERC-20 transfers) +- deploy contracts + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, which means standard EVM wallets and tooling can be used to manage accounts and interact with Sei-based dApps. + +### What a Wallet Does on Sei + +On Sei, a wallet typically enables you to: + +- Manage your Sei address/account and balances +- Sign and send transactions to Sei validators +- Interact with EVM smart contracts (tokens, DeFi, NFTs, games) +- Connect to dApps via common wallet connectors (e.g., injected providers) + +Because Sei is designed for performance, users benefit from a smooth transaction experience driven by: + +- **Fast finality (~400ms)**: transactions confirm quickly, improving UX for trading and real-time apps. +- **Parallelization**: Sei’s architecture enables higher throughput, helping wallets and dApps process many independent transactions efficiently. +- **EVM compatibility**: existing Ethereum-based wallet patterns (EOA signing, RPC calls, contract interactions) apply with minimal changes. + +### Connecting an EVM Wallet to Sei (Typical Steps) + +1. Add Sei’s EVM network details in your wallet (RPC URL, chain ID, currency symbol). +2. Switch to the Sei network. +3. Use the wallet to sign transactions and interact with Sei dApps. + +Example (generic CLI check using an EVM RPC endpoint): + +```bash +# Query latest block number on Sei EVM via JSON-RPC +curl -s -X POST \ + -H "Content-Type: application/json" \ + --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \ + https://YOUR_SEI_EVM_RPC_URL +``` + +### Sending Tokens via a Smart Contract (Solidity Context) + +When you transfer an ERC-20 token on Sei’s EVM, your wallet signs a transaction calling the token contract: + +```solidity +// Standard ERC-20 transfer call pattern +IERC20(token).transfer(recipient, amount); +``` + +Your wallet signs and submits that contract call transaction to Sei; Sei finalizes it quickly, and the token balances update on-chain. + +## Key Security Tips + +- Never share your **seed phrase** or **private key**. +- Prefer a **hardware wallet** for significant value. +- Verify dApp URLs and transaction prompts before signing. +- Keep backups offline and consider multi-device redundancy for recovery. + +## Summary + +A wallet is a key-management and transaction-signing tool that lets you control blockchain assets. In general, it works by generating/storing private keys, deriving addresses, and signing transactions that the network verifies. On Sei Network, wallets work with familiar EVM patterns while benefiting from Sei’s **parallelization** and **~400ms finality** for fast, responsive on-chain interactions. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-whale-and-how-does-it-work.mdx b/content/answers/what-is-a-whale-and-how-does-it-work.mdx new file mode 100644 index 00000000..24433c7e --- /dev/null +++ b/content/answers/what-is-a-whale-and-how-does-it-work.mdx @@ -0,0 +1,156 @@ +--- +title: 'What is a Whale and How Does It Work?' +description: 'Learn about what is whale and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'whale', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Whale and How Does It Work? + +## Overview + +A **whale** is an individual, entity, or wallet address that holds a **large amount of a cryptocurrency or token** relative to the overall supply or typical holders. Because their holdings are significant, whales can influence market liquidity, price volatility, governance outcomes, and on-chain activity patterns. + +In SEO terms, if you’re asking **“what is whale”** in crypto, it generally refers to a “big holder” whose actions can be visible on-chain and sometimes move markets. + +## How It Works + +### Why whales matter + +Whales can impact a network or market due to the size of their holdings: + +- **Market impact (trading/liquidity):** Large buys/sells can move price, widen spreads, or drain liquidity in pools and order books. +- **Volatility events:** Whale transfers to/from exchanges, bridges, or custodians are often interpreted as potential sell/buy pressure. +- **Governance influence:** In token-based governance, whales may have outsized voting power (directly or via delegation). +- **Protocol interactions:** Whales can materially affect staking, lending, and liquidity provisioning by moving large amounts quickly. + +### Common whale behaviors on-chain + +- **Accumulation/distribution:** Gradual buying to avoid slippage vs. selling in tranches. +- **Liquidity provision:** Adding/removing significant liquidity from AMMs, affecting price and depth. +- **Staking and delegation:** Concentrating stake to earn rewards or influence validator selection (in PoS systems). +- **Arbitrage and MEV strategies:** Taking advantage of price differences or transaction ordering where applicable. + +### How whales are identified + +There is no universal threshold for “whale.” It’s usually defined **relative to the token’s supply and ecosystem**, for example: + +- Top **0.1%** of holders +- Addresses holding **≥1%** of supply +- Wallets above a high USD value threshold (e.g., **$1M+** in assets) + +Analytics platforms and explorers often label whales by balance size, known exchange/custodian addresses, and behavioral patterns. + +## On Sei Network + +On **Sei Network**, whales behave similarly to other chains—moving large token balances, providing liquidity, trading, and participating in governance—but several Sei-specific characteristics shape how whale activity plays out: + +- **Fast finality (~400ms):** Large transfers and trades can confirm quickly, so whale-driven price moves or liquidity shifts can occur and settle rapidly. +- **Parallelization:** Sei’s parallelized execution helps the network handle high-throughput activity (including periods of intense trading) more efficiently, which matters when whales trigger bursts of transactions. +- **EVM compatibility:** Whale activity is easy to monitor and interact with using familiar Ethereum tooling (EVM wallets, Solidity contracts, and standard indexing patterns). Many “whale tracking” approaches used on Ethereum can be applied on Sei’s EVM. + +### Monitoring whale activity on Sei + +Typical ways to track whales on Sei include: + +- **Watching large ERC-20 transfers** (EVM side) or large native token transfers. +- **Following liquidity pool events** (adds/removes) on DEXs. +- **Tracking staking and governance moves** (where applicable) for large delegations or votes. + +## Practical Examples + +### Query large token transfers (EVM logs) with `cast` (Foundry) + +You can scan recent blocks for `Transfer(address,address,uint256)` events of an ERC-20 token and filter for large amounts. + +```bash +# Replace RPC_URL and TOKEN with your Sei EVM RPC endpoint and token contract address +export RPC_URL="https://YOUR_SEI_EVM_RPC" +export TOKEN="0xYourTokenAddress" + +# ERC-20 Transfer event signature: +# Transfer(address,address,uint256) +export TRANSFER_TOPIC="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" + +# Example: get logs in a block range +cast logs \ + --rpc-url $RPC_URL \ + --from-block 1000000 \ + --to-block 1001000 \ + --address $TOKEN \ + $TRANSFER_TOPIC +``` + +From there, you can decode logs and apply a threshold (e.g., transfers greater than 100,000 tokens) to identify “whale” movements. + +### Listen for whale transfers in TypeScript (ethers.js) + +This example subscribes to `Transfer` events and prints transfers above a threshold. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = 'https://YOUR_SEI_EVM_RPC'; +const TOKEN = '0xYourTokenAddress'; + +// Minimal ERC-20 ABI for Transfer events +const abi = ['event Transfer(address indexed from, address indexed to, uint256 value)', 'function decimals() view returns (uint8)']; + +async function main() { + const provider = new ethers.JsonRpcProvider(RPC_URL); + const token = new ethers.Contract(TOKEN, abi, provider); + + const decimals: number = await token.decimals(); + const threshold = ethers.parseUnits('100000', decimals); // whale threshold (example) + + token.on('Transfer', (from: string, to: string, value: bigint, event: any) => { + if (value >= threshold) { + console.log('Whale transfer detected:'); + console.log({ from, to, value: value.toString(), txHash: event.log.transactionHash }); + } + }); + + console.log('Listening for whale transfers...'); +} + +main().catch(console.error); +``` + +### (Optional) Basic on-chain threshold check in Solidity + +If you’re building a protocol on Sei EVM and want to apply special handling for very large holders/transfers (e.g., risk checks), you can define a threshold: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract WhaleThreshold { + uint256 public immutable whaleThreshold; + + constructor(uint256 _whaleThreshold) { + whaleThreshold = _whaleThreshold; + } + + function isWhaleBalance(uint256 balance) external view returns (bool) { + return balance >= whaleThreshold; + } +} +``` + +## Key Takeaways + +- A **whale** is a holder with **enough tokens to meaningfully influence** liquidity, price action, governance, or protocol dynamics. +- Whale behavior is typically tracked through **large transfers, exchange interactions, liquidity events, and staking/governance activity**. +- On **Sei Network**, whale activity can propagate quickly due to **~400ms finality**, and Sei’s **parallelization** plus **EVM compatibility** makes it practical to monitor and build tooling around whale movements using standard EVM workflows. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-wrapped-token-and-how-does-it-work.mdx b/content/answers/what-is-a-wrapped-token-and-how-does-it-work.mdx new file mode 100644 index 00000000..5e031bc7 --- /dev/null +++ b/content/answers/what-is-a-wrapped-token-and-how-does-it-work.mdx @@ -0,0 +1,141 @@ +--- +title: 'What is a Wrapped Token and How Does It Work?' +description: 'Learn about what is wrapped token and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'wrapped', 'token', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Wrapped Token and How Does It Work? + +## Overview + +A **wrapped token** is a blockchain token that represents another asset (often from a different chain) at a **1:1 value**, backed by reserves and redeemable for the underlying asset. In other words, _what is wrapped token_ usually refers to a “proxy” version of an asset that’s been packaged to work in an ecosystem where the original asset isn’t natively supported. + +Wrapped tokens are commonly used to bring liquidity and functionality (like DeFi trading, lending, and collateralization) to assets across different blockchains without moving the original chain’s native token standard into the new environment. + +## How It Works + +Wrapped tokens typically rely on a **mint-and-burn** model with **custody or locking**: + +1. **Deposit / Lock the underlying asset** + + - A user (or bridge) deposits the original asset into a smart contract (lock) or with a custodian (hold). + - Example: locking BTC to create WBTC; locking ETH to create WETH (ETH isn’t an ERC-20 token, so wrapping standardizes it). + +2. **Mint wrapped tokens** + + - Once the deposit is verified, an equivalent amount of wrapped tokens is **minted** on the target chain/standard. + - The wrapped token supply should match the amount of underlying asset locked/held. + +3. **Use the wrapped token** + + - The wrapped token can now be transferred, traded, or used in smart contracts as a standard token for that environment (e.g., ERC-20 on EVM chains). + +4. **Redeem (burn) to get the original asset back** + - The user returns wrapped tokens to the system, which **burns** them. + - The locked/held underlying asset is **released** to the user. + +### Key Properties and Tradeoffs + +- **Pegged value (1:1)**: Wrapped tokens aim to track the underlying asset’s value because they are redeemable for it. +- **Bridge/custody risk**: Many wrapped tokens depend on bridges, validators, or custodians—this introduces trust and smart contract risks. +- **Liquidity and composability**: Wrapping enables assets to participate in DeFi protocols, AMMs, lending markets, and other contract interactions. + +## On Sei Network + +On **Sei Network**, wrapped tokens enable assets from other ecosystems to be used in Sei’s high-performance environment, including **EVM-compatible** smart contracts and tooling. This matters because: + +- **EVM compatibility** means wrapped assets can be used directly in Solidity-based protocols deployed on Sei (DEXs, lending, derivatives, vaults). +- **Parallelization** allows the network to process many transactions concurrently, improving throughput and responsiveness for trading-heavy activity where wrapped asset liquidity is often used. +- **~400ms finality** can provide a faster user experience for transfers and DeFi interactions involving wrapped tokens (e.g., swaps, collateral updates, liquidations), reducing waiting time between actions. + +Wrapped tokens on Sei are commonly minted and redeemed via **bridges** or cross-chain protocols that lock/burn an asset on the source chain and mint/unlock its wrapped representation on Sei. As with any network, the exact safety model depends on the specific bridge (smart contracts, validator set, security assumptions, audits, and operational controls). + +## Example: Using a Wrapped Token in an EVM Contract (Sei) + +Many wrapped tokens on EVM chains follow the ERC-20 interface. Below is a basic Solidity example that accepts deposits of a wrapped token (e.g., a wrapped BTC or wrapped ETH representation) on Sei’s EVM. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function transfer(address to, uint256 amount) external returns (bool); + function balanceOf(address who) external view returns (uint256); +} + +contract WrappedTokenVault { + IERC20 public immutable wrappedToken; + + mapping(address => uint256) public balances; + + constructor(address _wrappedToken) { + wrappedToken = IERC20(_wrappedToken); + } + + function deposit(uint256 amount) external { + require(amount > 0, "amount=0"); + require(wrappedToken.transferFrom(msg.sender, address(this), amount), "transferFrom failed"); + balances[msg.sender] += amount; + } + + function withdraw(uint256 amount) external { + require(balances[msg.sender] >= amount, "insufficient balance"); + balances[msg.sender] -= amount; + require(wrappedToken.transfer(msg.sender, amount), "transfer failed"); + } + + function vaultBalance() external view returns (uint256) { + return wrappedToken.balanceOf(address(this)); + } +} +``` + +## Example: Checking a Wrapped Token Balance (TypeScript) + +If you’re interacting with Sei’s EVM, you can use standard Ethereum libraries to query ERC-20 balances. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const provider = new ethers.JsonRpcProvider(RPC_URL); + +const erc20Abi = ['function balanceOf(address) view returns (uint256)', 'function decimals() view returns (uint8)']; + +async function main() { + const tokenAddress = '0xYourWrappedTokenAddress'; + const user = '0xYourWalletAddress'; + + const token = new ethers.Contract(tokenAddress, erc20Abi, provider); + const [bal, decimals] = await Promise.all([token.balanceOf(user), token.decimals()]); + + console.log('Balance:', ethers.formatUnits(bal, decimals)); +} + +main().catch(console.error); +``` + +## Best Practices and Security Considerations + +- **Verify backing and redemption**: For “what is wrapped token” questions, the most important detail is whether the token is actually redeemable 1:1 and how reserves are proven (on-chain locking vs. custodian attestations). +- **Assess bridge risk**: Review audits, security model, validator assumptions, and incident history of the bridge issuing the wrapped token. +- **Use canonical assets where possible**: Prefer widely adopted, well-audited wrapped assets and official/recognized bridge routes for Sei. +- **Confirm token contracts**: Always use the correct contract address (especially on EVM networks) to avoid spoofed tokens. + +## Summary + +A wrapped token is a 1:1 representation of another asset, created so it can be used in a different blockchain environment or token standard. It works by locking (or custodying) the underlying asset and minting a wrapped version, then burning the wrapped token to redeem the original. On Sei Network, wrapped tokens are especially useful because Sei’s EVM compatibility, parallelized execution, and ~400ms finality make cross-asset DeFi interactions faster and more composable—while the primary risk remains the security model of the bridge or custodian backing the wrap. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx b/content/answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx new file mode 100644 index 00000000..7a7e199e --- /dev/null +++ b/content/answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx @@ -0,0 +1,162 @@ +--- +title: 'What is a Zero-knowledge Proof and How Does It Work?' +description: 'Learn about what is zero-knowledge proof and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'zero-knowledge', 'proof', 'zero', 'knowledge', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is a Zero-knowledge Proof and How Does It Work? + +## Overview + +A **zero-knowledge proof (ZKP)** is a cryptographic method that lets a _prover_ convince a _verifier_ that a statement is true **without revealing any underlying data** (the “witness”) beyond the fact that the statement holds. In other words, it answers the question **“what is zero-knowledge proof”** as: a proof that provides _validity_ without _disclosure_. + +Zero-knowledge proofs are widely used in blockchain to enable **privacy**, **scalable verification**, and **trust-minimized authentication**, while keeping sensitive information off-chain. + +## How It Works + +### Core properties + +A system is considered zero-knowledge when it satisfies three main properties: + +- **Completeness**: If the statement is true and both parties follow the protocol, the verifier accepts. +- **Soundness**: If the statement is false, a dishonest prover cannot convince the verifier (except with negligible probability). +- **Zero-knowledge**: The verifier learns nothing about the secret witness beyond the truth of the statement. + +### Intuition: proving knowledge without revealing it + +A ZKP typically proves a relation like: + +> “I know a secret `w` such that `C(w)` is true.” + +Examples: + +- “I know the private key that controls this address.” +- “This transaction is valid and balances, but the amounts are hidden.” +- “I am over 18, without revealing my birthdate.” + +The prover produces a **proof object** derived from the witness and a public statement. The verifier checks the proof using public information and accepts/rejects. + +### Interactive vs. non-interactive ZKPs + +- **Interactive ZKPs** involve back-and-forth challenges between verifier and prover. +- **Non-interactive ZKPs (NIZKs)** produce a single proof that anyone can verify later. Blockchains prefer NIZKs because they fit the “publish once, verify by all” model. + +Common families you’ll see in blockchain: + +- **zk-SNARKs**: Small proofs, fast verification; often require a trusted setup (depending on the scheme). +- **zk-STARKs**: Transparent setup and post-quantum friendly; proofs are typically larger. +- **Bulletproofs**: No trusted setup; commonly used for range proofs, but verification can be heavier. + +### Why blockchains use ZKPs + +ZKPs are used to: + +- **Improve privacy**: Prove correctness of hidden data (amounts, identity attributes). +- **Scale execution**: Prove a large computation occurred correctly, with cheap verification on-chain. +- **Reduce trust**: Replace trusted intermediaries with cryptographic verification. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **parallelized execution**, **~400ms finality**, and **EVM compatibility**. While ZKPs are not required to use Sei, they integrate naturally in two common ways: + +1. **On-chain verification of ZK proofs via EVM contracts** + Because Sei supports EVM smart contracts, you can deploy Solidity verifiers (e.g., Groth16/Plonk verifiers generated by ZK toolchains) and verify proofs directly on-chain. + +2. **High-throughput apps that benefit from fast settlement** + ZK-enabled apps (private mints, identity attestations, proof-based access control, rollup bridges) can benefit from Sei’s fast finality and parallelization—proof verification and related state transitions can be confirmed quickly, and independent transactions can execute concurrently. + +### Typical Sei ZKP flow (application pattern) + +1. **Off-chain**: User generates a proof with a ZK circuit (e.g., “I know a secret meeting these constraints”). +2. **On-chain (Sei EVM)**: User submits the proof to a verifier contract. +3. **Contract**: Verifies proof and then executes application logic (mint, transfer, permission, etc.). +4. **Finality**: The result settles with Sei’s low-latency finality, enabling responsive UX. + +## Example: Verifying a Proof in a Solidity Contract (Conceptual) + +In practice, your ZK toolchain generates a verifier contract with an interface like `verifyProof(...)`. Your application contract calls it before allowing state changes. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IZKVerifier { + function verifyProof( + bytes calldata proof, + uint256[] calldata publicInputs + ) external view returns (bool); +} + +contract ZKProtectedAction { + IZKVerifier public verifier; + + constructor(address _verifier) { + verifier = IZKVerifier(_verifier); + } + + function doAction(bytes calldata proof, uint256[] calldata publicInputs) external { + // Example statement: "I know a secret that satisfies constraints" + // publicInputs might include a commitment, nullifier, or Merkle root. + require(verifier.verifyProof(proof, publicInputs), "Invalid ZK proof"); + + // If the proof is valid, proceed with application logic + // e.g., mint, unlock access, update state, etc. + } +} +``` + +## Example: Submitting a Proof from a TypeScript Script (Sei EVM) + +Below is a minimal pattern for sending a proof to a Sei EVM contract using `ethers`. You’d replace `proof` and `publicInputs` with outputs from your ZK prover. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const PRIVATE_KEY = process.env.PRIVATE_KEY!; +const CONTRACT = '0xYourContractAddress'; + +const abi = ['function doAction(bytes proof, uint256[] publicInputs) external']; + +async function main() { + const provider = new ethers.JsonRpcProvider(RPC_URL); + const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + + const zkApp = new ethers.Contract(CONTRACT, abi, wallet); + + // Produced off-chain by a ZK prover + const proof = '0x...'; // bytes + const publicInputs = [ + /* e.g. root, nullifierHash, commitment */ + ]; + + const tx = await zkApp.doAction(proof, publicInputs); + await tx.wait(); + + console.log('Submitted proof tx:', tx.hash); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); +``` + +## Key Takeaways + +- **What is zero-knowledge proof**: a way to prove a statement is true **without revealing** the secret data that makes it true. +- ZKPs rely on cryptographic guarantees (completeness, soundness, zero-knowledge) to enable privacy and scalable verification. +- On **Sei Network**, ZK-powered applications can leverage **EVM compatibility** for verifier contracts, plus **parallelization** and **~400ms finality** for fast, high-throughput settlement. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-atomic-swap-and-how-does-it-work.mdx b/content/answers/what-is-an-atomic-swap-and-how-does-it-work.mdx new file mode 100644 index 00000000..4a2a9fe1 --- /dev/null +++ b/content/answers/what-is-an-atomic-swap-and-how-does-it-work.mdx @@ -0,0 +1,176 @@ +--- +title: 'What is an Atomic Swap and How Does It Work?' +description: 'Learn about what is atomic swap and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'atomic', 'swap', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an Atomic Swap and How Does It Work? + +## Overview + +An **atomic swap** is a trust-minimized way to exchange two different cryptocurrencies directly between two parties **without a centralized exchange or custodian**. The “atomic” part means the swap either completes entirely for both sides or it doesn’t happen at all—preventing partial fills or one-sided loss. + +In other words, when people ask **“what is atomic swap”**, the answer is: a cryptographic mechanism for cross-chain (or cross-network) token exchange with built-in all-or-nothing guarantees. + +## How It Works + +Atomic swaps are commonly implemented using **Hashed Timelock Contracts (HTLCs)** or related constructions. The goal is to ensure that each party can only claim the other party’s funds if they satisfy a cryptographic condition within a specified time window; otherwise, funds can be refunded. + +### Key building blocks + +- **Hashlock**: Funds can be claimed only by revealing a secret `s` such that `hash(s) = h`. +- **Timelock**: A deadline after which the sender can reclaim funds if the swap doesn’t complete. +- **Atomicity guarantee**: Either: + - both parties successfully redeem using the same secret, or + - both parties eventually refund after timeouts. + +### Typical HTLC flow (two chains A and B) + +1. **Alice picks a secret** + + - Alice generates a random secret `s` and computes `h = hash(s)`. + +2. **Alice locks funds on Chain A** + + - Alice creates an HTLC on Chain A that pays Bob **only if** Bob reveals `s` (matching `h`) before time `T1`. + - If not redeemed by `T1`, Alice can refund. + +3. **Bob locks funds on Chain B** + + - After seeing Alice’s HTLC, Bob creates a similar HTLC on Chain B that pays Alice **only if** Alice reveals `s` before time `T2`, where `T2 < T1`. + - If not redeemed by `T2`, Bob can refund. + +4. **Alice redeems on Chain B** + + - Alice claims Bob’s locked funds by revealing `s` on Chain B. + +5. **Bob learns the secret and redeems on Chain A** + + - Because `s` is now public on Chain B, Bob extracts it and uses it to redeem Alice’s locked funds on Chain A. + +6. **Refund paths (if something goes wrong)** + - If Alice never redeems Bob’s HTLC, Bob refunds after `T2`. + - If Bob never redeems Alice’s HTLC, Alice refunds after `T1`. + +### What atomic swaps require + +- Compatible scripting or smart contract capabilities to support hashlocks and timelocks (or an equivalent mechanism). +- Reliable on-chain finality so both parties can safely proceed at each step. +- Good timeout selection (`T1` longer than `T2`) to ensure the refund path remains safe. + +## On Sei Network + +Sei is a high-performance Layer 1 with **EVM compatibility**, fast block times, and **~400ms finality**, which improves the practical user experience of atomic swap-like workflows where each step depends on timely, confirmed on-chain state. + +### Why Sei’s architecture helps + +- **Fast finality (~400ms):** Atomic swaps involve sequential actions (lock → verify → lock → redeem). Faster finality reduces the time counterparties must wait between steps and lowers exposure to market volatility during the swap window. +- **Parallelization:** Sei’s parallelized execution helps the chain maintain high throughput under load—useful for swap-heavy environments (e.g., DEX activity or many concurrent HTLC redemptions). +- **EVM compatibility:** You can implement HTLC-style logic using Solidity on Sei’s EVM, enabling Ethereum-style tooling and contract patterns. + +### Example: Simple HTLC-style contract (Solidity) + +Below is a minimal illustrative HTLC pattern for Sei EVM. It locks ETH-like native value (or can be adapted for ERC-20) and allows a recipient to claim by revealing the correct preimage before the timeout; otherwise the sender refunds after the deadline. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract SimpleHTLC { + address public immutable sender; + address public immutable receiver; + bytes32 public immutable hashlock; // h = keccak256(s) + uint256 public immutable timelock; // unix timestamp + + bool public withdrawn; + bool public refunded; + bytes32 public preimage; // revealed secret (stored for demonstration) + + constructor(address _receiver, bytes32 _hashlock, uint256 _timelock) payable { + require(msg.value > 0, "Must lock value"); + require(_receiver != address(0), "Bad receiver"); + require(_timelock > block.timestamp, "Timelock must be in future"); + + sender = msg.sender; + receiver = _receiver; + hashlock = _hashlock; + timelock = _timelock; + } + + // Receiver claims funds by revealing secret s such that keccak256(s) == hashlock + function withdraw(bytes32 _preimage) external { + require(msg.sender == receiver, "Not receiver"); + require(!withdrawn && !refunded, "Already completed"); + require(block.timestamp < timelock, "Expired"); + require(keccak256(abi.encodePacked(_preimage)) == hashlock, "Invalid preimage"); + + withdrawn = true; + preimage = _preimage; + + (bool ok, ) = receiver.call{value: address(this).balance}(""); + require(ok, "Transfer failed"); + } + + // Sender refunds after timelock + function refund() external { + require(msg.sender == sender, "Not sender"); + require(!withdrawn && !refunded, "Already completed"); + require(block.timestamp >= timelock, "Not expired"); + + refunded = true; + + (bool ok, ) = sender.call{value: address(this).balance}(""); + require(ok, "Transfer failed"); + } +} +``` + +### Deploying on Sei EVM (example) + +Using Foundry (or similar tooling), you’d point your RPC to Sei’s EVM endpoint and deploy as you would on any EVM chain: + +```bash +export RPC_URL="https://" +export PRIVATE_KEY="" + +forge create --rpc-url "$RPC_URL" \ + --private-key "$PRIVATE_KEY" \ + src/SimpleHTLC.sol:SimpleHTLC \ + --constructor-args \ + --value 0.1ether +``` + +> Note: For real deployments, you typically implement ERC-20 support, stronger event logging, reentrancy protections, better secret handling, and careful timeout/confirmation policies across both networks. + +## Benefits and Limitations + +### Benefits + +- **No centralized custodian:** Reduces exchange counterparty risk. +- **All-or-nothing execution:** Funds are either swapped or safely refunded. +- **Transparency:** On-chain verification of locking and redemption. + +### Limitations + +- **Liquidity and UX:** Finding counterparties and handling timeouts can be complex. +- **Cross-chain complexity:** Requires each chain to support compatible primitives and reliable confirmation/finality assumptions. +- **Time risk:** Market moves during the lock period; short finality (like Sei’s ~400ms) helps reduce waiting time, but timeouts must still be carefully chosen. + +## Related Terms (Glossary) + +- **HTLC (Hashed Timelock Contract):** The most common mechanism for atomic swaps. +- **Hashlock / Timelock:** Conditions that enforce secret-based redemption and time-based refunds. +- **Cross-chain swap:** A broader category of swaps between different chains; atomic swaps are one trust-minimized method. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-evm-and-how-does-it-work.mdx b/content/answers/what-is-an-evm-and-how-does-it-work.mdx new file mode 100644 index 00000000..3ea18725 --- /dev/null +++ b/content/answers/what-is-an-evm-and-how-does-it-work.mdx @@ -0,0 +1,160 @@ +--- +title: 'What is an EVM and How Does It Work?' +description: 'Learn about what is EVM and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'evm', 'what', 'EVM', 'evm', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an EVM and How Does It Work? + +## Overview + +An **EVM (Ethereum Virtual Machine)** is the runtime environment that executes smart contracts and processes state changes on Ethereum and other EVM-compatible blockchains. When people ask **“what is EVM”**, they’re referring to the standardized virtual machine that interprets contract bytecode, enforces deterministic execution, and charges **gas** for computation to prevent abuse. + +## How It Works + +### 1) Smart contracts compile to bytecode + +Developers write contracts in high-level languages (most commonly Solidity). The code is compiled into **EVM bytecode**, a low-level instruction set that the EVM can execute. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public value; + + function inc() external { + value += 1; + } +} +``` + +When deployed, the contract’s bytecode is stored on-chain, and every node can execute the same code to verify results. + +### 2) The EVM is deterministic + +The EVM is designed so that every validator/node, given the same: + +- starting state, +- transaction input (calldata), +- and block context (e.g., block number, timestamp), + +will compute the **same output state**. This determinism is essential for consensus. + +### 3) Transactions trigger execution + +Users don’t “run” contracts directly; they submit a **transaction** that calls a contract function. The EVM executes the function by: + +- loading calldata, +- reading/writing state (storage), +- emitting logs/events, +- returning data or reverting on failure. + +### 4) Gas metering prevents resource abuse + +Each EVM opcode has a defined **gas cost**. The sender specifies: + +- `gasLimit` (maximum units of gas they’re willing to spend), +- `maxFeePerGas` / `maxPriorityFeePerGas` (fee pricing, on EIP-1559 style networks). + +If execution consumes more gas than the limit, the transaction **reverts**, but gas spent up to that point is still paid (except for certain refunds). + +### 5) EVM state model: stack, memory, storage + +The EVM uses three main data areas: + +- **Stack**: a simple LIFO structure used by opcodes (fast, temporary). +- **Memory**: temporary byte-addressable data for the duration of a call. +- **Storage**: persistent key-value storage associated with each contract (expensive to write). + +This model is why storage writes cost more gas than computation or memory use. + +### 6) Calls, contract creation, and reverts + +The EVM supports: + +- **CALL/DELEGATECALL/STATICCALL**: invoking other contracts (with different context rules). +- **CREATE/CREATE2**: deploying new contracts. +- **REVERT**: aborting changes while returning an error payload (commonly used by Solidity). + +### 7) Receipts, logs, and indexing + +Contracts can emit **events** (logs). Logs aren’t part of contract storage, but they are included in transaction receipts and are efficiently searchable by off-chain indexers and apps. + +## On Sei Network + +Sei is an **EVM-compatible Layer 1**, meaning it can execute EVM bytecode and support common Ethereum tooling while benefiting from Sei’s performance characteristics. + +### EVM compatibility on Sei + +On Sei, “what is EVM” effectively means the same execution environment developers already know: + +- Write Solidity contracts +- Compile to EVM bytecode +- Deploy and interact using standard tools (e.g., Foundry/Hardhat, ethers.js) + +This allows many Ethereum-native contracts and libraries to be reused with minimal changes. + +### High-performance execution characteristics + +Sei’s architecture is designed for high throughput and fast confirmation, which impacts the developer and user experience: + +- **Parallelization**: Sei is built to process many independent transactions concurrently, increasing throughput when transactions don’t contend for the same state. +- **~400ms finality**: Transactions reach finality quickly, enabling responsive on-chain apps and better UX for trading, gaming, and real-time applications. + +### Tooling example (ethers.js) + +Below is a simple example of calling a deployed contract on an EVM-compatible chain like Sei. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = 'https://YOUR_SEI_EVM_RPC'; +const provider = new ethers.JsonRpcProvider(RPC_URL); + +const CONTRACT_ADDRESS = '0xYourContractAddress'; +const ABI = ['function value() view returns (uint256)', 'function inc()']; + +async function main() { + const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, provider); + + const v = await contract.value(); + console.log('value =', v.toString()); +} + +main().catch(console.error); +``` + +### Developer workflow (deploy with Foundry) + +A typical workflow to deploy an EVM contract to Sei is the same pattern used on Ethereum—compile, broadcast a transaction, and verify behavior. + +```bash +# Build +forge build + +# Deploy (example; configure RPC and private key securely) +forge create \ + --rpc-url https://YOUR_SEI_EVM_RPC \ + --private-key $PRIVATE_KEY \ + src/Counter.sol:Counter +``` + +## Key Takeaways + +- **What is EVM?** A deterministic virtual machine that executes smart contract bytecode with gas metering and a standardized state model. +- The EVM enables **portable smart contracts** across many networks that implement EVM semantics. +- **On Sei Network**, EVM compatibility plus **parallelization** and **~400ms finality** can deliver faster confirmations and higher throughput while preserving familiar Ethereum development patterns. + +## Related Documentation + +- [EVM Overview](/evm) +- [Networks & RPC](/evm/networks) +- [Deploy with Hardhat](/evm/evm-hardhat) +- [Deploy with Foundry](/evm/evm-foundry) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx b/content/answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx new file mode 100644 index 00000000..107b0e88 --- /dev/null +++ b/content/answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx @@ -0,0 +1,144 @@ +--- +title: 'What is an Impermanent Loss and How Does It Work?' +description: 'Learn about what is impermanent loss and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'impermanent', 'loss', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an Impermanent Loss and How Does It Work? + +## Overview + +Impermanent loss (IL) is the difference in value between holding two assets in your wallet versus depositing them into an automated market maker (AMM) liquidity pool, measured at the time you withdraw. It’s called “impermanent” because the loss can shrink or disappear if prices return to the level where you deposited—though it becomes permanent once you withdraw while the price ratio is still changed. + +In plain terms: if one token in the pool moves in price relative to the other, the AMM rebalances your pool share, and you may end up with more of the losing asset and less of the winning one compared to simply holding. + +## How It Works + +### Why impermanent loss happens in AMMs + +Most AMMs (e.g., Uniswap v2-style pools) maintain a pricing relationship using a **constant product** formula: + +- **x \* y = k**, where `x` and `y` are the reserves of token X and token Y. + +Traders arbitrage the pool price back to the market price. When the external price changes, arbitrage trades against the pool until the pool’s ratio matches the new price. That process changes the pool reserves—and therefore changes what you, as a liquidity provider (LP), effectively hold. + +### The “loss” is relative to holding + +Impermanent loss is not necessarily a loss in absolute USD terms—you can still profit if both assets go up. It’s a loss **relative to the alternative strategy of holding the assets outside the pool**. + +### IL grows with price divergence + +For a 50/50 constant-product pool, impermanent loss depends on how much the price ratio changes. A commonly used approximation for IL when token A changes by a factor `p` relative to token B is: + +- **IL(p) = 2√p / (1 + p) − 1** + +Where: + +- `p = new_price / old_price` (relative price change of one asset vs the other) +- IL is typically expressed as a negative percentage (e.g., `-5.72%`) + +Example reference points (50/50 pool, no fees): + +- Price moves **+25%** → IL ≈ **-0.6%** +- Price moves **+100% (2×)** → IL ≈ **-5.72%** +- Price moves **+400% (5×)** → IL ≈ **-25.5%** + +### Fees can offset impermanent loss + +AMMs usually pay LPs trading fees. Your net outcome is: + +- **Net PnL ≈ Trading fees + incentives − impermanent loss** + +High trading volume and fee rates can outweigh IL, while low volume pools may not compensate for it. + +### When it becomes “permanent” + +Impermanent loss becomes realized if you withdraw liquidity while the price ratio is different from when you deposited. If the price ratio returns to the original level, IL can reduce significantly (though not necessarily to zero if there are other factors like fees, rebalances, or concentrated liquidity ranges). + +### Common factors that influence impermanent loss + +- **Volatility:** Higher volatility between the pair increases IL risk. +- **Correlation:** Highly correlated assets (e.g., stablecoin pairs) tend to have lower IL. +- **Pool design:** Constant product vs stableswap curves, concentrated liquidity, or dynamic fees. +- **Time and volume:** More time can mean more fees, but also more chance of divergence. + +## On Sei Network + +On Sei Network, impermanent loss is the same core phenomenon you see on other AMM-based DEXs: providing liquidity can underperform holding when the relative price of the pair diverges. What differs is the trading environment where that IL is generated and compensated. + +### Faster markets, faster fee accrual + +Sei’s **~400ms finality** and high throughput make it well-suited for active onchain trading. In general, faster execution and more responsive markets can translate into: + +- More frequent trades (potentially more fee generation for LPs) +- Quicker arbitrage to align pool prices with external markets + +This doesn’t eliminate impermanent loss, but it can affect the balance between **fees earned** and **IL incurred**. + +### Parallelization and throughput + +Sei’s **parallelization** (processing many non-conflicting transactions concurrently) supports dense trading activity and reduces congestion. For LPs, this may improve: + +- Market responsiveness and user experience +- Consistency of pool activity during high demand + +Again, IL mechanics remain the same, but the chain’s performance can influence whether fee revenue keeps pace with IL. + +### EVM compatibility and familiar AMM mechanics + +With Sei’s **EVM compatibility**, many AMM designs and liquidity strategies familiar from Ethereum can be deployed on Sei. That means: + +- Constant-product pools behave as expected (x \* y = k) +- Impermanent loss analysis and tooling generally carry over +- Solidity-based strategies, vaults, and LP management contracts can be built similarly + +## Example: Estimating Impermanent Loss + +### Quick calculation (TypeScript) + +Use the standard 50/50 constant-product IL formula: + +```typescript +// Impermanent loss for a 50/50 constant-product AMM (e.g., Uniswap v2 style) +// p = price change factor (e.g., 2 means +100% relative move) +export function impermanentLoss(p: number): number { + if (p <= 0) throw new Error('p must be > 0'); + const il = (2 * Math.sqrt(p)) / (1 + p) - 1; + return il; // negative number, e.g., -0.0572 for -5.72% +} + +// Examples: +console.log(impermanentLoss(1)); // 0 (no price change) +console.log(impermanentLoss(2)); // ~ -0.0572 (-5.72%) +console.log(impermanentLoss(0.5)); // ~ -0.0572 (symmetry for half price) +``` + +### Interpreting the result + +- If `impermanentLoss(2) ≈ -0.0572`, you underperform holding by ~5.72% **before fees and incentives**. +- If the pool earned >5.72% in fees/incentives over that period, you could still come out ahead. + +## Practical Tips to Manage Impermanent Loss + +- **Choose correlated pairs** (e.g., stable/stable, LST/LST) to reduce divergence risk. +- **Prefer higher-volume pools** where fees have a better chance of offsetting IL. +- **Understand the AMM design** (constant product vs stableswap vs concentrated liquidity) and its IL profile. +- **Track net performance** (fees + incentives − IL), not IL alone. +- **Plan exit timing**: withdrawing after large price divergence realizes IL. + +## Summary + +If you’re asking “**what is impermanent loss**,” it’s the opportunity cost LPs face when AMM rebalancing causes their pooled position to underperform simply holding the tokens. It arises from the AMM’s pricing mechanics during relative price changes and is often (but not always) offset by trading fees and incentives. On Sei Network, the same principles apply, with the chain’s fast finality, parallelization, and EVM compatibility supporting high-activity trading environments where fee dynamics may be more favorable for active pools. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-interchain-security-and-how-does-it-work.mdx b/content/answers/what-is-an-interchain-security-and-how-does-it-work.mdx new file mode 100644 index 00000000..ca6deaa7 --- /dev/null +++ b/content/answers/what-is-an-interchain-security-and-how-does-it-work.mdx @@ -0,0 +1,112 @@ +--- +title: 'What is an Interchain Security and How Does It Work?' +description: 'Learn about what is interchain security and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'cosmos-sdk', 'what', 'interchain', 'security', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an Interchain Security and How Does It Work? + +## Overview + +Interchain Security is a framework for sharing blockchain security across multiple chains in a Cosmos ecosystem, allowing a “consumer” chain to inherit the economic security of a “provider” chain’s validator set. In practice, it means a new chain can launch with strong security without bootstrapping its own validator and staking economy from scratch. + +If you’re searching **what is interchain security**, the core idea is: **one chain provides validator-backed security, and other chains reuse that security while remaining independent in features and governance.** + +## How It Works + +### Shared security concepts (general blockchain context) + +In proof-of-stake (PoS) blockchains, security is primarily derived from: + +- **Stake at risk** (the total value that can be slashed) +- **Validator set quality** (decentralization, operational reliability) +- **Slashing and incentives** (penalizing misbehavior, rewarding correct behavior) + +A new chain typically needs time to accumulate stake, attract validators, and build credibility. Shared security models reduce this bootstrapping problem by letting one chain “rent” or “inherit” security from another. + +### Interchain Security in Cosmos + +In Cosmos, Interchain Security (often abbreviated **ICS**) is most commonly implemented via the **provider/consumer chain** model: + +- **Provider chain**: The chain with established stake and validator set (e.g., Cosmos Hub in the canonical ICS model). +- **Consumer chain**: A chain that uses the provider’s validator set to produce blocks and enforce consensus rules. + +Key mechanics generally include: + +1. **Validator set replication** + The consumer chain mirrors (or derives) the provider’s validator set. Validators run infrastructure for the consumer chain in addition to the provider chain. + +2. **Cross-chain coordination (via IBC)** + The provider and consumer chains coordinate validator updates, evidence of misbehavior, and reward distribution via IBC channels and standardized packets. + +3. **Slashing for consumer-chain faults** + If a validator double-signs or otherwise violates consensus rules on the consumer chain, evidence can be relayed to the provider chain, which can **slash** the validator’s stake on the provider chain. This is the crux of shared security: the stake “at risk” lives on the provider. + +4. **Reward sharing** + Consumer chains typically pay validators (and often delegators) by sending fees and/or inflation rewards back to the provider chain, aligning incentives for validators to secure the consumer chain. + +### Common Interchain Security models + +Depending on the Cosmos stack and design, “interchain security” may refer to one of these approaches: + +- **Replicated security (ICS / provider-consumer)** + Consumer chain inherits the provider validator set; slashing happens on the provider. Strongest form of shared security. + +- **Mesh security / mutual security** + Multiple chains coordinate to secure each other (less common, more complex trade-offs). + +- **Opt-in security** + Validators opt in to secure additional chains; security may be partial depending on participation and stake distribution. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility** and fast finality (often ~**400ms**), designed to support demanding applications while maintaining Cosmos interoperability. While Interchain Security is a Cosmos concept (typically built around Cosmos SDK + IBC), how it applies to Sei depends on the specific deployment model of a given chain in the ecosystem: + +- **Sei as a high-performance execution environment** + Sei’s parallelized execution and fast finality improve user and application experience, but **Interchain Security is about consensus security and validator stake at risk**, not execution speed. In other words, Sei’s parallelization helps throughput and latency; interchain security helps a chain launch and operate with stronger economic security. + +- **Interoperability via IBC** + Interchain Security relies on cross-chain messaging for validator set updates and slashing evidence. Cosmos chains that integrate with Sei through IBC can combine Sei’s fast settlement characteristics with Cosmos-native interoperability patterns. + +- **EVM applications and shared security considerations** + For EVM-compatible chains or appchains in the Cosmos ecosystem, interchain security can be especially attractive: teams can focus on EVM runtime, contracts, and app logic while relying on an established validator set elsewhere—reducing the need to bootstrap a separate staking token and validator market. + +> Practical takeaway: **Sei’s strengths (parallelization, fast finality, EVM compatibility) complement but do not replace interchain security.** Interchain security is a consensus-layer security sharing model; Sei is a high-performance L1 that can participate in the broader Cosmos ecosystem patterns where relevant. + +## Why Interchain Security Matters + +- **Faster, safer chain launches**: New chains can start with robust security from day one. +- **Better capital efficiency**: Less duplication of staking/security across many chains. +- **Validator incentive alignment**: Security providers are compensated; consumer chains gain credible security. +- **Ecosystem scalability**: Many specialized chains can exist without each needing to build an independent security base. + +## High-Level Message Flow (Illustrative) + +Below is a simplified illustration of how provider/consumer interchain security coordination typically looks (exact modules and packet formats depend on the ICS version and chain implementations): + +```text +Provider Chain (stake + slashing) <--- IBC ---> Consumer Chain (blocks + apps) + | | + | validator set updates | block production using + |---------------------------------------------> | provider validator set + | | + | slashing evidence (e.g., double-sign) | + |<--------------------------------------------- | + | | + | apply slash + distribute rewards | +``` + +## Summary + +**What is interchain security?** It’s a shared security framework where a consumer chain leverages the validator set and economic security of a provider chain, typically coordinated via IBC, with slashing enforced on the provider. In the Cosmos ecosystem, it enables scalable multi-chain growth by reducing the need for every new chain to bootstrap its own security. On Sei, these ideas can complement Sei’s high-performance design—Sei optimizes execution and finality, while interchain security (when used) optimizes how consensus security is provisioned across chains. + +## Related Documentation + +- [Cosmos SDK](/cosmos-sdk) +- [Transactions](/cosmos-sdk/transactions) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-interoperability-and-how-does-it-work.mdx b/content/answers/what-is-an-interoperability-and-how-does-it-work.mdx new file mode 100644 index 00000000..262b1dbd --- /dev/null +++ b/content/answers/what-is-an-interoperability-and-how-does-it-work.mdx @@ -0,0 +1,185 @@ +--- +title: 'What is an Interoperability and How Does It Work?' +description: 'Learn about what is interoperability and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'interoperability', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an Interoperability and How Does It Work? + +## Overview + +Interoperability is the ability of different systems, applications, or networks to communicate, exchange data, and use that data correctly without special effort from the user. In blockchain, interoperability enables separate chains and apps to transfer assets, messages, and state changes across network boundaries. + +In short, **what is interoperability** in crypto? It’s the set of standards and mechanisms that let blockchains “talk” to each other securely and predictably. + +## How It Works + +Blockchain interoperability typically happens through **cross-chain messaging** and **asset bridging**. While implementations vary, most approaches rely on a few core components: + +### Cross-chain messaging (the core primitive) + +Cross-chain messaging moves _information_ (not just tokens) from Chain A to Chain B—e.g., “User deposited collateral,” “This contract call happened,” or “Mint tokens on the destination.” A common high-level flow is: + +1. **Event on source chain:** A user triggers a transaction (deposit, lock, burn, or message send). +2. **Proof or verification:** The destination chain (or an intermediary network) verifies that the source event occurred. +3. **Execution on destination chain:** A contract on the destination chain executes logic based on the verified message (mint, unlock, call a function, update state). + +### Token bridging (a common use case) + +Token bridges move value between chains, usually with one of these models: + +- **Lock-and-mint:** Lock tokens on Chain A, mint wrapped tokens on Chain B. +- **Burn-and-mint:** Burn wrapped tokens on Chain B, mint/unlock on Chain A when returning. +- **Liquidity-based bridges:** Use liquidity pools on both sides; transfers are balanced through market makers/relayers. + +### Verification models + +Interoperability security depends heavily on how the destination verifies the source chain: + +- **Light-client / proof-based verification:** Destination validates cryptographic proofs of the source chain’s state (often considered the strongest model when correctly implemented). +- **Validator/committee or multisig attestation:** A trusted set of signers attests to events (simpler, but trust assumptions are higher). +- **Optimistic verification:** Messages are assumed valid unless challenged within a time window (faster UX, but depends on fraud proofs and challengers). +- **Oracle/relay-based designs:** External systems relay data; trust shifts to the oracle/relay mechanism. + +### Why interoperability matters + +Interoperability unlocks: + +- **Composable apps across chains** (use liquidity or features wherever they exist) +- **Better liquidity and market access** (assets move to where demand is) +- **Scalability and specialization** (different chains optimize for different workloads) +- **Cross-ecosystem user experiences** (one app can span multiple networks) + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, designed for fast, scalable on-chain applications. Interoperability on Sei commonly centers around: + +### EVM-compatible contracts and tooling + +Because Sei supports EVM, developers can deploy Solidity smart contracts and integrate with familiar wallets and tools. This makes it easier to build cross-chain applications that reuse existing EVM-based patterns for bridging and messaging. + +### Fast settlement for cross-chain UX + +Sei’s ~**400ms finality** helps reduce the perceived waiting time between a source-chain action and a destination-chain effect (subject to the bridge/messaging protocol’s own security model and confirmation requirements). Faster finality can improve: + +- bridging UX (quicker confirmations on Sei side), +- cross-chain arbitrage and trading workflows, +- multi-step cross-chain app flows where Sei is a hub or destination. + +### Parallelization for high throughput + +Sei’s **parallelization** enables higher throughput and more consistent performance under load, which benefits interoperability-heavy apps such as: + +- cross-chain DEX aggregators, +- bridging routers, +- intent-based systems and relayers that process many messages/transactions. + +### Typical interoperability patterns for Sei apps + +Developers often implement one of these patterns when Sei is involved: + +- **Bridge assets to Sei:** Users move tokens to Sei for trading, lending, or app usage. +- **Send a cross-chain message to a Sei contract:** A source-chain action triggers a contract call on Sei after verification. +- **Use Sei as a fast execution layer:** Execute latency-sensitive logic on Sei and synchronize outcomes back to other networks. + +## Example: Solidity interface for a cross-chain message receiver (EVM) + +Below is a simplified pattern often used by messaging protocols: a receiver contract that accepts a verified message and executes application logic. Exact function signatures vary by protocol. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface ICrossChainMessenger { + // A generic "send" interface (protocol-specific in practice) + function sendMessage( + uint256 dstChainId, + address dstReceiver, + bytes calldata message + ) external payable; +} + +contract SeiMessageReceiver { + address public trustedMessenger; + + event MessageReceived(uint256 srcChainId, address srcSender, bytes payload); + + constructor(address _trustedMessenger) { + trustedMessenger = _trustedMessenger; + } + + // Called by the messaging protocol after it verifies the source-chain event/proof + function onMessage( + uint256 srcChainId, + address srcSender, + bytes calldata payload + ) external { + require(msg.sender == trustedMessenger, "UNTRUSTED_MESSENGER"); + + // Application logic goes here: + // - update state + // - mint/unlock tokens + // - execute actions based on payload + emit MessageReceived(srcChainId, srcSender, payload); + } +} +``` + +## Example: Sending a cross-chain message (TypeScript) + +This example shows the shape of an EVM-style transaction to a messenger contract. You’ll swap in the real messenger address/ABI and parameters for the protocol you use. + +```typescript +import { ethers } from 'ethers'; + +async function sendCrossChainMessage() { + const rpcUrl = process.env.RPC_URL!; + const pk = process.env.PRIVATE_KEY!; + const provider = new ethers.JsonRpcProvider(rpcUrl); + const wallet = new ethers.Wallet(pk, provider); + + const messengerAddress = '0xYourMessenger'; + const messengerAbi = ['function sendMessage(uint256 dstChainId, address dstReceiver, bytes message) payable']; + + const messenger = new ethers.Contract(messengerAddress, messengerAbi, wallet); + + const dstChainId = 1234; // destination chain id (example) + const dstReceiver = '0xDestinationReceiver'; + const payload = ethers.toUtf8Bytes('hello from source chain'); + + const tx = await messenger.sendMessage(dstChainId, dstReceiver, payload, { + value: ethers.parseEther('0.01') // if protocol fees are required + }); + + console.log('sent:', tx.hash); + await tx.wait(); + console.log('confirmed'); +} + +sendCrossChainMessage().catch(console.error); +``` + +## Key Considerations (Security & UX) + +- **Trust assumptions:** The verification model (light client vs multisig vs optimistic) determines your risk profile. +- **Finality and confirmations:** Even with fast finality on Sei, other chains and bridges may require additional confirmations. +- **Replay protection:** Messages should include nonces/unique identifiers to prevent duplicates. +- **Failure handling:** Design for partial failures (message delivered but execution reverts, delayed relays, or chain congestion). +- **Monitoring:** Index events and track message lifecycle (sent → verified → executed) for support and reliability. + +## Summary + +Interoperability is what allows blockchains and applications to exchange assets and messages across different networks—unlocking cross-chain liquidity, composability, and better user experiences. On Sei Network, interoperability benefits from **EVM compatibility**, **parallelization**, and **~400ms finality**, enabling fast, scalable execution for cross-chain apps and workflows. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-nft-and-how-does-it-work.mdx b/content/answers/what-is-an-nft-and-how-does-it-work.mdx new file mode 100644 index 00000000..43f1f06c --- /dev/null +++ b/content/answers/what-is-an-nft-and-how-does-it-work.mdx @@ -0,0 +1,146 @@ +--- +title: 'What is an NFT and How Does It Work?' +description: 'Learn about what is NFT and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'NFT', 'nft', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an NFT and How Does It Work? + +## Overview + +An NFT (non-fungible token) is a unique blockchain-based token that represents ownership or proof of authenticity for a specific item—such as digital art, game items, collectibles, tickets, or real-world assets. Unlike cryptocurrencies (which are interchangeable), each NFT is distinct and can carry unique metadata, making it suitable for tracking individual assets. + +If you’re searching **what is NFT**, the simplest definition is: an NFT is a token that proves a particular wallet controls a specific, unique digital asset (or a claim to one). + +## How It Works + +### Non-fungible vs. fungible + +- **Fungible tokens** (e.g., ETH, USDC) are interchangeable: 1 token equals any other token of the same type. +- **Non-fungible tokens** are not interchangeable: each token has a unique identifier and may have different attributes, history, and value. + +### Core components of NFTs + +1. **Smart contract** + NFTs are created and managed by smart contracts. The contract defines: + + - How new NFTs are minted + - Ownership rules and transfers + - Metadata references (often a URI) + - Optional royalties or custom logic + +2. **Token ID + Contract Address** + On EVM chains, an NFT is commonly identified by: + + - The NFT contract address + - A `tokenId` (unique within the contract) + +3. **Ownership tracking** + Ownership is recorded on-chain. When an NFT is transferred, the blockchain updates which address owns that `tokenId`. + +4. **Metadata and media storage** + Most NFTs don’t store large files directly on-chain. Instead, the NFT points to metadata (usually JSON), which points to the media (image/video/etc.): + - **On-chain metadata**: stored directly in the contract (more permanent, more expensive) + - **Off-chain metadata**: stored on centralized servers or decentralized storage (IPFS/Arweave) + +A typical metadata JSON includes: + +- `name`, `description` +- `image` URL (or IPFS URI) +- `attributes` (traits) + +### Common NFT standards (EVM) + +- **ERC-721**: one-of-one NFTs (each token ID is unique) +- **ERC-1155**: semi-fungible / batch-minting standard (useful for game items and editions) + +### Minting and transferring (high-level flow) + +1. **Mint**: a transaction calls the NFT contract to create a new token ID and assign it to a wallet address. +2. **List/Sell**: marketplaces use approvals to let a marketplace contract transfer NFTs on your behalf if sold. +3. **Transfer**: a transaction moves ownership from one address to another. +4. **Provenance**: transaction history provides an auditable trail of transfers and creation events. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, meaning NFTs can be built and interacted with using familiar Ethereum tools and standards like **ERC-721** and **ERC-1155**. This lets developers and users mint, transfer, and trade NFTs with the same contract patterns and wallet workflows used across the EVM ecosystem. + +Key implications for NFTs on Sei: + +- **Fast user experience**: Sei’s ~**400ms finality** helps NFT mints, transfers, and marketplace actions confirm quickly, improving UX during drops and high-demand events. +- **Scalability via parallelization**: Sei’s parallelization helps process many transactions efficiently, which is especially helpful for large NFT mints, active marketplaces, and games where lots of NFT actions happen concurrently. +- **EVM tooling support**: You can use Solidity, popular libraries (e.g., OpenZeppelin), and common developer tooling to deploy NFT contracts on Sei’s EVM. + +## Example: Minimal ERC-721 NFT Contract (Solidity) + +Below is a simple ERC-721 contract using OpenZeppelin. This is a common starting point for NFTs on EVM-compatible networks like Sei. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; + +contract MyNFT is ERC721, Ownable { + uint256 public nextTokenId; + + constructor() ERC721("MyNFT", "MNFT") Ownable(msg.sender) {} + + function mint(address to) external onlyOwner returns (uint256 tokenId) { + tokenId = nextTokenId++; + _safeMint(to, tokenId); + } +} +``` + +### Adding metadata (tokenURI) + +In many NFT projects, `tokenURI(tokenId)` returns a URL/IPFS URI for metadata. You can implement this by extending `ERC721URIStorage` or by building URIs yourself (for example, `ipfs://.../{tokenId}.json`). + +## Example: Read NFT Owner with TypeScript (ethers) + +This shows how a dApp can query NFT ownership from an ERC-721 contract. + +```typescript +import { ethers } from 'ethers'; + +const rpcUrl = process.env.RPC_URL!; +const provider = new ethers.JsonRpcProvider(rpcUrl); + +const nftAddress = '0xYourNftContractAddress'; +const abi = ['function ownerOf(uint256 tokenId) view returns (address)']; + +async function main() { + const nft = new ethers.Contract(nftAddress, abi, provider); + const tokenId = 1; + + const owner = await nft.ownerOf(tokenId); + console.log(`Owner of token ${tokenId}:`, owner); +} + +main().catch(console.error); +``` + +## Practical Notes and Common Misconceptions + +- **NFT ownership vs. file ownership**: owning an NFT usually means owning the token and its on-chain record, not necessarily copyright to the artwork unless explicitly granted. +- **Metadata permanence matters**: “decentralized” storage (IPFS/Arweave) can improve durability compared to a traditional web server. +- **Royalties aren’t guaranteed by default**: royalty enforcement often depends on marketplaces unless the NFT ecosystem uses enforceable mechanisms. + +## Summary + +An NFT is a unique token on a blockchain that proves ownership and enables transfer of a distinct asset via smart contracts. In general, NFTs work by combining on-chain ownership records with metadata that describes the asset. On **Sei Network**, NFTs benefit from **EVM compatibility**, **parallelization**, and ~**400ms finality**, enabling fast, scalable minting and trading experiences. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-an-oracles-and-how-does-it-work.mdx b/content/answers/what-is-an-oracles-and-how-does-it-work.mdx new file mode 100644 index 00000000..259b1497 --- /dev/null +++ b/content/answers/what-is-an-oracles-and-how-does-it-work.mdx @@ -0,0 +1,157 @@ +--- +title: 'What is an Oracles and How Does It Work?' +description: 'Learn about what is oracles and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'oracles', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is an Oracles and How Does It Work? + +## Overview + +Oracles are services that deliver external (off-chain) data and computation results to blockchain smart contracts. In other words, they bridge the gap between deterministic on-chain code and real-world information like asset prices, weather, sports results, randomness, or cross-chain events. If you’re searching **what is oracles**, the core idea is: smart contracts can’t directly “fetch” internet data, so they rely on oracles to bring that data on-chain in a verifiable way. + +## How It Works + +### Why smart contracts need oracles + +Smart contracts must be deterministic—every node re-executes the same transaction and must arrive at the same result. If a contract could call an external API directly (e.g., a price feed endpoint), different nodes might see different responses, breaking consensus. Oracles solve this by **publishing data on-chain** in a way contracts can read deterministically. + +### Common oracle models + +- **Push-based (data feed) oracles:** The oracle posts updated values (e.g., ETH/USD) to an on-chain contract at a set cadence or when thresholds are met. Contracts read the latest stored value. +- **Pull/request-response oracles:** A contract requests data; an oracle network fulfills it by delivering a response transaction back to the chain. +- **Cross-chain oracles / relayers:** Bring information about events on another chain (e.g., “this transaction finalized on chain X”) to the destination chain. +- **Randomness oracles (VRF):** Provide verifiable randomness with cryptographic proofs, commonly used in gaming and NFT mints. + +### Trust, security, and verification + +Oracles introduce an additional trust layer (“oracle risk”). Systems mitigate this via: + +- **Decentralization:** Multiple independent oracle nodes provide data. +- **Aggregation:** Median/weighted averages reduce single-source manipulation. +- **Cryptographic proofs:** Signatures, threshold signatures, VRF proofs, attestations. +- **Economic incentives:** Staking, slashing, reputation systems. +- **Data freshness & validation:** Heartbeats, deviation thresholds, circuit breakers. + +### Typical on-chain pattern + +Most applications consume oracle data by reading from a known on-chain contract: + +```solidity +// Example interface for a price feed oracle contract. +// The exact interface depends on the oracle provider you use. +interface IPriceFeed { + function latestAnswer() external view returns (int256); + function latestTimestamp() external view returns (uint256); +} + +contract UsesOraclePrice { + IPriceFeed public immutable feed; + + constructor(address feedAddress) { + feed = IPriceFeed(feedAddress); + } + + function getPrice() external view returns (int256 price, uint256 updatedAt) { + price = feed.latestAnswer(); + updatedAt = feed.latestTimestamp(); + } +} +``` + +Applications often add safeguards—e.g., reject stale data: + +```solidity +function getSafePrice(uint256 maxAgeSeconds) external view returns (int256) { + int256 price = feed.latestAnswer(); + uint256 updatedAt = feed.latestTimestamp(); + require(block.timestamp - updatedAt <= maxAgeSeconds, "ORACLE_STALE"); + require(price > 0, "ORACLE_INVALID"); + return price; +} +``` + +## On Sei Network + +Sei Network is a high-performance Layer 1 with EVM compatibility designed for low-latency, high-throughput applications. Oracles on Sei work the same conceptually as on other chains—**oracle providers publish data on-chain, and Sei smart contracts read it**—but Sei’s performance characteristics can improve how oracle-driven apps behave in production. + +### Why oracles matter on Sei + +- **DeFi & derivatives:** Lending, perps, options, and stablecoins depend on high-quality price feeds. +- **Real-time apps:** Prediction markets, gaming, and marketplaces can use data feeds and VRF-style randomness. +- **Cross-chain experiences:** Bridging and interop systems often rely on oracle/relayer components for event attestations. + +### Performance considerations (what changes on Sei) + +- **Fast finality (~400ms):** Oracle updates can reach finality quickly, reducing latency between off-chain events and on-chain usability—critical for trading and liquidation logic. +- **Parallelization:** Sei’s parallel execution design can help high-volume oracle update transactions and downstream reads coexist more efficiently, especially during periods of high network activity. +- **EVM compatibility:** Many oracle integration patterns and Solidity contracts are portable to Sei’s EVM environment, so teams can reuse familiar tooling and contract designs. + +### Example: consuming an oracle price on Sei (EVM) + +Deploy or connect to an oracle feed contract address on Sei, then read it from your Solidity app: + +```solidity +pragma solidity ^0.8.20; + +interface ISeiPriceFeed { + function latestAnswer() external view returns (int256); + function latestTimestamp() external view returns (uint256); +} + +contract SeiLendingRiskChecks { + ISeiPriceFeed public immutable seiFeed; + + constructor(address feed) { + seiFeed = ISeiPriceFeed(feed); + } + + function isHealthy(uint256 collateralValue, uint256 debtValue) external view returns (bool) { + // Example oracle usage: ensure price is fresh enough for risk checks + uint256 updatedAt = seiFeed.latestTimestamp(); + require(block.timestamp - updatedAt <= 30, "PRICE_TOO_OLD"); + + // Your protocol math would incorporate oracle price(s) here. + return collateralValue * 100 >= debtValue * 150; // e.g., 150% collateralization + } +} +``` + +### Reading oracle data from an app (TypeScript) + +With EVM-compatible RPC endpoints, you can read from oracle contracts using `ethers`: + +```typescript +import { ethers } from 'ethers'; + +const rpcUrl = process.env.SEI_EVM_RPC!; +const provider = new ethers.JsonRpcProvider(rpcUrl); + +// Minimal ABI for a typical price feed interface +const abi = ['function latestAnswer() view returns (int256)', 'function latestTimestamp() view returns (uint256)']; + +async function readOracle(feedAddress: string) { + const feed = new ethers.Contract(feedAddress, abi, provider); + const [price, ts] = await Promise.all([feed.latestAnswer(), feed.latestTimestamp()]); + return { price: price.toString(), updatedAt: Number(ts) }; +} +``` + +## Key Takeaways + +- If you’re asking **what is oracles**, it means: a bridge that brings off-chain data and results onto the blockchain so smart contracts can act on real-world events. +- Oracles work by publishing verified data on-chain (push) or responding to on-chain requests (pull), often using decentralization and cryptographic proofs to reduce trust risk. +- On Sei Network, oracles integrate through familiar EVM patterns while benefiting from Sei’s **parallelization** and **~400ms finality**, enabling faster, more responsive oracle-driven applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-blockchain-and-how-does-it-work.mdx b/content/answers/what-is-blockchain-and-how-does-it-work.mdx new file mode 100644 index 00000000..6c0c2d88 --- /dev/null +++ b/content/answers/what-is-blockchain-and-how-does-it-work.mdx @@ -0,0 +1,118 @@ +--- +title: 'What is Blockchain and How Does It Work?' +description: 'Learn about what is blockchain and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'blockchain', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Blockchain and How Does It Work? + +## Overview + +Blockchain is a shared, tamper-resistant digital ledger that records transactions and data across a network of computers rather than a single centralized database. Instead of trusting one administrator, participants rely on cryptography and a consensus mechanism to agree on the ledger’s state. In short, **what is blockchain**: a way to coordinate and verify data among many parties with strong integrity guarantees. + +## How It Works + +### Blocks, Transactions, and Hashes + +A blockchain groups data (most commonly transactions) into **blocks**. Each block typically contains: + +- A list of transactions (or state changes) +- A timestamp and metadata +- A **cryptographic hash** of its contents +- The **previous block’s hash**, linking blocks together + +Because each block references the prior block, altering historical data changes the hash and breaks the chain, making tampering obvious and extremely difficult. + +### Distributed Network (Nodes) + +A blockchain runs on a peer-to-peer network of **nodes** that: + +- Receive and broadcast transactions +- Validate rules (e.g., signatures, balances, smart contract logic) +- Store and synchronize the ledger + +Some nodes also produce blocks (often called validators/miners, depending on the chain). + +### Consensus: Agreeing on One History + +Since many nodes may see transactions in different orders, blockchains use **consensus algorithms** to agree on a single canonical chain. Common approaches include: + +- **Proof of Work (PoW):** miners solve computational puzzles (e.g., Bitcoin) +- **Proof of Stake (PoS):** validators stake tokens and are selected to propose/attest blocks + +Consensus prevents double-spending and ensures the network converges on one shared ledger state. + +### Cryptographic Signatures and Ownership + +Users control accounts with private keys. Transactions are authorized via **digital signatures**, which nodes verify using the corresponding public key. This enables permissionless participation without a central identity provider. + +### Smart Contracts and State + +Many modern blockchains (e.g., Ethereum-compatible chains) support **smart contracts**—programs stored on-chain that execute deterministically. The blockchain maintains a global **state** (balances, contract storage, etc.), updated by each block. + +## On Sei Network + +Sei is a high-performance Layer 1 blockchain designed for fast finality and scalable execution while supporting **EVM compatibility**, making it straightforward to deploy Ethereum-style smart contracts. Key characteristics include: + +- **Parallelization:** Sei is built to execute workloads efficiently by leveraging parallel processing where possible, improving throughput under real-world demand. +- **~400ms finality:** Transactions can reach finality in roughly hundreds of milliseconds, enabling low-latency applications such as trading, gaming, and real-time payments. +- **EVM compatibility:** Developers can use familiar Ethereum tooling (Solidity, Hardhat/Foundry, ethers.js/web3.js) to build and deploy contracts to Sei’s EVM environment. + +Practically, this means the core idea of **what is blockchain**—a shared ledger maintained by consensus—applies on Sei as well, but with an emphasis on speed, parallel execution, and compatibility with the Ethereum developer ecosystem. + +## Example: A Simple Smart Contract (EVM) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public value; + + function increment() external { + value += 1; + } +} +``` + +## Example: Deploying with Hardhat (Conceptual) + +```bash +# install dependencies +npm i --save-dev hardhat @nomicfoundation/hardhat-toolbox + +# compile +npx hardhat compile + +# deploy (requires setting a Sei EVM RPC URL and funded deployer key) +npx hardhat run scripts/deploy.ts --network sei +``` + +## Why Blockchain Matters + +- **Integrity:** Data is hard to alter retroactively due to hashing + consensus. +- **Transparency and auditability:** Ledgers can be publicly verifiable (depending on the chain). +- **Reduced reliance on intermediaries:** Rules can be enforced by code (smart contracts). +- **Programmable value:** Smart contracts enable DeFi, NFTs, on-chain games, and more. + +## Key Terms (Glossary) + +- **Block:** A batch of transactions/state changes added to the chain. +- **Hash:** A cryptographic fingerprint of data; small changes produce a completely different output. +- **Node:** A computer participating in the network by relaying/verifying data. +- **Validator:** A node that helps produce/confirm blocks under the consensus rules. +- **Finality:** The point at which a transaction is considered irreversible (Sei targets ~400ms finality). +- **Smart contract:** On-chain program that executes deterministically and updates state. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-defi-and-how-does-it-work.mdx b/content/answers/what-is-defi-and-how-does-it-work.mdx new file mode 100644 index 00000000..94a26ae8 --- /dev/null +++ b/content/answers/what-is-defi-and-how-does-it-work.mdx @@ -0,0 +1,134 @@ +--- +title: 'What is DeFi and How Does It Work?' +description: 'Learn about what is DeFi and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'DeFi', 'defi', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is DeFi and How Does It Work? + +## Overview + +DeFi (Decentralized Finance) is a category of financial applications built on public blockchains that lets users borrow, lend, trade, earn yield, and manage assets without relying on traditional intermediaries like banks or brokers. In DeFi, software (smart contracts) enforces rules transparently, and users keep control of their funds through their own wallets. + +In other words, **what is DeFi**? It’s an open, programmable financial system where anyone with an internet connection can interact with financial services directly on-chain. + +## How It Works + +### Core building blocks + +- **Wallets & self-custody:** Users connect a wallet (e.g., MetaMask) to DeFi apps and sign transactions. Funds are typically controlled by the user’s private keys, not by an institution. +- **Smart contracts:** On-chain programs that hold assets, apply rules (interest rates, collateral requirements, swap pricing), and execute transactions deterministically. +- **Tokens:** Assets represented on-chain (e.g., stablecoins, governance tokens, LP tokens). Tokens can represent currencies, claims on pooled liquidity, voting power, or receipts for deposits. +- **Liquidity pools & AMMs (Automated Market Makers):** Instead of matching buyers and sellers in an order book, many DEXs use pools of tokens and a pricing formula to enable swaps. +- **Oracles:** Services that deliver off-chain data (like asset prices) to smart contracts, enabling lending, derivatives, and other price-dependent logic. +- **Collateral & overcollateralization:** Many DeFi lending markets require borrowers to post collateral worth more than the loan to reduce default risk. +- **Composability (“money legos”):** DeFi protocols can integrate with each other—one protocol’s token can be used as collateral in another, enabling complex strategies. + +### Typical DeFi flows + +#### 1) Swapping assets (DEX) + +1. User connects a wallet to a DEX. +2. User approves the DEX contract to spend a token (ERC-20 approval model). +3. User submits a swap transaction. +4. The smart contract transfers tokens, calculates output based on pool state, and returns the swapped asset to the user. + +#### 2) Lending and borrowing + +1. Lenders deposit assets into a lending pool and receive interest-bearing receipts. +2. Borrowers deposit collateral and borrow another asset. +3. The protocol tracks collateralization ratios; positions may be liquidated if undercollateralized. +4. Interest accrues automatically based on utilization and risk parameters. + +#### 3) Yield and liquidity providing + +1. Liquidity providers deposit a pair of tokens into a pool. +2. They receive LP tokens representing their share. +3. Fees (and sometimes incentives) accrue to LPs, but LPs can face **impermanent loss** if relative prices move. + +### Security and risks to understand + +- **Smart contract risk:** Bugs or exploits can cause loss of funds. +- **Oracle risk:** Bad price feeds can trigger incorrect liquidations or mispricing. +- **Liquidity and market risk:** Slippage, impermanent loss, and volatility can affect outcomes. +- **Governance risk:** Parameter changes (fees, collateral factors) can materially impact users. + +## On Sei Network + +Sei is a high-performance Layer 1 designed to support high-throughput, low-latency DeFi. DeFi on Sei works the same conceptually—wallets sign transactions, smart contracts run on-chain, and users interact with DEXs, lending protocols, and other apps—but it benefits from Sei’s performance characteristics: + +- **Parallelization:** Sei is built to execute many transactions concurrently when possible, improving throughput for DeFi activity like swaps, liquidations, and arbitrage. +- **~400ms finality:** Fast finality helps DeFi apps feel more responsive and can reduce uncertainty during time-sensitive actions (e.g., trading, rebalancing, liquidation events). +- **EVM compatibility:** Solidity-based smart contracts and EVM tooling can be used to build and deploy DeFi applications on Sei, making it easier to port existing Ethereum-compatible designs or launch new ones with familiar developer workflows. + +### Example: Connecting to Sei and reading chain info (TypeScript) + +```typescript +import { ethers } from 'ethers'; + +// Use Sei's EVM-compatible RPC endpoint (replace with an official/your chosen RPC). +const rpcUrl = 'https://YOUR_SEI_EVM_RPC'; +const provider = new ethers.JsonRpcProvider(rpcUrl); + +async function main() { + const [blockNumber, network] = await Promise.all([provider.getBlockNumber(), provider.getNetwork()]); + + console.log('Chain ID:', network.chainId.toString()); + console.log('Latest block:', blockNumber); +} + +main().catch(console.error); +``` + +### Example: Basic ERC-20 approval pattern (Solidity) + +Many DeFi interactions require approving a protocol to spend your tokens before calling the protocol’s main function (swap, deposit, etc.). + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function approve(address spender, uint256 amount) external returns (bool); +} + +contract ApproveExample { + function approveToken( + address token, + address spender, + uint256 amount + ) external { + // In practice, approval is usually done directly by the user wallet, + // but this illustrates the common DeFi pattern. + IERC20(token).approve(spender, amount); + } +} +``` + +## Why DeFi Matters + +DeFi expands access to financial services by making them: + +- **Open:** Anyone can participate without permission (subject to the app’s own rules and local laws). +- **Transparent:** On-chain transactions and many protocol parameters are publicly verifiable. +- **Programmable:** Developers can build new financial products by composing existing primitives. +- **Interoperable:** Standards like ERC-20 and EVM tooling make integrations easier across apps—especially on EVM-compatible chains like Sei. + +## Key Takeaways + +- **What is DeFi?** A decentralized, smart contract–based financial ecosystem on blockchains. +- DeFi operates through wallets, tokens, smart contracts, liquidity pools, lending markets, and oracles. +- On **Sei Network**, DeFi can take advantage of **parallel execution**, **~400ms finality**, and **EVM compatibility** to support fast, scalable on-chain finance. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..68e6424c --- /dev/null +++ b/content/answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,156 @@ +--- +title: 'What is Delegated Staking in Crypto and How Does It Work?' +description: 'Learn about what is delegated staking and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'delegated', 'staking', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Delegated Staking in Crypto and How Does It Work? + +## Overview + +Delegated staking is a staking method where token holders (“delegators”) assign their staking power to a validator who participates in consensus and earns staking rewards on their behalf. It lets users earn staking yield without running validator infrastructure, while still supporting network security. + +In most delegated staking systems, delegators keep ownership of their tokens but lock (bond) them to a validator and share rewards—minus a validator commission fee. + +## How It Works + +### 1) Proof-of-Stake basics + +In Proof-of-Stake (PoS) networks, validators are selected to propose/verify blocks based on the amount of stake backing them. More stake generally increases a validator’s likelihood of being chosen and earning rewards. + +### 2) Delegation: assigning stake to a validator + +When you delegate, you choose a validator and bond your tokens to them. This stake: + +- Increases the validator’s total voting power +- Helps the network resist attacks (since more value is economically at risk) +- Entitles you to a portion of the validator’s earned rewards + +Delegation does **not** usually transfer custody to the validator; it records an on-chain relationship between your account and the validator. + +### 3) Rewards and commission + +Validators earn rewards from mechanisms such as: + +- Block rewards / inflationary issuance +- Transaction fees (depending on the chain) +- MEV/other protocol-specific revenue (chain dependent) + +Validators typically take a **commission rate** (e.g., 5%–10%) from the rewards attributable to their delegators. The remaining rewards are distributed proportionally to delegators based on their share of the validator’s total delegated stake. + +### 4) Unbonding (undelegation) and liquidity trade-offs + +Most delegated staking requires a **bonding period** (tokens are locked) and an **unbonding period** (a delay before tokens become transferable after you undelegate). These constraints: + +- Reduce “stake flight” that could destabilize consensus +- Improve security by making it costly to rapidly move stake in reaction to short-term events + +Some ecosystems also support liquid staking derivatives (LSDs) that provide liquidity while remaining staked, but that is separate from basic delegated staking. + +### 5) Slashing: the primary risk + +If a validator misbehaves (e.g., double-signing) or is consistently offline, PoS chains may apply **slashing**—a penalty that reduces the validator’s stake and can also affect delegators bonded to that validator. + +Common validator risks delegators should evaluate: + +- Uptime/reliability (missed blocks can reduce rewards or trigger penalties) +- Security practices (key management, infra hardening) +- Commission rate and history of changes +- Governance participation and community reputation + +## On Sei Network + +Sei Network is a high-performance Layer 1 designed for fast trading and consumer apps, featuring **~400ms finality** and **parallelized** transaction execution. Delegated staking on Sei follows the standard PoS delegation model (delegators bond SEI to validators), but benefits from Sei’s performance characteristics: + +- **Fast user experience:** Sei’s ~400ms finality makes staking-related actions (delegations, redelegations, claims—subject to protocol rules) feel responsive. +- **High throughput via parallelization:** Sei’s parallelization helps the network handle high activity while maintaining predictable performance, which is important for maintaining validator uptime and consistent block production. +- **EVM compatibility:** Sei’s EVM support enables Solidity-based applications to integrate staking-aware experiences (e.g., dashboards, portfolio trackers, governance tooling), while the underlying staking/security model continues to be enforced at the chain level. + +### Typical staking flow on Sei + +1. Pick a validator (review uptime, commission, and track record). +2. Delegate SEI to that validator (bonding your stake). +3. Earn rewards over time; optionally claim/compound. +4. Undelegate when needed (subject to the network’s unbonding rules). + +## Example: Delegate staking on Sei (CLI) + +Below is a representative Cosmos SDK-style CLI flow (exact flags/denoms may differ by network and version). Replace placeholders with your values. + +```bash +# 1) Check available validators +seid query staking validators --limit 50 + +# 2) Delegate 100 SEI (example denom: use the chain's base denom in practice) +# Replace: +# - with a valoper address +# - with the correct base denom amount +# - with your local key name +seid tx staking delegate 100000000usei \ + --from \ + --gas auto \ + --gas-adjustment 1.3 \ + --fees 2000usei \ + -y + +# 3) Check your delegations +seid query staking delegations + +# 4) Withdraw staking rewards from a validator +seid tx distribution withdraw-rewards \ + --from \ + --commission false \ + --gas auto \ + --gas-adjustment 1.3 \ + --fees 2000usei \ + -y + +# 5) Undelegate (unbond) when you want to exit +seid tx staking unbond 100000000usei \ + --from \ + --gas auto \ + --gas-adjustment 1.3 \ + --fees 2000usei \ + -y +``` + +## Key Benefits and Risks + +### Benefits + +- **Accessibility:** Earn staking rewards without operating a validator. +- **Network security:** Your stake helps secure the chain and supports decentralization. +- **Flexibility:** You can switch validators (redelegate) on many PoS networks, subject to rules. + +### Risks + +- **Slashing:** Validator downtime or malicious behavior can reduce stake. +- **Lockups:** Bonding/unbonding periods limit liquidity. +- **Validator centralization:** Delegating to a small set of large validators can reduce network resilience. + +## FAQ (Glossary-Style) + +**What is delegated staking?** +Delegated staking is when token holders delegate their stake to validators who secure the network and share rewards with delegators after taking a commission. + +**Do I lose custody of my tokens when delegating?** +Typically no—delegation records an on-chain bonding relationship. Your tokens are locked for staking but remain associated with your address. + +**How do I choose a validator?** +Look at uptime, slashing history, commission rate (and whether it changes often), operational transparency, and community reputation. + +**Is delegated staking available on Sei?** +Yes. Delegators can stake SEI by delegating to validators, benefiting from Sei’s high performance, parallelization, and ~400ms finality for a smooth staking experience. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..2494ec07 --- /dev/null +++ b/content/answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,171 @@ +--- +title: 'What is Front-running in Crypto and How Does It Work?' +description: 'Learn about what is front-running and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'front-running', 'front', 'running', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Front-running in Crypto and How Does It Work? + +## Overview + +Front-running in crypto is a type of transaction-order manipulation where someone uses knowledge of a pending transaction to submit their own transaction first, profiting from the price impact the original transaction will cause. In practice, it exploits how public mempools and transaction priority (typically via fees) allow certain actors to “cut in line.” + +In other words, **what is front-running**? It’s placing trades or transactions ahead of others by observing them before they are finalized on-chain. + +## How It Works + +### 1) The mempool makes pending actions visible + +Most blockchains broadcast unconfirmed transactions to a public “mempool.” Searchers (often bots) monitor the mempool for transactions that will move prices—especially swaps on AMMs and large trades on DEXs. + +### 2) Priority mechanisms let attackers go first + +If the network selects transactions based on fee bidding (or validators can choose ordering), a searcher can submit a competing transaction with a higher effective fee so it is included earlier in the block. + +### 3) Common front-running patterns + +#### **Classic front-run (buy before a buy / sell before a sell)** + +- Victim submits a large swap, e.g., `USDC -> TOKEN`. +- Attacker sees it pending and submits the same swap with higher fees. +- Attacker gets the better price before the victim’s trade pushes the price up. +- The victim executes at a worse price (more slippage). + +#### **Sandwich attack (front-run + back-run)** + +A sandwich is a coordinated two-transaction strategy: + +1. **Front-run**: attacker buys the token right before the victim’s swap. +2. Victim’s swap executes and moves price upward. +3. **Back-run**: attacker sells right after, capturing profit from the price movement. + +This is especially common on AMMs where trade execution deterministically changes pool reserves. + +#### **Liquidation / arbitrage priority** + +Attackers may front-run: + +- liquidations in lending protocols, +- arbitrage opportunities between pools, +- NFT mints with limited supply, +- governance actions with market impact. + +### 4) Why it’s profitable + +Front-running extracts value by: + +- capturing price improvement that would have gone to the victim, +- forcing the victim into worse execution (slippage), +- exploiting deterministic pricing and public visibility. + +### 5) Key terms related to front-running + +- **MEV (Maximal/Minor Extractable Value):** Profits made from transaction ordering and inclusion. +- **Searcher:** A bot/operator looking for MEV opportunities. +- **Private orderflow / private mempool:** Transaction submission paths intended to reduce public exposure before inclusion. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **parallelized execution**, **EVM compatibility**, and **~400ms finality**, which changes the practical dynamics of front-running compared to slower chains. + +### Faster finality reduces the attack window + +On many networks, pending transactions can sit in the mempool for seconds or minutes, giving bots ample time to react. With Sei’s **fast block times and ~400ms finality**, the time between broadcast and finalization is typically shorter—reducing (but not eliminating) the window in which adversaries can observe and compete for priority. + +### Parallelization can increase throughput and reduce congestion-driven MEV + +Sei’s parallelization improves throughput and reduces contention for blockspace in many scenarios. Lower congestion often means fewer extreme fee auctions and less opportunity for opportunistic “fee-bump” races—one of the common enablers of front-running in fee-market systems. + +### EVM compatibility means Ethereum-style MEV patterns can exist + +Because Sei supports EVM execution, familiar patterns like AMM sandwiching and swap front-running can still occur in EVM-based dApps. The best mitigations—slippage controls, private routing, and MEV-aware design—remain relevant for Sei-based applications. + +## Example: How a Sandwich Works (EVM/AMM) + +Below is a simplified illustration of the **sequence** (not a complete exploit) showing how two attacker swaps can wrap a victim swap. + +```solidity +// PSEUDOCODE: simplified illustration of a sandwich sequence on an AMM. +// Not production code. Real implementations depend on the DEX router and token approvals. + +interface IRouter { + function swapExactTokensForTokens( + uint amountIn, + uint amountOutMin, + address[] calldata path, + address to, + uint deadline + ) external returns (uint[] memory amounts); +} + +contract SandwichIllustration { + IRouter public router; + + constructor(address _router) { + router = IRouter(_router); + } + + function frontRunBuy( + uint amountIn, + uint amountOutMin, + address[] calldata path + ) external { + // Attacker buys the target token first + router.swapExactTokensForTokens( + amountIn, + amountOutMin, + path, + msg.sender, + block.timestamp + ); + } + + function backRunSell( + uint amountIn, + uint amountOutMin, + address[] calldata path + ) external { + // After victim trade moves price, attacker sells back + router.swapExactTokensForTokens( + amountIn, + amountOutMin, + path, + msg.sender, + block.timestamp + ); + } +} +``` + +## How to Reduce Front-running Risk + +### For users + +- **Set conservative slippage** (lower tolerance reduces sandwich profitability). +- **Use limit orders** where available (more deterministic execution). +- **Use private transaction routing** (when supported by your wallet/dApp). +- **Avoid trading during high volatility** when mempool monitoring is most profitable. + +### For dApp builders (including on Sei EVM) + +- Prefer **RFQ / intent-based trading** or **batch auctions** for price discovery. +- Implement **MEV-aware router logic** and consider **anti-sandwich protections**. +- Consider **commit-reveal** or **delayed reveal** designs for sensitive actions (mints, bids). +- Add guardrails: minimum received checks, TWAP/oracle validations, and rate limits where appropriate. + +## Summary + +Front-running is the practice of exploiting visibility into pending blockchain transactions to execute a profit-making transaction first, often by paying higher fees or leveraging transaction ordering. It commonly appears as swap front-running and sandwich attacks on DEXs. On Sei Network, **fast (~400ms) finality** and **parallelized execution** can reduce the time and congestion conditions that enable some front-running strategies, while **EVM compatibility** means familiar MEV patterns—and mitigations—still apply. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..d919f857 --- /dev/null +++ b/content/answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,135 @@ +--- +title: 'What is Liquid Staking in Crypto and How Does It Work?' +description: 'Learn about what is liquid staking and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'liquid', 'staking', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Liquid Staking in Crypto and How Does It Work? + +## Overview + +Liquid staking is a way to stake your crypto to help secure a blockchain and earn staking rewards while still keeping your stake _usable_ in DeFi. Instead of locking your tokens and losing liquidity, you receive a liquid staking token (often called an LST) that represents your staked position and can be traded or used as collateral. + +If you’re searching “**what is liquid staking**,” the simplest definition is: it’s staking with a receipt token that preserves liquidity. + +## How It Works + +### 1) Traditional staking vs. liquid staking + +- **Traditional staking:** You delegate or lock tokens with a validator, earn rewards, but your tokens are typically illiquid until you unbond/unstake (often with a waiting period). +- **Liquid staking:** You stake via a liquid staking protocol, and in return you receive an LST (e.g., `stTOKEN`). That LST tracks the value of your staked position and can be used in DeFi while rewards accrue. + +### 2) Minting a liquid staking token (LST) + +A liquid staking protocol generally: + +1. Accepts deposits of the chain’s staking token (e.g., `SEI` on Sei). +2. Delegates those tokens across one or more validators. +3. Mints an LST to you, representing your claim on the underlying staked tokens + accrued rewards (minus protocol fees). + +Depending on the design, the LST value updates in one of two common ways: + +- **Rebasing model:** Your LST balance increases over time as rewards accrue. +- **Exchange-rate model:** Your LST balance stays the same, but the amount of underlying tokens redeemable per LST increases over time (an increasing exchange rate). + +### 3) Using LSTs in DeFi + +Because LSTs are liquid, you can often: + +- Swap them on DEXs +- Provide liquidity in AMMs +- Use them as collateral for borrowing/lending +- Build leveraged staking strategies (higher risk) + +### 4) Redeeming (unstaking) from liquid staking + +To exit, you typically: + +- **Redeem via protocol:** Burn your LST to claim underlying tokens. This may require an **unbonding period** (chain-dependent). +- **Sell on secondary markets:** Swap the LST for the base asset immediately (subject to liquidity and potential discount/premium). + +### 5) Benefits and risks + +**Benefits** + +- Earn staking rewards **and** keep liquidity +- Improved capital efficiency for DeFi users +- Potentially diversified validator delegation managed by the protocol + +**Risks** + +- **Smart contract risk:** The liquid staking protocol may have bugs or vulnerabilities. +- **Slashing risk:** If validators misbehave, staked funds can be penalized (slashed), affecting LST value. +- **Liquidity/peg risk:** LSTs can trade at a discount/premium depending on market conditions. +- **Centralization risk:** If too much stake concentrates in a single protocol or validator set. + +## On Sei Network + +Sei is a high-performance Layer 1 with **~400ms finality**, built for throughput and optimized execution. Liquid staking on Sei follows the same core model—stake `SEI`, receive an LST—but benefits from Sei’s fast confirmations and modern execution environment. + +### Why liquid staking fits Sei + +- **Fast finality (~400ms):** Staking-related transactions (minting LSTs, swaps, DeFi actions) can confirm quickly, improving the usability of LSTs in active trading and DeFi strategies. +- **Parallelization:** Sei’s parallelized execution helps DeFi apps (DEXs, money markets) handle higher throughput, which can make LST markets and integrations smoother under load. +- **EVM compatibility:** Because Sei supports EVM, liquid staking protocols and DeFi integrations can be built using familiar Solidity tooling and standards, enabling easier adoption of LSTs across EVM-style applications. + +### Typical Sei liquid staking flow + +1. Deposit `SEI` into a liquid staking protocol. +2. Protocol delegates to validators to earn staking rewards and secure the network. +3. You receive an LST (ERC-20-style on Sei EVM) representing your staked `SEI`. +4. Use the LST across Sei’s DeFi ecosystem (swap, lend, provide liquidity). +5. Redeem the LST back to `SEI` (subject to protocol rules and any unbonding constraints), or swap it on a DEX. + +## Example: Interacting with an LST (EVM-style) + +Below is a minimal Solidity example showing how a DeFi contract might accept an LST as collateral (ERC-20 interface). The exact token address and integrations depend on the liquid staking provider on Sei. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function balanceOf(address account) external view returns (uint256); +} + +contract LstVault { + IERC20 public immutable lst; // e.g., stSEI-like token + + mapping(address => uint256) public deposited; + + constructor(address _lst) { + lst = IERC20(_lst); + } + + function deposit(uint256 amount) external { + require(amount > 0, "amount=0"); + require(lst.transferFrom(msg.sender, address(this), amount), "transfer failed"); + deposited[msg.sender] += amount; + } + + function vaultBalance() external view returns (uint256) { + return lst.balanceOf(address(this)); + } +} +``` + +## Key Takeaways + +- Liquid staking lets you earn staking rewards while keeping liquidity via an LST. +- LSTs can be used throughout DeFi, but carry smart contract, slashing, and liquidity risks. +- On Sei, liquid staking benefits from **fast finality (~400ms)**, **parallelized execution**, and **EVM compatibility**, making it well-suited for high-velocity DeFi use cases. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-mev-and-why-it-matters.mdx b/content/answers/what-is-mev-and-why-it-matters.mdx new file mode 100644 index 00000000..98fd82dd --- /dev/null +++ b/content/answers/what-is-mev-and-why-it-matters.mdx @@ -0,0 +1,139 @@ +--- +title: 'What is MEV and Why It Matters' +description: 'Learn about what is MEV and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'MEV', 'mev', 'and', 'why', 'matters'] +--- + +import { Callout } from 'nextra/components'; + +# What is MEV and Why It Matters + +## Overview + +MEV (Maximal/Maximum Extractable Value) is the additional profit that can be captured by controlling the ordering, inclusion, or exclusion of transactions in a block beyond standard transaction fees. It matters because it affects user execution quality (slippage, failed transactions), market fairness, and network trust—especially on high-activity chains and DeFi-heavy ecosystems. + +In practice, when people ask **“what is MEV”**, they’re usually referring to strategies where validators, block builders, or sophisticated traders exploit transaction ordering to extract value from other users’ transactions. + +## How It Works + +MEV exists because blockchains are not just execution environments—they are _sequencing systems_. Before a block is finalized, someone (a validator, proposer, sequencer, or builder) decides which transactions get in and in what order. If an actor can predict outcomes and influence ordering, they may capture profit. + +### Where MEV comes from + +Most MEV opportunities come from public, transparent mempools and deterministic execution: + +- **Public visibility of pending transactions**: If you can see a large swap about to happen, you can trade before/after it. +- **Ordering control**: If you can place your transaction in a specific position, you can change the price a user gets. +- **Atomicity and composability**: DeFi transactions often include multiple steps that can be profitably rearranged around. + +### Common MEV patterns + +1. **Sandwich attacks** + An attacker places a buy before a victim swap and a sell after it, profiting from the induced price movement while the victim gets worse execution. + +2. **DEX arbitrage** + When prices diverge across AMMs/venues, bots race to arbitrage. This can be benign (improves price alignment) but can congest blocks and raise fees. + +3. **Liquidation MEV** + In lending protocols, liquidations can be profitable. Searchers compete to liquidate accounts, sometimes paying high fees or using private orderflow. + +4. **Backrunning** + Placing a transaction immediately after another to capture an expected state change (e.g., arbitrage after a large trade). + +5. **Time-bandit attacks (reorg MEV)** + In extreme cases, participants may attempt to reorganize recent blocks if the MEV opportunity is worth more than the cost/risk. + +### Why MEV matters + +- **User harm**: worse execution prices, increased slippage, more failed transactions. +- **Higher fees and congestion**: searchers bid up gas to win races. +- **Centralization pressure**: sophisticated infrastructure (private relays/builders) can dominate extraction. +- **Protocol risk**: extreme MEV can incentivize chain instability (e.g., reorg attempts). + +## On Sei Network + +Sei is a high-performance Layer 1 with **~400ms finality**, strong performance characteristics, and **EVM compatibility**, which changes the MEV landscape in important ways. + +### Fast finality reduces some MEV surface area + +With ~400ms finality, the window to observe pending transactions and react is tighter than on slower-finality networks. This can reduce certain “race-based” MEV dynamics (especially those that rely on long propagation delays and multi-block maneuvering), though it does not eliminate MEV entirely—ordering still matters within a block. + +### Parallelization and throughput impact MEV dynamics + +Sei’s execution architecture emphasizes **parallelization** and high throughput. In general, higher throughput can: + +- **Reduce congestion-driven MEV** by making blockspace less scarce during normal conditions. +- **Change competitive dynamics** among searchers because more transactions can be included without as many failures. +- Still leave **ordering-sensitive** opportunities (e.g., swaps on AMMs, liquidations) that depend on state changes rather than pure congestion. + +### EVM compatibility brings familiar MEV vectors—and familiar mitigations + +Because Sei supports EVM, common Ethereum-style DeFi patterns (AMMs, aggregators, lending markets) can exist on Sei, and so can familiar MEV behaviors like sandwiching and arbitrage. This also means common mitigation patterns used by EVM developers are applicable: + +- **Use slippage protections carefully** (too wide increases sandwich risk; too tight causes reverts). +- **Prefer intent-based / RFQ routing** when available to reduce mempool exposure. +- **Batching and commitment schemes** (where appropriate) to reduce predictability. +- **Design liquidation mechanisms** that reduce winner-takes-all races (e.g., auctions, capped incentives). + +## Practical Examples (EVM) + +### Example: Sandwich risk in an AMM swap + +A typical AMM swap call (e.g., UniswapV2-style) is vulnerable if users allow large slippage. Attackers look for swaps with permissive `amountOutMin`. + +```solidity +// Example pattern: user swap with a large slippage tolerance +// (Not a full AMM implementation; illustrates the call shape.) +interface IRouter { + function swapExactTokensForTokens( + uint amountIn, + uint amountOutMin, + address[] calldata path, + address to, + uint deadline + ) external returns (uint[] memory amounts); +} +``` + +**Mitigation idea:** keep `amountOutMin` tight and use robust quoting (TWAP/aggregator quotes), while balancing revert risk in volatile markets. + +### Example: Setting a conservative deadline and slippage + +```solidity +function swapWithProtection( + IRouter router, + uint amountIn, + uint quotedOut, + uint maxSlippageBps, + address[] calldata path +) external { + uint amountOutMin = quotedOut * (10_000 - maxSlippageBps) / 10_000; + + router.swapExactTokensForTokens( + amountIn, + amountOutMin, + path, + msg.sender, + block.timestamp + 60 // short deadline reduces exposure window + ); +} +``` + +This does not “solve” MEV, but it reduces the profit margin attackers can reliably extract. + +## Key Takeaways + +- **What is MEV?** Extra value extracted by controlling or exploiting transaction ordering, inclusion, or exclusion in blocks. +- **Why it matters:** it can harm users (slippage, failed txs), increase fees, and create centralization/security risks. +- **On Sei Network:** Sei’s **~400ms finality**, high throughput, and **parallelization** can reduce certain timing-based MEV pressures, while **EVM compatibility** means familiar MEV patterns (and mitigations) still apply. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-minting-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-minting-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..69fa968f --- /dev/null +++ b/content/answers/what-is-minting-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,218 @@ +--- +title: 'What is Minting in Crypto and How Does It Work?' +description: 'Learn about what is minting and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'minting', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Minting in Crypto and How Does It Work? + +## Overview + +Minting in crypto is the process of creating new tokens or non-fungible tokens (NFTs) on a blockchain by recording them in a smart contract and assigning ownership. When people ask **what is minting**, they’re usually referring to how new digital assets come into existence on-chain—either as newly issued supply (fungible tokens) or as unique items (NFTs). + +Unlike “printing” money off-chain, minting is verifiable: the blockchain’s state updates to reflect new token IDs or new balances, and the transaction history provides an auditable trail of creation and ownership. + +## How It Works + +### Minting vs. Mining (and Why People Confuse Them) + +- **Mining** (typical in Proof-of-Work chains) is a consensus mechanism where miners expend computation to add blocks and may receive newly issued coins as rewards. +- **Minting** is the on-chain act of **issuing** tokens—usually via a smart contract function (e.g., `mint`) or via protocol rules (e.g., staking rewards in some Proof-of-Stake systems). + +A chain can have minting without mining (most smart-contract platforms), and it can have both (e.g., mining produces blocks and issuance). + +### What Actually Happens During Minting + +At a high level, minting involves: + +1. **Authorization**: A contract checks whether the caller is allowed to mint (e.g., contract owner, minter role, sale contract, or a permissionless rule). +2. **State update**: The contract increases total supply (fungible tokens) or creates a new token ID + metadata linkage (NFTs). +3. **Ownership assignment**: The newly minted asset is assigned to an address (the minter or a recipient). +4. **Events emitted**: Standard events (like ERC-20 `Transfer` from `0x0` or ERC-721 `Transfer` from `0x0`) signal to indexers and wallets that minting occurred. +5. **Fees/gas paid**: The transaction requires gas; some mints also require payment in native tokens or another token. + +### Types of Minting + +**Fungible token minting (ERC-20-like)** +Creates interchangeable units (e.g., 1,000 tokens) and increases total supply. Often used for: + +- Token launches (initial supply) +- Emissions schedules (staking rewards) +- Treasury or incentives + +**NFT minting (ERC-721 / ERC-1155-like)** +Creates a unique token ID (ERC-721) or a semi-fungible token type with a supply (ERC-1155). Used for: + +- Digital art and collectibles +- Game items +- Membership/access passes +- On-chain credentials + +### Common Minting Models + +- **Owner/admin minting**: Only a privileged account can mint. +- **Role-based minting**: Multiple “minter” addresses can mint (e.g., using `MINTER_ROLE`). +- **Permissionless/public mint**: Anyone can mint under defined constraints (price, allowlist, max per wallet). +- **Lazy minting**: Metadata is prepared off-chain; the actual mint is executed later (often at purchase time) by a marketplace or sale contract. +- **Protocol-level minting**: Some networks mint new tokens as part of validator/staking reward distribution—implemented in the chain’s core logic rather than a user-deployed contract. + +### Security and Supply Considerations + +Minting directly affects supply and ownership, so best practices include: + +- **Cap / max supply** to prevent infinite issuance (for many assets) +- **Access control** (e.g., owner or roles) and careful key management +- **Reentrancy-safe payments** for paid mints +- **Metadata integrity** (immutable URIs, content addressing like IPFS/Arweave, or on-chain metadata) +- **Clear emissions schedules** and transparency around inflation + +## On Sei Network + +On Sei, minting works the same way conceptually—assets are created by on-chain transactions that update contract or protocol state—but it benefits from Sei’s performance characteristics. + +- **EVM compatibility**: You can deploy standard Solidity contracts (ERC-20, ERC-721, ERC-1155) and use familiar minting patterns and tooling. +- **High throughput via parallelization**: Sei is designed to execute many transactions in parallel when they don’t conflict, which can help high-demand mints (e.g., NFT drops or large-scale token distributions) process more efficiently. +- **Fast finality (~400ms)**: Mint transactions can reach finality quickly, improving user experience for real-time mint flows (wallet confirmation, reveal mechanics, claim experiences). + +### Example: Minting an ERC-20 Token (Solidity) + +Below is a minimal ERC-20-style example showing a restricted `mint` function. (In production, prefer audited libraries like OpenZeppelin.) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract SimpleERC20 { + string public name = "Example Token"; + string public symbol = "EXM"; + uint8 public decimals = 18; + + uint256 public totalSupply; + address public owner; + + mapping(address => uint256) public balanceOf; + + event Transfer(address indexed from, address indexed to, uint256 value); + + modifier onlyOwner() { + require(msg.sender == owner, "NOT_OWNER"); + _; + } + + constructor() { + owner = msg.sender; + } + + function mint(address to, uint256 amount) external onlyOwner { + require(to != address(0), "BAD_TO"); + + totalSupply += amount; + balanceOf[to] += amount; + + // ERC-20 convention: mint emits Transfer from zero address + emit Transfer(address(0), to, amount); + } + + function transfer(address to, uint256 amount) external returns (bool) { + require(balanceOf[msg.sender] >= amount, "INSUFFICIENT_BALANCE"); + require(to != address(0), "BAD_TO"); + + balanceOf[msg.sender] -= amount; + balanceOf[to] += amount; + + emit Transfer(msg.sender, to, amount); + return true; + } +} +``` + +### Example: Minting an NFT (ERC-721-style, Solidity) + +This simplified example illustrates minting a unique token ID to a recipient. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract SimpleNFT { + string public name = "Example NFT"; + string public symbol = "ENFT"; + + address public owner; + uint256 public nextTokenId; + + mapping(uint256 => address) public ownerOf; + + event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); + + modifier onlyOwner() { + require(msg.sender == owner, "NOT_OWNER"); + _; + } + + constructor() { + owner = msg.sender; + } + + function mint(address to) external onlyOwner returns (uint256 tokenId) { + require(to != address(0), "BAD_TO"); + + tokenId = nextTokenId++; + ownerOf[tokenId] = to; + + // ERC-721 convention: mint emits Transfer from zero address + emit Transfer(address(0), to, tokenId); + } +} +``` + +### Example: Sending a Mint Transaction on Sei (EVM) with ethers.js + +If you have a deployed token/NFT contract with a `mint` function, you can call it using standard Ethereum tooling against Sei’s EVM RPC. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const PRIVATE_KEY = process.env.PRIVATE_KEY!; +const CONTRACT_ADDRESS = '0xYourContractAddress'; + +const ABI = ['function mint(address to, uint256 amount) external']; + +async function main() { + const provider = new ethers.JsonRpcProvider(RPC_URL); + const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + + const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, wallet); + + const to = '0xRecipientAddress'; + const amount = ethers.parseUnits('1000', 18); + + const tx = await contract.mint(to, amount); + console.log('Submitted tx:', tx.hash); + + const receipt = await tx.wait(); + console.log('Confirmed in block:', receipt.blockNumber); +} + +main().catch(console.error); +``` + +## Key Takeaways (Quick Glossary Summary) + +- **What is minting**: Creating new crypto tokens or NFTs by writing their creation into a blockchain’s state. +- **How it works**: A smart contract (or protocol rules) authorizes minting, updates supply/ownership, emits events, and finalizes via consensus. +- **On Sei Network**: Minting is EVM-compatible and benefits from Sei’s parallelization and fast (~400ms) finality—useful for responsive, high-volume mint experiences. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx b/content/answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx new file mode 100644 index 00000000..fec57977 --- /dev/null +++ b/content/answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx @@ -0,0 +1,111 @@ +--- +title: 'What is Proof Of History and How Does It Secure the Blockchain?' +description: 'Learn about what is proof of history and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'proof', 'history', 'and', 'how', 'does', 'secure', 'the', 'blockchain'] +--- + +import { Callout } from 'nextra/components'; + +# What is Proof Of History and How Does It Secure the Blockchain? + +## Overview + +Proof of History (PoH) is a cryptographic technique that creates a verifiable, ordered record of time—effectively a “clock”—for blockchain events. It does this by producing a sequence of hashes where each output depends on the previous one, making the passage of time and event ordering auditable. For the target query _what is proof of history_, the core idea is: PoH proves that specific data existed **at or before** a certain point in a cryptographic timeline. + +PoH is best known from Solana’s design, where it’s used to improve throughput by providing a high-speed source of ordering for transactions. + +## How It Works + +### 1) Verifiable delay via sequential hashing + +PoH relies on a computation that is: + +- **Fast to verify** +- **Inherently sequential to compute** (you can’t parallelize “the next hash” without the previous hash) + +A simplified model looks like: + +1. Start with a seed value. +2. Repeatedly hash it: + - `h1 = hash(seed)` + - `h2 = hash(h1)` + - `h3 = hash(h2)` +3. At any time, insert (“stamp”) an event into the sequence by hashing in the event data, creating a cryptographic proof that the event occurred _after_ some number of hashes. + +Because each step depends on the prior step, producing `hn` implies the producer performed the preceding `n-1` steps in order. Observers can verify the sequence and confirm that time (measured in hash-steps) advanced. + +### 2) Event ordering without relying solely on timestamps + +In distributed systems, wall-clock time is hard: nodes can disagree, clocks drift, and timestamps can be manipulated. PoH offers an alternative: + +- **Relative time** is measured by the number of sequential hash steps. +- Events are ordered by their position in the PoH sequence. + +This can reduce coordination overhead when many nodes need to agree on ordering. + +### 3) How PoH contributes to blockchain security + +PoH by itself is not usually a full consensus mechanism; it is typically paired with a consensus protocol (e.g., PoS). Its security contribution is mainly: + +- **Tamper-evident ordering:** Rewriting history requires regenerating the sequential hash chain from the point of alteration onward. +- **Deterministic sequencing:** Nodes can verify a proposed order of transactions/events against the PoH record. +- **Reduced ambiguity in leader proposals:** If a leader proposes a block with PoH references, validators can more easily validate ordering claims. + +However, PoH does **not** replace: + +- **Sybil resistance** (usually provided by PoS/PoW) +- **Finality rules** (how the network resolves forks and finalizes state) +- **Economic security** (stake slashing, incentives, etc.) + +### 4) Conceptual example (hash chain “clock”) + +Below is a simplified illustration of building a sequential hash chain. This is not a production PoH implementation, but it shows the “sequential and verifiable” property: + +```typescript +import { createHash } from 'crypto'; + +function sha256(data: Buffer | string) { + return createHash('sha256').update(data).digest('hex'); +} + +// Build a simple sequential hash chain +let h = sha256('seed'); +for (let i = 0; i < 5; i++) { + h = sha256(h); + console.log(`step=${i + 1} hash=${h}`); +} + +// "Stamp" an event by hashing it into the chain at a specific step +const event = JSON.stringify({ tx: '0xabc...', note: 'example event' }); +const stamped = sha256(h + event); +console.log('stamped_event_hash=', stamped); +``` + +Verification is straightforward: recompute the chain from the seed up to the claimed step and check the resulting hashes match. + +## On Sei Network + +Sei Network does **not** use Proof of History as its consensus clock. Instead, Sei is designed for high throughput and low latency via **parallelization** and fast finality (approximately **~400ms**), while maintaining strong consensus guarantees. + +Key points for how this relates to Sei: + +- **Ordering and finality on Sei:** Transaction ordering and block production are handled by Sei’s consensus and execution pipeline, with rapid finality that reduces the need for an external “proof of time” construct like PoH. +- **Parallel execution:** Sei’s architecture focuses on executing transactions in parallel when possible, improving performance without relying on PoH-based sequencing. +- **EVM compatibility:** Sei’s EVM environment allows Solidity smart contracts to run with familiar tooling. Timing/ordering assumptions for smart contracts on Sei should be based on **block height/finality** and Sei’s consensus rules—not PoH-style time proofs. + +If you’re building on Sei, treat PoH as a helpful glossary concept for understanding how some chains optimize ordering, but rely on Sei’s native properties—**parallelization** and **~400ms finality**—for performance and settlement guarantees. + +## Why It Matters + +Understanding _what is proof of history_ helps clarify a broader design space in blockchain architecture: some networks accelerate throughput by proving event ordering with a cryptographic time sequence, while others (like Sei) achieve performance through **fast finality and parallel execution** without adopting PoH. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx b/content/answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx new file mode 100644 index 00000000..4c2db1cb --- /dev/null +++ b/content/answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx @@ -0,0 +1,128 @@ +--- +title: 'What is Proof Of Stake and How Does It Secure the Blockchain?' +description: 'Learn about what is proof of stake and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'proof', 'stake', 'and', 'how', 'does', 'secure', 'the', 'blockchain'] +--- + +import { Callout } from 'nextra/components'; + +# What is Proof Of Stake and How Does It Secure the Blockchain? + +## Overview + +Proof of Stake (PoS) is a blockchain consensus mechanism where validators secure the network by locking up (“staking”) the chain’s native tokens and participating in block production and validation. Instead of relying on energy-intensive mining like Proof of Work, PoS uses economic incentives—rewards for honest behavior and penalties for malicious behavior—to keep the ledger accurate and tamper-resistant. + +In short, **what is proof of stake**? It’s a system where **stake (capital at risk)** replaces **computational power** as the primary resource used to reach consensus and secure the blockchain. + +## How It Works + +### 1) Validators Stake Tokens to Join Consensus + +- Participants lock tokens in a staking contract/module to become validators (or delegate stake to validators). +- The amount staked typically influences a validator’s ability to be selected to propose blocks and earn rewards. + +### 2) Block Proposal and Attestation/Validation + +While implementations vary across chains, most PoS systems follow this pattern: + +- **Proposer selection:** A validator is chosen (often pseudo-randomly, weighted by stake) to propose the next block. +- **Voting/attestation:** Other validators verify the proposed block (transactions, signatures, state transitions) and vote/attest to it. +- **Finalization:** Once enough stake has voted according to the chain’s rules, the block is considered final (or finalized after a short sequence of steps). + +### 3) Economic Security: Rewards and Slashing + +PoS security comes from **making attacks expensive**: + +- **Rewards:** Validators earn inflationary rewards and/or transaction fees for proposing and validating blocks. +- **Slashing/penalties:** Validators can lose part of their stake for provable misbehavior, such as: + - **Double-signing** (signing conflicting blocks) + - **Surround votes / equivocation** (protocol-specific forms of conflicting votes) + - **Downtime** (often penalized via smaller “liveness” penalties rather than full slashing) + +Because stake is locked and slashable, attackers risk losing significant capital if they try to rewrite history or approve invalid blocks. + +### 4) Why Proof of Stake Is Secure + +PoS secures a blockchain through: + +- **Sybil resistance:** Gaining influence requires acquiring stake, not creating many identities. +- **Costliness of attacks:** Controlling consensus generally requires obtaining a large fraction of total staked tokens, which is expensive and risky. +- **Detectability and punishment:** Many attacks are objectively provable on-chain, enabling automatic slashing. +- **Fast recovery:** If malicious validators are slashed and removed, honest stake can reassert control without requiring specialized hardware. + +### 5) Delegation and Staking for Users + +Many PoS networks allow token holders to: + +- **Delegate** tokens to validators to earn a portion of rewards. +- Increase the network’s security by spreading stake across reliable validators. + +> Note: Delegation typically does not transfer custody, but it does expose delegators to validator performance and (in some systems) slashing risk. + +## On Sei Network + +Sei Network uses a Proof of Stake model to secure consensus and provide fast, reliable transaction finality—designed for high-performance applications. Sei’s architecture emphasizes **parallelization** to maximize throughput while maintaining robust validator-based security, and it supports **EVM compatibility**, enabling Solidity smart contracts to run on Sei. + +Key implications for PoS on Sei: + +- **Fast finality (~400ms):** Sei is engineered for very low-latency confirmation and finality, which improves user experience and reduces uncertainty for trading, gaming, and real-time apps. +- **Parallelization:** Sei processes transactions efficiently by executing where possible in parallel, while PoS validators still enforce correctness of state transitions and ordering rules. +- **EVM compatibility:** Developers can deploy and secure Solidity smart contracts under Sei’s PoS security model, benefiting from familiar tooling while leveraging Sei’s performance characteristics. + +### Staking and Validator Participation (Conceptual Flow) + +1. Validators stake SEI to participate in consensus. +2. Validators propose blocks, validate transactions, and sign votes. +3. Honest validators receive rewards; misbehavior or persistent faults can be penalized. +4. Delegators can stake by delegating to validators to help secure the network and earn staking rewards. + +## Example Commands (Staking/Validator Operations) + +Below are illustrative examples of typical Cosmos-SDK-style workflows used by PoS networks (exact commands/flags may differ based on your Sei tooling and environment). + +### Check Validator Set / Network Status + +```bash +seid status +seid query staking validators +``` + +### Delegate Stake to a Validator + +```bash +seid tx staking delegate 1000000usei \ + --from \ + --chain-id \ + --gas auto --gas-adjustment 1.3 --fees 2000usei +``` + +### Undelegate Stake + +```bash +seid tx staking unbond 1000000usei \ + --from \ + --chain-id \ + --gas auto --gas-adjustment 1.3 --fees 2000usei +``` + +## Why Proof of Stake Matters + +Proof of Stake is widely used because it offers: + +- **Strong security via economic incentives** +- **Lower energy usage than mining-based systems** +- **Flexible participation through delegation** +- **Potential for faster finality and better UX** + +On Sei Network, PoS underpins **high-speed, parallelized execution** and **~400ms finality**, providing a secure foundation for performant, EVM-compatible decentralized applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx b/content/answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx new file mode 100644 index 00000000..6c28cac0 --- /dev/null +++ b/content/answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx @@ -0,0 +1,132 @@ +--- +title: 'What is Proof Of Work and How Does It Secure the Blockchain?' +description: 'Learn about what is proof of work and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'proof', 'work', 'and', 'how', 'does', 'secure', 'the', 'blockchain'] +--- + +import { Callout } from 'nextra/components'; + +# What is Proof Of Work and How Does It Secure the Blockchain? + +## Overview + +Proof of Work (PoW) is a blockchain consensus mechanism where network participants (miners) compete to solve a computational puzzle to earn the right to add the next block. The core idea is that producing a valid block is intentionally expensive, making it impractical for attackers to rewrite history. If you’re asking **what is proof of work**, it’s essentially a “costly-to-create, easy-to-verify” method of securing a shared ledger without trusting a central party. + +## How It Works + +### 1) Miners build a candidate block + +Miners collect pending transactions from the mempool, verify them (signatures, balances, rules), and assemble a candidate block. The block includes: + +- A list of transactions +- A reference to the previous block (hash) +- A timestamp and other metadata +- A **nonce** (a number miners vary to search for a valid hash) + +### 2) The PoW puzzle (hashing) + +Most PoW systems use a cryptographic hash function (e.g., SHA-256) and require the block hash to be below a network-defined target. Because hashes appear random, miners must try many nonces until they find a hash that meets the difficulty requirement. + +Conceptually: + +1. Compute `blockHash = Hash(blockHeader)` +2. Check if `blockHash < target` +3. If not, change nonce and try again + +This is what makes PoW “work”: the only reliable strategy is brute-force trial and error. + +### 3) Difficulty adjustment + +To keep block production at a predictable rate, networks periodically adjust difficulty (the target threshold). If blocks are found too quickly, difficulty increases; if too slowly, difficulty decreases. This stabilizes the cadence of new blocks even as total mining power changes. + +### 4) Verification by full nodes + +Once a miner finds a valid block, it broadcasts it to the network. Full nodes independently verify: + +- PoW is valid (hash meets target) +- Transactions are valid and not double-spent +- Block correctly references the prior chain tip + +Verification is fast compared to mining, which is critical: honest nodes can cheaply reject invalid blocks. + +### 5) Chain selection and finality (probabilistic) + +PoW networks typically follow a “most work” rule (often approximated by the longest chain with the most cumulative difficulty). Finality is **probabilistic**: a transaction becomes increasingly irreversible as more blocks are added on top of it. + +## How Proof of Work Secures the Blockchain + +### Makes attacks expensive + +To rewrite history (e.g., reverse payments), an attacker must redo the PoW for the target block _and_ catch up to and surpass the honest chain’s cumulative work. This requires enormous computational power and energy, making sustained attacks costly. + +### Discourages double-spends + +A would-be double-spender must build an alternative chain where the spending transaction is removed or replaced. The more confirmations a transaction has, the more work the attacker must redo. + +### Aligns incentives through rewards + +Miners receive block rewards and/or transaction fees, encouraging them to follow protocol rules. Attacking the network can undermine confidence and the value of the reward itself, creating an economic disincentive. + +### Provides Sybil resistance + +In open networks, anyone can create unlimited identities. PoW ties influence to scarce real-world resources (compute/energy), not identities, helping prevent fake-node flooding from controlling consensus. + +## Simple Example (Conceptual) + +Below is a toy example showing the basic idea of mining: find a nonce so a hash meets a “difficulty” condition. Real blockchains use more complex headers and difficulty targets, but the principle is the same. + +```typescript +import { createHash } from 'crypto'; + +function sha256(input: string): string { + return createHash('sha256').update(input).digest('hex'); +} + +// Very simplified "difficulty": require the hash to start with N zeros +const difficultyZeros = 4; + +const prevHash = '000000abc123...'; // previous block hash (placeholder) +const merkleRoot = 'def456...'; // transactions root (placeholder) +let nonce = 0; + +while (true) { + const header = `${prevHash}|${merkleRoot}|${nonce}`; + const hash = sha256(header); + + if (hash.startsWith('0'.repeat(difficultyZeros))) { + console.log('Mined!'); + console.log({ nonce, hash }); + break; + } + nonce++; +} +``` + +## Tradeoffs of Proof of Work + +- **Energy/operational cost:** Security comes from expending real resources, which can be energy-intensive. +- **Hardware centralization risk:** Specialized hardware (ASICs) can concentrate mining power. +- **Lower throughput and slower finality:** Many PoW networks prioritize decentralization and security, often resulting in longer confirmation times. + +## On Sei Network + +Sei Network does **not** use Proof of Work. Sei is a high-performance Layer 1 designed for fast execution and settlement, offering **~400ms finality**, **parallelized transaction execution**, and **EVM compatibility** for deploying Solidity smart contracts. + +Where PoW provides security by requiring miners to spend compute to propose blocks, Sei achieves security and fast finality through modern consensus and execution design, including: + +- **Rapid finality (~400ms):** Transactions become final quickly compared to probabilistic PoW confirmation models. +- **Parallelization:** Many transactions can be executed concurrently, improving throughput and reducing contention. +- **EVM compatibility:** Developers can deploy and interact with smart contracts using familiar Ethereum tooling while benefiting from Sei’s performance characteristics. + +If your goal is understanding **what is proof of work** for blockchain security: PoW secures networks by making block production costly and rewriting history prohibitively expensive. On Sei, similar security objectives are met without PoW, enabling significantly faster finality and higher performance for applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..06fa29e8 --- /dev/null +++ b/content/answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,120 @@ +--- +title: 'What is Sharding in Crypto and How Does It Work?' +description: 'Learn about what is sharding and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'sharding', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Sharding in Crypto and How Does It Work? + +## Overview + +Sharding is a scalability technique that splits a blockchain’s data and workload across multiple smaller partitions (“shards”) so the network can process transactions in parallel. Instead of every node executing and storing everything, each shard handles a subset of transactions and state, increasing throughput while aiming to preserve decentralization. + +In simple terms, **what is sharding**: it’s dividing one blockchain into many coordinated “mini-chains” that together form a single network. + +## How It Works + +### 1) Partitioning the Network (Shards) + +A sharded blockchain divides responsibility across multiple groups of nodes: + +- **Transaction sharding**: transactions are routed to specific shards. +- **State sharding**: account/contract state is split across shards. +- **Data sharding**: historical data and availability responsibilities may be partitioned. + +Each shard processes its own transactions and maintains its own portion of the ledger/state. + +### 2) Parallel Execution + +In a traditional (non-sharded) blockchain, every validator typically re-executes all transactions. With sharding: + +- Shard A can process its transactions at the same time as Shard B, C, etc. +- Total throughput increases roughly with the number of shards (subject to overhead and bottlenecks). + +### 3) Cross-Shard Communication + +Many applications require interaction across shards (e.g., sending assets from an account in Shard 1 to a contract in Shard 2). Sharded systems need mechanisms for: + +- **Message passing** between shards (often asynchronous). +- **Atomicity guarantees** (ensuring cross-shard actions don’t partially complete). +- **Finality coordination** (deciding when a cross-shard action is considered “done”). + +Cross-shard operations introduce complexity and can reduce some of the gains from parallelism if not designed carefully. + +### 4) Security Model (Validator Assignment) + +To prevent attackers from taking over a single shard, sharded networks typically: + +- Randomly assign validators to shards. +- Rotate assignments periodically. +- Use shared security or a beacon/coordination layer to unify consensus and finality. + +### 5) Tradeoffs + +Sharding improves scalability but comes with tradeoffs: + +- **Complexity**: cross-shard messages, receipts, and proofs are non-trivial. +- **Latency**: cross-shard actions may take longer than same-shard transactions. +- **Developer overhead**: apps may need to be “shard-aware,” depending on the design. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility** that achieves scalability through **parallelization** rather than exposing an explicit multi-shard architecture to developers. In practice, this means: + +- **Parallel execution**: Sei is built to execute independent transactions concurrently, increasing throughput without requiring application developers to manage cross-shard logic. +- **Fast finality (~400ms)**: transactions can reach finality quickly, improving user experience for trading, games, and other latency-sensitive apps. +- **EVM compatibility**: Solidity smart contracts can run on Sei, benefiting from the network’s performance characteristics without needing special sharding-aware contract patterns. + +### Sharding vs. Sei’s Parallelization (Why It Matters) + +If you’re evaluating **what is sharding** as a scaling path, it’s helpful to compare it to Sei’s approach: + +- Sharding scales by **splitting the chain** into multiple partitions and coordinating across them. +- Sei scales by **keeping one cohesive network** while executing non-conflicting work in parallel, aiming to deliver high throughput with simpler mental models for developers. + +For many dApps, Sei’s parallelization provides “shard-like” performance benefits (more concurrent processing) while avoiding common sharding pain points like cross-shard composability constraints. + +## Practical Example (EVM Perspective) + +Below is a simple Solidity contract that increments a counter. On networks that parallelize execution effectively, many users calling `increment()` on different contracts/accounts can be processed concurrently when transactions don’t conflict on the same state. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +contract Counter { + uint256 public count; + + function increment() external { + count += 1; + } +} +``` + +To deploy and interact (example using Foundry). Replace RPC with a Sei EVM endpoint: + +```bash +export RPC_URL="https://" +export PRIVATE_KEY="" + +forge create --rpc-url $RPC_URL --private-key $PRIVATE_KEY src/Counter.sol:Counter +``` + +## Key Takeaways + +- **Sharding** is a method for scaling blockchains by splitting work and state across multiple shards that process transactions in parallel. +- The hardest parts are **cross-shard communication**, **atomic composability**, and **maintaining security** across shards. +- **Sei Network** delivers high throughput via **parallelization** and **~400ms finality** with **EVM compatibility**, providing many scalability benefits without requiring developers to design around explicit shards. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..0acf8ea9 --- /dev/null +++ b/content/answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,121 @@ +--- +title: 'What is Slashing in Crypto and How Does It Work?' +description: 'Learn about what is slashing and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'slashing', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Slashing in Crypto and How Does It Work? + +## Overview + +Slashing is a penalty mechanism in proof-of-stake (PoS) blockchains where a validator (or their delegators) loses some of their staked tokens for breaking consensus rules or failing to perform required duties. In short, _what is slashing_ refers to the on-chain enforcement that makes attacks and persistent misbehavior economically costly, helping keep the network secure and reliable. + +## How It Works + +In PoS systems, validators lock up stake to earn rewards for proposing/attesting blocks and maintaining uptime. Slashing creates “skin in the game” by making the stake _at risk_ if a validator acts maliciously or negligently. + +### Why slashing exists + +- **Economic security:** Attackers must risk real value; penalties can exceed potential profit. +- **Safety guarantees:** Discourages actions that could cause consensus failures or chain forks. +- **Reliability:** Incentivizes validators to stay online and correctly participate. + +### Common behaviors that can trigger slashing + +Exact conditions vary by chain, but often include: + +- **Double-signing / equivocation:** Signing two conflicting blocks or votes for the same height/round. +- **Surround vote / conflicting attestations:** Protocol-specific forms of voting inconsistencies (common in some PoS designs). +- **Extended downtime (in some networks):** Missing too many required votes/blocks can lead to penalties (sometimes “jailing” rather than stake loss, depending on the chain’s design). + +### What typically happens when a validator is slashed + +1. **Detection:** On-chain evidence of misbehavior is submitted or automatically observed. +2. **Penalty:** A portion of the validator’s stake is burned or redistributed (chain-specific). +3. **Jailing / tombstoning (optional):** The validator may be temporarily removed from the active set or permanently banned. +4. **Unbonding impact:** Funds may be locked for an unbonding period; slashing can occur during this window on many PoS chains. +5. **Delegator impact:** Delegators may share the penalty proportionally because they chose that validator (varies by chain and configuration). + +### Slashing vs. jailing + +- **Slashing:** Economic penalty (loss of stake). +- **Jailing:** Operational penalty (removal from validator set for a time). A validator can be jailed without being slashed, or both can occur together, depending on the offense. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with EVM compatibility and fast finality (often ~400ms). Like other PoS networks, Sei relies on validators staking tokens and following consensus rules; slashing/jailing mechanisms help ensure validators remain honest and available so the network can maintain strong safety guarantees even under high throughput and parallel execution. + +Key points for Sei: + +- **Consensus security at high speed:** Sei’s rapid finality means the network depends on validators behaving correctly and consistently; slashing discourages equivocation and other consensus violations that could undermine finality. +- **Operational reliability:** Validator availability is critical to keep block production smooth and maintain performance. Downtime penalties (often implemented as jailing and/or slashing depending on the specific parameters) incentivize robust infrastructure. +- **EVM compatibility doesn’t change slashing mechanics:** Slashing applies to validator behavior at the consensus layer, not to EVM smart contract execution. EVM contracts can still integrate staking-related data or monitor validator status via on-chain queries, but they do not “slash” validators directly (that’s protocol-governed). + +> Note: The exact slashing percentages, jailing durations, and conditions are defined by Sei’s on-chain parameters and can evolve via governance. + +## Practical Implications for Users and Delegators + +If you delegate stake to a validator: + +- You earn rewards when the validator performs well. +- You take on **shared risk**: if that validator is slashed, your delegated stake can be reduced proportionally. +- Choosing reputable validators (uptime, history, security practices) is essential risk management. + +If you run a validator: + +- Use redundant infrastructure, monitoring, and secure key management (HSMs/remote signers where applicable). +- Avoid configurations that could cause double-signing (e.g., running the same validator key on multiple active nodes without safeguards). + +## Example: Checking Validator / Staking State (Cosmos SDK-style CLI) + +Sei is built on Cosmos SDK foundations, so many networks in this ecosystem expose staking and validator data through standard interfaces. Exact commands may differ by Sei version and tooling, but typical patterns look like: + +```bash +# Query validator info (operator address format) +seid query staking validator + +# Query slashing signing info (consensus address format) +seid query slashing signing-info + +# Query staking params (may include unbonding time, etc.) +seid query staking params +``` + +## Example: Reading Staking Data Programmatically (TypeScript via REST) + +Many Cosmos-based chains expose REST endpoints (via LCD or similar). A simplified example: + +```typescript +import fetch from 'node-fetch'; + +async function getValidator(valoper: string) { + const url = `https:///cosmos/staking/v1beta1/validators/${valoper}`; + const res = await fetch(url); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return res.json(); +} + +(async () => { + const data = await getValidator('seivaloper1...'); + console.log(data.validator?.description?.moniker, data.validator?.commission); +})(); +``` + +## Key Takeaways + +- **What is slashing:** a protocol-level penalty that reduces a validator’s stake when they break consensus rules or violate required behavior. +- **How it works:** misbehavior is proven on-chain, a stake penalty is applied, and the validator may be jailed/removed from active duty. +- **On Sei Network:** slashing supports consensus security and reliability, complementing Sei’s high throughput, parallelization, and fast (~400ms) finality while remaining independent of EVM smart contract logic. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx b/content/answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx new file mode 100644 index 00000000..b8b956a9 --- /dev/null +++ b/content/answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx @@ -0,0 +1,147 @@ +--- +title: 'What is Staking in Blockchain and How Does It Work?' +description: 'Learn about what is staking and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'staking', 'blockchain', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Staking in Blockchain and How Does It Work? + +## Overview + +Staking is the process of locking up cryptocurrency to help secure a blockchain network and participate in its operations—typically by validating transactions and producing new blocks. In return, stakers can earn rewards (often called staking rewards) and may gain governance rights, depending on the network. + +If you’re searching **what is staking**, the simplest definition is: _staking is earning protocol rewards by committing tokens to support a proof‑of‑stake (PoS) blockchain’s security and consensus._ + +## How It Works + +### Proof of Stake vs. Proof of Work (quick context) + +- **Proof of Work (PoW):** miners use computing power to compete to add blocks (e.g., Bitcoin). +- **Proof of Stake (PoS):** validators are chosen (directly or probabilistically) based on staked tokens and other factors to propose/validate blocks. + +Staking is primarily associated with PoS and PoS-derived consensus mechanisms. + +### Core components of staking + +1. **Stake (bonded tokens):** You lock tokens into a staking module or smart contract. +2. **Validators (or validator set):** Entities running infrastructure that participates in consensus. +3. **Delegators:** Token holders who stake by delegating to validators (common in Cosmos SDK chains). +4. **Rewards:** Paid from inflation, transaction fees, MEV-related mechanisms, or a combination. +5. **Slashing (risk):** If a validator misbehaves (e.g., double-signing) or is frequently offline, some staked tokens can be penalized. + +### Typical staking flow + +1. **Choose a validator** (or run your own). +2. **Bond tokens** (lock them for staking). +3. **Earn rewards over time** as the network produces blocks. +4. **Unbond/unstake** when you want liquidity again—often with an unbonding period. + +### Key concepts and tradeoffs + +- **Unbonding period:** Many networks enforce a delay to unstake to protect network security. +- **APY variability:** Rewards can change based on total stake, inflation, fees, and validator performance/commission. +- **Validator commission:** Delegators usually share rewards with the validator. +- **Custody:** Some staking is non-custodial (you retain keys), while some exchange staking is custodial. + +## Types of Staking + +### 1) Native protocol staking + +You stake the chain’s native token directly in the protocol’s consensus (e.g., Cosmos SDK chains). This is the most “fundamental” form of staking because it directly secures the network. + +### 2) Liquid staking + +You stake but receive a liquid token representation (a derivative) that can be used in DeFi while still earning staking rewards. This adds smart contract and depegging risks. + +### 3) Exchange/pooled staking + +A centralized platform stakes on your behalf. It can be simpler, but introduces counterparty and custody risk. + +## Benefits of Staking + +- **Network security:** More stake generally increases the cost of attacks. +- **Rewards:** Stakers earn yield-like rewards for participating in consensus. +- **Governance:** Some networks allow stakers to vote on upgrades and parameters. +- **Ecosystem alignment:** Incentivizes long-term participation. + +## Risks and Considerations + +- **Slashing:** Loss of funds due to validator misbehavior or downtime. +- **Lockups/unbonding:** Funds may be illiquid for a period. +- **Smart contract risk (liquid staking/DeFi):** Contract exploits or oracle failures. +- **Centralization risk:** Concentration of stake in a few validators can weaken resilience. +- **Tax and accounting:** Rewards may be taxable depending on jurisdiction. + +## On Sei Network + +Sei Network is a high-performance Layer 1 blockchain built for low-latency trading and DeFi, with **EVM compatibility** and fast execution. Staking on Sei follows the **Cosmos SDK-style delegated proof of stake**, where token holders can **delegate** SEI to validators who secure the network and participate in consensus. + +### What staking does on Sei + +- **Secures consensus:** Validators and delegators help maintain network integrity and finality. +- **Enables participation:** Delegators select validators, supporting decentralization and liveness. +- **Rewards distribution:** Stakers earn rewards tied to network economics (e.g., fees and protocol incentives, depending on network parameters). + +### Why Sei staking is distinct + +- **Fast finality (~400ms):** Sei’s quick block finality means consensus participation and validator performance are especially important for low-latency apps (trading, perps, onchain order books, etc.). +- **Parallelization:** Sei’s architecture emphasizes parallel execution, which increases throughput and makes validator infrastructure quality (uptime, latency, reliability) particularly relevant. +- **EVM compatibility:** Developers can build EVM apps while the underlying network security is still anchored by PoS staking on Sei. + +> Practical implication: when delegating on Sei, validator uptime and operational performance can affect reward consistency and slashing risk—important in a chain optimized for speed. + +## Example: Staking via CLI (Conceptual) + +Below is a typical Cosmos SDK-style workflow to **delegate** tokens to a validator. Exact binary name, chain ID, and denomination may vary by Sei version and environment (mainnet/testnet). + +```bash +# Check wallet address +seid keys show mykey -a + +# Delegate 1000000 usei to a validator (example) +seid tx staking delegate 1000000usei \ + --from mykey \ + --chain-id \ + --gas auto \ + --gas-adjustment 1.3 \ + --fees +``` + +To **unbond/undelegate**: + +```bash +seid tx staking undelegate 1000000usei \ + --from mykey \ + --chain-id \ + --gas auto \ + --gas-adjustment 1.3 \ + --fees +``` + +## FAQs (Quick) + +**What is staking used for?** +To secure PoS networks, validate transactions, and earn rewards for participation. + +**Do you lose crypto when staking?** +Not typically, but you can lose some via slashing, and you may face lockups/unbonding delays. + +**Is staking the same as lending?** +No. Staking supports consensus/security; lending provides liquidity to borrowers. Risks and mechanics differ. + +## Summary + +Staking is a mechanism used by proof‑of‑stake blockchains to secure the network by locking tokens and empowering validators to produce and validate blocks. In exchange, participants may earn rewards and governance rights, but must consider risks like slashing and unbonding delays. On **Sei Network**, staking underpins a high-performance chain with **parallelization** and **~400ms finality**, while supporting an ecosystem that includes **EVM-compatible** applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx b/content/answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx new file mode 100644 index 00000000..187c2fcb --- /dev/null +++ b/content/answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx @@ -0,0 +1,154 @@ +--- +title: 'What is the IBC Protocol and How Does It Work?' +description: 'Learn about what is IBC protocol and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'cosmos-sdk', 'what', 'IBC', 'protocol', 'the', 'ibc', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is the IBC Protocol and How Does It Work? + +## Overview + +The **Inter-Blockchain Communication (IBC) Protocol** is a standardized protocol for **secure, permissionless messaging and asset transfers between independent blockchains**. In short, _what is IBC protocol_? It’s the interoperability layer used across the Cosmos ecosystem (and beyond) to move tokens and data across chains **without relying on centralized bridges**. + +IBC achieves this by using **light clients** to verify another chain’s state and a **packet-based message format** to send and receive cross-chain messages over ordered or unordered channels. + +## How It Works + +### 1) Core Components + +IBC is implemented as a set of modules and standards (ICS — Interchain Standards). The key building blocks are: + +- **Clients (Light Clients)**: On-chain verification objects that track another chain’s consensus state (e.g., Tendermint/CometBFT light client). +- **Connections**: A negotiated, authenticated relationship between two chains’ IBC modules (built on clients). +- **Channels**: Logical pathways over a connection that carry application-specific packets (e.g., token transfers). +- **Packets**: The actual cross-chain messages (data + sequencing + timeouts). +- **Relayers**: Off-chain processes that **observe events** on one chain and **submit proofs** to the other chain. Relayers do not need trust; they just transport data and proofs. + +### 2) The Trust Model (Why IBC Is Safer Than Many Bridges) + +IBC does **not** depend on a multisig or centralized validator set to attest to events. Instead: + +- Chain A maintains a light client of Chain B (and vice versa). +- When a packet is sent from Chain A to Chain B, a relayer submits: + - the packet data + - a cryptographic proof that the packet commitment exists on Chain A +- Chain B verifies the proof against Chain A’s light client state. + +Security depends on the **consensus security of the connected chains** (and correct client verification), not on a third-party bridge operator. + +### 3) Packet Lifecycle (High-Level Flow) + +1. **Handshake** + + - Establish **clients → connection → channel** through on-chain handshakes. + +2. **Send Packet** + + - An IBC application (e.g., token transfer) writes a **packet commitment** to Chain A’s state. + +3. **Relay** + + - A relayer fetches the packet and proof from Chain A and submits it to Chain B. + +4. **Receive + Verify** + + - Chain B verifies the proof via the light client, processes the packet, and writes an acknowledgment. + +5. **Acknowledgment** + + - The relayer submits the acknowledgment proof back to Chain A, completing the flow. + +6. **Timeouts** + - If the packet is not received within a specified time/height, the sender can reclaim funds or trigger timeout logic. + +### 4) IBC Token Transfers (ICS-20) + +The most common IBC application is **ICS-20 fungible token transfer**, often shown as: + +- **Escrow + voucher minting** + - When transferring a native token from its origin chain to another chain, the origin chain **escrows** it. + - The destination chain **mints a voucher representation** (an IBC denom) that can be redeemed back. + +This avoids “wrapped token” trust assumptions typical of external bridges—redemption is governed by IBC verification. + +### 5) Beyond Tokens: General Messaging + +IBC is generic; it can transport arbitrary application packets. Examples include: + +- Interchain accounts / remote execution +- Cross-chain queries (depending on application design) +- Cross-chain governance and coordination +- Interchain middleware (e.g., fee middleware) + +## On Sei Network + +Sei is a high-performance Layer 1 with **~400ms finality**, **parallelized execution**, and **EVM compatibility** (in addition to Cosmos SDK capabilities). IBC on Sei enables fast, secure interoperability with Cosmos ecosystem chains, with user experience benefits driven by Sei’s performance characteristics: + +- **Fast cross-chain UX**: Sei’s rapid finality helps make IBC transfers and acknowledgments feel near-instant once packets reach Sei. +- **High throughput**: Sei’s parallelization helps handle many simultaneous IBC-related transactions (e.g., receives, acknowledgments) efficiently. +- **EVM compatibility**: Applications can use Sei’s EVM environment while still leveraging the Cosmos interoperability stack (IBC) at the network level, enabling cross-ecosystem designs. + +Common Sei IBC use cases include: + +- Moving assets to/from other IBC-enabled networks (DEX liquidity, collateral, treasury operations). +- Cross-chain app composition where Sei provides fast execution and other chains provide specialized assets or services. +- Routing tokens via interchain paths where Sei participates as a source, destination, or hop. + +## Common Terms You’ll See + +- **Port**: Identifies an IBC application module (e.g., `transfer` for ICS-20). +- **Channel ID**: A specific channel such as `channel-0`, `channel-12`, etc. +- **Denom Trace**: The path a token took through IBC channels, which determines its IBC denom on the receiving chain. +- **Ordered vs Unordered Channels** + - Ordered: packets must be processed in sequence. + - Unordered: packets can be processed independently. + +## Practical Example: Sending an IBC Token Transfer + +The exact CLI and flags vary by chain configuration, but a typical Cosmos SDK/IBC transfer command looks like: + +```bash +seid tx ibc-transfer transfer transfer \ + --from \ + --gas auto --gas-adjustment 1.3 \ + --fees 2000usei \ + --node \ + --chain-id +``` + +Example (illustrative placeholders): + +```bash +seid tx ibc-transfer transfer transfer channel-0 sei1... 1000000usei \ + --from mywallet \ + --gas auto --gas-adjustment 1.3 \ + --fees 2000usei \ + --chain-id sei-1 +``` + +After broadcasting: + +- The transfer module emits IBC events (packet send). +- A relayer picks it up and submits the receive proof to the counterparty chain (and later relays the acknowledgment back). + +## Key Benefits of IBC + +- **Trust-minimized interoperability**: Uses light-client verification instead of multisigs. +- **Permissionless operation**: Anyone can run a relayer. +- **Standardized applications**: ICS specifications make cross-chain behavior consistent. +- **Composable ecosystem**: Enables chains like Sei to specialize (performance, execution environment) while staying connected to shared liquidity and assets. + +## Summary + +IBC is the Cosmos ecosystem’s standard for **secure cross-chain communication**, enabling token transfers and arbitrary messages via **light clients, channels, packets, and relayers**. On Sei Network, IBC benefits from Sei’s **~400ms finality**, **parallel execution**, and **EVM compatibility**, enabling fast, scalable cross-chain experiences for both Cosmos SDK and EVM-based applications. + +## Related Documentation + +- [Cosmos SDK](/cosmos-sdk) +- [Transactions](/cosmos-sdk/transactions) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-tvl-and-why-it-matters.mdx b/content/answers/what-is-tvl-and-why-it-matters.mdx new file mode 100644 index 00000000..f6ef6260 --- /dev/null +++ b/content/answers/what-is-tvl-and-why-it-matters.mdx @@ -0,0 +1,158 @@ +--- +title: 'What is TVL and Why It Matters' +description: 'Learn about what is TVL and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'TVL', 'tvl', 'and', 'why', 'matters'] +--- + +import { Callout } from 'nextra/components'; + +# What is TVL and Why It Matters + +## Overview + +TVL (Total Value Locked) is the total amount of assets deposited into a blockchain application or ecosystem—most commonly DeFi protocols like DEXs, lending markets, and staking vaults. In practice, TVL is used as a shorthand indicator of how much capital is actively committed to a protocol, which often correlates with usage, liquidity, and perceived trust. + +When people ask **“what is TVL?”**, they’re typically asking how much value is currently locked in smart contracts and what that implies about adoption, liquidity depth, and potential risk. + +## How It Works + +### What TVL includes + +TVL generally counts the on-chain value held by a protocol’s smart contracts, such as: + +- Liquidity in AMM pools (e.g., token A + token B reserves) +- Collateral deposited into lending protocols +- Assets deposited into yield vaults/strategies +- Some forms of staking or restaking (depends on methodology) + +TVL is usually reported in a common unit (often USD) by taking the on-chain balances and multiplying by current market prices. + +### A simplified formula + +At a high level: + +- **TVL (USD)** = Σ (token_balance_in_contract × token_price_USD) + +For example, if a protocol holds: + +- 1,000,000 USDC and +- 500 ETH at $2,000/ETH + +Then TVL ≈ $1,000,000 + (500 × $2,000) = $2,000,000. + +### Why TVL moves + +TVL can change for multiple reasons: + +1. **Net deposits/withdrawals**: Users add or remove liquidity/collateral. +2. **Price changes**: Token prices rise/fall, changing USD-denominated TVL even if token balances remain constant. +3. **Incentives and migrations**: Emissions, points, or better yields can pull liquidity across protocols. +4. **Security incidents**: Exploits can reduce TVL quickly due to losses or withdrawals. + +### TVL vs related metrics + +- **TVL** measures capital committed, not necessarily activity. +- **Volume** measures trading activity (e.g., DEX volume), not how much liquidity is parked. +- **Market cap** measures token supply value, not how much is deposited in protocols. +- **Liquidity** is often a component of TVL (especially in AMMs) but can also be reported as “available liquidity” or “depth.” + +### Limitations and common pitfalls + +TVL is useful, but it can be misleading if taken alone: + +- **Double counting**: The same asset may be counted multiple times if it’s re-deposited into layered protocols (e.g., LP token deposited into a vault). +- **Price volatility**: USD TVL can spike or crash due to price moves rather than user behavior. +- **Inconsistent definitions**: Some dashboards include staking, bridged assets, or borrowed assets differently. +- **Quality matters**: High TVL doesn’t automatically mean a protocol is safe, sustainable, or efficient. + +## Why TVL Matters + +TVL is widely used because it helps evaluate: + +- **Liquidity and slippage**: Higher TVL in AMMs often implies better liquidity and lower price impact for trades. +- **Protocol adoption**: Rising TVL may indicate growing user confidence and participation. +- **Capital efficiency**: Comparing TVL to fees/revenue can suggest whether a protocol is generating meaningful returns per dollar locked. +- **Composability and ecosystem health**: TVL concentration across apps can signal where liquidity and activity are clustered. +- **Risk exposure**: TVL reflects how much value is at risk in smart contracts; higher TVL can make protocols bigger targets and raise the stakes of security. + +## On Sei Network + +On Sei, TVL reflects the value deposited into **Sei-native applications** (including EVM smart contracts on Sei) such as DEXs, lending markets, and vaults. Because Sei is designed for high throughput with **parallelized execution** and **~400ms finality**, TVL can be especially meaningful for liquidity-driven use cases where fast confirmations and responsive trading experiences attract and retain capital. + +Key implications for TVL on Sei: + +- **Better user experience can support stickier liquidity**: Fast finality and performant execution can reduce friction for LPs and traders, which may positively influence TVL over time. +- **Parallelization can help protocols scale with demand**: As usage grows, Sei’s architecture helps mitigate bottlenecks that can make depositing, withdrawing, rebalancing, or trading costly and slow on other networks—factors that often impact TVL retention. +- **EVM compatibility broadens protocol and asset support**: Sei’s EVM environment enables Solidity-based apps and tooling, potentially accelerating deployment and liquidity onboarding, which can contribute to TVL growth. + +When evaluating TVL on Sei (or any chain), consider pairing it with chain- and app-level metrics such as: + +- DEX trading volume and fees +- Active users/wallet interactions +- Borrow utilization and interest rates (for lending) +- TVL composition (stablecoins vs volatile assets) +- Security posture (audits, bug bounties, risk monitoring) + +## How TVL is Queried (Example) + +If you want to compute TVL for a simple AMM pool or vault, you typically: + +1. Read token balances from the protocol contracts. +2. Convert balances to a common unit using price oracles or off-chain pricing. +3. Sum the values. + +### Solidity (read ERC-20 balances) + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +interface IERC20 { + function balanceOf(address account) external view returns (uint256); + function decimals() external view returns (uint8); +} + +contract TVLHelper { + function tokenBalance(address token, address protocolContract) + external + view + returns (uint256) + { + return IERC20(token).balanceOf(protocolContract); + } +} +``` + +### TypeScript (query balances with ethers) + +```typescript +import { ethers } from 'ethers'; + +const ERC20_ABI = ['function balanceOf(address) view returns (uint256)', 'function decimals() view returns (uint8)']; + +export async function getTokenBalance(rpcUrl: string, token: string, holder: string) { + const provider = new ethers.JsonRpcProvider(rpcUrl); + const erc20 = new ethers.Contract(token, ERC20_ABI, provider); + + const [bal, dec] = await Promise.all([erc20.balanceOf(holder), erc20.decimals()]); + + return Number(ethers.formatUnits(bal, dec)); +} +``` + +> Note: To turn balances into USD TVL, you’ll also need a pricing source (on-chain oracle or off-chain price feed) and a methodology that avoids double counting. + +## Summary + +**What is TVL?** TVL is the total value of assets deposited into a protocol’s smart contracts, commonly used to gauge liquidity, adoption, and capital commitment in DeFi. It matters because it influences trading conditions, reflects ecosystem confidence, and helps compare protocols—especially when combined with activity and risk metrics. On **Sei Network**, TVL is supported by Sei’s **parallelized execution**, **~400ms finality**, and **EVM compatibility**, which can improve user experience and scalability for liquidity-intensive applications. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/content/answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx b/content/answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx new file mode 100644 index 00000000..0e90c0b7 --- /dev/null +++ b/content/answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx @@ -0,0 +1,248 @@ +--- +title: 'What is Yield Farming in Crypto and How Does It Work?' +description: 'Learn about what is yield farming and how it works in blockchain and on Sei Network.' +keywords: ['sei', 'blockchain', 'glossary', 'what', 'yield', 'farming', 'crypto', 'and', 'how', 'does', 'work'] +--- + +import { Callout } from 'nextra/components'; + +# What is Yield Farming in Crypto and How Does It Work? + +## Overview + +Yield farming is a DeFi strategy where users deposit crypto assets into smart contract protocols to earn returns, typically paid as interest, fees, and/or newly minted incentive tokens. In practice, it’s a way to “put your crypto to work” by supplying liquidity or lending assets in exchange for ongoing rewards. + +When people search **what is yield farming**, they’re usually referring to earning variable, protocol-driven yields by providing capital to decentralized markets (DEXs, lending markets, derivatives, or vaults). + +## How It Works + +### 1) You deposit assets into a protocol + +Yield farming generally starts with depositing tokens into a smart contract: + +- **Lending markets:** Deposit USDC/ETH, earn interest from borrowers. +- **DEX liquidity pools:** Deposit a pair (e.g., USDC/SEI) to facilitate trading, earn swap fees. +- **Vaults/strategies:** Deposit into an aggregator that auto-compounds rewards and rebalances. + +In return you receive a **receipt token** (often called LP tokens, aTokens, cTokens, vault shares) representing your claim on the pool plus earned yield. + +### 2) The protocol generates yield from one or more sources + +Common yield sources include: + +- **Trading fees:** DEX users pay fees; liquidity providers receive a share. +- **Borrow interest:** Borrowers pay interest; lenders receive it. +- **Incentives (liquidity mining):** Protocols distribute governance/reward tokens to attract liquidity. +- **MEV/strategy yield (vaults):** Some vaults capture additional returns via automated strategies (varies by design). + +Yields are often advertised as: + +- **APR (Annual Percentage Rate):** Simple annualized rate (no compounding assumed). +- **APY (Annual Percentage Yield):** Includes compounding effects (auto-compounding vaults often quote APY). + +### 3) Rewards accrue over time and can be claimed/compounded + +Depending on the protocol, rewards may: + +- Accrue continuously and be claimable anytime +- Be distributed per block/epoch +- Auto-compound back into the position (vaults) + +### 4) You can “stack” strategies (composability) + +DeFi is composable: users can layer strategies to increase yields, e.g.: + +1. Provide liquidity to a DEX (earn fees + incentives) +2. Stake the LP token in a farm (earn additional incentives) +3. Use a vault to auto-compound (improve effective APY) + +This stacking can amplify returns—but also risk. + +### 5) Key risks in yield farming + +Yield farming returns are not guaranteed. Key risks include: + +- **Smart contract risk:** Bugs/exploits can lead to loss of funds. +- **Impermanent loss (IL):** Providing liquidity to volatile pairs can underperform holding the tokens outright. +- **Liquidation risk:** If leverage is used (borrow against collateral), price moves can trigger liquidation. +- **Token incentive risk:** Rewards paid in volatile tokens can drop in value. +- **Oracle/bridge risk:** Cross-chain assets and price feeds can fail or be attacked. +- **Governance risk:** Protocol parameters can change, impacting yield. + +## On Sei Network + +Sei Network is a high-performance Layer 1 with **EVM compatibility**, designed for low-latency trading and DeFi. Yield farming on Sei follows the same DeFi fundamentals (liquidity provision, lending, staking LP/vault shares), but benefits from Sei’s network characteristics: + +- **Fast finality (~400ms):** Positions can be entered/exited and rewards compounded with minimal settlement delay—useful for active liquidity management and vault strategies. +- **Parallelization:** High throughput and parallel transaction execution can improve user experience during demand spikes, reducing congestion for common DeFi interactions (swaps, adds/removes liquidity, claims). +- **EVM compatibility:** Many familiar Ethereum-style DeFi primitives (ERC-20 tokens, AMMs, staking/farming contracts, vault patterns) can be deployed and used with standard tooling. + +Typical yield farming flows on Sei include: + +- **AMM liquidity pools** (earn swap fees and incentives) +- **Staking LP tokens** in farming contracts (earn additional token emissions) +- **Lending/borrowing markets** (earn interest on supplied assets; optional looping strategies increase yield at higher risk) +- **Vaults/auto-compounders** (optimize harvesting and compounding frequency, potentially improving net APY after costs) + +## Example: Yield Farming Pattern (Solidity) + +Below is a simplified example of a “farm” contract where users stake an LP token and earn a reward token over time. This pattern is common across EVM chains, including Sei’s EVM environment. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; + +contract SimpleFarm { + using SafeERC20 for IERC20; + + IERC20 public immutable lpToken; + IERC20 public immutable rewardToken; + + uint256 public rewardRatePerSecond; // rewards emitted per second + uint256 public lastUpdate; + uint256 public accRewardPerShare; // scaled by 1e12 + uint256 public totalStaked; + + mapping(address => uint256) public staked; + mapping(address => uint256) public rewardDebt; + + constructor(IERC20 _lpToken, IERC20 _rewardToken, uint256 _rate) { + lpToken = _lpToken; + rewardToken = _rewardToken; + rewardRatePerSecond = _rate; + lastUpdate = block.timestamp; + } + + function _updatePool() internal { + if (block.timestamp <= lastUpdate) return; + if (totalStaked == 0) { + lastUpdate = block.timestamp; + return; + } + uint256 dt = block.timestamp - lastUpdate; + uint256 rewards = dt * rewardRatePerSecond; + accRewardPerShare += (rewards * 1e12) / totalStaked; + lastUpdate = block.timestamp; + } + + function pendingRewards(address user) external view returns (uint256) { + uint256 _acc = accRewardPerShare; + if (block.timestamp > lastUpdate && totalStaked != 0) { + uint256 dt = block.timestamp - lastUpdate; + uint256 rewards = dt * rewardRatePerSecond; + _acc += (rewards * 1e12) / totalStaked; + } + return (staked[user] * _acc) / 1e12 - rewardDebt[user]; + } + + function deposit(uint256 amount) external { + _updatePool(); + _harvest(msg.sender); + + lpToken.safeTransferFrom(msg.sender, address(this), amount); + staked[msg.sender] += amount; + totalStaked += amount; + + rewardDebt[msg.sender] = (staked[msg.sender] * accRewardPerShare) / 1e12; + } + + function withdraw(uint256 amount) external { + _updatePool(); + _harvest(msg.sender); + + staked[msg.sender] -= amount; + totalStaked -= amount; + lpToken.safeTransfer(msg.sender, amount); + + rewardDebt[msg.sender] = (staked[msg.sender] * accRewardPerShare) / 1e12; + } + + function harvest() external { + _updatePool(); + _harvest(msg.sender); + rewardDebt[msg.sender] = (staked[msg.sender] * accRewardPerShare) / 1e12; + } + + function _harvest(address user) internal { + uint256 accumulated = (staked[user] * accRewardPerShare) / 1e12; + uint256 pending = accumulated - rewardDebt[user]; + if (pending > 0) { + rewardToken.safeTransfer(user, pending); + } + } +} +``` + +## Example: Interacting with a Farm on Sei (TypeScript) + +Using `ethers` against Sei’s EVM RPC looks similar to Ethereum. + +```typescript +import { ethers } from 'ethers'; + +const RPC_URL = process.env.SEI_EVM_RPC!; +const PRIVATE_KEY = process.env.PRIVATE_KEY!; + +const provider = new ethers.JsonRpcProvider(RPC_URL); +const wallet = new ethers.Wallet(PRIVATE_KEY, provider); + +// Minimal ABI +const farmAbi = ['function deposit(uint256 amount) external', 'function withdraw(uint256 amount) external', 'function harvest() external', 'function pendingRewards(address user) view returns (uint256)']; + +const erc20Abi = ['function approve(address spender, uint256 amount) external returns (bool)', 'function decimals() view returns (uint8)']; + +async function main() { + const farmAddress = '0xFARM_CONTRACT_ADDRESS'; + const lpTokenAddress = '0xLP_TOKEN_ADDRESS'; + + const farm = new ethers.Contract(farmAddress, farmAbi, wallet); + const lp = new ethers.Contract(lpTokenAddress, erc20Abi, wallet); + + const decimals: number = await lp.decimals(); + const amount = ethers.parseUnits('1.0', decimals); + + // Approve LP token spending + const approveTx = await lp.approve(farmAddress, amount); + await approveTx.wait(); + + // Deposit into the farm + const depositTx = await farm.deposit(amount); + await depositTx.wait(); + + // Check pending rewards + const pending = await farm.pendingRewards(wallet.address); + console.log('Pending rewards:', pending.toString()); + + // Harvest rewards + const harvestTx = await farm.harvest(); + await harvestTx.wait(); +} + +main().catch(console.error); +``` + +## Practical Tips for Yield Farming + +- **Prefer audited, battle-tested protocols** and verify token contracts and pool addresses. +- **Understand IL** before providing liquidity to volatile pairs; stablecoin pairs often have lower IL. +- **Compare net yield**, not just headline APY—account for token volatility and any fees. +- **Start small** and monitor positions; yields and incentives can change quickly. +- **Use Sei’s fast finality** to rebalance/exit efficiently when market conditions shift, but avoid over-trading if fees and tax considerations (jurisdiction-dependent) apply. + +## Summary + +Yield farming is the practice of earning returns by supplying crypto to DeFi protocols, commonly through lending and providing DEX liquidity, with rewards coming from fees, interest, and incentive tokens. On Sei Network, yield farming uses familiar EVM-based DeFi patterns while benefiting from **parallelization** and **~400ms finality**, enabling smoother interactions and faster position management in high-activity markets. + +## Related Documentation + +- [Getting Started](/learn) +- [Token Standards](/learn/dev-token-standards) +- [Staking](/learn/general-staking) +- [Oracles](/learn/oracles) + +--- + +_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ diff --git a/package.json b/package.json index 01383da1..604fc3e6 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "lint-staged": "^15.5.2", "next-sitemap": "^4.2.3", "node-fetch": "^3.3.2", + "openai": "^6.15.0", "pagefind": "^1.3.0", "pino-pretty": "^13.0.0", "playwright": "^1.56.1", diff --git a/scripts/generate-answers.js b/scripts/generate-answers.js index d8f802ce..457c0dfb 100644 --- a/scripts/generate-answers.js +++ b/scripts/generate-answers.js @@ -3,35 +3,45 @@ * Generate SEO-friendly answer pages from seed questions. * * Usage: - * node scripts/generate-answers.js # Generate all missing answers + * node scripts/generate-answers.js # Generate all missing answers (reads from CSV) * node scripts/generate-answers.js --dry-run # Preview what would be generated * node scripts/generate-answers.js --force # Regenerate all answers * node scripts/generate-answers.js --id=deploy-smart-contract-sei # Generate specific answer - * node scripts/generate-answers.js --csv=path/to/file.csv # Generate from CSV + * node scripts/generate-answers.js --csv=path/to/file.csv # Generate from custom CSV * node scripts/generate-answers.js --import-csv=path/to/file.csv # Import CSV to seed-questions.json * node scripts/generate-answers.js --priority=high # Only high priority (MSV >= 1000) * node scripts/generate-answers.js --priority=medium # Medium+ priority (MSV >= 100) * node scripts/generate-answers.js --category=evm # Only specific category * node scripts/generate-answers.js --min-msv=500 # Custom MSV threshold * node scripts/generate-answers.js --limit=10 # Limit number of questions + * node scripts/generate-answers.js --concurrency=5 # Parallel requests (default: 5) * * Configuration: - * Set AI_PROVIDER env var to 'claude', 'gemini', 'groq', or 'manual' (default: manual) - * Set ANTHROPIC_API_KEY, GEMINI_API_KEY, or GROQ_API_KEY for AI generation + * Set AI_PROVIDER env var to 'gemini', 'openai', or 'claude' + * Auto-detects provider based on available API keys (prefers gemini as it's free) * - * The script reads questions from src/data/seed-questions.json and generates - * MDX files in content/answers/ that are: + * API Keys (set whichever you have): + * GEMINI_API_KEY - Google Gemini (FREE tier available - recommended) + * OPENAI_API_KEY - OpenAI/ChatGPT (paid) + * ANTHROPIC_API_KEY - Claude (paid) + * + * The script reads questions from content/answers/pseocontent.csv by default + * (falls back to src/data/seed-questions.json) and generates MDX files in + * content/answers/ that are: * - Hidden from navigation (via _meta.js) * - Accessible via direct URL * - Included in sitemap for SEO + * - Sorted by MSV (Monthly Search Volume) for priority ordering */ const fs = require('fs'); const path = require('path'); +const OpenAI = require('openai'); const SEED_QUESTIONS_PATH = path.join(__dirname, '../src/data/seed-questions.json'); const ANSWERS_DIR = path.join(__dirname, '../content/answers'); -const CONTENT_DIR = path.join(__dirname, '../content'); +const DEFAULT_CSV_PATH = path.join(__dirname, '../content/answers/pseocontent.csv'); +const DEFAULT_CONCURRENCY = 5; // Category to related docs mapping for "Learn more" links const CATEGORY_DOCS = { @@ -195,57 +205,6 @@ function csvToQuestions(rows) { }); } -/** - * Generate MDX content for a question (manual/placeholder mode) - */ -function generateManualMDX(question) { - const { id, question: q, category, keyword } = question; - const relatedDocs = CATEGORY_DOCS[category] || CATEGORY_DOCS.glossary; - const slug = id || slugify(q); - - // Build keywords array - const keywordParts = keyword ? keyword.split(' ').filter((k) => k.length > 2) : []; - const slugParts = slug.split('-').filter((k) => k.length > 2); - const allKeywords = ['sei', 'blockchain', category, ...new Set([...keywordParts, ...slugParts])]; - - const relatedLinks = relatedDocs.map((doc) => `- [${doc.title}](${doc.href})`).join('\n'); - - return `--- -title: '${q.replace(/'/g, "\\'")}' -description: 'Learn about ${keyword || q.replace(/'/g, "\\'")} and how it works in blockchain and on Sei Network.' -keywords: [${allKeywords.map((k) => `'${k}'`).join(', ')}] ---- - -import { Callout } from 'nextra/components'; - -# ${q} - - -This guide explains ${keyword || 'this concept'} in the context of blockchain technology and Sei Network. - - -{/* TODO: Add comprehensive answer here */} - -## Overview - -_This content is being prepared. Please check the related documentation below._ - -## How It Works on Sei - -Sei is a high-performance Layer 1 blockchain with EVM compatibility. Here's how ${keyword || 'this concept'} applies to Sei: - -_Content coming soon._ - -## Related Documentation - -${relatedLinks} - ---- - -_Have a question that's not answered here? Join our [Discord](https://discord.gg/sei) community._ -`; -} - /** * Generate answer using Gemini API (free tier) */ @@ -269,40 +228,53 @@ Guidelines: - Do NOT include the question as a heading (it will be added separately) - Format the response as markdown content (not full MDX) -Respond with ONLY the markdown content for the answer body.`; +Respond with ONLY the markdown content for the answer body. + +IMPORTANT: DO NOT OMIT CONTENTS TO BE ADDED LATER. ADD EVERYTHING TO THE ANSWER.`; + + // Try models in order of preference (newest first) + const models = ['gemini-2.0-flash', 'gemini-1.5-flash-latest', 'gemini-1.5-flash']; + let lastError = null; + + for (const model of models) { + const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + contents: [{ parts: [{ text: prompt }] }], + generationConfig: { + temperature: 0.7, + maxOutputTokens: 2048 + } + }) + }); - const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - contents: [{ parts: [{ text: prompt }] }], - generationConfig: { - temperature: 0.7, - maxOutputTokens: 2048 - } - }) - }); + if (response.ok) { + const data = await response.json(); + return data.candidates?.[0]?.content?.parts?.[0]?.text || ''; + } - if (!response.ok) { - throw new Error(`Gemini API error: ${response.status} ${response.statusText}`); + // If 404, try next model + if (response.status === 404) { + lastError = `Model ${model} not found`; + continue; + } + + // For other errors, throw immediately + const errorText = await response.text(); + throw new Error(`Gemini API error: ${response.status} ${response.statusText} - ${errorText}`); } - const data = await response.json(); - return data.candidates?.[0]?.content?.parts?.[0]?.text || ''; + throw new Error(`Gemini API error: No available models. Last error: ${lastError}`); } /** - * Generate answer using Groq API (free tier) + * Generate answer using OpenAI API with flex service tier */ -async function generateWithGroq(question, apiKey) { +async function generateWithOpenAI(question, apiKey) { const { question: q, category, keyword } = question; - const prompt = `You are a technical documentation assistant for Sei Network, a high-performance Layer 1 blockchain with EVM compatibility. - -Generate a comprehensive, SEO-friendly answer for this question: "${q}" - -Target keyword: ${keyword || 'N/A'} -Category: ${category} + const instructions = `You are a technical documentation assistant for Sei Network, a high-performance Layer 1 blockchain with EVM compatibility. Guidelines: - Start with a clear, concise definition (2-3 sentences) @@ -316,26 +288,27 @@ Guidelines: Respond with ONLY the markdown content for the answer body.`; - const response = await fetch('https://api.groq.com/openai/v1/chat/completions', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${apiKey}` - }, - body: JSON.stringify({ - model: 'llama-3.1-70b-versatile', - messages: [{ role: 'user', content: prompt }], - temperature: 0.7, - max_tokens: 2048 - }) + const input = `Generate a comprehensive, SEO-friendly answer for this question: "${q}" + +Target keyword: ${keyword || 'N/A'} +Category: ${category}`; + + const client = new OpenAI({ + apiKey, + timeout: 15 * 1000 * 60 // 15 minutes timeout }); - if (!response.ok) { - throw new Error(`Groq API error: ${response.status} ${response.statusText}`); - } + const response = await client.responses.create( + { + model: 'gpt-5.2', + instructions, + input, + service_tier: 'flex' + }, + { timeout: 15 * 1000 * 60 } + ); - const data = await response.json(); - return data.choices?.[0]?.message?.content || ''; + return response.output_text || ''; } /** @@ -478,11 +451,24 @@ async function main() { const categoryFilter = args.find((a) => a.startsWith('--category='))?.split('=')[1]; const minMsv = parseInt(args.find((a) => a.startsWith('--min-msv='))?.split('=')[1] || '0', 10); const limit = parseInt(args.find((a) => a.startsWith('--limit='))?.split('=')[1] || '0', 10); + const concurrency = parseInt(args.find((a) => a.startsWith('--concurrency='))?.split('=')[1] || String(DEFAULT_CONCURRENCY), 10); - const provider = process.env.AI_PROVIDER || 'manual'; const claudeKey = process.env.ANTHROPIC_API_KEY; const geminiKey = process.env.GEMINI_API_KEY; - const groqKey = process.env.GROQ_API_KEY; + const openaiKey = process.env.OPENAI_API_KEY; + + // Auto-detect provider: prefer gemini (free), then check others + let provider = process.env.AI_PROVIDER; + if (!provider) { + if (geminiKey) provider = 'gemini'; + else if (openaiKey) provider = 'openai'; + else if (claudeKey) provider = 'claude'; + } + + if (!provider) { + console.error('❌ No AI provider configured. Set one of: GEMINI_API_KEY, OPENAI_API_KEY, or ANTHROPIC_API_KEY'); + process.exit(1); + } // Handle import-only mode if (importCsvPath) { @@ -492,10 +478,11 @@ async function main() { console.log(`\n📝 Answer Generator for Sei Docs`); console.log(` Provider: ${provider}`); + console.log(` Concurrency: ${concurrency}`); console.log(` Dry run: ${dryRun}`); console.log(` Force regenerate: ${force}`); + console.log(` Source: ${csvPath || 'content/answers/pseocontent.csv (default)'}`); if (specificId) console.log(` Specific ID: ${specificId}`); - if (csvPath) console.log(` CSV source: ${csvPath}`); if (priorityFilter) console.log(` Priority filter: ${priorityFilter}`); if (categoryFilter) console.log(` Category filter: ${categoryFilter}`); if (minMsv) console.log(` Min MSV: ${minMsv}`); @@ -512,16 +499,22 @@ async function main() { } } - // Load questions from CSV or JSON + // Load questions from CSV (default) or JSON fallback let questions; - if (csvPath) { - const content = fs.readFileSync(csvPath, 'utf8'); + const effectiveCsvPath = csvPath || DEFAULT_CSV_PATH; + + if (fs.existsSync(effectiveCsvPath)) { + const content = fs.readFileSync(effectiveCsvPath, 'utf8'); const rows = parseCSV(content); questions = csvToQuestions(rows); - console.log(`📄 Loaded ${questions.length} questions from CSV\n`); - } else { + console.log(`📄 Loaded ${questions.length} questions from CSV: ${effectiveCsvPath}\n`); + } else if (fs.existsSync(SEED_QUESTIONS_PATH)) { const seedData = JSON.parse(fs.readFileSync(SEED_QUESTIONS_PATH, 'utf8')); questions = seedData.questions; + console.log(`📄 Loaded ${questions.length} questions from JSON\n`); + } else { + console.error('❌ No question source found. Create content/answers/pseocontent.csv or src/data/seed-questions.json'); + process.exit(1); } // Apply filters @@ -566,34 +559,31 @@ async function main() { let skipped = 0; let failed = 0; - for (const question of questions) { + /** + * Process a single question - returns result object + */ + async function processQuestion(question) { const slug = question.id || slugify(question.question); const filePath = path.join(ANSWERS_DIR, `${slug}.mdx`); const exists = fs.existsSync(filePath); if (exists && !force) { console.log(`⏭️ Skipping (exists): ${slug}`); - skipped++; - continue; + return { status: 'skipped', slug }; } console.log(`📄 Generating: ${slug}`); try { - let content; - - if (provider === 'claude' && claudeKey) { - const aiContent = await generateWithClaude(question, claudeKey); - content = wrapInMDX(question, aiContent); - } else if (provider === 'gemini' && geminiKey) { - const aiContent = await generateWithGemini(question, geminiKey); - content = wrapInMDX(question, aiContent); - } else if (provider === 'groq' && groqKey) { - const aiContent = await generateWithGroq(question, groqKey); - content = wrapInMDX(question, aiContent); - } else { - content = generateManualMDX(question); + let aiContent; + if (provider === 'gemini') { + aiContent = await generateWithGemini(question, geminiKey); + } else if (provider === 'openai') { + aiContent = await generateWithOpenAI(question, openaiKey); + } else if (provider === 'claude') { + aiContent = await generateWithClaude(question, claudeKey); } + const content = wrapInMDX(question, aiContent); if (dryRun) { console.log(` Would write to: ${filePath}`); @@ -603,16 +593,42 @@ async function main() { console.log(` ✅ Written: ${filePath}`); } - generated++; + return { status: 'generated', slug }; + } catch (error) { + console.error(` ❌ Failed (${slug}): ${error.message}`); + return { status: 'failed', slug, error: error.message }; + } + } - // Rate limiting for API calls - if (provider !== 'manual') { - await new Promise((r) => setTimeout(r, 1000)); + /** + * Process questions in parallel batches with concurrency limit + */ + async function processInBatches(items, batchSize) { + const results = []; + for (let i = 0; i < items.length; i += batchSize) { + const batch = items.slice(i, i + batchSize); + const batchNum = Math.floor(i / batchSize) + 1; + const totalBatches = Math.ceil(items.length / batchSize); + console.log(`\n🔄 Processing batch ${batchNum}/${totalBatches} (${batch.length} items)...`); + + const batchResults = await Promise.all(batch.map(processQuestion)); + results.push(...batchResults); + + // Small delay between batches to avoid rate limiting + if (i + batchSize < items.length) { + await new Promise((r) => setTimeout(r, 500)); } - } catch (error) { - console.error(` ❌ Failed: ${error.message}`); - failed++; } + return results; + } + + const results = await processInBatches(questions, concurrency); + + // Tally results + for (const result of results) { + if (result.status === 'generated') generated++; + else if (result.status === 'skipped') skipped++; + else if (result.status === 'failed') failed++; } console.log(`\n📊 Summary:`); diff --git a/yarn.lock b/yarn.lock index cac44f8e..4a96a885 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6980,6 +6980,11 @@ oniguruma-to-es@^4.3.3: regex "^6.0.1" regex-recursion "^6.0.2" +openai@^6.15.0: + version "6.15.0" + resolved "https://registry.yarnpkg.com/openai/-/openai-6.15.0.tgz#94f23643a50206a6ae889e9df8fc3bfb2dbf2c2b" + integrity sha512-F1Lvs5BoVvmZtzkUEVyh8mDQPPFolq4F+xdsx/DO8Hee8YF3IGAlZqUIsF+DVGhqf4aU0a3bTghsxB6OIsRy1g== + ox@0.10.5: version "0.10.5" resolved "https://registry.yarnpkg.com/ox/-/ox-0.10.5.tgz#dbef388065011b0109a25ed60359ca04cdd56434" From aba934f20c679fed88681375128fe5f392b5b1ec Mon Sep 17 00:00:00 2001 From: alexander-sei Date: Fri, 9 Jan 2026 22:26:53 +0100 Subject: [PATCH 3/5] fix build --- next-env.d.ts | 2 +- scripts/generate-answers.js | 2 +- {content/answers => scripts}/pseocontent.csv | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename {content/answers => scripts}/pseocontent.csv (100%) diff --git a/next-env.d.ts b/next-env.d.ts index 20e7bcfb..1511519d 100644 --- a/next-env.d.ts +++ b/next-env.d.ts @@ -1,6 +1,6 @@ /// /// -import './.next/dev/types/routes.d.ts'; +import './.next/types/routes.d.ts'; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/scripts/generate-answers.js b/scripts/generate-answers.js index 457c0dfb..3f56df76 100644 --- a/scripts/generate-answers.js +++ b/scripts/generate-answers.js @@ -40,7 +40,7 @@ const OpenAI = require('openai'); const SEED_QUESTIONS_PATH = path.join(__dirname, '../src/data/seed-questions.json'); const ANSWERS_DIR = path.join(__dirname, '../content/answers'); -const DEFAULT_CSV_PATH = path.join(__dirname, '../content/answers/pseocontent.csv'); +const DEFAULT_CSV_PATH = path.join(__dirname, './pseocontent.csv'); const DEFAULT_CONCURRENCY = 5; // Category to related docs mapping for "Learn more" links diff --git a/content/answers/pseocontent.csv b/scripts/pseocontent.csv similarity index 100% rename from content/answers/pseocontent.csv rename to scripts/pseocontent.csv From 66a7cbdf6361079e4b4ba34f878b94ba3b7108ef Mon Sep 17 00:00:00 2001 From: alexander-sei Date: Fri, 9 Jan 2026 22:41:23 +0100 Subject: [PATCH 4/5] switch path and improve script --- content/{answers => ai-answers}/_meta.js | 2 +- ...-vs-sidechain-key-differences-explained.mdx | 0 .../what-are-airdrops-and-how-do-they-work.mdx | 0 ...hat-are-event-logs-and-how-do-they-work.mdx | 0 .../what-are-gas-fees-and-how-do-they-work.mdx | 0 ...re-staking-rewards-and-how-do-they-work.mdx | 0 ...what-are-zk-snarks-and-how-do-they-work.mdx | 0 ...s-a-block-explorer-and-how-does-it-work.mdx | 0 ...-is-a-block-height-and-how-does-it-work.mdx | 0 ...-is-a-block-reward-and-how-does-it-work.mdx | 0 ...at-is-a-block-time-and-how-does-it-work.mdx | 0 ...s-a-burn-mechanism-and-how-does-it-work.mdx | 0 ...t-is-a-chain-reorg-and-how-does-it-work.mdx | 0 ...t-is-a-cold-wallet-and-how-does-it-work.mdx | 0 ...is-a-composability-and-how-does-it-work.mdx | 0 ...onsensus-mechanism-and-how-does-it-work.mdx | 0 ...cross-chain-bridge-and-how-does-it-work.mdx | 0 ...is-a-crypto-oracle-and-how-does-it-work.mdx | 0 ...a-custodial-wallet-and-how-does-it-work.mdx | 0 .../what-is-a-daos-and-how-does-it-work.mdx | 0 ...at-is-a-flash-loan-and-how-does-it-work.mdx | 0 ...a-gas-optimization-and-how-does-it-work.mdx | 0 .../what-is-a-gas-war-and-how-does-it-work.mdx | 0 ...is-a-genesis-block-and-how-does-it-work.mdx | 0 ...overnance-proposal-and-how-does-it-work.mdx | 0 ...a-governance-token-and-how-does-it-work.mdx | 0 ...hat-is-a-hard-fork-and-how-does-it-work.mdx | 0 ...hat-is-a-hash-rate-and-how-does-it-work.mdx | 0 ...at-is-a-hot-wallet-and-how-does-it-work.mdx | 0 ...layer-1-blockchain-and-how-does-it-work.mdx | 0 ...a-layer-2-solution-and-how-does-it-work.mdx | 0 ...-is-a-light-client-and-how-does-it-work.mdx | 0 ...s-a-liquidity-pool-and-how-does-it-work.mdx | 0 .../what-is-a-lsdfi-and-how-does-it-work.mdx | 0 .../what-is-a-mainnet-and-how-does-it-work.mdx | 0 ...a-multi-sig-wallet-and-how-does-it-work.mdx | 0 ...n-custodial-wallet-and-how-does-it-work.mdx | 0 ...-is-a-rebase-token-and-how-does-it-work.mdx | 0 .../what-is-a-rollup-and-how-does-it-work.mdx | 0 ...what-is-a-rug-pull-and-how-does-it-work.mdx | 0 ...hat-is-a-sidechain-and-how-does-it-work.mdx | 0 ...what-is-a-slippage-and-how-does-it-work.mdx | 0 ...s-a-smart-contract-and-how-does-it-work.mdx | 0 ...art-contract-audit-and-how-does-it-work.mdx | 0 ...act-upgradeability-and-how-does-it-work.mdx | 0 ...hat-is-a-soft-fork-and-how-does-it-work.mdx | 0 ...at-is-a-stablecoin-and-how-does-it-work.mdx | 0 .../what-is-a-testnet-and-how-does-it-work.mdx | 0 ...at-is-a-token-burn-and-how-does-it-work.mdx | 0 ...at-is-a-tokenomics-and-how-does-it-work.mdx | 0 ...a-trustless-bridge-and-how-does-it-work.mdx | 0 ...hat-is-a-validator-and-how-does-it-work.mdx | 0 ...lidator-commission-and-how-does-it-work.mdx | 0 ...is-a-validator-set-and-how-does-it-work.mdx | 0 .../what-is-a-wallet-and-how-does-it-work.mdx | 0 .../what-is-a-whale-and-how-does-it-work.mdx | 0 ...is-a-wrapped-token-and-how-does-it-work.mdx | 0 ...ro-knowledge-proof-and-how-does-it-work.mdx | 0 ...-is-an-atomic-swap-and-how-does-it-work.mdx | 0 .../what-is-an-evm-and-how-does-it-work.mdx | 0 ...n-impermanent-loss-and-how-does-it-work.mdx | 0 ...nterchain-security-and-how-does-it-work.mdx | 0 ...n-interoperability-and-how-does-it-work.mdx | 0 .../what-is-an-nft-and-how-does-it-work.mdx | 0 ...what-is-an-oracles-and-how-does-it-work.mdx | 0 ...what-is-blockchain-and-how-does-it-work.mdx | 0 .../what-is-defi-and-how-does-it-work.mdx | 0 ...-staking-in-crypto-and-how-does-it-work.mdx | 0 ...-running-in-crypto-and-how-does-it-work.mdx | 0 ...-staking-in-crypto-and-how-does-it-work.mdx | 0 .../what-is-mev-and-why-it-matters.mdx | 0 ...-minting-in-crypto-and-how-does-it-work.mdx | 0 ...y-and-how-does-it-secure-the-blockchain.mdx | 0 ...e-and-how-does-it-secure-the-blockchain.mdx | 0 ...k-and-how-does-it-secure-the-blockchain.mdx | 0 ...sharding-in-crypto-and-how-does-it-work.mdx | 0 ...slashing-in-crypto-and-how-does-it-work.mdx | 0 ...king-in-blockchain-and-how-does-it-work.mdx | 0 ...s-the-ibc-protocol-and-how-does-it-work.mdx | 0 .../what-is-tvl-and-why-it-matters.mdx | 0 ...-farming-in-crypto-and-how-does-it-work.mdx | 0 scripts/generate-answers.js | 18 +++++------------- 82 files changed, 6 insertions(+), 14 deletions(-) rename content/{answers => ai-answers}/_meta.js (86%) rename content/{answers => ai-answers}/rollup-vs-sidechain-key-differences-explained.mdx (100%) rename content/{answers => ai-answers}/what-are-airdrops-and-how-do-they-work.mdx (100%) rename content/{answers => ai-answers}/what-are-event-logs-and-how-do-they-work.mdx (100%) rename content/{answers => ai-answers}/what-are-gas-fees-and-how-do-they-work.mdx (100%) rename content/{answers => ai-answers}/what-are-staking-rewards-and-how-do-they-work.mdx (100%) rename content/{answers => ai-answers}/what-are-zk-snarks-and-how-do-they-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-block-explorer-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-block-height-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-block-reward-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-block-time-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-burn-mechanism-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-chain-reorg-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-cold-wallet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-composability-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-consensus-mechanism-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-crypto-oracle-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-custodial-wallet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-daos-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-flash-loan-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-gas-optimization-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-gas-war-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-genesis-block-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-governance-proposal-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-governance-token-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-hard-fork-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-hash-rate-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-hot-wallet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-layer-2-solution-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-light-client-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-liquidity-pool-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-lsdfi-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-mainnet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-rebase-token-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-rollup-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-rug-pull-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-sidechain-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-slippage-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-smart-contract-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-smart-contract-audit-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-soft-fork-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-stablecoin-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-testnet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-token-burn-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-tokenomics-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-trustless-bridge-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-validator-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-validator-commission-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-validator-set-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-wallet-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-whale-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-wrapped-token-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-atomic-swap-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-evm-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-impermanent-loss-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-interchain-security-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-interoperability-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-nft-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-an-oracles-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-blockchain-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-defi-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-front-running-in-crypto-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-mev-and-why-it-matters.mdx (100%) rename content/{answers => ai-answers}/what-is-minting-in-crypto-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx (100%) rename content/{answers => ai-answers}/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx (100%) rename content/{answers => ai-answers}/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx (100%) rename content/{answers => ai-answers}/what-is-sharding-in-crypto-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-slashing-in-crypto-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-staking-in-blockchain-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-the-ibc-protocol-and-how-does-it-work.mdx (100%) rename content/{answers => ai-answers}/what-is-tvl-and-why-it-matters.mdx (100%) rename content/{answers => ai-answers}/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx (100%) diff --git a/content/answers/_meta.js b/content/ai-answers/_meta.js similarity index 86% rename from content/answers/_meta.js rename to content/ai-answers/_meta.js index 5439127a..cd8e7333 100644 --- a/content/answers/_meta.js +++ b/content/ai-answers/_meta.js @@ -2,7 +2,7 @@ export default { '*': { display: 'hidden', theme: { - sidebar: false, + sidebar: true, toc: true, breadcrumb: false, pagination: false diff --git a/content/answers/rollup-vs-sidechain-key-differences-explained.mdx b/content/ai-answers/rollup-vs-sidechain-key-differences-explained.mdx similarity index 100% rename from content/answers/rollup-vs-sidechain-key-differences-explained.mdx rename to content/ai-answers/rollup-vs-sidechain-key-differences-explained.mdx diff --git a/content/answers/what-are-airdrops-and-how-do-they-work.mdx b/content/ai-answers/what-are-airdrops-and-how-do-they-work.mdx similarity index 100% rename from content/answers/what-are-airdrops-and-how-do-they-work.mdx rename to content/ai-answers/what-are-airdrops-and-how-do-they-work.mdx diff --git a/content/answers/what-are-event-logs-and-how-do-they-work.mdx b/content/ai-answers/what-are-event-logs-and-how-do-they-work.mdx similarity index 100% rename from content/answers/what-are-event-logs-and-how-do-they-work.mdx rename to content/ai-answers/what-are-event-logs-and-how-do-they-work.mdx diff --git a/content/answers/what-are-gas-fees-and-how-do-they-work.mdx b/content/ai-answers/what-are-gas-fees-and-how-do-they-work.mdx similarity index 100% rename from content/answers/what-are-gas-fees-and-how-do-they-work.mdx rename to content/ai-answers/what-are-gas-fees-and-how-do-they-work.mdx diff --git a/content/answers/what-are-staking-rewards-and-how-do-they-work.mdx b/content/ai-answers/what-are-staking-rewards-and-how-do-they-work.mdx similarity index 100% rename from content/answers/what-are-staking-rewards-and-how-do-they-work.mdx rename to content/ai-answers/what-are-staking-rewards-and-how-do-they-work.mdx diff --git a/content/answers/what-are-zk-snarks-and-how-do-they-work.mdx b/content/ai-answers/what-are-zk-snarks-and-how-do-they-work.mdx similarity index 100% rename from content/answers/what-are-zk-snarks-and-how-do-they-work.mdx rename to content/ai-answers/what-are-zk-snarks-and-how-do-they-work.mdx diff --git a/content/answers/what-is-a-block-explorer-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-block-explorer-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-block-explorer-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-block-explorer-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-block-height-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-block-height-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-block-height-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-block-height-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-block-reward-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-block-reward-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-block-reward-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-block-reward-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-block-time-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-block-time-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-block-time-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-block-time-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-burn-mechanism-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-chain-reorg-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-chain-reorg-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-chain-reorg-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-chain-reorg-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-cold-wallet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-cold-wallet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-cold-wallet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-cold-wallet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-composability-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-composability-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-composability-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-composability-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-consensus-mechanism-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-cross-chain-bridge-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-crypto-oracle-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-custodial-wallet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-daos-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-daos-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-daos-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-daos-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-flash-loan-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-flash-loan-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-flash-loan-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-flash-loan-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-gas-optimization-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-gas-optimization-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-gas-optimization-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-gas-optimization-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-gas-war-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-gas-war-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-gas-war-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-gas-war-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-genesis-block-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-genesis-block-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-genesis-block-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-genesis-block-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-governance-proposal-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-governance-proposal-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-governance-proposal-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-governance-proposal-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-governance-token-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-governance-token-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-governance-token-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-governance-token-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-hard-fork-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-hard-fork-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-hard-fork-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-hard-fork-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-hash-rate-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-hash-rate-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-hash-rate-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-hash-rate-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-hot-wallet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-hot-wallet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-hot-wallet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-hot-wallet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-layer-1-blockchain-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-layer-2-solution-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-light-client-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-light-client-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-light-client-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-light-client-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-liquidity-pool-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-lsdfi-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-lsdfi-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-lsdfi-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-lsdfi-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-mainnet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-mainnet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-mainnet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-mainnet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-multi-sig-wallet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-non-custodial-wallet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-rebase-token-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-rebase-token-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-rebase-token-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-rebase-token-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-rollup-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-rollup-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-rollup-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-rollup-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-rug-pull-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-rug-pull-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-rug-pull-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-rug-pull-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-sidechain-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-sidechain-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-sidechain-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-sidechain-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-slippage-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-slippage-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-slippage-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-slippage-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-smart-contract-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-smart-contract-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-smart-contract-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-smart-contract-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-smart-contract-audit-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-smart-contract-upgradeability-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-soft-fork-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-soft-fork-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-soft-fork-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-soft-fork-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-stablecoin-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-stablecoin-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-stablecoin-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-stablecoin-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-testnet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-testnet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-testnet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-testnet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-token-burn-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-token-burn-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-token-burn-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-token-burn-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-tokenomics-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-tokenomics-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-tokenomics-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-tokenomics-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-trustless-bridge-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-validator-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-validator-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-validator-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-validator-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-validator-commission-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-validator-commission-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-validator-commission-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-validator-commission-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-validator-set-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-validator-set-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-validator-set-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-validator-set-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-wallet-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-wallet-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-wallet-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-wallet-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-whale-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-whale-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-whale-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-whale-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-wrapped-token-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-wrapped-token-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-wrapped-token-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-wrapped-token-and-how-does-it-work.mdx diff --git a/content/answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx b/content/ai-answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx rename to content/ai-answers/what-is-a-zero-knowledge-proof-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-atomic-swap-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-atomic-swap-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-atomic-swap-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-atomic-swap-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-evm-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-evm-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-evm-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-evm-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-impermanent-loss-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-interchain-security-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-interchain-security-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-interchain-security-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-interchain-security-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-interoperability-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-interoperability-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-interoperability-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-interoperability-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-nft-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-nft-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-nft-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-nft-and-how-does-it-work.mdx diff --git a/content/answers/what-is-an-oracles-and-how-does-it-work.mdx b/content/ai-answers/what-is-an-oracles-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-an-oracles-and-how-does-it-work.mdx rename to content/ai-answers/what-is-an-oracles-and-how-does-it-work.mdx diff --git a/content/answers/what-is-blockchain-and-how-does-it-work.mdx b/content/ai-answers/what-is-blockchain-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-blockchain-and-how-does-it-work.mdx rename to content/ai-answers/what-is-blockchain-and-how-does-it-work.mdx diff --git a/content/answers/what-is-defi-and-how-does-it-work.mdx b/content/ai-answers/what-is-defi-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-defi-and-how-does-it-work.mdx rename to content/ai-answers/what-is-defi-and-how-does-it-work.mdx diff --git a/content/answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-delegated-staking-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-front-running-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-liquid-staking-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/what-is-mev-and-why-it-matters.mdx b/content/ai-answers/what-is-mev-and-why-it-matters.mdx similarity index 100% rename from content/answers/what-is-mev-and-why-it-matters.mdx rename to content/ai-answers/what-is-mev-and-why-it-matters.mdx diff --git a/content/answers/what-is-minting-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-minting-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-minting-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-minting-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx b/content/ai-answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx similarity index 100% rename from content/answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx rename to content/ai-answers/what-is-proof-of-history-and-how-does-it-secure-the-blockchain.mdx diff --git a/content/answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx b/content/ai-answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx similarity index 100% rename from content/answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx rename to content/ai-answers/what-is-proof-of-stake-and-how-does-it-secure-the-blockchain.mdx diff --git a/content/answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx b/content/ai-answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx similarity index 100% rename from content/answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx rename to content/ai-answers/what-is-proof-of-work-and-how-does-it-secure-the-blockchain.mdx diff --git a/content/answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-sharding-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-slashing-in-crypto-and-how-does-it-work.mdx diff --git a/content/answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx b/content/ai-answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx rename to content/ai-answers/what-is-staking-in-blockchain-and-how-does-it-work.mdx diff --git a/content/answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx b/content/ai-answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx rename to content/ai-answers/what-is-the-ibc-protocol-and-how-does-it-work.mdx diff --git a/content/answers/what-is-tvl-and-why-it-matters.mdx b/content/ai-answers/what-is-tvl-and-why-it-matters.mdx similarity index 100% rename from content/answers/what-is-tvl-and-why-it-matters.mdx rename to content/ai-answers/what-is-tvl-and-why-it-matters.mdx diff --git a/content/answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx b/content/ai-answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx similarity index 100% rename from content/answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx rename to content/ai-answers/what-is-yield-farming-in-crypto-and-how-does-it-work.mdx diff --git a/scripts/generate-answers.js b/scripts/generate-answers.js index 3f56df76..aade3912 100644 --- a/scripts/generate-answers.js +++ b/scripts/generate-answers.js @@ -25,9 +25,9 @@ * OPENAI_API_KEY - OpenAI/ChatGPT (paid) * ANTHROPIC_API_KEY - Claude (paid) * - * The script reads questions from content/answers/pseocontent.csv by default + * The script reads questions from scripts/pseocontent.csv by default * (falls back to src/data/seed-questions.json) and generates MDX files in - * content/answers/ that are: + * content/ai-answers/ that are: * - Hidden from navigation (via _meta.js) * - Accessible via direct URL * - Included in sitemap for SEO @@ -39,7 +39,7 @@ const path = require('path'); const OpenAI = require('openai'); const SEED_QUESTIONS_PATH = path.join(__dirname, '../src/data/seed-questions.json'); -const ANSWERS_DIR = path.join(__dirname, '../content/answers'); +const ANSWERS_DIR = path.join(__dirname, '../content/ai-answers'); const DEFAULT_CSV_PATH = path.join(__dirname, './pseocontent.csv'); const DEFAULT_CONCURRENCY = 5; @@ -60,10 +60,6 @@ const CATEGORY_DOCS = { { title: 'Node Operations', href: '/node' }, { title: 'Validators', href: '/node/validators' } ], - 'cosmos-sdk': [ - { title: 'Cosmos SDK', href: '/cosmos-sdk' }, - { title: 'Transactions', href: '/cosmos-sdk/transactions' } - ], glossary: [ { title: 'Getting Started', href: '/learn' }, { title: 'Token Standards', href: '/learn/dev-token-standards' }, @@ -86,10 +82,6 @@ const KEYWORD_CATEGORIES = { node: 'node', 'validator set': 'node', 'validator commission': 'node', - // Cosmos - ibc: 'cosmos-sdk', - cosmos: 'cosmos-sdk', - 'interchain security': 'cosmos-sdk', // Default to glossary for general blockchain terms default: 'glossary' }; @@ -481,7 +473,7 @@ async function main() { console.log(` Concurrency: ${concurrency}`); console.log(` Dry run: ${dryRun}`); console.log(` Force regenerate: ${force}`); - console.log(` Source: ${csvPath || 'content/answers/pseocontent.csv (default)'}`); + console.log(` Source: ${csvPath || 'scripts/pseocontent.csv (default)'}`); if (specificId) console.log(` Specific ID: ${specificId}`); if (priorityFilter) console.log(` Priority filter: ${priorityFilter}`); if (categoryFilter) console.log(` Category filter: ${categoryFilter}`); @@ -513,7 +505,7 @@ async function main() { questions = seedData.questions; console.log(`📄 Loaded ${questions.length} questions from JSON\n`); } else { - console.error('❌ No question source found. Create content/answers/pseocontent.csv or src/data/seed-questions.json'); + console.error('❌ No question source found. Create scripts/pseocontent.csv or src/data/seed-questions.json'); process.exit(1); } From d18004e4bfa184d6f5f909909fe404811ead897d Mon Sep 17 00:00:00 2001 From: alexander-sei Date: Sun, 11 Jan 2026 01:26:17 +0100 Subject: [PATCH 5/5] work in improvements --- content/_meta.js | 8 + content/ai-answers/_meta.js | 3 +- content/ai-answers/index.mdx | 13 + ...vs-sidechain-key-differences-explained.mdx | 212 +++++++----- ...what-are-airdrops-and-how-do-they-work.mdx | 197 ++++++----- ...at-are-event-logs-and-how-do-they-work.mdx | 225 ++++++++----- ...what-are-gas-fees-and-how-do-they-work.mdx | 190 ++++++----- ...e-staking-rewards-and-how-do-they-work.mdx | 181 +++++++--- ...hat-are-zk-snarks-and-how-do-they-work.mdx | 213 ++++++------ ...-a-block-explorer-and-how-does-it-work.mdx | 243 ++++++++------ ...is-a-block-height-and-how-does-it-work.mdx | 167 +++++---- ...is-a-block-reward-and-how-does-it-work.mdx | 171 ++++++---- ...t-is-a-block-time-and-how-does-it-work.mdx | 170 ++++++---- ...-a-burn-mechanism-and-how-does-it-work.mdx | 197 +++++++---- ...-is-a-chain-reorg-and-how-does-it-work.mdx | 214 ++++++------ ...-is-a-cold-wallet-and-how-does-it-work.mdx | 194 ++++++----- ...s-a-composability-and-how-does-it-work.mdx | 260 +++++++------- ...nsensus-mechanism-and-how-does-it-work.mdx | 163 ++++++--- ...ross-chain-bridge-and-how-does-it-work.mdx | 269 +++++++++------ ...s-a-crypto-oracle-and-how-does-it-work.mdx | 214 ++++++------ ...-custodial-wallet-and-how-does-it-work.mdx | 164 +++++---- .../what-is-a-daos-and-how-does-it-work.mdx | 231 ++++++++----- ...t-is-a-flash-loan-and-how-does-it-work.mdx | 202 +++++++---- ...-gas-optimization-and-how-does-it-work.mdx | 261 ++++++++------- ...what-is-a-gas-war-and-how-does-it-work.mdx | 203 +++++++---- ...s-a-genesis-block-and-how-does-it-work.mdx | 164 +++++---- ...vernance-proposal-and-how-does-it-work.mdx | 194 ++++++----- ...-governance-token-and-how-does-it-work.mdx | 267 +++++++++------ ...at-is-a-hard-fork-and-how-does-it-work.mdx | 162 ++++++--- ...at-is-a-hash-rate-and-how-does-it-work.mdx | 177 +++++++--- ...t-is-a-hot-wallet-and-how-does-it-work.mdx | 193 ++++++++--- ...ayer-1-blockchain-and-how-does-it-work.mdx | 198 ++++++----- ...-layer-2-solution-and-how-does-it-work.mdx | 180 +++++----- ...is-a-light-client-and-how-does-it-work.mdx | 221 ++++++------ ...-a-liquidity-pool-and-how-does-it-work.mdx | 209 ++++++++---- .../what-is-a-lsdfi-and-how-does-it-work.mdx | 209 +++++++----- ...what-is-a-mainnet-and-how-does-it-work.mdx | 198 +++++------ ...-multi-sig-wallet-and-how-does-it-work.mdx | 289 ++++++++++------ ...-custodial-wallet-and-how-does-it-work.mdx | 210 ++++++------ ...is-a-rebase-token-and-how-does-it-work.mdx | 238 +++++++------ .../what-is-a-rollup-and-how-does-it-work.mdx | 230 +++++++------ ...hat-is-a-rug-pull-and-how-does-it-work.mdx | 219 +++++++----- ...at-is-a-sidechain-and-how-does-it-work.mdx | 197 ++++++----- ...hat-is-a-slippage-and-how-does-it-work.mdx | 171 ++++++---- ...-a-smart-contract-and-how-does-it-work.mdx | 184 +++++----- ...rt-contract-audit-and-how-does-it-work.mdx | 316 ++++++++++-------- ...ct-upgradeability-and-how-does-it-work.mdx | 215 +++++++----- ...at-is-a-soft-fork-and-how-does-it-work.mdx | 175 ++++++---- ...t-is-a-stablecoin-and-how-does-it-work.mdx | 204 ++++++----- ...what-is-a-testnet-and-how-does-it-work.mdx | 204 +++++++---- ...t-is-a-token-burn-and-how-does-it-work.mdx | 192 ++++++----- ...t-is-a-tokenomics-and-how-does-it-work.mdx | 288 +++++++++------- ...-trustless-bridge-and-how-does-it-work.mdx | 219 +++++++----- ...at-is-a-validator-and-how-does-it-work.mdx | 201 ++++++----- ...idator-commission-and-how-does-it-work.mdx | 173 +++++----- ...s-a-validator-set-and-how-does-it-work.mdx | 176 +++++----- .../what-is-a-wallet-and-how-does-it-work.mdx | 190 +++++++---- .../what-is-a-whale-and-how-does-it-work.mdx | 237 +++++++------ ...s-a-wrapped-token-and-how-does-it-work.mdx | 163 +++++---- ...o-knowledge-proof-and-how-does-it-work.mdx | 211 ++++++------ ...is-an-atomic-swap-and-how-does-it-work.mdx | 204 ++++++----- .../what-is-an-evm-and-how-does-it-work.mdx | 206 ++++++------ ...-impermanent-loss-and-how-does-it-work.mdx | 226 ++++++++----- ...terchain-security-and-how-does-it-work.mdx | 182 ++++++---- ...-interoperability-and-how-does-it-work.mdx | 228 ++++++------- .../what-is-an-nft-and-how-does-it-work.mdx | 192 +++++++---- ...hat-is-an-oracles-and-how-does-it-work.mdx | 205 +++++++----- ...hat-is-blockchain-and-how-does-it-work.mdx | 184 ++++++---- .../what-is-defi-and-how-does-it-work.mdx | 218 ++++++++---- ...staking-in-crypto-and-how-does-it-work.mdx | 216 ++++++------ ...running-in-crypto-and-how-does-it-work.mdx | 251 ++++++++------ ...staking-in-crypto-and-how-does-it-work.mdx | 191 +++++++---- .../what-is-mev-and-why-it-matters.mdx | 197 ++++++----- ...minting-in-crypto-and-how-does-it-work.mdx | 244 +++++++------- ...-and-how-does-it-secure-the-blockchain.mdx | 159 ++++++--- ...-and-how-does-it-secure-the-blockchain.mdx | 174 ++++++---- ...-and-how-does-it-secure-the-blockchain.mdx | 172 +++++----- ...harding-in-crypto-and-how-does-it-work.mdx | 178 ++++++---- ...lashing-in-crypto-and-how-does-it-work.mdx | 164 +++++---- ...ing-in-blockchain-and-how-does-it-work.mdx | 194 ++++++----- ...-the-ibc-protocol-and-how-does-it-work.mdx | 207 +++++++----- .../what-is-tvl-and-why-it-matters.mdx | 217 ++++++------ ...farming-in-crypto-and-how-does-it-work.mdx | 301 ++++++++--------- scripts/generate-answers.js | 135 ++++++-- 84 files changed, 9904 insertions(+), 6780 deletions(-) create mode 100644 content/ai-answers/index.mdx diff --git a/content/_meta.js b/content/_meta.js index 3182add0..1aa15529 100644 --- a/content/_meta.js +++ b/content/_meta.js @@ -22,5 +22,13 @@ export default { node: { title: 'Operate', type: 'page' + }, + 'ai-answers': { + display: 'hidden', + type: 'page', + theme: { + sidebar: true, + toc: true + } } }; diff --git a/content/ai-answers/_meta.js b/content/ai-answers/_meta.js index cd8e7333..13b56543 100644 --- a/content/ai-answers/_meta.js +++ b/content/ai-answers/_meta.js @@ -1,8 +1,7 @@ export default { '*': { - display: 'hidden', theme: { - sidebar: true, + sidebar: false, toc: true, breadcrumb: false, pagination: false diff --git a/content/ai-answers/index.mdx b/content/ai-answers/index.mdx new file mode 100644 index 00000000..06ff2973 --- /dev/null +++ b/content/ai-answers/index.mdx @@ -0,0 +1,13 @@ +--- +title: 'Blockchain Glossary & Concepts' +description: 'AI-assisted explanations of blockchain concepts, DeFi terms, and crypto fundamentals for the Sei ecosystem.' +keywords: ['sei', 'blockchain', 'glossary', 'crypto', 'defi', 'concepts'] +--- + +import { Callout } from 'nextra/components'; + +# Blockchain Glossary & Concepts + + + This section contains AI-assisted explanations of common blockchain and crypto concepts. While we strive for accuracy, please verify information independently before making decisions. + diff --git a/content/ai-answers/rollup-vs-sidechain-key-differences-explained.mdx b/content/ai-answers/rollup-vs-sidechain-key-differences-explained.mdx index 8b73644a..3bd21e58 100644 --- a/content/ai-answers/rollup-vs-sidechain-key-differences-explained.mdx +++ b/content/ai-answers/rollup-vs-sidechain-key-differences-explained.mdx @@ -1,154 +1,196 @@ --- title: 'Rollup Vs Sidechain: Key Differences Explained' description: 'Learn about what is rollup vs sidechain and how it works in blockchain and on Sei Network.' -keywords: ['sei', 'blockchain', 'glossary', 'what', 'rollup', 'sidechain', 'key', 'differences', 'explained'] +keywords: ['sei', 'blockchain', 'glossary', 'what', 'rollup', 'sidechain', 'differences', 'explained'] --- import { Callout } from 'nextra/components'; -# Rollup Vs Sidechain: Key Differences Explained +export const jsonLd = { + '@context': 'https://schema.org', + '@graph': [ + { + '@type': 'FAQPage', + mainEntity: [ + { + '@type': 'Question', + name: 'Rollup Vs Sidechain: Key Differences Explained', + acceptedAnswer: { + '@type': 'Answer', + text: 'Rollups and sidechains are scaling approaches that move transaction execution off a main chain to improve throughput and lower fees, but they differ fundamentally in how they inherit security. Rollups post transaction data (or proofs) to a base layer and rely on that layer for settlement and, largely, security. Sidechains are separate blockchains with their own consensus that connect to a main chain via a bridge, so their security depends on the sidechain validator set and bridge design.' + } + } + ] + }, + { + '@type': 'TechArticle', + headline: 'Rollup Vs Sidechain: Key Differences Explained', + description: 'Learn about what is rollup vs sidechain and how it works in blockchain and on Sei Network.', + author: { + '@type': 'Organization', + name: 'Sei Network', + url: 'https://sei.io' + }, + publisher: { + '@type': 'Organization', + name: 'Sei Network', + url: 'https://sei.io' + }, + about: { + '@type': 'Thing', + name: 'what is rollup vs sidechain' + }, + articleSection: 'glossary', + inLanguage: 'en' + } + ] +}; -## Overview + +