From cf3dc69b9a02127e7a8c6bc87b907b88f2458aa1 Mon Sep 17 00:00:00 2001 From: enitrat Date: Thu, 9 Oct 2025 11:48:35 +0200 Subject: [PATCH] feat: embeddings for 2025 starknet blog --- ingesters/__tests__/IngesterFactory.test.ts | 1 + ingesters/src/IngesterFactory.ts | 4 + .../src/ingesters/StarknetBlogIngester.ts | 153 + ingesters/src/types/index.ts | 1 + .../results/optimized_mcp_program.json | 4 +- python/optimizers/results/optimized_rag.json | 4 +- .../results/optimized_retrieval_program.json | 4 +- python/src/cairo_coder/core/types.py | 1 + .../src/cairo_coder/dspy/query_processor.py | 1 + python/src/scripts/docs_crawler.py | 14 +- python/src/scripts/filter_2025_blogs.py | 147 + .../scripts/summarizer/doc_dump_summarizer.py | 30 +- .../summarizer/generated/blog_summary.md | 4450 +++++++++++++++++ 13 files changed, 4796 insertions(+), 18 deletions(-) create mode 100644 ingesters/src/ingesters/StarknetBlogIngester.ts create mode 100644 python/src/scripts/filter_2025_blogs.py create mode 100644 python/src/scripts/summarizer/generated/blog_summary.md diff --git a/ingesters/__tests__/IngesterFactory.test.ts b/ingesters/__tests__/IngesterFactory.test.ts index 0f5b7dd..41ea1c9 100644 --- a/ingesters/__tests__/IngesterFactory.test.ts +++ b/ingesters/__tests__/IngesterFactory.test.ts @@ -75,6 +75,7 @@ describe('IngesterFactory', () => { DocumentSource.CORELIB_DOCS, DocumentSource.SCARB_DOCS, DocumentSource.STARKNET_JS, + DocumentSource.STARKNET_BLOG, ]); }); }); diff --git a/ingesters/src/IngesterFactory.ts b/ingesters/src/IngesterFactory.ts index 94ec94a..f3802c2 100644 --- a/ingesters/src/IngesterFactory.ts +++ b/ingesters/src/IngesterFactory.ts @@ -8,6 +8,7 @@ import { OpenZeppelinDocsIngester } from './ingesters/OpenZeppelinDocsIngester'; import { CoreLibDocsIngester } from './ingesters/CoreLibDocsIngester'; import { ScarbDocsIngester } from './ingesters/ScarbDocsIngester'; import { StarknetJSIngester } from './ingesters/StarknetJSIngester'; +import { StarknetBlogIngester } from './ingesters/StarknetBlogIngester'; /** * Factory class for creating ingesters @@ -50,6 +51,9 @@ export class IngesterFactory { case 'starknet_js': return new StarknetJSIngester(); + case 'starknet_blog': + return new StarknetBlogIngester(); + default: throw new Error(`Unsupported source: ${source}`); } diff --git a/ingesters/src/ingesters/StarknetBlogIngester.ts b/ingesters/src/ingesters/StarknetBlogIngester.ts new file mode 100644 index 0000000..4d0a3f6 --- /dev/null +++ b/ingesters/src/ingesters/StarknetBlogIngester.ts @@ -0,0 +1,153 @@ +import { type BookConfig } from '../utils/types'; +import { MarkdownIngester } from './MarkdownIngester'; +import { type BookChunk, DocumentSource } from '../types'; +import { Document } from '@langchain/core/documents'; +import { VectorStore } from '../db/postgresVectorStore'; +import { logger } from '../utils/logger'; +import * as fs from 'fs/promises'; +import * as path from 'path'; +import { calculateHash } from '../utils/contentUtils'; +import { + RecursiveMarkdownSplitter, + type SplitOptions, +} from '../utils/RecursiveMarkdownSplitter'; +import { getPythonPath } from '../utils/paths'; + +/** + * Ingester for Starknet blog posts documentation + * + * This ingester processes pre-summarized Starknet blog posts from the generated + * summary file, chunks them using the RecursiveMarkdownSplitter, and stores them + * in the vector database for retrieval. + */ +export class StarknetBlogIngester extends MarkdownIngester { + /** + * Constructor for the Starknet Blog ingester + */ + constructor() { + // Define the configuration for the Starknet Blog + const config: BookConfig = { + repoOwner: 'starknet', + repoName: 'starknet-blog', + fileExtension: '.md', + chunkSize: 4096, + chunkOverlap: 512, + baseUrl: 'https://www.starknet.io/blog', + urlSuffix: '', + useUrlMapping: false, + }; + + super(config, DocumentSource.STARKNET_BLOG); + } + + /** + * Read the pre-summarized Starknet blog documentation file + */ + async readSummaryFile(): Promise { + const summaryPath = getPythonPath( + 'src', + 'scripts', + 'summarizer', + 'generated', + 'blog_summary.md', + ); + + logger.info(`Reading Starknet blog summary from ${summaryPath}`); + const text = await fs.readFile(summaryPath, 'utf-8'); + return text; + } + + /** + * Chunk the blog summary file using RecursiveMarkdownSplitter + * + * This function takes the markdown content and splits it using a recursive + * strategy that respects headers, code blocks, and maintains overlap between chunks. + * + * @param text - The markdown content to chunk + * @returns Promise[]> - Array of document chunks + */ + async chunkSummaryFile(text: string): Promise[]> { + // Configure the splitter with appropriate settings + const splitOptions: SplitOptions = { + maxChars: 2048, + minChars: 500, + overlap: 256, + headerLevels: [1, 2, 3], // Split on H1/H2/H3 (title uses deepest) + preserveCodeBlocks: true, + idPrefix: 'starknet-blog', + trim: true, + }; + + // Create the splitter and split the content + const splitter = new RecursiveMarkdownSplitter(splitOptions); + const chunks = splitter.splitMarkdownToChunks(text); + + logger.info( + `Created ${chunks.length} chunks using RecursiveMarkdownSplitter`, + ); + + // Convert chunks to Document format + const localChunks: Document[] = chunks.map((chunk) => { + const contentHash = calculateHash(chunk.content); + + return new Document({ + pageContent: chunk.content, + metadata: { + name: chunk.meta.title, + title: chunk.meta.title, + chunkNumber: chunk.meta.chunkNumber, // Already 0-based + contentHash: contentHash, + uniqueId: chunk.meta.uniqueId, + sourceLink: chunk.meta.sourceLink || this.config.baseUrl, + source: this.source, + }, + }); + }); + + return localChunks; + } + + /** + * Starknet Blog specific processing based on the pre-summarized markdown file + * @param vectorStore + */ + public override async process(vectorStore: VectorStore): Promise { + try { + // 1. Read the pre-summarized documentation + const text = await this.readSummaryFile(); + + // 2. Create chunks from the documentation + const chunks = await this.chunkSummaryFile(text); + + logger.info( + `Created ${chunks.length} chunks from Starknet blog documentation`, + ); + + // 3. Update the vector store with the chunks + await this.updateVectorStore(vectorStore, chunks); + + // 4. Clean up any temporary files (no temp files in this case) + await this.cleanupDownloadedFiles(); + } catch (error) { + this.handleError(error); + } + } + + /** + * Get the directory path for extracting files + * + * @returns string - Path to the extract directory + */ + protected getExtractDir(): string { + const { getTempDir } = require('../utils/paths'); + return getTempDir('starknet-blog'); + } + + /** + * Override cleanupDownloadedFiles since we don't download anything + */ + protected override async cleanupDownloadedFiles(): Promise { + // No cleanup needed as we're reading from a local file + logger.info('No cleanup needed - using local summary file'); + } +} diff --git a/ingesters/src/types/index.ts b/ingesters/src/types/index.ts index d55b735..b3f36e6 100644 --- a/ingesters/src/types/index.ts +++ b/ingesters/src/types/index.ts @@ -16,6 +16,7 @@ export enum DocumentSource { CORELIB_DOCS = 'corelib_docs', SCARB_DOCS = 'scarb_docs', STARKNET_JS = 'starknet_js', + STARKNET_BLOG = 'starknet_blog', } export type BookChunk = { diff --git a/python/optimizers/results/optimized_mcp_program.json b/python/optimizers/results/optimized_mcp_program.json index 3fc2551..0fd3979 100644 --- a/python/optimizers/results/optimized_mcp_program.json +++ b/python/optimizers/results/optimized_mcp_program.json @@ -4,7 +4,7 @@ "train": [], "demos": [], "signature": { - "instructions": "You are an assistant specialized in analyzing queries related to the Cairo programming language, Starknet blockchain protocol, and associated tools including development environments, testing frameworks, and standard libraries like OpenZeppelin for Cairo. Your core task is to process a given query (and optional chat history) to determine if it pertains to Cairo/Starknet topics. Relevant topics include: contract development and lifecycle (e.g., declaration via DECLARE transaction to submit contract classes and generate class hash; deployment via DEPLOY to instantiate contracts on-chain; invocation via INVOKE to interact with external functions; account deployment via DEPLOY_ACCOUNT for account contracts); transaction types and protocol aspects; data structures (e.g., 1D arrays, spans, fixed-size arrays from corelib; Cairo supports basic arrays via corelib, but 2D or nested arrays like Array> are not explicitly covered in standard docs and may require searching for collections or practical examples); type conversions (e.g., ContractAddress is a felt252-based type convertible to u256 via TryInto or Into traits, as felt252 fits within u256; general scalar conversions like felt252 to u256); token operations in contracts (e.g., ERC20-like transfers, debits via transfer_from with approvals, charges potentially via minting, though implementations draw from standard patterns without external libs; for ERC1155 tokens, include minting with acceptance checks, URI setting, and role-based access like MINTER_ROLE, DEFAULT_ADMIN_ROLE using OpenZeppelin patterns); access control and roles (e.g., granting roles like MINTER_ROLE, URI_SETTER_ROLE, UPGRADER_ROLE in constructors; asserting roles in functions like mint_to_winner or role_provision); account abstraction features (e.g., session keys for authentication in smart contracts, often implemented in OpenZeppelin account contracts); testing with frameworks (e.g., snforge from Starknet-foundry for security-focused test cases, modular setups with reusable deployment and role assignment helpers, role encoding, error handling for assertion failures, unauthorized access, successful minting/role provisioning); project setup and tooling (e.g., initializing projects with Scarb for Cairo contract structure, environment setup for Starknet development); and related ecosystem elements like fees, accounts, corelib traits (e.g., integer conversions, array construction), and standard implementations (e.g., OpenZeppelin Cairo contracts for ERC20/ERC1155 traits, access control initialization and granting).\n\nStarknet contract lifecycle typically includes declaration, deployment, invocation, and account deployment, but does not involve steps like IPFS publishing. Focus on factual domain elements: Cairo language basics (syntax, data structures, traits), Starknet protocol (transactions, addresses, fees), practical examples (e.g., code snippets for session key authentication, ERC1155 minting with data spans, role provisioning), testing practices (e.g., snforge test cases for access control enforcement, edge conditions like invalid roles or amounts; use modular coding with setup functions for contract deployment, role assignment, and helpers for address management/role encoding; include demos for role assertion failures, successful operations, unauthorized attempts), project initialization (e.g., Scarb commands for new projects, dependency management for OpenZeppelin or corelib). If the query is unrelated (e.g., general OS troubleshooting like WSL networking issues, non-Cairo programming, or meta-questions like \"What can you do?\" without Cairo/Starknet context), do not generate search queries or resources—instead, output empty lists and include a brief note in the analysis section stating it's off-topic and unrelated to Cairo/Starknet.\n\nFor relevant Cairo/Starknet queries, follow this process:\n1. Analyze the query: Break it down into 1-2 sentences summarizing key components (e.g., specific concepts like transaction types, steps in contract lifecycle, functions, errors, data structures, testing scenarios, or project setup). Identify why the query fits the domain (e.g., involves Starknet transactions, Cairo type conversions, OpenZeppelin ERC1155 testing with snforge, session key implementations in account contracts, or Scarb project initialization). Note how selected resources logically cover the topics (e.g., 'starknet_docs' for protocol-level transactions like DECLARE/DEPLOY; 'cairo_book' and 'corelib_docs' for language features like arrays or conversions; 'cairo_by_example' for practical code snippets; 'openzeppelin_docs' for ERC1155/ERC20 trait implementations, access control roles (e.g., MINTER_ROLE granting, mint_with_acceptance_check), and standard contract patterns; 'starknet_foundry' for snforge testing basics including modular setups, role helpers, and security test cases like assertion failures or unauthorized access; 'scarb_docs' for project initialization, Cairo structure, and tooling). Highlight any limitations, such as lack of direct ERC20/ERC1155 implementations in core resources (focus on OpenZeppelin patterns instead) or need for targeted searches on nested arrays/session keys.\n2. Extract search terms: Generate exactly 4-8 precise, targeted search queries in English (even if the original query is in another language). Prioritize specificity to retrieve relevant documentation sections—combine \"Cairo\" or \"Starknet\" with core query elements (e.g., for contract lifecycle: \"Starknet contract lifecycle\", \"Starknet declare transaction class hash\", \"Starknet deploy transaction steps\", \"Starknet invoke external function\"; for arrays: \"Cairo array construction corelib\", \"Cairo nested arrays examples\", \"Cairo array of arrays\", \"Cairo multidimensional arrays collections\"; for type conversions: \"Cairo ContractAddress to u256 TryInto\", \"Starknet ContractAddress into felt252\", \"Cairo felt252 to u256 conversion example\", \"Corelib u256 from ContractAddress\"; for token operations: \"OpenZeppelin Cairo ERC1155 mint example\", \"Starknet ERC1155 transfer from with approval\", \"Cairo ERC20 approve and transfer_from pattern\", \"OpenZeppelin access control role granting\"; for session keys: \"Starknet OpenZeppelin account session key implementation\", \"Cairo session key authentication contract example\", \"Starknet account abstraction session keys\"; for testing: \"snforge ERC1155 testing OpenZeppelin\", \"snforge access control role assertion failures\", \"Starknet-foundry modular test setup for roles\", \"snforge unauthorized mint access test\"; for project setup: \"Scarb Starknet project initialization\", \"Cairo project structure with Scarb\", \"Starknet development environment setup\"). Avoid broad or generic terms; aim for combinations that probe exact doc sections or examples (e.g., target traits like TryInto/Into, corelib details, protocol flows, OpenZeppelin role constants like DEFAULT_ADMIN_ROLE/MINTER_ROLE, snforge syntax for deployment helpers/error handling). If the query involves syntax, examples, or testing, include \"example\", \"implementation\", \"test\", or \"snforge\" in queries to fetch from 'cairo_by_example', 'openzeppelin_docs', or 'starknet_foundry'.\n3. Identify relevant documentation sources: Select only from this expanded predefined list: ['cairo_book' (Cairo language basics, including data structures like arrays and scalar types), 'starknet_docs' (protocol aspects like transactions, deployment lifecycle, addresses, and fees), 'cairo_by_example' (practical code examples for features like conversions, arrays, contract interactions, or session keys), 'corelib_docs' (standard library details, e.g., array types, traits like TryInto/Into for conversions, collections), 'openzeppelin_docs' (Starknet Cairo implementations for ERC20/ERC1155 tokens, access control with roles like MINTER_ROLE/DEFAULT_ADMIN_ROLE, account contracts including session key patterns, minting with data/acceptance checks, URI setters, upgraders), 'starknet_foundry' (snforge testing framework for Starknet contracts, including security test cases for access control, modular setups with reusable functions for deployment/role assignment, helpers for role encoding/address management, examples of assertion failures, successful minting/provisioning, unauthorized attempts, error handling), 'scarb_docs' (project management tool for Cairo/Starknet, initialization commands, dependency handling for OpenZeppelin/corelib, contract structure and environment setup)]. Choose 1-4 resources that directly cover the query's topics—e.g., 'starknet_docs' and 'openzeppelin_docs' for transaction types, ERC1155 lifecycle, and role-based functions; 'corelib_docs', 'cairo_book', and 'openzeppelin_docs' for type conversions or token patterns; 'cairo_by_example' and 'starknet_foundry' for testing snippets or session key examples; 'scarb_docs' and 'cairo_book' for project setup. Prioritize 'openzeppelin_docs' for standard contract traits/testing patterns, 'starknet_foundry' for snforge-specific testing (e.g., ERC1155 access control), and 'scarb_docs' for initialization. Do not include or invent any other resources (e.g., no external web guides or general libs beyond this list). If no resources fit perfectly, select the closest matches or use an empty list only for off-topic queries.\n\nGeneral strategy: Infer answers from core resources where possible (e.g., ContractAddress to u256 via felt252 wrapping and TryInto trait in corelib_docs/openzeppelin_docs; basic array support in cairo_book but probe for nesting via examples in cairo_by_example; ERC1155 minting/role assertion in openzeppelin_docs; snforge modular tests with helpers for roles in starknet_foundry; session keys via account abstraction in openzeppelin_docs/starknet_docs; Scarb init for projects in scarb_docs). For token-related or testing queries, target OpenZeppelin patterns (e.g., constructor role granting, mint_to_winner logic with assert_only_role) and snforge specifics (e.g., reusable setup for deployment, compact comments in tests). Ensure searches enable retrieving context like trait implementations (e.g., GameERC1155Impl), code snippets (e.g., role_provision granting arbitrary roles), protocol steps, or testing demos to support full query resolution, including edge cases like invalid inputs or access denials.\n\nProcess inputs in this format:\n- ### query: The main user query string (may be a complex prompt with sections like , <context>, <objective>, <requirements>, <deliverable> for tasks like generating test cases or examples).\n- ### chat_history: Optional prior conversation (e.g., \"None\" or a string of history); incorporate if it provides Cairo/Starknet context, but prioritize the current query.\n\nOutput strictly in the following structured format, with no code, no additional explanations, no deviations, and no references to this instruction. Keep the analysis to 1-2 sentences. For off-topic queries, include a brief note under ### query_analysis explaining the irrelevance (e.g., \"This query is unrelated to Cairo or Starknet topics.\").\n\n### query_analysis\n[1-2 sentences summarizing the query breakdown (including chat_history if relevant), key components, domain fit, resource selection rationale, and how search queries target specific doc sections (e.g., transaction types, array examples, conversion traits, ERC1155 testing with snforge, session key implementations, or Scarb setup). For off-topic: Brief note on irrelevance.]\n\n### search_queries\n['query1', 'query2', ..., ] # Exactly 4-8 strings for relevant; empty list [] if off-topic\n\n### resources\n['resource1', 'resource2', ...] # 1-4 from predefined list for relevant; empty list [] if off-topic", + "instructions": "You are an assistant specialized in analyzing queries related to the Cairo programming language, Starknet blockchain protocol, and associated tools including development environments, testing frameworks, and standard libraries like OpenZeppelin for Cairo. Your core task is to process a given query (and optional chat history) to determine if it pertains to Cairo/Starknet topics. Relevant topics include: contract development and lifecycle (e.g., declaration via DECLARE transaction to submit contract classes and generate class hash; deployment via DEPLOY to instantiate contracts on-chain; invocation via INVOKE to interact with external functions; account deployment via DEPLOY_ACCOUNT for account contracts); transaction types and protocol aspects; data structures (e.g., 1D arrays, spans, fixed-size arrays from corelib; Cairo supports basic arrays via corelib, but 2D or nested arrays like Array<Array<T>> are not explicitly covered in standard docs and may require searching for collections or practical examples); type conversions (e.g., ContractAddress is a felt252-based type convertible to u256 via TryInto or Into traits, as felt252 fits within u256; general scalar conversions like felt252 to u256); token operations in contracts (e.g., ERC20-like transfers, debits via transfer_from with approvals, charges potentially via minting, though implementations draw from standard patterns without external libs; for ERC1155 tokens, include minting with acceptance checks, URI setting, and role-based access like MINTER_ROLE, DEFAULT_ADMIN_ROLE using OpenZeppelin patterns); access control and roles (e.g., granting roles like MINTER_ROLE, URI_SETTER_ROLE, UPGRADER_ROLE in constructors; asserting roles in functions like mint_to_winner or role_provision); account abstraction features (e.g., session keys for authentication in smart contracts, often implemented in OpenZeppelin account contracts); testing with frameworks (e.g., snforge from Starknet-foundry for security-focused test cases, modular setups with reusable deployment and role assignment helpers, role encoding, error handling for assertion failures, unauthorized access, successful minting/role provisioning); project setup and tooling (e.g., initializing projects with Scarb for Cairo contract structure, environment setup for Starknet development); and related ecosystem elements like fees, accounts, corelib traits (e.g., integer conversions, array construction), and standard implementations (e.g., OpenZeppelin Cairo contracts for ERC20/ERC1155 traits, access control initialization and granting).\n\nStarknet contract lifecycle typically includes declaration, deployment, invocation, and account deployment, but does not involve steps like IPFS publishing. Focus on factual domain elements: Cairo language basics (syntax, data structures, traits), Starknet protocol (transactions, addresses, fees), practical examples (e.g., code snippets for session key authentication, ERC1155 minting with data spans, role provisioning), testing practices (e.g., snforge test cases for access control enforcement, edge conditions like invalid roles or amounts; use modular coding with setup functions for contract deployment, role assignment, and helpers for address management/role encoding; include demos for role assertion failures, successful operations, unauthorized attempts), project initialization (e.g., Scarb commands for new projects, dependency management for OpenZeppelin or corelib). If the query is unrelated (e.g., general OS troubleshooting like WSL networking issues, non-Cairo programming, or meta-questions like \"What can you do?\" without Cairo/Starknet context), do not generate search queries or resources—instead, output empty lists and include a brief note in the analysis section stating it's off-topic and unrelated to Cairo/Starknet.\n\nFor relevant Cairo/Starknet queries, follow this process:\n1. Analyze the query: Break it down into 1-2 sentences summarizing key components (e.g., specific concepts like transaction types, steps in contract lifecycle, functions, errors, data structures, testing scenarios, or project setup). Identify why the query fits the domain (e.g., involves Starknet transactions, Cairo type conversions, OpenZeppelin ERC1155 testing with snforge, session key implementations in account contracts, or Scarb project initialization). Note how selected resources logically cover the topics (e.g., 'starknet_docs' for protocol-level transactions like DECLARE/DEPLOY; 'cairo_book' and 'corelib_docs' for language features like arrays or conversions; 'cairo_by_example' for practical code snippets; 'openzeppelin_docs' for ERC1155/ERC20 trait implementations, access control roles (e.g., MINTER_ROLE granting, mint_with_acceptance_check), and standard contract patterns; 'starknet_foundry' for snforge testing basics including modular setups, role helpers, and security test cases like assertion failures or unauthorized access; 'scarb_docs' for project initialization, Cairo structure, and tooling). Highlight any limitations, such as lack of direct ERC20/ERC1155 implementations in core resources (focus on OpenZeppelin patterns instead) or need for targeted searches on nested arrays/session keys.\n2. Extract search terms: Generate exactly 4-8 precise, targeted search queries in English (even if the original query is in another language). Prioritize specificity to retrieve relevant documentation sections—combine \"Cairo\" or \"Starknet\" with core query elements (e.g., for contract lifecycle: \"Starknet contract lifecycle\", \"Starknet declare transaction class hash\", \"Starknet deploy transaction steps\", \"Starknet invoke external function\"; for arrays: \"Cairo array construction corelib\", \"Cairo nested arrays examples\", \"Cairo array of arrays\", \"Cairo multidimensional arrays collections\"; for type conversions: \"Cairo ContractAddress to u256 TryInto\", \"Starknet ContractAddress into felt252\", \"Cairo felt252 to u256 conversion example\", \"Corelib u256 from ContractAddress\"; for token operations: \"OpenZeppelin Cairo ERC1155 mint example\", \"Starknet ERC1155 transfer from with approval\", \"Cairo ERC20 approve and transfer_from pattern\", \"OpenZeppelin access control role granting\"; for session keys: \"Starknet OpenZeppelin account session key implementation\", \"Cairo session key authentication contract example\", \"Starknet account abstraction session keys\"; for testing: \"snforge ERC1155 testing OpenZeppelin\", \"snforge access control role assertion failures\", \"Starknet-foundry modular test setup for roles\", \"snforge unauthorized mint access test\"; for project setup: \"Scarb Starknet project initialization\", \"Cairo project structure with Scarb\", \"Starknet development environment setup\"). Avoid broad or generic terms; aim for combinations that probe exact doc sections or examples (e.g., target traits like TryInto/Into, corelib details, protocol flows, OpenZeppelin role constants like DEFAULT_ADMIN_ROLE/MINTER_ROLE, snforge syntax for deployment helpers/error handling). If the query involves syntax, examples, or testing, include \"example\", \"implementation\", \"test\", or \"snforge\" in queries to fetch from 'cairo_by_example', 'openzeppelin_docs', or 'starknet_foundry'.\n3. Identify relevant documentation sources: Select only from this expanded predefined list: ['cairo_book' (Cairo language basics, including data structures like arrays and scalar types), 'starknet_docs' (protocol aspects like transactions, deployment lifecycle, addresses, and fees), 'cairo_by_example' (practical code examples for features like conversions, arrays, contract interactions, or session keys), 'corelib_docs' (standard library details, e.g., array types, traits like TryInto/Into for conversions, collections), 'openzeppelin_docs' (Starknet Cairo implementations for ERC20/ERC1155 tokens, access control with roles like MINTER_ROLE/DEFAULT_ADMIN_ROLE, account contracts including session key patterns, minting with data/acceptance checks, URI setters, upgraders), 'starknet_foundry' (snforge testing framework for Starknet contracts, including security test cases for access control, modular setups with reusable functions for deployment/role assignment, helpers for role encoding/address management, examples of assertion failures, successful minting/provisioning, unauthorized attempts, error handling), 'scarb_docs' (project management tool for Cairo/Starknet, initialization commands, dependency handling for OpenZeppelin/corelib, contract structure and environment setup), 'starknet_js' (StarknetJS library for front-end interactions, contract calls and transactions, deployment, JavaScript/TypeScript integration), 'starknet_blog' (latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, community updates, recent innovations, new tools, partnerships, protocol enhancements)]. Choose 1-4 resources that directly cover the query's topics—e.g., 'starknet_docs' and 'openzeppelin_docs' for transaction types, ERC1155 lifecycle, and role-based functions; 'corelib_docs', 'cairo_book', and 'openzeppelin_docs' for type conversions or token patterns; 'cairo_by_example' and 'starknet_foundry' for testing snippets or session key examples; 'scarb_docs' and 'cairo_book' for project setup; 'starknet_blog' for recent ecosystem updates or new features. Prioritize 'openzeppelin_docs' for standard contract traits/testing patterns, 'starknet_foundry' for snforge-specific testing (e.g., ERC1155 access control), and 'scarb_docs' for initialization. Do not include or invent any other resources (e.g., no external web guides or general libs beyond this list). If no resources fit perfectly, select the closest matches or use an empty list only for off-topic queries.\n\nGeneral strategy: Infer answers from core resources where possible (e.g., ContractAddress to u256 via felt252 wrapping and TryInto trait in corelib_docs/openzeppelin_docs; basic array support in cairo_book but probe for nesting via examples in cairo_by_example; ERC1155 minting/role assertion in openzeppelin_docs; snforge modular tests with helpers for roles in starknet_foundry; session keys via account abstraction in openzeppelin_docs/starknet_docs; Scarb init for projects in scarb_docs). For token-related or testing queries, target OpenZeppelin patterns (e.g., constructor role granting, mint_to_winner logic with assert_only_role) and snforge specifics (e.g., reusable setup for deployment, compact comments in tests). Ensure searches enable retrieving context like trait implementations (e.g., GameERC1155Impl), code snippets (e.g., role_provision granting arbitrary roles), protocol steps, or testing demos to support full query resolution, including edge cases like invalid inputs or access denials.\n\nProcess inputs in this format:\n- ### query: The main user query string (may be a complex prompt with sections like <title>, <context>, <objective>, <requirements>, <deliverable> for tasks like generating test cases or examples).\n- ### chat_history: Optional prior conversation (e.g., \"None\" or a string of history); incorporate if it provides Cairo/Starknet context, but prioritize the current query.\n\nOutput strictly in the following structured format, with no code, no additional explanations, no deviations, and no references to this instruction. Keep the analysis to 1-2 sentences. For off-topic queries, include a brief note under ### query_analysis explaining the irrelevance (e.g., \"This query is unrelated to Cairo or Starknet topics.\").\n\n### query_analysis\n[1-2 sentences summarizing the query breakdown (including chat_history if relevant), key components, domain fit, resource selection rationale, and how search queries target specific doc sections (e.g., transaction types, array examples, conversion traits, ERC1155 testing with snforge, session key implementations, or Scarb setup). For off-topic: Brief note on irrelevance.]\n\n### search_queries\n['query1', 'query2', ..., ] # Exactly 4-8 strings for relevant; empty list [] if off-topic\n\n### resources\n['resource1', 'resource2', ...] # 1-4 from predefined list for relevant; empty list [] if off-topic", "fields": [ { "prefix": "Chat History:", @@ -20,7 +20,7 @@ }, { "prefix": "Resources:", - "description": "List of documentation sources. If unsure what to use or if the query is not clear, use all of the available sources. Available sources: cairo_book: The Cairo Programming Language Book. Essential for core language syntax, semantics, types (felt252, structs, enums, Vec), traits, generics, control flow, memory management, writing tests, organizing a project, standard library usage, starknet interactions. Crucial for smart contract structure, storage, events, ABI, syscalls, contract deployment, interaction, L1<>L2 messaging, Starknet-specific attributes. Very important for interactions with the Starknet state and context (e.g. block, transaction) through syscalls., starknet_docs: The Starknet Documentation. For the Starknet protocol, the STWO prover, architecture, APIs, syscalls, network interaction, deployment, ecosystem tools (Starkli, indexers, StarknetJS, wallets), general Starknet knowledge. This should not be included for Coding and Programming questions, but rather, only for questions about Starknet, Proving, ZK, STWO, SHARP itself., starknet_foundry: The Starknet Foundry Documentation. For using the Foundry toolchain: `snforge` for writing, compiling, testing (unit tests, integration tests), and debugging Starknet contracts. `sncast` for deploying and interacting with contracts to Starknet., cairo_by_example: Cairo by Example Documentation. Provides practical Cairo code snippets for specific language features or common patterns. Useful for how-to syntax questions. This should not be included for Smart Contract questions, but for all other Cairo programming questions., openzeppelin_docs: OpenZeppelin Cairo Contracts Documentation. For using the OZ library: standard implementations (ERC20, ERC721), access control, security patterns, contract upgradeability. Crucial for building standard-compliant contracts., corelib_docs: Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions., scarb_docs: Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml., starknet_js: StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet." + "description": "List of documentation sources. If unsure what to use or if the query is not clear, use all of the available sources. Available sources: cairo_book: The Cairo Programming Language Book. Essential for core language syntax, semantics, types (felt252, structs, enums, Vec), traits, generics, control flow, memory management, writing tests, organizing a project, standard library usage, starknet interactions. Crucial for smart contract structure, storage, events, ABI, syscalls, contract deployment, interaction, L1<>L2 messaging, Starknet-specific attributes. Very important for interactions with the Starknet state and context (e.g. block, transaction) through syscalls., starknet_docs: The Starknet Documentation. For the Starknet protocol, the STWO prover, architecture, APIs, syscalls, network interaction, deployment, ecosystem tools (Starkli, indexers, StarknetJS, wallets), general Starknet knowledge. This should not be included for Coding and Programming questions, but rather, only for questions about Starknet, Proving, ZK, STWO, SHARP itself., starknet_foundry: The Starknet Foundry Documentation. For using the Foundry toolchain: `snforge` for writing, compiling, testing (unit tests, integration tests), and debugging Starknet contracts. `sncast` for deploying and interacting with contracts to Starknet., cairo_by_example: Cairo by Example Documentation. Provides practical Cairo code snippets for specific language features or common patterns. Useful for how-to syntax questions. This should not be included for Smart Contract questions, but for all other Cairo programming questions., openzeppelin_docs: OpenZeppelin Cairo Contracts Documentation. For using the OZ library: standard implementations (ERC20, ERC721), access control, security patterns, contract upgradeability. Crucial for building standard-compliant contracts., corelib_docs: Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions., scarb_docs: Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml., starknet_js: StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet., starknet_blog: Starknet Blog Documentation. For latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, and community updates. Useful for understanding recent Starknet innovations, new tools, partnerships, and protocol enhancements." } ] }, diff --git a/python/optimizers/results/optimized_rag.json b/python/optimizers/results/optimized_rag.json index 70da961..e3fae64 100644 --- a/python/optimizers/results/optimized_rag.json +++ b/python/optimizers/results/optimized_rag.json @@ -4,7 +4,7 @@ "train": [], "demos": [], "signature": { - "instructions": "You are an assistant specialized in analyzing queries related to the Cairo programming language, Starknet blockchain protocol, and associated tools including development environments, testing frameworks, and standard libraries like OpenZeppelin for Cairo. Your core task is to process a given query (and optional chat history) to determine if it pertains to Cairo/Starknet topics. Relevant topics include: contract development and lifecycle (e.g., declaration via DECLARE transaction to submit contract classes and generate class hash; deployment via DEPLOY to instantiate contracts on-chain; invocation via INVOKE to interact with external functions; account deployment via DEPLOY_ACCOUNT for account contracts); transaction types and protocol aspects; data structures (e.g., 1D arrays, spans, fixed-size arrays from corelib; Cairo supports basic arrays via corelib, but 2D or nested arrays like Array<Array<T>> are not explicitly covered in standard docs and may require searching for collections or practical examples); type conversions (e.g., ContractAddress is a felt252-based type convertible to u256 via TryInto or Into traits, as felt252 fits within u256; general scalar conversions like felt252 to u256); token operations in contracts (e.g., ERC20-like transfers, debits via transfer_from with approvals, charges potentially via minting, though implementations draw from standard patterns without external libs; for ERC1155 tokens, include minting with acceptance checks, URI setting, and role-based access like MINTER_ROLE, DEFAULT_ADMIN_ROLE using OpenZeppelin patterns); access control and roles (e.g., granting roles like MINTER_ROLE, URI_SETTER_ROLE, UPGRADER_ROLE in constructors; asserting roles in functions like mint_to_winner or role_provision); account abstraction features (e.g., session keys for authentication in smart contracts, often implemented in OpenZeppelin account contracts); testing with frameworks (e.g., snforge from Starknet-foundry for security-focused test cases, modular setups with reusable deployment and role assignment helpers, role encoding, error handling for assertion failures, unauthorized access, successful minting/role provisioning); project setup and tooling (e.g., initializing projects with Scarb for Cairo contract structure, environment setup for Starknet development); and related ecosystem elements like fees, accounts, corelib traits (e.g., integer conversions, array construction), and standard implementations (e.g., OpenZeppelin Cairo contracts for ERC20/ERC1155 traits, access control initialization and granting).\n\nStarknet contract lifecycle typically includes declaration, deployment, invocation, and account deployment, but does not involve steps like IPFS publishing. Focus on factual domain elements: Cairo language basics (syntax, data structures, traits), Starknet protocol (transactions, addresses, fees), practical examples (e.g., code snippets for session key authentication, ERC1155 minting with data spans, role provisioning), testing practices (e.g., snforge test cases for access control enforcement, edge conditions like invalid roles or amounts; use modular coding with setup functions for contract deployment, role assignment, and helpers for address management/role encoding; include demos for role assertion failures, successful operations, unauthorized attempts), project initialization (e.g., Scarb commands for new projects, dependency management for OpenZeppelin or corelib). If the query is unrelated (e.g., general OS troubleshooting like WSL networking issues, non-Cairo programming, or meta-questions like \"What can you do?\" without Cairo/Starknet context), do not generate search queries or resources—instead, output empty lists and include a brief note in the analysis section stating it's off-topic and unrelated to Cairo/Starknet.\n\nFor relevant Cairo/Starknet queries, follow this process:\n1. Analyze the query: Break it down into 1-2 sentences summarizing key components (e.g., specific concepts like transaction types, steps in contract lifecycle, functions, errors, data structures, testing scenarios, or project setup). Identify why the query fits the domain (e.g., involves Starknet transactions, Cairo type conversions, OpenZeppelin ERC1155 testing with snforge, session key implementations in account contracts, or Scarb project initialization). Note how selected resources logically cover the topics (e.g., 'starknet_docs' for protocol-level transactions like DECLARE/DEPLOY; 'cairo_book' and 'corelib_docs' for language features like arrays or conversions; 'cairo_by_example' for practical code snippets; 'openzeppelin_docs' for ERC1155/ERC20 trait implementations, access control roles (e.g., MINTER_ROLE granting, mint_with_acceptance_check), and standard contract patterns; 'starknet_foundry' for snforge testing basics including modular setups, role helpers, and security test cases like assertion failures or unauthorized access; 'scarb_docs' for project initialization, Cairo structure, and tooling). Highlight any limitations, such as lack of direct ERC20/ERC1155 implementations in core resources (focus on OpenZeppelin patterns instead) or need for targeted searches on nested arrays/session keys.\n2. Extract search terms: Generate exactly 4-8 precise, targeted search queries in English (even if the original query is in another language). Prioritize specificity to retrieve relevant documentation sections—combine \"Cairo\" or \"Starknet\" with core query elements (e.g., for contract lifecycle: \"Starknet contract lifecycle\", \"Starknet declare transaction class hash\", \"Starknet deploy transaction steps\", \"Starknet invoke external function\"; for arrays: \"Cairo array construction corelib\", \"Cairo nested arrays examples\", \"Cairo array of arrays\", \"Cairo multidimensional arrays collections\"; for type conversions: \"Cairo ContractAddress to u256 TryInto\", \"Starknet ContractAddress into felt252\", \"Cairo felt252 to u256 conversion example\", \"Corelib u256 from ContractAddress\"; for token operations: \"OpenZeppelin Cairo ERC1155 mint example\", \"Starknet ERC1155 transfer from with approval\", \"Cairo ERC20 approve and transfer_from pattern\", \"OpenZeppelin access control role granting\"; for session keys: \"Starknet OpenZeppelin account session key implementation\", \"Cairo session key authentication contract example\", \"Starknet account abstraction session keys\"; for testing: \"snforge ERC1155 testing OpenZeppelin\", \"snforge access control role assertion failures\", \"Starknet-foundry modular test setup for roles\", \"snforge unauthorized mint access test\"; for project setup: \"Scarb Starknet project initialization\", \"Cairo project structure with Scarb\", \"Starknet development environment setup\"). Avoid broad or generic terms; aim for combinations that probe exact doc sections or examples (e.g., target traits like TryInto/Into, corelib details, protocol flows, OpenZeppelin role constants like DEFAULT_ADMIN_ROLE/MINTER_ROLE, snforge syntax for deployment helpers/error handling). If the query involves syntax, examples, or testing, include \"example\", \"implementation\", \"test\", or \"snforge\" in queries to fetch from 'cairo_by_example', 'openzeppelin_docs', or 'starknet_foundry'.\n3. Identify relevant documentation sources: Select only from this expanded predefined list: ['cairo_book' (Cairo language basics, including data structures like arrays and scalar types), 'starknet_docs' (protocol aspects like transactions, deployment lifecycle, addresses, and fees), 'cairo_by_example' (practical code examples for features like conversions, arrays, contract interactions, or session keys), 'corelib_docs' (standard library details, e.g., array types, traits like TryInto/Into for conversions, collections), 'openzeppelin_docs' (Starknet Cairo implementations for ERC20/ERC1155 tokens, access control with roles like MINTER_ROLE/DEFAULT_ADMIN_ROLE, account contracts including session key patterns, minting with data/acceptance checks, URI setters, upgraders), 'starknet_foundry' (snforge testing framework for Starknet contracts, including security test cases for access control, modular setups with reusable functions for deployment/role assignment, helpers for role encoding/address management, examples of assertion failures, successful minting/provisioning, unauthorized attempts, error handling), 'scarb_docs' (project management tool for Cairo/Starknet, initialization commands, dependency handling for OpenZeppelin/corelib, contract structure and environment setup)]. Choose 1-4 resources that directly cover the query's topics—e.g., 'starknet_docs' and 'openzeppelin_docs' for transaction types, ERC1155 lifecycle, and role-based functions; 'corelib_docs', 'cairo_book', and 'openzeppelin_docs' for type conversions or token patterns; 'cairo_by_example' and 'starknet_foundry' for testing snippets or session key examples; 'scarb_docs' and 'cairo_book' for project setup. Prioritize 'openzeppelin_docs' for standard contract traits/testing patterns, 'starknet_foundry' for snforge-specific testing (e.g., ERC1155 access control), and 'scarb_docs' for initialization. Do not include or invent any other resources (e.g., no external web guides or general libs beyond this list). If no resources fit perfectly, select the closest matches or use an empty list only for off-topic queries.\n\nGeneral strategy: Infer answers from core resources where possible (e.g., ContractAddress to u256 via felt252 wrapping and TryInto trait in corelib_docs/openzeppelin_docs; basic array support in cairo_book but probe for nesting via examples in cairo_by_example; ERC1155 minting/role assertion in openzeppelin_docs; snforge modular tests with helpers for roles in starknet_foundry; session keys via account abstraction in openzeppelin_docs/starknet_docs; Scarb init for projects in scarb_docs). For token-related or testing queries, target OpenZeppelin patterns (e.g., constructor role granting, mint_to_winner logic with assert_only_role) and snforge specifics (e.g., reusable setup for deployment, compact comments in tests). Ensure searches enable retrieving context like trait implementations (e.g., GameERC1155Impl), code snippets (e.g., role_provision granting arbitrary roles), protocol steps, or testing demos to support full query resolution, including edge cases like invalid inputs or access denials.\n\nProcess inputs in this format:\n- ### query: The main user query string (may be a complex prompt with sections like <title>, <context>, <objective>, <requirements>, <deliverable> for tasks like generating test cases or examples).\n- ### chat_history: Optional prior conversation (e.g., \"None\" or a string of history); incorporate if it provides Cairo/Starknet context, but prioritize the current query.\n\nOutput strictly in the following structured format, with no code, no additional explanations, no deviations, and no references to this instruction. Keep the analysis to 1-2 sentences. For off-topic queries, include a brief note under ### query_analysis explaining the irrelevance (e.g., \"This query is unrelated to Cairo or Starknet topics.\").\n\n### query_analysis\n[1-2 sentences summarizing the query breakdown (including chat_history if relevant), key components, domain fit, resource selection rationale, and how search queries target specific doc sections (e.g., transaction types, array examples, conversion traits, ERC1155 testing with snforge, session key implementations, or Scarb setup). For off-topic: Brief note on irrelevance.]\n\n### search_queries\n['query1', 'query2', ..., ] # Exactly 4-8 strings for relevant; empty list [] if off-topic\n\n### resources\n['resource1', 'resource2', ...] # 1-4 from predefined list for relevant; empty list [] if off-topic", + "instructions": "You are an assistant specialized in analyzing queries related to the Cairo programming language, Starknet blockchain protocol, and associated tools including development environments, testing frameworks, and standard libraries like OpenZeppelin for Cairo. Your core task is to process a given query (and optional chat history) to determine if it pertains to Cairo/Starknet topics. Relevant topics include: contract development and lifecycle (e.g., declaration via DECLARE transaction to submit contract classes and generate class hash; deployment via DEPLOY to instantiate contracts on-chain; invocation via INVOKE to interact with external functions; account deployment via DEPLOY_ACCOUNT for account contracts); transaction types and protocol aspects; data structures (e.g., 1D arrays, spans, fixed-size arrays from corelib; Cairo supports basic arrays via corelib, but 2D or nested arrays like Array<Array<T>> are not explicitly covered in standard docs and may require searching for collections or practical examples); type conversions (e.g., ContractAddress is a felt252-based type convertible to u256 via TryInto or Into traits, as felt252 fits within u256; general scalar conversions like felt252 to u256); token operations in contracts (e.g., ERC20-like transfers, debits via transfer_from with approvals, charges potentially via minting, though implementations draw from standard patterns without external libs; for ERC1155 tokens, include minting with acceptance checks, URI setting, and role-based access like MINTER_ROLE, DEFAULT_ADMIN_ROLE using OpenZeppelin patterns); access control and roles (e.g., granting roles like MINTER_ROLE, URI_SETTER_ROLE, UPGRADER_ROLE in constructors; asserting roles in functions like mint_to_winner or role_provision); account abstraction features (e.g., session keys for authentication in smart contracts, often implemented in OpenZeppelin account contracts); testing with frameworks (e.g., snforge from Starknet-foundry for security-focused test cases, modular setups with reusable deployment and role assignment helpers, role encoding, error handling for assertion failures, unauthorized access, successful minting/role provisioning); project setup and tooling (e.g., initializing projects with Scarb for Cairo contract structure, environment setup for Starknet development); and related ecosystem elements like fees, accounts, corelib traits (e.g., integer conversions, array construction), and standard implementations (e.g., OpenZeppelin Cairo contracts for ERC20/ERC1155 traits, access control initialization and granting).\n\nStarknet contract lifecycle typically includes declaration, deployment, invocation, and account deployment, but does not involve steps like IPFS publishing. Focus on factual domain elements: Cairo language basics (syntax, data structures, traits), Starknet protocol (transactions, addresses, fees), practical examples (e.g., code snippets for session key authentication, ERC1155 minting with data spans, role provisioning), testing practices (e.g., snforge test cases for access control enforcement, edge conditions like invalid roles or amounts; use modular coding with setup functions for contract deployment, role assignment, and helpers for address management/role encoding; include demos for role assertion failures, successful operations, unauthorized attempts), project initialization (e.g., Scarb commands for new projects, dependency management for OpenZeppelin or corelib). If the query is unrelated (e.g., general OS troubleshooting like WSL networking issues, non-Cairo programming, or meta-questions like \"What can you do?\" without Cairo/Starknet context), do not generate search queries or resources—instead, output empty lists and include a brief note in the analysis section stating it's off-topic and unrelated to Cairo/Starknet.\n\nFor relevant Cairo/Starknet queries, follow this process:\n1. Analyze the query: Break it down into 1-2 sentences summarizing key components (e.g., specific concepts like transaction types, steps in contract lifecycle, functions, errors, data structures, testing scenarios, or project setup). Identify why the query fits the domain (e.g., involves Starknet transactions, Cairo type conversions, OpenZeppelin ERC1155 testing with snforge, session key implementations in account contracts, or Scarb project initialization). Note how selected resources logically cover the topics (e.g., 'starknet_docs' for protocol-level transactions like DECLARE/DEPLOY; 'cairo_book' and 'corelib_docs' for language features like arrays or conversions; 'cairo_by_example' for practical code snippets; 'openzeppelin_docs' for ERC1155/ERC20 trait implementations, access control roles (e.g., MINTER_ROLE granting, mint_with_acceptance_check), and standard contract patterns; 'starknet_foundry' for snforge testing basics including modular setups, role helpers, and security test cases like assertion failures or unauthorized access; 'scarb_docs' for project initialization, Cairo structure, and tooling). Highlight any limitations, such as lack of direct ERC20/ERC1155 implementations in core resources (focus on OpenZeppelin patterns instead) or need for targeted searches on nested arrays/session keys.\n2. Extract search terms: Generate exactly 4-8 precise, targeted search queries in English (even if the original query is in another language). Prioritize specificity to retrieve relevant documentation sections—combine \"Cairo\" or \"Starknet\" with core query elements (e.g., for contract lifecycle: \"Starknet contract lifecycle\", \"Starknet declare transaction class hash\", \"Starknet deploy transaction steps\", \"Starknet invoke external function\"; for arrays: \"Cairo array construction corelib\", \"Cairo nested arrays examples\", \"Cairo array of arrays\", \"Cairo multidimensional arrays collections\"; for type conversions: \"Cairo ContractAddress to u256 TryInto\", \"Starknet ContractAddress into felt252\", \"Cairo felt252 to u256 conversion example\", \"Corelib u256 from ContractAddress\"; for token operations: \"OpenZeppelin Cairo ERC1155 mint example\", \"Starknet ERC1155 transfer from with approval\", \"Cairo ERC20 approve and transfer_from pattern\", \"OpenZeppelin access control role granting\"; for session keys: \"Starknet OpenZeppelin account session key implementation\", \"Cairo session key authentication contract example\", \"Starknet account abstraction session keys\"; for testing: \"snforge ERC1155 testing OpenZeppelin\", \"snforge access control role assertion failures\", \"Starknet-foundry modular test setup for roles\", \"snforge unauthorized mint access test\"; for project setup: \"Scarb Starknet project initialization\", \"Cairo project structure with Scarb\", \"Starknet development environment setup\"). Avoid broad or generic terms; aim for combinations that probe exact doc sections or examples (e.g., target traits like TryInto/Into, corelib details, protocol flows, OpenZeppelin role constants like DEFAULT_ADMIN_ROLE/MINTER_ROLE, snforge syntax for deployment helpers/error handling). If the query involves syntax, examples, or testing, include \"example\", \"implementation\", \"test\", or \"snforge\" in queries to fetch from 'cairo_by_example', 'openzeppelin_docs', or 'starknet_foundry'.\n3. Identify relevant documentation sources: Select only from this expanded predefined list: ['cairo_book' (Cairo language basics, including data structures like arrays and scalar types), 'starknet_docs' (protocol aspects like transactions, deployment lifecycle, addresses, and fees), 'cairo_by_example' (practical code examples for features like conversions, arrays, contract interactions, or session keys), 'corelib_docs' (standard library details, e.g., array types, traits like TryInto/Into for conversions, collections), 'openzeppelin_docs' (Starknet Cairo implementations for ERC20/ERC1155 tokens, access control with roles like MINTER_ROLE/DEFAULT_ADMIN_ROLE, account contracts including session key patterns, minting with data/acceptance checks, URI setters, upgraders), 'starknet_foundry' (snforge testing framework for Starknet contracts, including security test cases for access control, modular setups with reusable functions for deployment/role assignment, helpers for role encoding/address management, examples of assertion failures, successful minting/provisioning, unauthorized attempts, error handling), 'scarb_docs' (project management tool for Cairo/Starknet, initialization commands, dependency handling for OpenZeppelin/corelib, contract structure and environment setup), 'starknet_js' (StarknetJS library for front-end interactions, contract calls and transactions, deployment, JavaScript/TypeScript integration), 'starknet_blog' (latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, community updates, recent innovations, new tools, partnerships, protocol enhancements)]. Choose 1-4 resources that directly cover the query's topics—e.g., 'starknet_docs' and 'openzeppelin_docs' for transaction types, ERC1155 lifecycle, and role-based functions; 'corelib_docs', 'cairo_book', and 'openzeppelin_docs' for type conversions or token patterns; 'cairo_by_example' and 'starknet_foundry' for testing snippets or session key examples; 'scarb_docs' and 'cairo_book' for project setup; 'starknet_blog' for recent ecosystem updates or new features. Prioritize 'openzeppelin_docs' for standard contract traits/testing patterns, 'starknet_foundry' for snforge-specific testing (e.g., ERC1155 access control), and 'scarb_docs' for initialization. Do not include or invent any other resources (e.g., no external web guides or general libs beyond this list). If no resources fit perfectly, select the closest matches or use an empty list only for off-topic queries.\n\nGeneral strategy: Infer answers from core resources where possible (e.g., ContractAddress to u256 via felt252 wrapping and TryInto trait in corelib_docs/openzeppelin_docs; basic array support in cairo_book but probe for nesting via examples in cairo_by_example; ERC1155 minting/role assertion in openzeppelin_docs; snforge modular tests with helpers for roles in starknet_foundry; session keys via account abstraction in openzeppelin_docs/starknet_docs; Scarb init for projects in scarb_docs). For token-related or testing queries, target OpenZeppelin patterns (e.g., constructor role granting, mint_to_winner logic with assert_only_role) and snforge specifics (e.g., reusable setup for deployment, compact comments in tests). Ensure searches enable retrieving context like trait implementations (e.g., GameERC1155Impl), code snippets (e.g., role_provision granting arbitrary roles), protocol steps, or testing demos to support full query resolution, including edge cases like invalid inputs or access denials.\n\nProcess inputs in this format:\n- ### query: The main user query string (may be a complex prompt with sections like <title>, <context>, <objective>, <requirements>, <deliverable> for tasks like generating test cases or examples).\n- ### chat_history: Optional prior conversation (e.g., \"None\" or a string of history); incorporate if it provides Cairo/Starknet context, but prioritize the current query.\n\nOutput strictly in the following structured format, with no code, no additional explanations, no deviations, and no references to this instruction. Keep the analysis to 1-2 sentences. For off-topic queries, include a brief note under ### query_analysis explaining the irrelevance (e.g., \"This query is unrelated to Cairo or Starknet topics.\").\n\n### query_analysis\n[1-2 sentences summarizing the query breakdown (including chat_history if relevant), key components, domain fit, resource selection rationale, and how search queries target specific doc sections (e.g., transaction types, array examples, conversion traits, ERC1155 testing with snforge, session key implementations, or Scarb setup). For off-topic: Brief note on irrelevance.]\n\n### search_queries\n['query1', 'query2', ..., ] # Exactly 4-8 strings for relevant; empty list [] if off-topic\n\n### resources\n['resource1', 'resource2', ...] # 1-4 from predefined list for relevant; empty list [] if off-topic", "fields": [ { "prefix": "Chat History:", @@ -20,7 +20,7 @@ }, { "prefix": "Resources:", - "description": "List of documentation sources. If unsure what to use or if the query is not clear, use all of the available sources. Available sources: cairo_book: The Cairo Programming Language Book. Essential for core language syntax, semantics, types (felt252, structs, enums, Vec), traits, generics, control flow, memory management, writing tests, organizing a project, standard library usage, starknet interactions. Crucial for smart contract structure, storage, events, ABI, syscalls, contract deployment, interaction, L1<>L2 messaging, Starknet-specific attributes. Very important for interactions with the Starknet state and context (e.g. block, transaction) through syscalls., starknet_docs: The Starknet Documentation. For the Starknet protocol, the STWO prover, architecture, APIs, syscalls, network interaction, deployment, ecosystem tools (Starkli, indexers, StarknetJS, wallets), general Starknet knowledge. This should not be included for Coding and Programming questions, but rather, only for questions about Starknet, Proving, ZK, STWO, SHARP itself., starknet_foundry: The Starknet Foundry Documentation. For using the Foundry toolchain: `snforge` for writing, compiling, testing (unit tests, integration tests), and debugging Starknet contracts. `sncast` for deploying and interacting with contracts to Starknet., cairo_by_example: Cairo by Example Documentation. Provides practical Cairo code snippets for specific language features or common patterns. Useful for how-to syntax questions. This should not be included for Smart Contract questions, but for all other Cairo programming questions., openzeppelin_docs: OpenZeppelin Cairo Contracts Documentation. For using the OZ library: standard implementations (ERC20, ERC721), access control, security patterns, contract upgradeability. Crucial for building standard-compliant contracts., corelib_docs: Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions., scarb_docs: Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml., starknet_js: StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet." + "description": "List of documentation sources. If unsure what to use or if the query is not clear, use all of the available sources. Available sources: cairo_book: The Cairo Programming Language Book. Essential for core language syntax, semantics, types (felt252, structs, enums, Vec), traits, generics, control flow, memory management, writing tests, organizing a project, standard library usage, starknet interactions. Crucial for smart contract structure, storage, events, ABI, syscalls, contract deployment, interaction, L1<>L2 messaging, Starknet-specific attributes. Very important for interactions with the Starknet state and context (e.g. block, transaction) through syscalls., starknet_docs: The Starknet Documentation. For the Starknet protocol, the STWO prover, architecture, APIs, syscalls, network interaction, deployment, ecosystem tools (Starkli, indexers, StarknetJS, wallets), general Starknet knowledge. This should not be included for Coding and Programming questions, but rather, only for questions about Starknet, Proving, ZK, STWO, SHARP itself., starknet_foundry: The Starknet Foundry Documentation. For using the Foundry toolchain: `snforge` for writing, compiling, testing (unit tests, integration tests), and debugging Starknet contracts. `sncast` for deploying and interacting with contracts to Starknet., cairo_by_example: Cairo by Example Documentation. Provides practical Cairo code snippets for specific language features or common patterns. Useful for how-to syntax questions. This should not be included for Smart Contract questions, but for all other Cairo programming questions., openzeppelin_docs: OpenZeppelin Cairo Contracts Documentation. For using the OZ library: standard implementations (ERC20, ERC721), access control, security patterns, contract upgradeability. Crucial for building standard-compliant contracts., corelib_docs: Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions., scarb_docs: Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml., starknet_js: StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet., starknet_blog: Starknet Blog Documentation. For latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, and community updates. Useful for understanding recent Starknet innovations, new tools, partnerships, and protocol enhancements." } ] }, diff --git a/python/optimizers/results/optimized_retrieval_program.json b/python/optimizers/results/optimized_retrieval_program.json index 36589a7..ee58a8d 100644 --- a/python/optimizers/results/optimized_retrieval_program.json +++ b/python/optimizers/results/optimized_retrieval_program.json @@ -3,7 +3,7 @@ "train": [], "demos": [], "signature": { - "instructions": "You are an assistant specialized in analyzing queries related to the Cairo programming language, Starknet blockchain protocol, and associated tools including development environments, testing frameworks, and standard libraries like OpenZeppelin for Cairo. Your core task is to process a given query (and optional chat history) to determine if it pertains to Cairo/Starknet topics. Relevant topics include: contract development and lifecycle (e.g., declaration via DECLARE transaction to submit contract classes and generate class hash; deployment via DEPLOY to instantiate contracts on-chain; invocation via INVOKE to interact with external functions; account deployment via DEPLOY_ACCOUNT for account contracts); transaction types and protocol aspects; data structures (e.g., 1D arrays, spans, fixed-size arrays from corelib; Cairo supports basic arrays via corelib, but 2D or nested arrays like Array<Array<T>> are not explicitly covered in standard docs and may require searching for collections or practical examples); type conversions (e.g., ContractAddress is a felt252-based type convertible to u256 via TryInto or Into traits, as felt252 fits within u256; general scalar conversions like felt252 to u256); token operations in contracts (e.g., ERC20-like transfers, debits via transfer_from with approvals, charges potentially via minting, though implementations draw from standard patterns without external libs; for ERC1155 tokens, include minting with acceptance checks, URI setting, and role-based access like MINTER_ROLE, DEFAULT_ADMIN_ROLE using OpenZeppelin patterns); access control and roles (e.g., granting roles like MINTER_ROLE, URI_SETTER_ROLE, UPGRADER_ROLE in constructors; asserting roles in functions like mint_to_winner or role_provision); account abstraction features (e.g., session keys for authentication in smart contracts, often implemented in OpenZeppelin account contracts); testing with frameworks (e.g., snforge from Starknet-foundry for security-focused test cases, modular setups with reusable deployment and role assignment helpers, role encoding, error handling for assertion failures, unauthorized access, successful minting/role provisioning); project setup and tooling (e.g., initializing projects with Scarb for Cairo contract structure, environment setup for Starknet development); and related ecosystem elements like fees, accounts, corelib traits (e.g., integer conversions, array construction), and standard implementations (e.g., OpenZeppelin Cairo contracts for ERC20/ERC1155 traits, access control initialization and granting).\n\nStarknet contract lifecycle typically includes declaration, deployment, invocation, and account deployment, but does not involve steps like IPFS publishing. Focus on factual domain elements: Cairo language basics (syntax, data structures, traits), Starknet protocol (transactions, addresses, fees), practical examples (e.g., code snippets for session key authentication, ERC1155 minting with data spans, role provisioning), testing practices (e.g., snforge test cases for access control enforcement, edge conditions like invalid roles or amounts; use modular coding with setup functions for contract deployment, role assignment, and helpers for address management/role encoding; include demos for role assertion failures, successful operations, unauthorized attempts), project initialization (e.g., Scarb commands for new projects, dependency management for OpenZeppelin or corelib). If the query is unrelated (e.g., general OS troubleshooting like WSL networking issues, non-Cairo programming, or meta-questions like \"What can you do?\" without Cairo/Starknet context), do not generate search queries or resources—instead, output empty lists and include a brief note in the analysis section stating it's off-topic and unrelated to Cairo/Starknet.\n\nFor relevant Cairo/Starknet queries, follow this process:\n1. Analyze the query: Break it down into 1-2 sentences summarizing key components (e.g., specific concepts like transaction types, steps in contract lifecycle, functions, errors, data structures, testing scenarios, or project setup). Identify why the query fits the domain (e.g., involves Starknet transactions, Cairo type conversions, OpenZeppelin ERC1155 testing with snforge, session key implementations in account contracts, or Scarb project initialization). Note how selected resources logically cover the topics (e.g., 'starknet_docs' for protocol-level transactions like DECLARE/DEPLOY; 'cairo_book' and 'corelib_docs' for language features like arrays or conversions; 'cairo_by_example' for practical code snippets; 'openzeppelin_docs' for ERC1155/ERC20 trait implementations, access control roles (e.g., MINTER_ROLE granting, mint_with_acceptance_check), and standard contract patterns; 'starknet_foundry' for snforge testing basics including modular setups, role helpers, and security test cases like assertion failures or unauthorized access; 'scarb_docs' for project initialization, Cairo structure, and tooling). Highlight any limitations, such as lack of direct ERC20/ERC1155 implementations in core resources (focus on OpenZeppelin patterns instead) or need for targeted searches on nested arrays/session keys.\n2. Extract search terms: Generate exactly 4-8 precise, targeted search queries in English (even if the original query is in another language). Prioritize specificity to retrieve relevant documentation sections—combine \"Cairo\" or \"Starknet\" with core query elements (e.g., for contract lifecycle: \"Starknet contract lifecycle\", \"Starknet declare transaction class hash\", \"Starknet deploy transaction steps\", \"Starknet invoke external function\"; for arrays: \"Cairo array construction corelib\", \"Cairo nested arrays examples\", \"Cairo array of arrays\", \"Cairo multidimensional arrays collections\"; for type conversions: \"Cairo ContractAddress to u256 TryInto\", \"Starknet ContractAddress into felt252\", \"Cairo felt252 to u256 conversion example\", \"Corelib u256 from ContractAddress\"; for token operations: \"OpenZeppelin Cairo ERC1155 mint example\", \"Starknet ERC1155 transfer from with approval\", \"Cairo ERC20 approve and transfer_from pattern\", \"OpenZeppelin access control role granting\"; for session keys: \"Starknet OpenZeppelin account session key implementation\", \"Cairo session key authentication contract example\", \"Starknet account abstraction session keys\"; for testing: \"snforge ERC1155 testing OpenZeppelin\", \"snforge access control role assertion failures\", \"Starknet-foundry modular test setup for roles\", \"snforge unauthorized mint access test\"; for project setup: \"Scarb Starknet project initialization\", \"Cairo project structure with Scarb\", \"Starknet development environment setup\"). Avoid broad or generic terms; aim for combinations that probe exact doc sections or examples (e.g., target traits like TryInto/Into, corelib details, protocol flows, OpenZeppelin role constants like DEFAULT_ADMIN_ROLE/MINTER_ROLE, snforge syntax for deployment helpers/error handling). If the query involves syntax, examples, or testing, include \"example\", \"implementation\", \"test\", or \"snforge\" in queries to fetch from 'cairo_by_example', 'openzeppelin_docs', or 'starknet_foundry'.\n3. Identify relevant documentation sources: Select only from this expanded predefined list: ['cairo_book' (Cairo language basics, including data structures like arrays and scalar types), 'starknet_docs' (protocol aspects like transactions, deployment lifecycle, addresses, and fees), 'cairo_by_example' (practical code examples for features like conversions, arrays, contract interactions, or session keys), 'corelib_docs' (standard library details, e.g., array types, traits like TryInto/Into for conversions, collections), 'openzeppelin_docs' (Starknet Cairo implementations for ERC20/ERC1155 tokens, access control with roles like MINTER_ROLE/DEFAULT_ADMIN_ROLE, account contracts including session key patterns, minting with data/acceptance checks, URI setters, upgraders), 'starknet_foundry' (snforge testing framework for Starknet contracts, including security test cases for access control, modular setups with reusable functions for deployment/role assignment, helpers for role encoding/address management, examples of assertion failures, successful minting/provisioning, unauthorized attempts, error handling), 'scarb_docs' (project management tool for Cairo/Starknet, initialization commands, dependency handling for OpenZeppelin/corelib, contract structure and environment setup)]. Choose 1-4 resources that directly cover the query's topics—e.g., 'starknet_docs' and 'openzeppelin_docs' for transaction types, ERC1155 lifecycle, and role-based functions; 'corelib_docs', 'cairo_book', and 'openzeppelin_docs' for type conversions or token patterns; 'cairo_by_example' and 'starknet_foundry' for testing snippets or session key examples; 'scarb_docs' and 'cairo_book' for project setup. Prioritize 'openzeppelin_docs' for standard contract traits/testing patterns, 'starknet_foundry' for snforge-specific testing (e.g., ERC1155 access control), and 'scarb_docs' for initialization. Do not include or invent any other resources (e.g., no external web guides or general libs beyond this list). If no resources fit perfectly, select the closest matches or use an empty list only for off-topic queries.\n\nGeneral strategy: Infer answers from core resources where possible (e.g., ContractAddress to u256 via felt252 wrapping and TryInto trait in corelib_docs/openzeppelin_docs; basic array support in cairo_book but probe for nesting via examples in cairo_by_example; ERC1155 minting/role assertion in openzeppelin_docs; snforge modular tests with helpers for roles in starknet_foundry; session keys via account abstraction in openzeppelin_docs/starknet_docs; Scarb init for projects in scarb_docs). For token-related or testing queries, target OpenZeppelin patterns (e.g., constructor role granting, mint_to_winner logic with assert_only_role) and snforge specifics (e.g., reusable setup for deployment, compact comments in tests). Ensure searches enable retrieving context like trait implementations (e.g., GameERC1155Impl), code snippets (e.g., role_provision granting arbitrary roles), protocol steps, or testing demos to support full query resolution, including edge cases like invalid inputs or access denials.\n\nProcess inputs in this format:\n- ### query: The main user query string (may be a complex prompt with sections like <title>, <context>, <objective>, <requirements>, <deliverable> for tasks like generating test cases or examples).\n- ### chat_history: Optional prior conversation (e.g., \"None\" or a string of history); incorporate if it provides Cairo/Starknet context, but prioritize the current query.\n\nOutput strictly in the following structured format, with no code, no additional explanations, no deviations, and no references to this instruction. Keep the analysis to 1-2 sentences. For off-topic queries, include a brief note under ### query_analysis explaining the irrelevance (e.g., \"This query is unrelated to Cairo or Starknet topics.\").\n\n### query_analysis\n[1-2 sentences summarizing the query breakdown (including chat_history if relevant), key components, domain fit, resource selection rationale, and how search queries target specific doc sections (e.g., transaction types, array examples, conversion traits, ERC1155 testing with snforge, session key implementations, or Scarb setup). For off-topic: Brief note on irrelevance.]\n\n### search_queries\n['query1', 'query2', ..., ] # Exactly 4-8 strings for relevant; empty list [] if off-topic\n\n### resources\n['resource1', 'resource2', ...] # 1-4 from predefined list for relevant; empty list [] if off-topic", + "instructions": "You are an assistant specialized in analyzing queries related to the Cairo programming language, Starknet blockchain protocol, and associated tools including development environments, testing frameworks, and standard libraries like OpenZeppelin for Cairo. Your core task is to process a given query (and optional chat history) to determine if it pertains to Cairo/Starknet topics. Relevant topics include: contract development and lifecycle (e.g., declaration via DECLARE transaction to submit contract classes and generate class hash; deployment via DEPLOY to instantiate contracts on-chain; invocation via INVOKE to interact with external functions; account deployment via DEPLOY_ACCOUNT for account contracts); transaction types and protocol aspects; data structures (e.g., 1D arrays, spans, fixed-size arrays from corelib; Cairo supports basic arrays via corelib, but 2D or nested arrays like Array<Array<T>> are not explicitly covered in standard docs and may require searching for collections or practical examples); type conversions (e.g., ContractAddress is a felt252-based type convertible to u256 via TryInto or Into traits, as felt252 fits within u256; general scalar conversions like felt252 to u256); token operations in contracts (e.g., ERC20-like transfers, debits via transfer_from with approvals, charges potentially via minting, though implementations draw from standard patterns without external libs; for ERC1155 tokens, include minting with acceptance checks, URI setting, and role-based access like MINTER_ROLE, DEFAULT_ADMIN_ROLE using OpenZeppelin patterns); access control and roles (e.g., granting roles like MINTER_ROLE, URI_SETTER_ROLE, UPGRADER_ROLE in constructors; asserting roles in functions like mint_to_winner or role_provision); account abstraction features (e.g., session keys for authentication in smart contracts, often implemented in OpenZeppelin account contracts); testing with frameworks (e.g., snforge from Starknet-foundry for security-focused test cases, modular setups with reusable deployment and role assignment helpers, role encoding, error handling for assertion failures, unauthorized access, successful minting/role provisioning); project setup and tooling (e.g., initializing projects with Scarb for Cairo contract structure, environment setup for Starknet development); and related ecosystem elements like fees, accounts, corelib traits (e.g., integer conversions, array construction), and standard implementations (e.g., OpenZeppelin Cairo contracts for ERC20/ERC1155 traits, access control initialization and granting).\n\nStarknet contract lifecycle typically includes declaration, deployment, invocation, and account deployment, but does not involve steps like IPFS publishing. Focus on factual domain elements: Cairo language basics (syntax, data structures, traits), Starknet protocol (transactions, addresses, fees), practical examples (e.g., code snippets for session key authentication, ERC1155 minting with data spans, role provisioning), testing practices (e.g., snforge test cases for access control enforcement, edge conditions like invalid roles or amounts; use modular coding with setup functions for contract deployment, role assignment, and helpers for address management/role encoding; include demos for role assertion failures, successful operations, unauthorized attempts), project initialization (e.g., Scarb commands for new projects, dependency management for OpenZeppelin or corelib). If the query is unrelated (e.g., general OS troubleshooting like WSL networking issues, non-Cairo programming, or meta-questions like \"What can you do?\" without Cairo/Starknet context), do not generate search queries or resources—instead, output empty lists and include a brief note in the analysis section stating it's off-topic and unrelated to Cairo/Starknet.\n\nFor relevant Cairo/Starknet queries, follow this process:\n1. Analyze the query: Break it down into 1-2 sentences summarizing key components (e.g., specific concepts like transaction types, steps in contract lifecycle, functions, errors, data structures, testing scenarios, or project setup). Identify why the query fits the domain (e.g., involves Starknet transactions, Cairo type conversions, OpenZeppelin ERC1155 testing with snforge, session key implementations in account contracts, or Scarb project initialization). Note how selected resources logically cover the topics (e.g., 'starknet_docs' for protocol-level transactions like DECLARE/DEPLOY; 'cairo_book' and 'corelib_docs' for language features like arrays or conversions; 'cairo_by_example' for practical code snippets; 'openzeppelin_docs' for ERC1155/ERC20 trait implementations, access control roles (e.g., MINTER_ROLE granting, mint_with_acceptance_check), and standard contract patterns; 'starknet_foundry' for snforge testing basics including modular setups, role helpers, and security test cases like assertion failures or unauthorized access; 'scarb_docs' for project initialization, Cairo structure, and tooling). Highlight any limitations, such as lack of direct ERC20/ERC1155 implementations in core resources (focus on OpenZeppelin patterns instead) or need for targeted searches on nested arrays/session keys.\n2. Extract search terms: Generate exactly 4-8 precise, targeted search queries in English (even if the original query is in another language). Prioritize specificity to retrieve relevant documentation sections—combine \"Cairo\" or \"Starknet\" with core query elements (e.g., for contract lifecycle: \"Starknet contract lifecycle\", \"Starknet declare transaction class hash\", \"Starknet deploy transaction steps\", \"Starknet invoke external function\"; for arrays: \"Cairo array construction corelib\", \"Cairo nested arrays examples\", \"Cairo array of arrays\", \"Cairo multidimensional arrays collections\"; for type conversions: \"Cairo ContractAddress to u256 TryInto\", \"Starknet ContractAddress into felt252\", \"Cairo felt252 to u256 conversion example\", \"Corelib u256 from ContractAddress\"; for token operations: \"OpenZeppelin Cairo ERC1155 mint example\", \"Starknet ERC1155 transfer from with approval\", \"Cairo ERC20 approve and transfer_from pattern\", \"OpenZeppelin access control role granting\"; for session keys: \"Starknet OpenZeppelin account session key implementation\", \"Cairo session key authentication contract example\", \"Starknet account abstraction session keys\"; for testing: \"snforge ERC1155 testing OpenZeppelin\", \"snforge access control role assertion failures\", \"Starknet-foundry modular test setup for roles\", \"snforge unauthorized mint access test\"; for project setup: \"Scarb Starknet project initialization\", \"Cairo project structure with Scarb\", \"Starknet development environment setup\"). Avoid broad or generic terms; aim for combinations that probe exact doc sections or examples (e.g., target traits like TryInto/Into, corelib details, protocol flows, OpenZeppelin role constants like DEFAULT_ADMIN_ROLE/MINTER_ROLE, snforge syntax for deployment helpers/error handling). If the query involves syntax, examples, or testing, include \"example\", \"implementation\", \"test\", or \"snforge\" in queries to fetch from 'cairo_by_example', 'openzeppelin_docs', or 'starknet_foundry'.\n3. Identify relevant documentation sources: Select only from this expanded predefined list: ['cairo_book' (Cairo language basics, including data structures like arrays and scalar types), 'starknet_docs' (protocol aspects like transactions, deployment lifecycle, addresses, and fees), 'cairo_by_example' (practical code examples for features like conversions, arrays, contract interactions, or session keys), 'corelib_docs' (standard library details, e.g., array types, traits like TryInto/Into for conversions, collections), 'openzeppelin_docs' (Starknet Cairo implementations for ERC20/ERC1155 tokens, access control with roles like MINTER_ROLE/DEFAULT_ADMIN_ROLE, account contracts including session key patterns, minting with data/acceptance checks, URI setters, upgraders), 'starknet_foundry' (snforge testing framework for Starknet contracts, including security test cases for access control, modular setups with reusable functions for deployment/role assignment, helpers for role encoding/address management, examples of assertion failures, successful minting/provisioning, unauthorized attempts, error handling), 'scarb_docs' (project management tool for Cairo/Starknet, initialization commands, dependency handling for OpenZeppelin/corelib, contract structure and environment setup), 'starknet_js' (StarknetJS library for front-end interactions, contract calls and transactions, deployment, JavaScript/TypeScript integration), 'starknet_blog' (latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, community updates, recent innovations, new tools, partnerships, protocol enhancements)]. Choose 1-4 resources that directly cover the query's topics—e.g., 'starknet_docs' and 'openzeppelin_docs' for transaction types, ERC1155 lifecycle, and role-based functions; 'corelib_docs', 'cairo_book', and 'openzeppelin_docs' for type conversions or token patterns; 'cairo_by_example' and 'starknet_foundry' for testing snippets or session key examples; 'scarb_docs' and 'cairo_book' for project setup; 'starknet_blog' for recent ecosystem updates or new features, starknet apps and protocols. Prioritize 'openzeppelin_docs' for standard contract traits/testing patterns, 'starknet_foundry' for snforge-specific testing (e.g., ERC1155 access control), and 'scarb_docs' for initialization. Do not include or invent any other resources (e.g., no external web guides or general libs beyond this list). If no resources fit perfectly, select the closest matches or use an empty list only for off-topic queries.\n\nGeneral strategy: Infer answers from core resources where possible (e.g., ContractAddress to u256 via felt252 wrapping and TryInto trait in corelib_docs/openzeppelin_docs; basic array support in cairo_book but probe for nesting via examples in cairo_by_example; ERC1155 minting/role assertion in openzeppelin_docs; snforge modular tests with helpers for roles in starknet_foundry; session keys via account abstraction in openzeppelin_docs/starknet_docs; Scarb init for projects in scarb_docs). For token-related or testing queries, target OpenZeppelin patterns (e.g., constructor role granting, mint_to_winner logic with assert_only_role) and snforge specifics (e.g., reusable setup for deployment, compact comments in tests). Ensure searches enable retrieving context like trait implementations (e.g., GameERC1155Impl), code snippets (e.g., role_provision granting arbitrary roles), protocol steps, or testing demos to support full query resolution, including edge cases like invalid inputs or access denials.\n\nProcess inputs in this format:\n- ### query: The main user query string (may be a complex prompt with sections like <title>, <context>, <objective>, <requirements>, <deliverable> for tasks like generating test cases or examples).\n- ### chat_history: Optional prior conversation (e.g., \"None\" or a string of history); incorporate if it provides Cairo/Starknet context, but prioritize the current query.\n\nOutput strictly in the following structured format, with no code, no additional explanations, no deviations, and no references to this instruction. Keep the analysis to 1-2 sentences. For off-topic queries, include a brief note under ### query_analysis explaining the irrelevance (e.g., \"This query is unrelated to Cairo or Starknet topics.\").\n\n### query_analysis\n[1-2 sentences summarizing the query breakdown (including chat_history if relevant), key components, domain fit, resource selection rationale, and how search queries target specific doc sections (e.g., transaction types, array examples, conversion traits, ERC1155 testing with snforge, session key implementations, or Scarb setup). For off-topic: Brief note on irrelevance.]\n\n### search_queries\n['query1', 'query2', ..., ] # Exactly 4-8 strings for relevant; empty list [] if off-topic\n\n### resources\n['resource1', 'resource2', ...] # 1-4 from predefined list for relevant; empty list [] if off-topic", "fields": [ { "prefix": "Chat History:", @@ -19,7 +19,7 @@ }, { "prefix": "Resources:", - "description": "List of documentation sources. If unsure what to use or if the query is not clear, use all of the available sources. Available sources: cairo_book: The Cairo Programming Language Book. Essential for core language syntax, semantics, types (felt252, structs, enums, Vec), traits, generics, control flow, memory management, writing tests, organizing a project, standard library usage, starknet interactions. Crucial for smart contract structure, storage, events, ABI, syscalls, contract deployment, interaction, L1<>L2 messaging, Starknet-specific attributes. Very important for interactions with the Starknet state and context (e.g. block, transaction) through syscalls., starknet_docs: The Starknet Documentation. For the Starknet protocol, the STWO prover, architecture, APIs, syscalls, network interaction, deployment, ecosystem tools (Starkli, indexers, StarknetJS, wallets), general Starknet knowledge. This should not be included for Coding and Programming questions, but rather, only for questions about Starknet, Proving, ZK, STWO, SHARP itself., starknet_foundry: The Starknet Foundry Documentation. For using the Foundry toolchain: `snforge` for writing, compiling, testing (unit tests, integration tests), and debugging Starknet contracts. `sncast` for deploying and interacting with contracts to Starknet., cairo_by_example: Cairo by Example Documentation. Provides practical Cairo code snippets for specific language features or common patterns. Useful for how-to syntax questions. This should not be included for Smart Contract questions, but for all other Cairo programming questions., openzeppelin_docs: OpenZeppelin Cairo Contracts Documentation. For using the OZ library: standard implementations (ERC20, ERC721), access control, security patterns, contract upgradeability. Crucial for building standard-compliant contracts., corelib_docs: Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions., scarb_docs: Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml., starknet_js: StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet." + "description": "List of documentation sources. If unsure what to use or if the query is not clear, use all of the available sources. Available sources: cairo_book: The Cairo Programming Language Book. Essential for core language syntax, semantics, types (felt252, structs, enums, Vec), traits, generics, control flow, memory management, writing tests, organizing a project, standard library usage, starknet interactions. Crucial for smart contract structure, storage, events, ABI, syscalls, contract deployment, interaction, L1<>L2 messaging, Starknet-specific attributes. Very important for interactions with the Starknet state and context (e.g. block, transaction) through syscalls., starknet_docs: The Starknet Documentation. For the Starknet protocol, the STWO prover, architecture, APIs, syscalls, network interaction, deployment, ecosystem tools (Starkli, indexers, StarknetJS, wallets), general Starknet knowledge. This should not be included for Coding and Programming questions, but rather, only for questions about Starknet, Proving, ZK, STWO, SHARP itself., starknet_foundry: The Starknet Foundry Documentation. For using the Foundry toolchain: `snforge` for writing, compiling, testing (unit tests, integration tests), and debugging Starknet contracts. `sncast` for deploying and interacting with contracts to Starknet., cairo_by_example: Cairo by Example Documentation. Provides practical Cairo code snippets for specific language features or common patterns. Useful for how-to syntax questions. This should not be included for Smart Contract questions, but for all other Cairo programming questions., openzeppelin_docs: OpenZeppelin Cairo Contracts Documentation. For using the OZ library: standard implementations (ERC20, ERC721), access control, security patterns, contract upgradeability. Crucial for building standard-compliant contracts., corelib_docs: Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions., scarb_docs: Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml., starknet_js: StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet., starknet_blog: Starknet Blog Documentation. For latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, and community updates. Useful for understanding recent Starknet innovations, new tools and applications on starknet, partnerships, and protocol enhancements." } ] }, diff --git a/python/src/cairo_coder/core/types.py b/python/src/cairo_coder/core/types.py index d76c7cb..60ac843 100644 --- a/python/src/cairo_coder/core/types.py +++ b/python/src/cairo_coder/core/types.py @@ -38,6 +38,7 @@ class DocumentSource(str, Enum): CORELIB_DOCS = "corelib_docs" SCARB_DOCS = "scarb_docs" STARKNET_JS = "starknet_js" + STARKNET_BLOG = "starknet_blog" class DocumentMetadata(TypedDict, total=False): diff --git a/python/src/cairo_coder/dspy/query_processor.py b/python/src/cairo_coder/dspy/query_processor.py index 1c5316c..6886bfc 100644 --- a/python/src/cairo_coder/dspy/query_processor.py +++ b/python/src/cairo_coder/dspy/query_processor.py @@ -26,6 +26,7 @@ DocumentSource.CORELIB_DOCS: "Cairo Core Library Documentation. For using the Cairo core library: basic types, stdlib functions, stdlib structs, macros, and other core concepts. Essential for Cairo programming questions.", DocumentSource.SCARB_DOCS: "Scarb Documentation. For using the Scarb package manager: building, compiling, generating compilation artifacts, managing dependencies, configuration of Scarb.toml.", DocumentSource.STARKNET_JS: "StarknetJS Documentation. For using the StarknetJS library: interacting with Starknet contracts, (calls and transactions), deploying Starknet contracts, front-end APIs, javascript integration examples, guides, tutorials and general JS/TS documentation for starknet.", + DocumentSource.STARKNET_BLOG: "Starknet Blog Documentation. For latest Starknet updates, announcements, feature releases, ecosystem developments, integration guides, and community updates. Useful for understanding recent Starknet innovations, new tools, partnerships, and protocol enhancements.", } # Ensure all DocumentSource variants are covered diff --git a/python/src/scripts/docs_crawler.py b/python/src/scripts/docs_crawler.py index b003b36..498440d 100755 --- a/python/src/scripts/docs_crawler.py +++ b/python/src/scripts/docs_crawler.py @@ -282,10 +282,6 @@ def extract_content(self, html: str, url: str) -> tuple[str, str]: if any(keyword in tag_id or keyword in tag_classes for keyword in boilerplate_keywords): tags_to_remove.append(tag) - # Now decompose all collected tags - for tag in tags_to_remove: - tag.decompose() - # Try to find main content main_content = None @@ -347,8 +343,6 @@ def compile_markdown(self) -> str: lines = [ f"# {self.domain} — Snapshot ({date_str})", "", - "", - "---", "" ] @@ -362,15 +356,17 @@ def compile_markdown(self) -> str: if not markdown or len(markdown.strip()) < 50: markdown = "*No content extracted.*" + # Add individual Sources block for this page lines.extend([ - f"**Source URL:** {url}", + "---", + "Sources:", + f" - {url}", + "---", "", f"## {title}", "", markdown, "", - "---", - "" ]) else: # Skip pages that failed to fetch or returned non-HTML content diff --git a/python/src/scripts/filter_2025_blogs.py b/python/src/scripts/filter_2025_blogs.py new file mode 100644 index 0000000..22066ef --- /dev/null +++ b/python/src/scripts/filter_2025_blogs.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +""" +Filter doc_dump.md to keep only blog entries published in 2025. + +Reads the doc_dump.md file, identifies individual pages separated by "---", +and filters to keep only those containing blog entries with 2025 dates. +""" + +import re +from pathlib import Path + + +def is_2025_blog_entry(content: str) -> bool: + """ + Check if content contains a blog entry from 2025. + + Looks for patterns like: + Home / Blog + Feb 5, 2023 · 2 min read + + Returns True if the date is from 2025. + """ + # Look for the blog pattern with date + # Pattern: Month Day, Year · time min read + blog_pattern = r'Home\s+/\s+Blog.*?(\w+\s+\d+,\s+(\d{4}))\s+·' + + matches = re.findall(blog_pattern, content, re.DOTALL | re.IGNORECASE) + + for match in matches: + year = match[1] + if year == '2025': + return True + + return False + + +def filter_doc_dump(input_file: Path, output_file: Path): + """ + Read doc_dump.md and filter to keep only 2025 blog entries. + Supports both old format (single Sources block) and new format (individual Sources blocks). + """ + with open(input_file, encoding='utf-8') as f: + content = f.read() + + filtered_pages = [] + total_pages = 0 + kept_pages = 0 + document_header = "" + + # Try new format first (individual Sources blocks) + page_pattern = r'(---\s*\nSources:\s*\n\s*-\s*[^\n]+\n---\s*\n+##[^#].*?)(?=\n---\s*\nSources:|\Z)' + matches = list(re.finditer(page_pattern, content, re.DOTALL)) + + if matches: + # New format detected + print("Detected new format (individual Sources blocks)") + + # Keep document header if present + header_match = re.match(r'^(.*?)(?=\n---\s*\nSources:)', content, re.DOTALL) + document_header = header_match.group(1).strip() if header_match else "" + + for match in matches: + page = match.group(1) + if not page.strip(): + continue + + total_pages += 1 + + # Check if this is a 2025 blog entry + if is_2025_blog_entry(page): + filtered_pages.append(page.strip()) + kept_pages += 1 + + # Extract URL for logging (from Sources block) + url_match = re.search(r'Sources:\s*\n\s*-\s*(.+)', page) + if url_match: + print(f"Keeping: {url_match.group(1)}") + else: + # Fall back to old format (**Source URL:** markers) + print("Detected old format (**Source URL:** markers)") + + pattern = re.compile(r'^\*\*Source URL:\*\*\s+(\S+)', re.MULTILINE) + page_matches = list(pattern.finditer(content)) + + for i, m in enumerate(page_matches): + url = m.group(1) + start = m.end() + end = page_matches[i + 1].start() if i + 1 < len(page_matches) else len(content) + page_content = content[start:end].strip() + + # Remove surrounding '---' separators + lines = page_content.splitlines() + while lines and lines[0].strip() == '---': + lines.pop(0) + while lines and lines[-1].strip() == '---': + lines.pop() + page_content = "\n".join(lines).strip() + + total_pages += 1 + + if is_2025_blog_entry(page_content): + # Convert to new format + new_format_page = f"---\nSources:\n - {url}\n---\n\n{page_content}" + filtered_pages.append(new_format_page) + kept_pages += 1 + print(f"Keeping: {url}") + + # Construct output with header and filtered pages + output_parts = [] + if document_header: + output_parts.append(document_header) + output_parts.append("") + output_parts.append("") + + output_parts.extend(filtered_pages) + output_content = '\n\n'.join(output_parts) + + # Write to output file + with open(output_file, 'w', encoding='utf-8') as f: + f.write(output_content) + + print(f"\n{'-'*60}") + print(f"Total pages processed: {total_pages}") + print(f"Pages kept (2025 blogs): {kept_pages}") + print(f"Pages removed: {total_pages - kept_pages}") + print(f"Output written to: {output_file}") + + +def main(): + # Paths + script_dir = Path(__file__).parent + python_dir = script_dir.parent.parent + input_file = python_dir / "doc_dump.md" + output_file = python_dir / "doc_dump_2025_blogs.md" + + if not input_file.exists(): + print(f"Error: Input file not found: {input_file}") + return + + print(f"Reading from: {input_file}") + print("Filtering for 2025 blog entries...\n") + + filter_doc_dump(input_file, output_file) + + +if __name__ == "__main__": + main() diff --git a/python/src/scripts/summarizer/doc_dump_summarizer.py b/python/src/scripts/summarizer/doc_dump_summarizer.py index 5182bda..df0dc98 100644 --- a/python/src/scripts/summarizer/doc_dump_summarizer.py +++ b/python/src/scripts/summarizer/doc_dump_summarizer.py @@ -90,8 +90,29 @@ def summarize_content(self, content: str) -> str: # Helpers @staticmethod def _parse_doc_dump(text: str) -> list[_DocPage]: - """Split the doc dump by '**Source URL:**' markers and return pages.""" - # Find all '**Source URL:** <url>' markers + """Parse doc dump - supports old format (with '**Source URL:**') and new format (individual Sources blocks).""" + # Try new format first (individual Sources blocks before each section) + # Pattern: ---\nSources:\n - <url>\n---\n\n## <title>... + page_pattern = re.compile( + r'---\s*\nSources:\s*\n\s*-\s*(\S+)\s*\n---\s*\n+(##[^#].*?)(?=\n---\s*\nSources:|\Z)', + re.DOTALL | re.MULTILINE + ) + + matches = list(page_pattern.finditer(text)) + + if matches: + # New format: individual Sources blocks + pages: list[_DocPage] = [] + for match in matches: + url = match.group(1) + content = match.group(2).strip() + pages.append(_DocPage(url=url, content=content)) + + if pages: + logger.info(f"Parsed {len(pages)} pages using new individual Sources block format") + return pages + + # Fall back to old format (with '**Source URL:**' markers) pattern = re.compile(r"^\*\*Source URL:\*\*\s+(\S+)", re.MULTILINE) pages: list[_DocPage] = [] matches = list(pattern.finditer(text)) @@ -103,6 +124,10 @@ def _parse_doc_dump(text: str) -> list[_DocPage]: content = text[start:end].strip() content = DocDumpSummarizer._strip_leading_trailing_separators(content) pages.append(_DocPage(url=url, content=content)) + + if pages: + logger.info(f"Parsed {len(pages)} pages using old **Source URL:** format") + return pages @staticmethod @@ -124,4 +149,3 @@ def _infer_title(pages: list[_DocPage]) -> str: seg = first.split('/')[-1] or "documentation" name = seg.replace('-', ' ').title() return f"# {name} Documentation Summary" - diff --git a/python/src/scripts/summarizer/generated/blog_summary.md b/python/src/scripts/summarizer/generated/blog_summary.md new file mode 100644 index 0000000..bdeb719 --- /dev/null +++ b/python/src/scripts/summarizer/generated/blog_summary.md @@ -0,0 +1,4450 @@ +# www.starknet.io — Snapshot (2025-10-09) + +--- + +Sources: + +- https://www.starknet.io/blog/introducing-garden-on-starknet-a-direct-path-for-btc-bridging/ + +--- + +## Bridge BTC to Starknet: Introducing Garden + +Home  /  Blog + +Apr 29, 2025 · 2 min read + +We’re thrilled to announce that Garden – a bridge for BTC-native liquidity – is now live on Starknet. This launch creates a direct, streamlined path for Bitcoin to flow into Starknet, focusing on speed, low fees, and minimal trust assumptions. + +## What Sets Garden Apart + +Garden’s integration with Starknet makes it easy for Bitcoin holders to access Starknet while keeping control of their assets. At the same time, it allows developers and DeFi protocols to tap into BTC liquidity, unlocking new possibilities for apps and flows across the Starknet ecosystem. Sending BTC to Starknet is now straightforward, whether using a crypto wallet like Argent or swapping directly on Garden. The entire process is simplified with a real-time system that finds the best route for your transaction, keeping costs low and execution fast, even for larger trades. On Garden, swap BTC, USDC, WBTC, cbBTC, and more from Bitcoin, Base, Arbitrum, Ethereum, Berachain, and Hyperliquid to Starknet in a single click. + +Bridge BTC to Starknet → + +## More About Starknet + +Starknet is a general-purpose L2 ZK-Rollup that operates above Ethereum and allows users to write and deploy smart contracts and interact with other contracts. Starknet produces bundled transactions offchain via STARK proofs, which are then submitted to Ethereum as a single transaction, allowing dApps to scale while benefiting from Ethereum’s security features massively. Starknet will be the first L2 to settle on both Bitcoin and Ethereum, unifying the two largest blockchains on a single layer. As an L2 on top of Bitcoin, Starknet will become Bitcoin’s execution layer, to trustlessly scale Bitcoin to thousands of transactions per second (TPS). + +Explore Starknet’s vision and roadmap to see how this aligns with broader ecosystem growth. If you’re deep into Bitcoin, building the next wave of DeFi, or just excited about where Ethereum is heading, now’s the time to plug in and bridge BTC to Starknet. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Atomiq brings wBTC to Starknet, enabling Bitcoin DeFi + + BTC-to-wBTC swaps are now live on Starknet using onchain escrows and Bitcoin PoW validation, with no bridges or custodians. + + April 16, 2025 + +- #### Starknet over Bitcoin: Vitalik, Dan Held, and Jeremy Rubin react + + Starknet will become the first Layer 2 to settle on Bitcoin. Learn what Vitalik Buterin and two Bitcoin OGs think about the move. + + March 30, 2025 + +- #### Bitcoin Lightning Network payments with STRK—now live on Starknet via Braavos + + Braavos now enables Bitcoin Lightning Network payments with STRK on Starknet—no BTC, no extra setup, just tap and pay + + March 13, 2025 + +- #### Starknet on Bitcoin and Ethereum: The first L2 to unify both chains + + Starknet will become Bitcoin’s execution layer, massively scaling Bitcoin and opening the door to complex Bitcoin applications. + + March 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/lombard-brings-bitcoin-to-starknet-through-lbtc-integration/ + +--- + +## Bringing Bitcoin to Starknet with Lombard's LBTC + +Home  /  Blog + +May 14, 2025 · 2 min read + +Starknet is proud to announce a strategic partnership with Lombard Protocol, a Bitcoin staking protocol and developer of LBTC. Lombard is bringing LBTC—the leading liquid staked Bitcoin asset—into the Starknet ecosystem, unlocking new earning opportunities and pushing forward a powerful vision: a single, scalable execution layer for both Ethereum and Bitcoin. + +## What is LBTC? + +LBTC is liquid-staked Bitcoin, built on top of Babylon, free to be used across DeFi. Each LBTC token is fully backed 1:1 by real BTC, staked to the Babylon Bitcoin staking protocol. Users obtain LBTC by staking native BTC on the Lombard Protocol, effectively locking their Bitcoin and receiving an equal amount of LBTC in return. This asset can be used for lending, borrowing, trading, and liquidity provisioning across many blockchains, including Ethereum, Base, and Sui. + +## LBTC on Starknet + +Over the coming months, users will be able to stake native BTC for LBTC and bridge LBTC to and from Starknet with ease. Starknet users will gain access to LBTC and Lombard’s DeFi vault through the upcoming integration. This initiative is designed to activate Bitcoin capital within the fast-growing Starknet DeFi ecosystem, offering a secure and seamless experience for both institutional and individual users. + +Institutions will gain a powerful tool to deploy Bitcoin capital across DeFi dApps with greater scalability. Retail users and app developers will benefit from increased liquidity, earn-generating strategies, and new use cases. + +## Lombard and Starknet + +Lombard Protocol’s mission to bring Bitcoin into DeFi aligns perfectly with Starknet’s long-term vision of becoming the execution layer for both Ethereum and Bitcoin. This collaboration represents a key milestone in building a modular, multi-chain DeFi ecosystem, where assets from both chains can flow freely and unlock new possibilities. + +With its focus on decentralization, Starknet is emerging as a natural home for Bitcoin assets in DeFi, offering a reliable foundation for BTC’s thriving in a cross-chain, modular ecosystem. + +**Stay tuned for the integration** + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-bitcoin-scaling/ + +--- + +## Starknet scaling Bitcoin: The first L2 to settle on Bitcoin & Ethereum + +Home  /  Blog + +Mar 11, 2025 · 7 min read + +Bitcoin is more than just a financial asset: It’s a movement rooted in individual sovereignty and the separation of money from the state. Over the past 16 years, it has empowered millions of people around the world to reclaim control over their assets, catalyzing a revolution in how we think about money and trust. And yet, most Bitcoin today sits static in wallets and exchanges, constrained by the limitations of the network’s original design: a lack of scalability and an inability to natively support applications beyond simple buying, selling, and transferring. + +Starknet is embarking on a journey to lift both of those limitations and unleash Bitcoin’s full potential, all while preserving its core principles. Developed in part by the inventors of STARK proofs, Starknet will become the first Layer 2 to settle on both Bitcoin and Ethereum, unifying the world’s largest blockchains on a single layer. The goal is **_to serve 1 billion Bitcoin users_,** introducing improved UX, scale, and liquidity—all without compromising on security or decentralization. + +Efforts across the Starknet ecosystem are already underway to prepare the grounds to achieve this goal. Alongside the continued research and advocacy for OP_CAT, the proposed Bitcoin upgrade that would pave the way for natively bridging Starknet to the network, the following announcements were just unveiled: + +- **Xverse integration**: The leading Bitcoin wallet, Xverse, will integrate with Starknet, enabling the use of Bitcoin assets on Starknet for the first time. +- **BTCFi Season**: The Starknet Foundation is introducing BTCFi Season, a program that will introduce a range of opportunities to put your Bitcoin to work through Starknet. +- **Strategic Bitcoin Reserve**: StarkWare, the company behind the STARK proof that contributes to the development of Starknet, is a Bitcoin-standard company and now has a Strategic Bitcoin Reserve (SBR), holding a growing portion of its treasury as BTC. +- **Lightning Network payments:** Anyone using the Braavos wallet mobile app can scan a QR code and make instant payments using STRK at any vendor that accepts Lightning Network payments. + +Now, let’s dive deeper into the vision for Starknet over Bitcoin. + +## The Starknet vision for Bitcoin + +### The challenge + +Bitcoin set the bar for the core values that make blockchain transformative: decentralization, trustlessness, and censorship-resistance. The vast majority of Bitcoin, however, isn’t being used for anything beyond buying, selling, and long-term investing (HODLing). + +While some investors view Bitcoin as digital gold—a long-term hedge against inflation and economic instability, rather than as an asset to actively trade or leverage—there is a demand for utilizing Bitcoin for purposes beyond that. Think, for example, of using Bitcoin as collateral to buy assets outside the digital domain or to earn the way you do with many other assets. Interviews and research conducted by StarkWare—the company that initially developed the zero-knowledge (ZK) technology that powers Starknet—identified three main barriers to doing so: + +- **Limited Bitcoin functionality:** The Bitcoin network doesn’t natively support complex applications, restricting it primarily to simple transactions and holding (HODLing). +- **Security & centralization risks:** Applications that enable DeFi actions outside of Bitcoin often involve custodial or third-party platforms that introduce risk (e.g. the Celsius, BlockFi, and FTX collapses). +- **Slow, costly transactions:** Bitcoin’s block times and fees can deter everyday transactions or more sophisticated onchain use cases. + +Starknet will make these challenges obsolete. + +### The Starknet solution + +As a Layer 2 on top of Bitcoin, Starknet will become **Bitcoin’s execution layer,** with the goal of trustlessly scaling Bitcoin from 13 transactions per second (TPS) to thousands**.** Because Starknet will enable native expressiveness on Bitcoin at scale for the first time, it will open the floodgates to more complex applications that were previously not supported on Bitcoin. + +With its battle-tested technology, Starknet will bring Bitcoin: + +- **Layer 2 scaling:** Starknet scales blockchain by executing many transactions offchain and bundling them into a single STARK proof that attests to their validity on L1. +- **STARK proofs:** These proofs are quantum-resistant and require no trusted setup, ensuring trustlessness and high security for all Bitcoin-centric activities on Starknet. +- **Instant & cheap transactions:** Starknet transactions finalize in seconds and cost fractions of a cent, addressing Bitcoin’s scalability bottleneck. +- **Expressiveness:** Developers will be able to build a wide variety of DeFi and other complex applications on Bitcoin through Starknet’s smart contract functionality. Applications such as staking, borrowing and lending, leveraged trading, and yield farming will become natively possible on Bitcoin via Starknet. + +With these advantages and more, Starknet is fully equipped to scale Bitcoin with integrity while expanding its utility. + +### Long-term impact + +By scaling Bitcoin and enabling more sophisticated applications on the Bitcoin blockchain in a trustless environment, Starknet will unleash the true potential of the world’s original blockchain. This will result in: + +- **Global reach:** The goal is for Starknet to serve **a billion Bitcoin users**, bringing mainstream financial-grade functionality to the Bitcoin network. +- **Security & decentralization:** Starknet enables Bitcoiners to do more with their Bitcoin on Starknet without compromising on security, as Starknet progresses toward its own decentralized operation. +- **Unified blockchain ecosystem:** With Bitcoin and Ethereum consolidated on Starknet’s execution layer, the broader blockchain community can enjoy faster, cheaper, and more secure onchain interactions. + +### Why Starknet? + +After years of operating on Ethereum, Starknet is the cheapest Layer 2 with Ethereum data availability (DA) and near-instant transaction confirmation, powered by the most advanced ZK tech stack in the blockchain industry. With the following advantages and more, Starknet is fully equipped to bring massive scale to Bitcoin while preserving its core principles: + +- **Proven track record:** The technology behind Starknet has already processed millions of transactions on Ethereum, with cumulative trading of +1.3 trillion USD. +- **Built by the original creators of STARKs:** The STARK proofs used on Starknet were developed by the original inventors of the technology itself. +- **Enhanced user experience:** Native account abstraction means more familiar login methods (fingerprint, face ID), and other features that simplify crypto usage. + +### Breakthrough research on Bitcoin scaling + +The StarkWare team that originally pioneered the technology behind Starknet has invested time and resources into Bitcoin research to promote Bitcoin scaling, bolstered by its OP_CAT research fund. These efforts have already yielded notable achievements. + +Collider-script, for example, introduced a method for enforcing covenants on Bitcoin outputs without requiring any changes to Bitcoin. Covenants are one of the primary components necessary for bringing smart contracts-and therefore expressiveness-to Bitcoin. This was followed by the demonstration of a demo bridge covenant on Bitcoin, which aims to be the foundation of a production-grade bridge from Bitcoin to Starknet. + +In an open-source effort, led by Weikeng Chen and Pinghzou Yuan, StarkWare has already verified the first-ever ZK proof on Bitcoin’s Signet test network using its STARK verifier. + +### Why now? + +While Starknet started by settling on the Ethereum blockchain, its roots in Bitcoin are deep—pre-Ethereum deep. It all started when Professor Eli Ben-Sasson, CEO and Co-Founder of StarkWare, spoke at the Bitcoin Conference in San Jose back in 2013. It was then that he first introduced the idea of using ZK proofs (specifically, the tech later called zk-STARK) to scale Bitcoin. + +Since then, Starknet emerged to bring massive scalability to Ethereum with STARK proofs as its core security technology. Now, as Bitcoin sees record global interest and demand, the time has come for Starknet to step up to its next challenge. + +## How will this be achieved? + +### The Starknet experience on Bitcoin now + +Bitcoin users deserve to be able to utilize their Bitcoin with confidence, and the highest level of security and decentralization. Starknet stakeholders have been and will continue to educate about and advocate for OP_CAT, a proposed Bitcoin upgrade that would, as StarkWare has identified, open the door to natively settling Starknet on Bitcoin. Even before the OP_CAT upgrade, however, efforts will be made to enable using Bitcoin on Starknet with the following kinds of bridges: + +#### Federated model (multisig) + +In the federated model of bridging Starknet to Bitcoin, a group of co-signers collectively safeguards the Bitcoin tokens locked and minted on Starknet through a multisig. The federation is accountable for minting an identical amount of wrapped Bitcoin on Starknet as the amount being bridged. The multisig bridge enables lower fees and elevated UX, but requires that the majority of the signers are honest participants, limiting network liveness. + +#### BitVM + +BitVM is the most secure way to bridge Bitcoin without OP_CAT. Instead of working with a multisig, BitVM requires that only one of the operators is honest. It enables this by enforcing the logic with a dispute-resolution mechanism powered by cryptographic proofs. + +### OP_CAT readiness + +The OP_CAT soft fork, if it passes, will open the door to covenants and native L2 scaling and expressiveness on Bitcoin, empowering the world’s first blockchain to live up to its potential to disrupt traditional financial systems. + +Covenants enable programmable spending rules and, therefore, native smart contracts. Together with STARK proofs, they make it possible to build a fully trustless, native bridge from Bitcoin to Starknet. This native bridge will function without any additional operators or trust assumptions, providing Bitcoin users with the maximal level of security, decentralization, and self-custody. + +A more technical, deeper dive into how Starknet will settle on Bitcoin will be shared in the coming days. + +## Next steps + +In the next few months, several products and partnerships will pave the way for the best possible L2 experience for Bitcoiners on Starknet. These include offerings and incentives that users will be able to enjoy, as well as announcements on major milestones in the research being conducted: + +- **Partnerships:** Starknet stakeholders are forming alliances with key Bitcoin ecosystem players, including wallet providers and researchers. +- **New products & offerings:** Multiple new products and retail offerings will be introduced in the coming months to encourage the adoption of Starknet for Bitcoin. +- **BTCFi Season:** The Starknet Foundation is introducing BTCFi Season, a program designed to open up a range of opportunities to all Bitcoin users. This program will incentivize Bitcoin holders to participate in DeFi on Starknet, allowing users to put their Bitcoin to work in a wide variety of ways. Sign up with your email to be among the first to know when the program goes live. +- **Research & Education:** Ongoing efforts focus on advocating for Bitcoin upgrades like OP_CAT and exploring how STARK proofs can scale Bitcoin’s functionality. StarkWare launched the OP_CAT Research Fund for this purpose. + +## What should you do now? + +Starknet stakeholders are already moving quickly to make Starknet the first Layer 2 to unify Bitcoin and Ethereum without compromising their integrity. What should you do in the meantime? + +Start by setting up a Starknet wallet and check out the Bitcoin DeFi opportunities on BTCFi Season. Browse Starknet’s apps—exactly the kinds of apps that Starknet will make possible on Bitcoin. If you’re a builder who is excited about Starknet as the unifying execution layer for Bitcoin and Ethereum and would like to build the next killer app, check out the Starknet docs to get started. + +Follow Starknet on X to stay updated on all upcoming news. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Introducing Garden on Starknet: A direct path for BTC bridging + + Garden is live on Starknet, offering a direct path for Bitcoin liquidity. Bridge Bitcoin to Starknet with Garden for fast, low-fee DeFi. + + April 29, 2025 + +- #### Atomiq brings wBTC to Starknet, enabling Bitcoin DeFi + + BTC-to-wBTC swaps are now live on Starknet using onchain escrows and Bitcoin PoW validation, with no bridges or custodians. + + April 16, 2025 + +- #### Starknet over Bitcoin: Vitalik, Dan Held, and Jeremy Rubin react + + Starknet will become the first Layer 2 to settle on Bitcoin. Learn what Vitalik Buterin and two Bitcoin OGs think about the move. + + March 30, 2025 + +- #### Bitcoin Lightning Network payments with STRK—now live on Starknet via Braavos + + Braavos now enables Bitcoin Lightning Network payments with STRK on Starknet—no BTC, no extra setup, just tap and pay + + March 13, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/decentralized-starknet-2025/ + +--- + +## Starknet’s Decentralization Roadmap in 2025 + +Home  /  Blog + +Feb 26, 2025 · 5 min read + +Blockchain makes it possible for people to control their assets and transact directly with others on a trustless, secure, and censorship-resistant network. That ideal has the potential to transform entire industries, and it can only be achieved on blockchains that are truly decentralized. Blockchains dominated by a single party or conglomerate don’t _really_ have an edge over traditional, centralized networks. + +With the goal of bringing blockchain’s promise to everyone, Starknet is on the path to becoming the first fully decentralized Layer 2 (L2) that massively scales Ethereum. The recent launch of the first phase of staking on Starknet was a leap toward greater decentralization. This year, efforts to enhance Starknet’s decentralization will ramp up on top of continued performance optimizations. + +## Decentralized Starknet in 2025 + +Ethereum was the first blockchain to enable general-purpose computing. It earned its reputation for staying true to the first principles of blockchain: decentralization and security. As a Layer on top of—and thus an extension of—Ethereum, Starknet must also be decentralized and secure. + +The terms “decentralization” and “security” are often used interchangeably. While it’s true that decentralization enhances security, we distinguish between the two in this post. That’s because, unlike other L2 rollups, Starknet has had its ironclad security technology—STARK proofs—in place from the beginning. There has never been a state update approved on Starknet that wasn’t validated by a proof. That means it’s virtually impossible for an invalid transaction to be processed on Starknet. This post will zero in specifically on Starknet’s decentralization journey, and the ways in which it will progress in 2025. + +Starknet’s road to decentralization runs on three main lanes: + +- **Staking:** Building economic security on Starknet toward the decentralized operation of its Proof-of-Stake (PoS) consensus mechanism + +- **Operation:** The decentralization of Starknet’s operation + +- **Governance:** The independence of the Starknet Security Council + +Let’s dive into Starknet’s progress in each of these lanes, and what’s coming up. + +#### Breaking speed records with 992 peak TPS + +Build Lightning-Fast, Scalable dApps on Starknet + +Explore Starknet + +##### + +### Staking + +Crucial to the decentralized operation of Starknet is the acquisition of economic security on the network, a process that is already under way. At a high level, here’s what this means: + +Starknet uses Proof-of-Stake (PoS) as its mechanism for preventing Sybil attacks, in which a single entity or group of entities creates multiple validators to gain disproportionate influence over the network. PoS prevents these attacks by requiring validators to stake tokens. This ensures influence over the network is proportional to the economic cost of acquiring and risking tokens, rather than the number of validators created. + +On Layer 1 PoS protocols, staking starts from genesis, and the consensus layer’s security generally improves with its economic value. For rollups, such as Starknet, the story is different. + +Rollups inherit the security of their settlement layer and accrue economic value even if they don’t decentralize their operation. This dynamic provides an advantage to rollups that _are_ on the path to decentralizing their protocol, such as Starknet. That’s because it opens the door to accumulating high amounts and a wide distribution of stake before the decentralization of the protocol. This sets decentralized, public Starknet up in a way that prevents the disproportionate influence of a select few on the network, fostering its stability and a wide distribution of validators. + +As such, Starknet is first gathering _economic security_ through staking, and only afterward allowing for decentralized operation of the protocol. + +To this end, Starknet staking began as an _application_, decoupled from consensus—Phase 1 of Starknet staking (Staking v1) went live on November 26, 2024, and has been accumulating economic security ever since. To date, more than 170 million in STRK is being staked by 63,000 delegators and 106 validators. + +Stake your STRK → + +Staking v2 will enter mainnet in Q2 of 2025, coupling staking rewards to stakers attesting blocks. Staking v3 will enter mainnet in Q4 of 2025, coupling staking rewards to block validation. Finally, Staking v4 will make validators fully responsible for maintaining and securing the network by producing, attesting, and proving blocks. + +Each stage of staking contributes to building economic security and opens the door to the decentralized operation of the Starknet protocol. + +### Operation + +In addition to economic security, the decentralization of Starknet’s operation requires a fully functional open-source stack with end-to-end functionality. Enter the SN Stack, which has just recently been made available and enables anyone to use the parts that power Starknet. + +The present architecture of public Starknet relies on the open-source Stone prover and a closed-source sequencer, which are complemented by the open-source Madara and Katana sequencers. Throughout 2025, public Starknet will migrate to a newer stack, founded on the next-gen Apollo sequencer and the Stwo prover, both of which will be open-source. Stwo will make proving on Starknet much more efficient. + +The next step toward the decentralized operation of Starknet will be the decentralization of the consensus layer. This means validators will vote on each Starknet block, and only a sufficient quorum of such votes will finalize a new block. Decentralized consensus is planned to go live on mainnet at the end of 2025. Here is the game plan in broad strokes: + +1. Starknet v0.14.0: Launch of the distributed sequencer architecture comprised of an internal network of 3f+1 nodes running consensus and taking turns building and proposing blocks +2. Production release of the next-gen-sequencer for anyone to run +3. Deployment on Testnet(s) +4. Deployment on Mainnet + +We have omitted subtler milestones pertaining to client diversity, which is crucial for a robust network. We’ll just say there are three _additional_ full nodes that are presently integrating consensus and block proposal functionality: Juno, Pathfinder, and Madara (which needs only consensus). + +### Governance + +Given a fixed protocol, there are “meta” matters pertaining to protocol changes. Governance of such matters is a difficult problem without any canonical solutions. For L1 networks, “the protocol” is practically defined by the majority of nodes in the network: If most nodes collaboratively modify their clients, the network remains the same while its protocol changes. Hence, L1 networks can have “informal” governance—nothing is set in stone. + +Rollups, on the other hand, have core contracts on their settlement layers. Even if all L2 clients were modified, the core contract itself can only change through action on the settlement layer. Hence, rollup governance requires explicit permissioning for modifying L1 core contracts. + +The Starknet Security Council is a governance mechanism that decentralizes control over core contracts (both on L1 and L2) pertaining to state updates, staking, and STRK minting (which is managed by smart contracts, unlike Ethereum, where rewards are implemented at the client level). + +Moreover, the Security Council’s capacity to perform L1 state updates allows it to bypass consensus in case of censorship of L1/L2 messages. Thus, the Security Council facilitates censorship resistance in addition to its governance functions. + +A Security Council is a first step toward the decentralized governance of a decentralized Starknet. However, the challenge is broader than formal control core contracts. The governance question has social and technical aspects that require much thought. Improving the decentralization of the mechanism is a core goal of decentralized Starknet. + +## Other features + +While big decentralization moves are set to be made on Starknet this year, other features that aren’t decentralization-related, such as additional fee reductions and UX/DevX improvements, will also be launched. + +**v0.13.4:** This version upgrade introduces: + +- **Stateful compression:** Will reduce fees + +- **L2 gas price:** Introduces fixed price, denominated in fri, for a single unit of L2 gas until fee market in v0.14.4; it decouples L2 computation fees from the L1 gas market + +- **Try/catch for function call failures** + +- **Cairo-native (Sierra → LLVM):** Will boost performance, and potentially TPS + +**v0.14.0:** In addition to the distributed sequencer and potentially Stwo integration, this version will introduce: + +- **2-second blocks, mempool, & fee market:** Better UX, DevX + +For a deeper dive into upcoming features, read the Starknet v0.13.4 pre-release notes, with more to come on v0.14.0. + +## Conclusion + +The journey toward decentralized, scalable blockchain is a monumental challenge, but it must be achieved if blockchain is to achieve its full potential. Starknet stands at the forefront of this mission, proving that scalability and decentralization can coexist without compromise. By advancing staking, open-sourcing its stack, and progressing toward decentralized governance, Starknet is not only shaping its own future but also setting a benchmark for what L2s can achieve. + +Stay tuned for updates about Starknet’s decentralization journey on X. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet launches phase 1 of its staking initiative on mainnet + + Get an overview of Starknet's phase 1 staking protocol, a major step in Starknet's journey toward full decentralization. + + November 26, 2024 + +- #### What is Staking in Blockchain? Understanding Crypto Staking’s Risks and Rewards + + Learn how staking plays a vital role in network integrity, decentralization, and security. + + September 29, 2024 + +- #### Snapshot X: Onchain governance by Starknet + + Snapshot X combines the security and verifiability of onchain voting with the frictionless ease and modularity for which Snapshot is known. + + September 9, 2024 + +- #### First Starknet community vote on mainnet + + The first community vote on Starknet mainnet proposes a minting curve to enable staking rewards on the network. + + September 9, 2024 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-v0135-blob-compression/ + +--- + +## Starknet v0.13.5: Lower Fees With Blob Compression + +Home  /  Blog + +Mar 25, 2025 · 4 min read + +By the time you’re reading this, Starknet will already be on **v0.13.5**—but all the big improvements came in **v0.13.4**. The v0.13.5 upgrade rolled out immediately after v0.13.4, bringing minor adjustments to help the ecosystem gear up for the next big upgrade. So, to keep things simple (and avoid confusion), let’s just call it **v0.13.5**, cool? + +The **v0.13.5** Starknet upgrade is now live on mainnet, significantly improving transaction costs and developer experience (DevX). This upgrade ensures that Starknet remains **cost-efficient, even as demand for Ethereum blobs increases**—by optimizing blob usage through state diff compression. Additionally, this version lays the groundwork for the **future fee market** by introducing a new concept: **L2 gas**. + +Let’s dive into what’s new and why it matters. + +## Shelter from the blobstorm + +With demand for Ethereum blobs steadily rising and costs becoming a growing concern, Starknet is staying ahead of the curve. The v0.13.5 upgrade continues Starknet’s commitment to low fees by significantly improving how data is submitted to Ethereum. By optimizing blob usage, it reduces the impact of rising blob costs and makes transactions more cost-efficient. + +The foundation for this was laid in **v0.13.3**, which introduced **stateless compression**. This allowed blobs to be submitted to L1 in a compressed form, reducing the overall size of data Starknet sends to Ethereum. Now, **v0.13.5 builds on this with stateful compression**, an upgrade that optimizes how storage keys are encoded over time, minimizing redundancy and making state updates far more efficient. + +### How does stateful compression work? + +Rather than treating every transaction’s data independently, **stateful compression** tracks and optimizes how storage keys appear over multiple state updates. This means that instead of repeatedly writing the full storage key in the state diff, Starknet can now reference it using an “alias” (a small integer)—**packing more diffs into each Ethereum blob** **and further driving down L1 costs**. + +With this upgrade, Starknet transactions remain as cost-efficient as possible, even in the face of rising Ethereum data costs, reinforcing Starknet’s position as a cost-efficient scaling solution built to last. + +## Future-proofing Starknet: Introducing L2 gas + +Optimizing blob compression is just one piece of making Starknet more cost-efficient for the long run. The next step? Redesigning how fees are structured altogether. + +This upgrade **lays the foundation for what comes next**. Enter **Layer 2** gas-a new resource model introduced in v0.13.5 that will serve as the backbone of **Starknet’s future fee market, planned for v0.14.0**. This shift will make fees more predictable, scalable, and sustainable, reducing volatility over time and setting the stage for a more efficient fee market. + +### What does each type of gas pay for? + +Until now, Starknet transaction fees were closely tied to Ethereum’s gas mechanics. That’s slowly changing. With L2 gas, **each transaction now specifies three separate gas resources and bids**, each covering different aspects of execution and data availability: + +- **L2 gas** covers all **L2-native resources**. +- **L1 gas** covers **L2→L1 messages** sent by the transaction. +- **L1 data gas (aka blob gas)** covers the cost incurred by the sequencer for **submitting state diffs as blobs on L1**. + +**By separating L2 execution costs from L1 gas**, Starknet is preparing the ground for a more predictable and scalable fee structure. This is a key step toward long-term cost stability and performance improvements. Over time, this will allow Starknet to fine-tune its own fee model-ensuring efficient pricing without being directly impacted by Ethereum’s fluctuating gas costs. + +## Don’t panic: Error handling for a better DevX + +Beyond fee reductions, v0.13.5 also gives developers a major improvement in contract execution: **error handling**. Smart contracts can now catch errors instead of aborting execution immediately. + +Allowing contracts to catch and handle execution failures translates to a more robust developer experience. With this change, developers gain greater control over execution flows and can now write more resilient applications that respond to unexpected conditions instead of just reverting. + +This is part of a broader shift towards making Starknet easier and more intuitive for developers. Alongside error handling, v0.13.5 introduces a new Wallet-Dapp API, streamlining how wallets and applications interact. It removes rigid dependencies on specific versions of Starknet.js, ensuring the ecosystem can rely on an agreed standard, while also leading to easier integrations between dApps and wallets. + +**Thinking about building on Starknet?** Now’s the time. With lower fees, better DevX, and a growing ecosystem, there’s never been a better moment to build on Starknet. + +## Laying the groundwork for what’s next + +While v0.13.5 brings improvements today, it’s also setting the stage for even bigger things ahead. One of the most intriguing additions is **Cairo-native execution**, a performance boost that allows contracts to run as native machine code instead of being interpreted by the Cairo VM. This optimization is undergoing extensive testing and isn’t being activated on mainnet just yet, but it signals the direction Starknet is heading: toward higher throughput, faster execution, and a network that can scale effortlessly. + +And that’s just the beginning. **v0.14.0 is coming**, bringing 2-second blocks, fee market, and even more efficiency improvements. Every upgrade moves Starknet closer to its goal: becoming a blockchain network that’s scalable, cost-efficient, developer-friendly, and built to last. + +**Want to see what’s coming next?** Explore upcoming features, release timelines, and how the network keeps evolving in the Starknet roadmap. + +## Final Thoughts + +With cheaper transactions, an improved execution model, and a clear path toward scalability, Starknet v0.13.5 is setting the stage for the future of blockchain applications. Whether you’re a developer, a builder, or an everyday user, this upgrade ensures that Starknet remains the best place to build and transact affordably. + +**For a deeper dive** into the technical intricacies of this upgrade, check out the Starknet v0.13.4 Pre-release Notes. And yeah, we’re calling it v0.13.5 here-get with the game. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet on Bitcoin and Ethereum: The first L2 to unify both chains + + Starknet will become Bitcoin’s execution layer, massively scaling Bitcoin and opening the door to complex Bitcoin applications. + + March 11, 2025 + +- #### Starknet’s road to decentralization in 2025 + + Discover Starknet’s roadmap to decentralization in 2025: protocol governance, sequencer evolution, and ecosystem empowerment. + + February 26, 2025 + +- #### The Starknet ‘Bolt’ upgrade: 2-second txs are here + + Read about Starknet v0.13.2 upgrade that boosts dApps performance on Ethereum with faster transactions, parallel execution, and block packing. + + August 28, 2024 + +- #### Cairo gets high marks from Starknet devs + + The developer experience on Starknet has changed significantly this past year, and here's what developers had to say about it. + + August 14, 2024 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-decentralization-a-roadmap-in-broad-strokes/ + +--- + +## Starknet’s Decentralization Roadmap in 2025 + +Home  /  Blog + +Feb 26, 2025 · 5 min read + +Blockchain makes it possible for people to control their assets and transact directly with others on a trustless, secure, and censorship-resistant network. That ideal has the potential to transform entire industries, and it can only be achieved on blockchains that are truly decentralized. Blockchains dominated by a single party or conglomerate don’t _really_ have an edge over traditional, centralized networks. + +With the goal of bringing blockchain’s promise to everyone, Starknet is on the path to becoming the first fully decentralized Layer 2 (L2) that massively scales Ethereum. The recent launch of the first phase of staking on Starknet was a leap toward greater decentralization. This year, efforts to enhance Starknet’s decentralization will ramp up on top of continued performance optimizations. + +## Decentralized Starknet in 2025 + +Ethereum was the first blockchain to enable general-purpose computing. It earned its reputation for staying true to the first principles of blockchain: decentralization and security. As a Layer on top of—and thus an extension of—Ethereum, Starknet must also be decentralized and secure. + +The terms “decentralization” and “security” are often used interchangeably. While it’s true that decentralization enhances security, we distinguish between the two in this post. That’s because, unlike other L2 rollups, Starknet has had its ironclad security technology—STARK proofs—in place from the beginning. There has never been a state update approved on Starknet that wasn’t validated by a proof. That means it’s virtually impossible for an invalid transaction to be processed on Starknet. This post will zero in specifically on Starknet’s decentralization journey, and the ways in which it will progress in 2025. + +Starknet’s road to decentralization runs on three main lanes: + +- **Staking:** Building economic security on Starknet toward the decentralized operation of its Proof-of-Stake (PoS) consensus mechanism + +- **Operation:** The decentralization of Starknet’s operation + +- **Governance:** The independence of the Starknet Security Council + +Let’s dive into Starknet’s progress in each of these lanes, and what’s coming up. + +#### Breaking speed records with 992 peak TPS + +Build Lightning-Fast, Scalable dApps on Starknet + +Explore Starknet + +##### + +### Staking + +Crucial to the decentralized operation of Starknet is the acquisition of economic security on the network, a process that is already under way. At a high level, here’s what this means: + +Starknet uses Proof-of-Stake (PoS) as its mechanism for preventing Sybil attacks, in which a single entity or group of entities creates multiple validators to gain disproportionate influence over the network. PoS prevents these attacks by requiring validators to stake tokens. This ensures influence over the network is proportional to the economic cost of acquiring and risking tokens, rather than the number of validators created. + +On Layer 1 PoS protocols, staking starts from genesis, and the consensus layer’s security generally improves with its economic value. For rollups, such as Starknet, the story is different. + +Rollups inherit the security of their settlement layer and accrue economic value even if they don’t decentralize their operation. This dynamic provides an advantage to rollups that _are_ on the path to decentralizing their protocol, such as Starknet. That’s because it opens the door to accumulating high amounts and a wide distribution of stake before the decentralization of the protocol. This sets decentralized, public Starknet up in a way that prevents the disproportionate influence of a select few on the network, fostering its stability and a wide distribution of validators. + +As such, Starknet is first gathering _economic security_ through staking, and only afterward allowing for decentralized operation of the protocol. + +To this end, Starknet staking began as an _application_, decoupled from consensus—Phase 1 of Starknet staking (Staking v1) went live on November 26, 2024, and has been accumulating economic security ever since. To date, more than 170 million in STRK is being staked by 63,000 delegators and 106 validators. + +Stake your STRK → + +Staking v2 will enter mainnet in Q2 of 2025, coupling staking rewards to stakers attesting blocks. Staking v3 will enter mainnet in Q4 of 2025, coupling staking rewards to block validation. Finally, Staking v4 will make validators fully responsible for maintaining and securing the network by producing, attesting, and proving blocks. + +Each stage of staking contributes to building economic security and opens the door to the decentralized operation of the Starknet protocol. + +### Operation + +In addition to economic security, the decentralization of Starknet’s operation requires a fully functional open-source stack with end-to-end functionality. Enter the SN Stack, which has just recently been made available and enables anyone to use the parts that power Starknet. + +The present architecture of public Starknet relies on the open-source Stone prover and a closed-source sequencer, which are complemented by the open-source Madara and Katana sequencers. Throughout 2025, public Starknet will migrate to a newer stack, founded on the next-gen Apollo sequencer and the Stwo prover, both of which will be open-source. Stwo will make proving on Starknet much more efficient. + +The next step toward the decentralized operation of Starknet will be the decentralization of the consensus layer. This means validators will vote on each Starknet block, and only a sufficient quorum of such votes will finalize a new block. Decentralized consensus is planned to go live on mainnet at the end of 2025. Here is the game plan in broad strokes: + +1. Starknet v0.14.0: Launch of the distributed sequencer architecture comprised of an internal network of 3f+1 nodes running consensus and taking turns building and proposing blocks +2. Production release of the next-gen-sequencer for anyone to run +3. Deployment on Testnet(s) +4. Deployment on Mainnet + +We have omitted subtler milestones pertaining to client diversity, which is crucial for a robust network. We’ll just say there are three _additional_ full nodes that are presently integrating consensus and block proposal functionality: Juno, Pathfinder, and Madara (which needs only consensus). + +### Governance + +Given a fixed protocol, there are “meta” matters pertaining to protocol changes. Governance of such matters is a difficult problem without any canonical solutions. For L1 networks, “the protocol” is practically defined by the majority of nodes in the network: If most nodes collaboratively modify their clients, the network remains the same while its protocol changes. Hence, L1 networks can have “informal” governance—nothing is set in stone. + +Rollups, on the other hand, have core contracts on their settlement layers. Even if all L2 clients were modified, the core contract itself can only change through action on the settlement layer. Hence, rollup governance requires explicit permissioning for modifying L1 core contracts. + +The Starknet Security Council is a governance mechanism that decentralizes control over core contracts (both on L1 and L2) pertaining to state updates, staking, and STRK minting (which is managed by smart contracts, unlike Ethereum, where rewards are implemented at the client level). + +Moreover, the Security Council’s capacity to perform L1 state updates allows it to bypass consensus in case of censorship of L1/L2 messages. Thus, the Security Council facilitates censorship resistance in addition to its governance functions. + +A Security Council is a first step toward the decentralized governance of a decentralized Starknet. However, the challenge is broader than formal control core contracts. The governance question has social and technical aspects that require much thought. Improving the decentralization of the mechanism is a core goal of decentralized Starknet. + +## Other features + +While big decentralization moves are set to be made on Starknet this year, other features that aren’t decentralization-related, such as additional fee reductions and UX/DevX improvements, will also be launched. + +**v0.13.4:** This version upgrade introduces: + +- **Stateful compression:** Will reduce fees + +- **L2 gas price:** Introduces fixed price, denominated in fri, for a single unit of L2 gas until fee market in v0.14.4; it decouples L2 computation fees from the L1 gas market + +- **Try/catch for function call failures** + +- **Cairo-native (Sierra → LLVM):** Will boost performance, and potentially TPS + +**v0.14.0:** In addition to the distributed sequencer and potentially Stwo integration, this version will introduce: + +- **2-second blocks, mempool, & fee market:** Better UX, DevX + +For a deeper dive into upcoming features, read the Starknet v0.13.4 pre-release notes, with more to come on v0.14.0. + +## Conclusion + +The journey toward decentralized, scalable blockchain is a monumental challenge, but it must be achieved if blockchain is to achieve its full potential. Starknet stands at the forefront of this mission, proving that scalability and decentralization can coexist without compromise. By advancing staking, open-sourcing its stack, and progressing toward decentralized governance, Starknet is not only shaping its own future but also setting a benchmark for what L2s can achieve. + +Stay tuned for updates about Starknet’s decentralization journey on X. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet launches phase 1 of its staking initiative on mainnet + + Get an overview of Starknet's phase 1 staking protocol, a major step in Starknet's journey toward full decentralization. + + November 26, 2024 + +- #### What is Staking in Blockchain? Understanding Crypto Staking’s Risks and Rewards + + Learn how staking plays a vital role in network integrity, decentralization, and security. + + September 29, 2024 + +- #### Snapshot X: Onchain governance by Starknet + + Snapshot X combines the security and verifiability of onchain voting with the frictionless ease and modularity for which Snapshot is known. + + September 9, 2024 + +- #### First Starknet community vote on mainnet + + The first community vote on Starknet mainnet proposes a minting curve to enable staking rewards on the network. + + September 9, 2024 + +--- + +Sources: + +- https://www.starknet.io/blog/cairo-improvements/ + +--- + +## DevEx improvements for Cairo developers are here + +Home  /  Blog + +Mar 23, 2025 · < 1 min read + +_This post was originally published on the Cairo website._ + +Cairo has heard your feedback and is actively working on addressing it! Here are some of the most requested features for Scarb and Starknet Foundry that have just been released for Cairo developers. + +## One-line installer + +Setting up Scarb and Starknet Foundry can be a bit tedious: It requires setting up asdf, adding the plugins for Scarb and Starknet Foundry, and installing the latest version. + +Now, all of this is replaced by a single one-liner: + +``` +curl --proto '=https' --tlsv1.2 -sSf https://sh.starkup.sh | sh +``` + +The following will: + +- Install asdf if you still don’t have it installed +- Download the latest version of the tools +- Set the global variables + +And that’s it! + +You should now have all the essential tools you need to start building, compiling, and testing Cairo contracts for Starknet. + +This tool tries to capture as many edge cases as possible, but no software is perfect. If you have any issues or requests, please open a new issue on the GitHub repo. + +## No more Cargo for Cairo + +Recent Scarb and Starknet Foundry users might have noticed that when updating to a new Starknet Foundry version, the complications begin with compiling… Rust? + +This wasn’t intuitive, and many users didn’t quite understand what was going on and why. For the full explanation, read the rest of this post on the Cairo website: + +Read full post → + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Cairo gets high marks from Starknet devs + + The developer experience on Starknet has changed significantly this past year, and here's what developers had to say about it. + + August 14, 2024 + +- #### ​​The What’s What of the Cairo World + + Delve into Starknet's foundational elements: Cairo VM, CASM, Cairo Zero, Cairo, and Sierra. Discover their pivotal role in Layer 2 scaling, enhancing Ethereum efficiency,… + + September 11, 2023 + +- #### The case for Appchains powered by a decentralized Starknet stack + + The Starknet Stack is in the midst of a remarkable growth spurt. We expect it to dominate the Appchain space due to its performance,… + + July 19, 2023 + +- #### Starknet Quantum Leap: Major Throughput Improvements are Here! + + Starknet Alpha V0.12.0 focuses on enhancing performance and user experience. The new version introduces a Rust-based implementation of the Sequencer, improving throughput by 10X… + + July 5, 2023 + +--- + +Sources: + +- https://www.starknet.io/blog/noir-on-starknet/ + +--- + +## Verify Noir ZK proofs on Starknet with Garaga SDK + +Home  /  Blog + +Mar 20, 2025 · 2 min read + +Zero-knowledge (ZK) proofs are key to building privacy-preserving applications. Starknet makes verifying these proofs both cheap and seamless, enabling the scalable development of ZK-enabled apps. The goal, therefore, is to constantly expand the umbrella of developers who enjoy access to efficient proof verification on Starknet. + +To that end, StarkWare and the Starknet Foundation now collaborate with Aztec, a leading privacy network, to introduce a new wave of developers to Starknet. Anyone using Noir—the popular ZK language—can now verify Noir proofs on Starknet without needing to write any Cairo code. This is made possible with the Garaga SDK, developed by Feltroid Prime and supported by StarkWare. So whether you are a Noir developer or a Cairo developer, you can now verify efficiently on Starknet. + +## Starknet: A hub for ZK-enabled apps + +Starknet’s native smart-contract language, Cairo, is purpose-built to harness the unparalleled power of STARK proofs. But the Starknet ecosystem continues to ensure developers using other programming languages can also benefit from Starknet’s capabilities, turning Starknet into a hub for ZK-enabled apps. + +Using Garaga, Noir developers can compile their programs to automatically generate a Cairo verifier, deploy it on Starknet, and verify proofs without writing any Cairo code—all while enjoying lower fees and enhanced performance. This makes it possible for Noir developers to build scalable applications ranging from ZK machine learning (ZKML) to Layer 2 (L2) and Layer 3 (L3) appchains, to other ZK-enabled dApps. + +## How Garaga SDK works + +Garaga makes deploying Noir verifiers on Starknet effortless. Here’s how it works: + +- **Noir-program compilation:** When you compile your Noir code using Garaga, it automatically produces a Noir prover, and a Noir verifier contract written in Cairo. +- **Easy deployment**: The generated verifier is ready for immediate deployment on Starknet. This means you don’t need to learn or write Cairo—Garaga handles the heavy lifting. +- **Cost & performance benefits**: By moving proof verification to Starknet, developers can leverage significantly lower transaction fees and faster processing than traditional onchain verification methods. + +## Get started + +Whether you’re an experienced Noir developer or just beginning your journey into ZK proofs, Garaga offers a cost-effective, high-performance platform to bring your ideas to life. + +For more detailed steps, see the Garaga documentation on generating a Starknet smart contract from your Noir program, or start building with Cairo today. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/develop-dapp-starknet-js/ + +--- + +## Develop End-to-End Starknet dApps with Starknet.js + +Home  /  Blog + +May 22, 2025 · 6 min read + +Starknet is a powerful Layer 2 scaling solution for Ethereum that enables developers to deploy and interact with **Cairo-based smart contracts**. But how do we build an end-to-end dApp, from **contract deployment** to **frontend interaction**? + +We relied on **Starkli** (Starknet CLI) to deploy contracts, which is a banger. However, with **Starknet.js**, we can **interact with contracts seamlessly from our frontend** without switching tools. In this guide, we will: + +- **Deploy a contract to Starknet** +- **Read from and write a contract using Starknet.js** +- **Integrate with a Next.js frontend** +- **Connect a Starknet crypto wallet (ArgentX or Braavos)** +- **Perform transactions (increase/decrease a counter)** + +By the end, you’ll have **a fully functional Starknet dApp** running with **Starknet.js**. + +The source code of this demo can be accessed here. + +# Getting Started + +## Prerequisites + +To follow this guide, ensure you have: + +- **Node.js** (v18+) +- **Yarn or npm** +- **A Starknet wallet (ArgentX or Braavos)** +- **Basic knowledge of TypeScript & Next.js** +- **Cairo (for smart contracts)** +- **Scarb (Starknet package manager)** + +There is a single command installation too! You can follow this 1 minute video guide. + +## **Step 1: Setting Up a New Project** + +Simply create a new folder where you want your project to be: + +``` +mkdir counter +scarb init +``` + +You should have the option to choose between the Cairo test and Starknet Foundry; I went ahead with the recommended one for this tutorial. + +This should create a src folder with a lib.cairo file, which will be our contract file in Cairo. This tutorial is not focused on learning cairo but for developers who want to learn Starknet.js, hence using a simple counter contract to interact with smart contract is used. + +This is new lib.cairo file in Cairo which has 3 major functions: + +- read the counter value +- increase the counter value with a custom argument provided through frontend +- decrease the counter value + +``` +// Cairo 2.9.2 + +#[starknet::interface] +trait ITestSession<TContractState> { + fn increase_counter(ref self: TContractState, value: u128); + fn decrease_counter(ref self: TContractState, value: u128); + fn get_counter(self: @TContractState) -> u128; +} + +#[starknet::contract] +mod test_session { + use starknet::storage::StoragePointerWriteAccess; + use starknet::storage::StoragePointerReadAccess; + + #[storage] + struct Storage { + count: u128, + } + + #[abi(embed_v0)] + impl TestSession of super::ITestSession<ContractState> { + fn increase_counter(ref self: ContractState, value: u128) { + self.count.write(self.count.read() + value); + } + + fn decrease_counter(ref self: ContractState, value: u128) { + let current = self.count.read(); + if current >= value { + self.count.write(current - value); + } else { + self.count.write(0); // Prevents underflow + } + } + + fn get_counter(self: @ContractState) -> u128 { + self.count.read() + } + } +} +``` + +Once the contract is there, we should build it to get the casm and sierra files. This can be done using these commands. Make sure to be inside the contracts folder. This step might take a while. + +``` +cd contracts +scarb build +``` + +After compiling, your **ABI** (Application Binary Interface) and contract artifacts will be inside target/dev/ including sierra and casm files. + +## **Step 2: Connecting to a Starknet Wallet** + +### Installing a wallet + +Download **ArgentX** or **Braavos**: + +• ArgentX Chrome Extension– standard account + +• Braavos Wallet + +Once installed, **create an account** and **fund it with Sepolia ETH**. + +## **Step 3: Deploying the Contract** + +We will use **Starknet.js** to deploy the contract. + +**For this tutorial, we’d need:** + +1. The contract’s ABI +2. The contract’s Address +3. An Argent or Braavos wallet +4. React.js [front-end framework] +5. Starknetjs [dependency]Make a new file called deploy.ts in the root directory. Since, our contract is already there as we’re using public RPC URL, we’d just be deploying a new instance of it. If you’re using your own new contract, follow these steps to deploy it. + +This is your deploy.ts file which is simply used to deploy your contract. Here we’re only deploying a new instance of it. You’d need a wallet account with the address, private key, and classHash of the contract. To save the ABI, I’ve logged it here and saved it in a separate JSON file inside public folder as you’d need to access it later. + +After your contract is deployed, save its address and check it on Starkscan/voyager. + +``` +import { + Contract, + Account, + json, + shortString, + RpcProvider, + hash, +} from "starknet"; +import fs from "fs"; + +async function main() { + const provider = new RpcProvider({ + nodeUrl: "https://starknet-sepolia.public.blastapi.io", + }); + + // Check that communication with provider is OK + const ci = await provider.getChainId(); + console.log("chain Id =", ci); + + // Initialize existing Argent X testnet accountn + const accountAddress = + "0x..."; + const privateKey = + "0x...."; + const account0 = new Account(provider, accountAddress, privateKey); + console.log("existing_ACCOUNT_ADDRESS =", accountAddress); + console.log("existing account connected.\n"); + + // Since we already have the classhash, we will be skipping this part + const testClassHash = + "0x396823b2b056397dc8f3da80d20ae8f4b0630d33b089b36ba3c3c9a7a51c7d0"; + + const deployResponse = await account0.deployContract({ classHash: testClassHash }); + await provider.waitForTransaction(deployResponse.transaction_hash); + + // Read ABI of Test contract + const { abi: testAbi } = await provider.getClassByHash(testClassHash); + if (testAbi === undefined) { + throw new Error("no abi."); + } + + // ✅ Log Full ABI + console.log("Full ABI:", JSON.stringify(testAbi, null, 2)); + + // Connect the new contract instance: + const myTestContract = new Contract(testAbi, deployResponse.contract_address, provider); + console.log("✅ Test Contract connected at =", myTestContract.address); +} + +// contract address: 0x75410d36a0690670137c3d15c01fcfa2ce094a4d0791dc769ef18c1c423a7f8 + +main() + .then(() => process.exit(0)) + .catch((error) => { + console.error(error); + process.exit(1); + }); +``` + +Use this command to run your deploy file. + +``` +npx tsx deploy.ts +``` + +I’ve attached my ABI.json file here for reference: + +``` +[ + { + "type": "impl", + "name": "TestSession", + "interface_name": "counter_starknetjs::ITestSession" + }, + { + "type": "interface", + "name": "counter_starknetjs::ITestSession", + "items": [ + { + "type": "function", + "name": "increase_counter", + "inputs": [ + { + "name": "value", + "type": "core::integer::u128" + } + ], + "outputs": [], + "state_mutability": "external" + }, + { + "type": "function", + "name": "decrease_counter", + "inputs": [ + { + "name": "value", + "type": "core::integer::u128" + } + ], + "outputs": [], + "state_mutability": "external" + }, + { + "type": "function", + "name": "get_counter", + "inputs": [], + "outputs": [ + { + "type": "core::integer::u128" + } + ], + "state_mutability": "view" + } + ] + }, + { + "type": "event", + "name": "counter_starknetjs::test_session::Event", + "kind": "enum", + "variants": [] + } + ] +``` + +## Step 4: Connecting contracts to frontend + +Create a new folder and initialize it with the next.js (App router), and install starknet-react, which uses starknet.js under the hood to interact with frontend. + +``` +mkdir web +npx create-next-app@latest starknet-counter +cd starknet-counter +npm install starknet @starknet-react/core @starknet-react/chains +``` + +Move your ABI.json file to the public folder to access it more easily. + +Create a new component called Providers.tsx to configure chains, providers, connectors, wallets, and accounts. This will be a client-side component. + +``` +"use client"; +import React from "react"; + +import { sepolia } from "@starknet-react/chains"; +import { + StarknetConfig, + argent, + braavos, + useInjectedConnectors, + voyager, + jsonRpcProvider +} from "@starknet-react/core"; + +export function Providers({ children }: { children: React.ReactNode }) { + const { connectors } = useInjectedConnectors({ + // Show these connectors if the user has no connector installed. + recommended: [ + argent(), + braavos(), + ], + // Hide recommended connectors if the user has any connector installed. + includeRecommended: "onlyIfNoConnectors", + // Randomize the order of the connectors. + order: "random" + }); + + return ( + <StarknetConfig + chains={[sepolia]} + provider={jsonRpcProvider({rpc: (chain) => ({nodeUrl: process.env.NEXT_PUBLIC_RPC_URL})})} + connectors={connectors} + explorer={voyager} + > + {children} + </StarknetConfig> + ); +} +``` + +Then go to your layout.tsx file and wrap it in the Providers component. Don’t forget to import it. This is how it should look like: + +``` +import type { Metadata } from "next"; +import { Geist, Geist_Mono } from "next/font/google"; +import "./globals.css"; +import { Providers } from "./components/Providers"; + +const geistSans = Geist({ + variable: "--font-geist-sans", + subsets: ["latin"], +}); + +const geistMono = Geist_Mono({ + variable: "--font-geist-mono", + subsets: ["latin"], +}); + +export const metadata: Metadata = { + title: "Counter Starknetjs", + description: "Counter demo by starknet js", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + <html lang="en"> + <body + className={`${geistSans.variable} ${geistMono.variable} antialiased`} + > + <Providers> + {children} + </Providers> + + </body> + </html> + ); +} +``` + +We’d need another component to check wallet connection; this will also be a client-side component that will let the users connect or disconnect their Braavos or Argent wallet while also showing their address. This is how my WalletBar.tsx file looks like: + +``` +"use client"; +import { useConnect, useDisconnect, useAccount } from "@starknet-react/core"; + +const WalletBar: React.FC = () => { + const { connect, connectors } = useConnect(); + const { disconnect } = useDisconnect(); + const { address } = useAccount(); + + return ( + <div className="flex flex-col items-center p-4 bg-gradient-to-br from-[#1A1A2E] to-[#0F3460] rounded-2xl shadow-lg w-full max-w-sm"> + {!address ? ( + <div className="flex flex-wrap justify-center gap-3"> + {connectors.map((connector) => ( + <button + key={connector.id} + onClick={() => connect({ connector })} + className="px-5 py-2 font-medium rounded-lg bg-[#0F3460] text-white border border-[#1B98E0] hover:bg-[#1B98E0] transition-all duration-300 shadow-md" + > + Connect {connector.id} + </button> + ))} + </div> + ) : ( + <div className="flex flex-col items-center space-y-3"> + <div className="text-sm bg-[#1B98E0] px-4 py-2 text-white font-semibold rounded-lg shadow-md"> + 🔗 Connected: {address.slice(0, 6)}...{address.slice(-4)} + </div> + <button + onClick={() => disconnect()} + className="px-5 py-2 font-medium rounded-lg bg-red-600 text-white border border-red-800 hover:bg-red-800 transition-all duration-300 shadow-md" + > + Disconnect + </button> + </div> + )} + </div> + ); +}; + +export default WalletBar; +``` + +## Step 4: Reading data from blockchain + +We’d modify our page.tsx file to read the data from blockchain and connect our wallet as well. This will also be loaded on the client side so, add “use client” on the top. + +We will be using pre-defined react hooks for this. + +``` +export default function Home() { + // ✅ Read the latest block + const { data: blockNumberData, isLoading: blockNumberIsLoading, isError: blockNumberIsError } = useBlockNumber({ blockIdentifier: "latest" }); + + // ✅ Read your balance + const { address: userAddress } = useAccount(); + const { isLoading: balanceIsLoading, isError: balanceIsError, error: balanceError, data: balanceData } = useBalance({ address: userAddress, watch: true }); +} +``` + +## Step 5: Interacting with smart contracts + +For this- we will call functions defined in the contract to increase or decrease the counter. + +``` +export default function Home() { + // ✅ Read from a contract + const contractAddress = "0x75410d36a0690670137c3d15c01fcfa2ce094a4d0791dc769ef18c1c423a7f8"; + const { data: readData, isError: readIsError, isLoading: readIsLoading, error: readError } = useReadContract({ + functionName: "get_counter", + args: [], + abi: ABI as Abi, + address: contractAddress, + watch: true, + refetchInterval: 1000, + }); + + // ✅ Increase & Decrease Counter + const [amount, setAmount] = useState<number | ''>(0); + const handleAmountChange = (event: React.ChangeEvent<HTMLInputElement>) => { + const value = event.target.value; + setAmount(value === "" ? "" : Number(value)); + }; +``` + +That’s it! + +You can design the UI as preferred. Here’s how a simple UI can look with all the basic functionality required: + +## **Conclusion** + +In this guide, we: + +- **Wrote & deployed a Starknet contract using Starknet.js** +- **Connected a Starknet wallet** +- **Interacted with the contract using Starknet.js** +- **Designed a Next.js frontend** + +This tutorial provides a **solid foundation** for building **full-stack dApps on Starknet**. The **full source code is available on GitHub**. + +## Resources: + +1. Source code on GitHub- https://github.com/reetbatra/starknetjs-counter +2. Official Starknet.js docs- https://starknetjs.com/docs/guides/intro +3. Starknet-react docs- https://www.starknet-react.com/docs/getting-started +4. Counter contract example- https://starknet-by-example.voyager.online/getting-started/basics/counter + +Stay tuned for more such tutorials along the way. See you in the trenches! + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/paymaster-the-secret-to-making-dapps-feel-like-web2/ + +--- + +## Paymaster: The Secret to Making dApps Feel Like Web2 | Starknet + +Home  /  Blog + +May 21, 2025 · 4 min read + +Imagine a world where gas fees no longer hinder smooth and frictionless transactions. With **Paymaster**, we’ve brought this vision to life by allowing users to pay their gas fees using **various tokens**, eliminating the need to hold ETH or STRK just to cover transaction costs. + +Whether you hold **stablecoins, major tokens, or other assets**, you can now transact freely, focusing entirely on using the dApp to its full potential without the hassle of gas management. + +In this blog, we’ll explore **Paymaster’s core functionalities**, its benefits, and how you can integrate it into your **Starknet dApp** for a seamless user experience. + +## What is Paymaster? + +**Paymaster** is an innovative solution that enables **gasless transactions** and flexible gas payments. Instead of requiring users to hold ETH or STRK for transaction fees, Paymaster allows dApps to either **sponsor gas fees** or let users pay using **any supported token**. + +### How Does Paymaster Work? + +1. **Sponsor Gas Fees**: The dApp covers the user’s gas costs, creating a frictionless onboarding experience. +2. **Flexible Token Payments**: Users can pay gas fees with any token they hold, not just ETH or STRK. +3. **Meta-Transactions**: Transactions can be executed on behalf of users, making interactions smoother. + +### Benefits of Paymaster: + +- **Frictionless UX** – No need for users to manage gas tokens. +- **Onboarding Simplification** – New users can interact with dApps without holding ETH. +- **Gas Payments in Any Token** – Users can pay gas fees with stablecoins or any supported token. +- **Improved dApp Adoption** – Lower barriers encourage more interaction. + +> **Use Case Example:**Imagine a DeFi platform where users can swap tokens without worrying about ETH for gas fees. Paymaster makes this possible! +> +> or… +> +> POAPs! You can sponsor user’s gas fees to mint NFTs for free! Now, if that is not onboarding your grandma onchain, idk what is + +--- + +## AVNU’s Paymaster on Starknet + +### **Architecture Overview** + +- **User chooses a gas token**: Instead of ETH, users select USDC, USDT, or another supported asset. +- **Signature Approval**: Users sign a transaction without needing ETH. +- **API Calls**: The dApp makes calls to fetch gas prices, generate typed data, and execute transactions. +- **Transaction Execution**: The Paymaster service handles the rest, ensuring smooth blockchain execution. + +Before diving into **AVNU’s Gasless SDK**, let’s first understand why we need **Paymaster** and whether there are alternative solutions. + +### **The Problem with Traditional Gas Fees** + +On Ethereum and Starknet, users must hold **ETH (or STRK)** to pay for transaction fees. This creates several friction points: + +- New users must **acquire ETH/STRK** before using a dApp. +- Managing multiple tokens for **gas and transactions** adds complexity. +- **Due to gas fee requirements, DeFi, gaming, and consumer applications** struggle with adoption + +- ### **Are There Alternative Solutions?** + + There are a few other solutions available: + + - **Meta-transactions** (Users sign messages, relayers execute the transaction, covering gas fees.) + - **Third-party sponsorship services** (Protocols or projects cover gas fees for new users.) + - **Layer 2 scaling** **solutions** reduce fees but still require ETH/STRK. + +Among these, **AVNU’s Paymaster** offers **a flexible** and **developer-friendly** approach, allowing both sponsorship and token-based gas payments. + +## **Gasless vs Gas-Free: Understanding the Difference** + +### **Gas-Free Transactions** + +Gas-Free means **no fees for the user or dApp**—transactions are executed without any cost. This typically requires a sponsor (like a project or protocol) covering all gas fees. + +### **Gasless Transactions** + +Gasless means the **user doesn’t need ETH** for gas but still pays fees using another token. This eliminates the need to manage ETH, making transactions smoother while keeping a decentralized cost structure. + +## **Do You Need an API Key for Paymaster?** + +### **When is an API Key Required?** + +An **API key is required** in the following cases: + +- **Sponsoring transactions** – If a dApp wants to cover the gas fees on behalf of users, it must authenticate via an API key. +- **Using advanced Paymaster features**, such as rewards-based gas sponsorship. +- **Building and executing typed data via the API** – Required for sponsored transactions. + +### **When is an API Key Not Required?** + +An **API key is NOT required** when: + +- The user is **paying gas fees themselves** using supported tokens (e.g., USDC, USDT, etc.). +- Checking **account compatibility** with the gasless service. +- Fetching **gas token prices** for display in the UI. + +--- + +## Implementing AVNU’s Paymaster in Your Starknet dApp + +## **Setting Up a Basic Starknet Project** + +Before jumping into AVNU’s Gasless SDK, let’s first set up a basic Starknet project. This will help you understand how Paymaster integrates into a real-world dApp. + +### **Step 1: Creating a New Starknet Project** + +Start by setting up a new JavaScript/TypeScript project for Starknet development. + +``` +mkdir starknet-gasless-dapp && cd starknet-gasless-dapp +npm init -y # or yarn init -y +``` + +### **Step 2: Installing Required Dependencies** + +``` +yarn add starknet dotenv @avnu/gasless-sdk axios +``` + +### + +### **Step 3: Setting Up a .env File for API Keys** + +Create a `.env` file to securely store your API keys: + +``` +touch .env +``` + +Inside `.env`, add: + +``` +PAYMASTER_API_KEY=your-api-key-here +``` + +### **Step 4: Setting Up a Basic Starknet Account & Contract Call** + +``` +import { Provider, Account, Contract } from "starknet"; +import dotenv from "dotenv"; +dotenv.config(); + +const provider = new Provider({ rpc: "https://starknet.api.avnu.fi" }); +const account = new Account(provider, "YOUR_ACCOUNT_ADDRESS", "YOUR_PRIVATE_KEY"); + +async function callContract() { + const contract = new Contract("CONTRACT_ADDRESS", ABI, account); + const result = await contract.call("functionName", [param1, param2]); + console.log("Result:", result); +} + +callContract(); +``` + +At this point, we have set up a basic Starknet project that interacts with a contract. However, **this setup still requires ETH/STRK for gas fees**—this is where AVNU’s Gasless SDK comes in. + +## **Using the Gasless SDK Without an API Key** + +If the user is paying gas fees in an alternative token, we can proceed without an API key. + +### **Checking Gasless Compatibility** + +``` +import { fetchAccountCompatibility } from '@avnu/gasless-sdk'; + +async function checkCompatibility(accountAddress) { + const compatibility = await fetchAccountCompatibility(accountAddress); + console.log("Gasless Compatible:", compatibility.isCompatible); +} +``` + +### **Fetching Gas Token Prices** + +``` +import { fetchGasTokenPrices } from '@avnu/gasless-sdk'; + +async function getGasPrices() { + const prices = await fetchGasTokenPrices(); + console.log("Gas Token Prices:", prices); +} +``` + +### **Executing a Gasless Transaction (User Pays with a Supported Token)** + +``` +import { executeCalls } from '@avnu/gasless-sdk'; + +async function executeGasless(account, calls) { + const response = await executeCalls(account, calls, { + gasTokenAddress: "USDC", // User pays gas in USDC + maxGasTokenAmount: BigInt(1000000000), + }); + console.log("Transaction Hash:", response.transactionHash); +} +``` + +## **Using the Gasless SDK With an API Key (Sponsored Transactions)** + +If the dApp wants to sponsor gas fees, we need to use an API key. Contact AVNU to get your own API key. + +### **Fetching Gasless Service Status** + +``` +import axios from 'axios'; +import dotenv from 'dotenv'; +dotenv.config(); + +async function checkGaslessStatus() { + const response = await axios.get('https://starknet.api.avnu.fi/paymaster/v1/status'); + console.log("Gasless Service Status:", response.data); +} +``` + +### **Building Typed Data for Sponsored Transactions** + +``` +async function buildTypedData(userAddress, calls) { + const response = await axios.post('https://starknet.api.avnu.fi/paymaster/v1/build-typed-data', { + userAddress, + gasTokenAddress: null, // Sponsored gas + maxGasTokenAmount: null, // Sponsored gas + calls, + }, { + headers: { 'api-key': process.env.PAYMASTER_API_KEY }, + }); + console.log("Typed Data:", response.data); +} +``` + +### **Executing Sponsored Transactions** + +``` +async function executeSponsoredTransaction(userAddress, typedData, signature) { + const response = await axios.post('https://starknet.api.avnu.fi/paymaster/v1/execute', { + userAddress, + typedData, + signature, + }, { + headers: { 'api-key': process.env.PAYMASTER_API_KEY }, + }); + console.log("Sponsored Transaction Hash:", response.data.transactionHash); +} +``` + +--- + +## Additional Resources + +- AVNU Docs +- Argent Wallet & Session Keys + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/on-chain-gaming-starknet-dojo/ + +--- + +## The Rise of On-Chain Gaming: Building on Starknet with Dojo Engine | Starknet + +Home  /  Blog + +May 8, 2025 · 6 min read + +Gaming has evolved significantly, from traditional board games to digital experiences, and now, to on-chain games — a completely new paradigm enabled by blockchain technology. As blockchain-based ecosystems flourish, particularly with the scaling solutions offered by layer 2 technologies, developers have begun exploring new business models, financial incentives, and decentralized ownership structures that were previously impossible. + +In this article, we’ll explore the need for on-chain games, their advantages, and how Dojo Engine helps developers build provable, decentralized, and autonomous games faster than ever before. + +## **History of Games: From Board Games to On-Chain Games** + +Games have been integral to human history, from ancient board games like Chess and Go to modern digital experiences like World of Warcraft and Fortnite. However, the underlying structure of games has remained largely centralized — players interact with a game world owned and controlled by a central entity (developers, publishers, or platforms). + +### + +### **The Transition to On-Chain Games** + +On-chain games introduce a revolutionary concept: games where both state and logic exist entirely on a blockchain. This means that: + +- The game’s rules and mechanics are enforced by smart contracts. +- Players have true ownership over in-game assets. +- The game state is public, auditable, and tamper-proof. +- Games can be composable, allowing external developers to build on top of existing game worlds. + +## + +## **Why Do We Need On-Chain Games?** + +While traditional games rely on centralized servers and game economies controlled by publishers, on-chain games offer a radically different approach: + +### **1. Financialization as Part of the Game** + +Unlike traditional games where financialization is often limited to NFTs, on-chain games integrate economic incentives and value transfer at their core. Players can earn, trade, and stake assets in ways that were previously impossible. + +### **2. Trustless Escrow and Arbitration** + +In traditional games, disputes over in-game assets or transactions rely on centralized authorities. On-chain games use the blockchain as an escrow and arbitrator, ensuring fairness and transparency. + +### **3. New, More Efficient Business Models** + +On-chain gaming allows for atomic payouts, decentralized revenue sharing, and permissionless modding. Developers can monetize gameplay through programmable economies rather than relying on ads or in-game purchases. + +### **4. Composability and Modding** + +The best games in history, such as DOTA and Counter-Strike, started as mods of existing games. On-chain games take this further by offering shared state and open APIs, allowing developers to create new game mechanics, spin-off games, and community-driven extensions. + +**Examples:** + +- **DOTA** (originally a Warcraft 3 mod, now a billion-dollar franchise) +- **Counter-Strike** (originally a Half-Life mod, now a leading FPS title) + +--- + +## **New User-Generated Content (UGC) Business Models** + +On-chain games enable headless games, atomic payouts, and games as protocols, ushering in a new era of community-driven game development. + +### **Examples:** + +- **Loot Survivor Clients** (players generate content in a shared game world) +- **DF Client Plugins** (modular expansions built on top of existing games) + +--- + +## **The Strength of On-Chain Games: Security & High Stakes** + +One of the biggest advantages of on-chain gaming is immutability and trustlessness. + +- **Blockchains exist for escrow**—this is their primary function. +- **On-chain games are impossible to cheat** because game logic is enforced at the smart contract level. +- **High-stakes competitive games** (with financial rewards) become possible without fear of exploitation. + +### **Example: Strategy Game with Buy-Ins** + +A highly competitive real-time strategy (RTS) game where players stake assets before a match. Since all transactions and logic are on-chain, cheating is impossible, and winnings are automatically distributed based on game outcomes. + +--- + +## **Types of On-Chain Games** + +### **1. Short Experiences (Rogue-Likes, Daily Challenges)** + +- Low cost, easy to pick up and play +- Baked-in token loops for rewards +- Game Examples: RYO, Loot Survivor, Paved + +### **2. Session-Based Games (With Stakes, RTS, Civilization-Like Games)** + +- Multiplayer & asynchronous mechanics +- Session-based with buy-ins and rewards +- Game Examples: Eternum, Sky Strife, Dark Forest, ZConquer + +### **3. Autonomous Worlds (Self-Evolving, Persistent Game Worlds)** + +- Decentralized and self-governing +- No single entity owns the game +- No fully autonomous world exists yet, but early prototypes are emerging + +## **What is Dojo?** + +Dojo is an open-source, community-driven provable game engine designed to accelerate on-chain game development. Before Dojo, developers had to build their own indexers, contract architectures, and game clients from scratch. + +With Dojo, developers can go from zero to a fully functional game in just a week. + +### **Why Dojo?** + +- Standardizes the development experience (DevX) for on-chain games +- Simplifies on-chain state management via models +- Minimizes boilerplate code +- Provides powerful developer tooling + +--- + +## **How Does Dojo Work?** + +Dojo extends the Cairo compiler, injects macros, and creates a standardized ORM-like state management system. All states are stored in a World contract, and Dojo contracts mutate this state. + +### **Architecture Overview** + +#### **World Contract** + +- Provides the interface for on-chain worlds +- Designed for composability and extensibility +- Registers models that extend storage +- Deploys contracts that extend logic +- Manages access control for data modifications + +--- + +## **What You Need for This Tutorial** + +To follow along, ensure you have: + +- Dojo installed (`dojoup`) +- Sozo, Katana, Torii, and Origami installed +- A basic understanding of Cairo and smart contract development + +### **Dojo Toolchain Overview** + +- **Sozo**: Command-line tool for managing Dojo projects +- **Torii**: Automatic indexer for your models (SQL/Postgres support) +- **Katana**: Local devnet for testing game logic +- **Origami**: Game development library with common patterns +- **BYO Client**: Official clients in Dojo.js, Unity, C, and more + +--- + +## **Building the Game: Red vs. Blue Team** + +### **Game Overview** + +We are developing **Red vs. Blue Team**, a **map control game** where players join either the **Red** or **Blue** team. Players can **paint tiles** on the game map and aim to **maintain control** of the most territory. However, each player is limited to **one action every 60 seconds**, making strategic tile placement critical. + +### **Game Components** + +To implement this game, we need: + +#### **1. Player Registration** + +- Players will be identified using their **wallet address**. +- Upon registration, a player selects a **team (Red or Blue)**. + +#### **2. Tile System** + +- The game board consists of **tiles**, each defined by **x and y keys**. +- Each tile has a **color** (either Red or Blue) to reflect the controlling team. + +### **Game Functions** + +#### **1. Register Player** + +- A new player joins the game by registering with their **wallet address**. +- The player selects a **team (Red or Blue)**. + +#### **2. Paint Tile** + +- A player selects a **tile (x, y)** to paint in their team’s color. +- A cooldown prevents players from painting **more than once every 60 seconds**. +- The team with the most painted tiles maintains control. + +--- + +# **Let’s jump into code!** + +Contracts and client folders are self-explanatory. However, the key is understanding how we need to run each of them and how they are interlinked. + +Please take a look at the source code here. I initialized the project using the Dojo starter kit. + +The client (React+Vite) application can be run using + +``` +npm install +npm run dev +``` + +Then start the Katana local node with the following command: + +``` +katana --disable-fee --allowed-origins "*" +``` + +In another terminal window, navigate again to the contracts directory and build the contracts using Sozo, and apply the migrations to deploy the contracts: + +``` +sozo build +sozo migrate apply +``` + +Start the Torii server, replacing 0x6457e5a40e8d0faf6996d8d0213d6ba2f44760606e110e03e3d239c5f769e87 with the actual world address if different: + +``` +torii --world 0x6457e5a40e8d0faf6996d8d0213d6ba2f44760606e110e03e3d239c5f769e87 --allowed-origins "*" +``` + +## **Models** + +Models define data structures annotated with `#[dojo::model]` for integration into Dojo. + +### **Tile Model (tile.cairo)** + +``` +#[derive(Copy, Drop, Serde)] +#[dojo::model] +struct Tile { + #[key] + x: u16, + #[key] + y: u16, + color: felt252 +} +``` + +- `#[key] x, y`: Primary keys for grid location. +- `color: felt252`: Stores tile color. + +Each tile represents a grid coordinate where players can paint. + +### **Player Model (player.cairo)** + +``` +const TIME_BETWEEN_ACTIONS: u64 = 120; + +#[derive(Copy, Drop, Serde)] +#[dojo::model] +struct Player { + #[key] + address: starknet::ContractAddress, + player: u32, + last_action: u64 +} + +#[generate_trait] +impl PlayerImpl of PlayerTrait { + fn check_can_place(self: Player) { + if starknet::get_block_timestamp() - self.last_action < TIME_BETWEEN_ACTIONS { + panic!("Not enough time has passed"); + } + } +} +``` + +- `TIME_BETWEEN_ACTIONS`: 120-second cooldown to prevent spam. +- `#[key] address`: Primary key for player identity. +- `check_can_place()`: Enforces action cooldown. + +This structure ensures fair play by restricting frequent updates. + +## **Contract Systems** + +Contracts define the logic that enables players to take actions like spawning and painting tiles. + +### **Actions Contract (actions.cairo)** + +``` +// define the interface +#[dojo::interface] +trait IActions { + fn spawn(); + fn paint(x: u16, y: u16, color: felt252); +} + +#[dojo::contract] +mod actions { + use super::{IActions}; + use starknet::{ContractAddress, get_caller_address, get_block_timestamp}; + use boot_camp_paint::models::{tile::{Tile}, player::{Player}}; + + #[abi(embed_v0)] + impl ActionsImpl of IActions<ContractState> { + fn spawn(world: IWorldDispatcher) { + let address = get_caller_address(); + let player = world.uuid(); + let existing_player = get!(world, (player), Player); + assert(existing_player.last_action == 0, "ACTIONS: player already exists"); + let last_action = get_block_timestamp(); + set!(world, Player { address, player, last_action }); + } + + fn paint(world: IWorldDispatcher, x: u16, y: u16, color: felt252) { + let address = get_caller_address(); + let player = get!(world, (address), Player); + assert(player.address == address, "ACTIONS: not player"); + set!(world, Tile { x, y, color }); + } + } +} +``` + +- **IActions Interface:** Defines the available actions: `spawn()` and `paint(x, y, color)`. +- **spawn() Function:** + - Retrieves the caller’s address. + - Generates a unique player ID. + - Ensures the player doesn’t already exist. + - Records the player in the world state. +- **paint() Function:** + - Retrieves the caller’s address. + - Verifies the caller is an existing player. + - Updates the tile color at the specified `(x, y)` coordinates. + +This system ensures that only registered players can modify tiles and prevents duplicate player creation. + +After running these contracts and building them, you should be able to spin up a local katana devnet. + +## **World Write** + +Once you run the contracts on Katana, you should get a console log of the contract address. Save it for later. + +## **Indexing** + +Then you should be able to start a torii server in a new terminal using this command. + +`torii --world 0x6457e5a40e8d0faf6996d8d0213d6ba2f44760606e110e03e3d239c5f769e87 --allowed-origins "*"` + +Based on this, you should see a graphQL link on the terminal that you can access which will automatically generate schema for you. + +Now, the only portion pending is frontend! Take a look at my older tutorial for the same. + +Wola! This is all you need to get started with dojo-engine. + +## Resources + +1. https://book.dojoengine.org/tutorial/dojo-starter +2. https://www.youtube.com/watch?v=xKYqFMibIB0 +3. https://www.youtube.com/watch?v=sj0lJjufby4 + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/cartridge-controller-lets-talk-about-smooth-ux-for-onchain-games/ + +--- + +## Cartridge Controller: Smoothest UX for onchain games + +Home  /  Blog + +May 5, 2025 · 3 min read + +The gaming industry is undergoing a massive transformation with the rise of Web3, bringing true ownership, decentralized economies, and seamless player experiences. However, one of the biggest roadblocks to mass adoption is the complexity of blockchain authentication and wallet management. + +Enter **Cartridge Controller**-a groundbreaking solution designed to make Web3 gaming as seamless as traditional gaming, eliminating the need for complex wallet interactions, gas fees, and private key management. + +In this blog, we’ll explore how Cartridge Controller is revolutionizing Web3 gaming. It enables developers to create frictionless player experiences with account abstraction, session keys, and smart authentication. + +Before we talk any further, try Art-Peace, an onchain game on Starknet, and don’t forget to log in via Cartridge to check for yourself how smooth the UX is! + +Did you notice how the crypto wallet never prompts you to sign every transaction repeatedly? And did I mention that the gas fees are also covered? It can’t get any better; it seems like a normal game, right? With no pop-ups? + +## **The Problem: Why Web3 Gaming Needs Better Authentication** + +Web3 games introduce features like play-to-earn mechanics, NFT-based assets, and decentralized ownership. However, these benefits often come at a cost: complex user onboarding and frustrating blockchain interaction. + +### **The Current Challenges in Web3 Gaming** + +- **Wallet Management** – Players must set up wallets like MetaMask or Argent to access a game. +- **Gas Fees & Transaction Signing** – Every in-game action (buying items, minting NFTs) requires a blockchain transaction, which means **manual approval and gas fees**. +- **Seed Phrases & Security Risks** – Traditional wallets require users to secure seed phrases, which are difficult for mainstream gamers to manage. +- **Interrupted Gameplay** – Constant signing and wallet pop-ups disrupt the immersive experience of gaming. + +This is where Cartridge Controller comes in. It simplifies Web3 authentication and transactions, making Web3 games feel as smooth as traditional games. + +## **Introducing Cartridge Controller: Web3 Gaming, Simplified** + +Cartridge Controller is a smart authentication system designed to remove the friction of blockchain interactions in Web3 gaming. + +### **How Does Cartridge Controller Work?** + +Instead of forcing players to sign every transaction manually, Cartridge Controller leverages account abstraction and session keys to enable gasless, passwordless, and seamless authentication. + +### **Key Features of** **Cartridge Controller\*\***:\*\* + +- **Walletless Authentication** – Players can sign in using familiar methods (Google, Discord, etc.) instead of managing wallets. +- **Session Keys** – Allows automatic signing of transactions for pre-approved actions, reducing pop-ups. +- **Gasless Transactions** – Removes players needing to hold ETH for gas fees. +- **Account Recovery** – No need to remember seed phrases; accounts can be linked to traditional authentication methods. +- **Security & Customization** – Developers can set up granular permissions for transaction execution. + +With Cartridge Controller, Web3 games can offer a frictionless experience, keeping players engaged without blockchain complexity. + +--- + +## + +## **How to Integrate Cartridge Controller in Your Web3 Game** + +Enough bragging now; let’s dive into setting up the Cartridge Controller in a Web3 game using React. + +#### **1. Install the Cartridge SDK** + +Start by installing the required dependencies: + +``` +yarn add @cartridge/controller starknet react +``` + +#### **2. Initialize the Cartridge Controller** + +Create a `controller.js` file and initialize the Cartridge Controller. + +``` +import { Controller } from '@cartridge/controller'; + +const controller = new Controller({ + app: 'your-game-id', + network: 'starknet-testnet', // or 'starknet-mainnet' +}); + +export default controller; +``` + +#### **3. Connect a Player’s Account** + +In your React component, add a login button that connects a player’s account. + +``` +import React, { useState } from 'react'; +import controller from './controller'; + +const Login = () => { + const [player, setPlayer] = useState(null); + + const connectPlayer = async () => { + const account = await controller.connect(); + setPlayer(account); + }; + + return ( + <div> + <button onClick={connectPlayer}>Login to Game</button> + {player && <p>Welcome, {player.address}!</p>} + </div> + ); +}; + +export default Login; +``` + +#### **4. Enable Session Keys for Seamless Transactions** + +With session keys, players can automatically sign transactions without manual confirmations. + +``` +const enableSessionKey = async () => { + await controller.authorize({ + actions: ['moveCharacter', 'claimReward'], // Pre-approved actions + duration: 3600, // 1 hour session + }); +}; +``` + +#### **5. Execute an In-Game Transaction Without Pop-Ups** + +``` +const purchaseItem = async () => { + await controller.execute({ + contract: '0xYourGameContract', + method: 'buyItem', + args: [1], // Buy item with ID 1 + }); +}; +``` + +## **Real-World Use Cases: How Web3 Games Can Use Cartridge Controller** + +### **1. NFT-Based Games** + +- Players can mint, trade, and equip NFTs without needing manual transaction approvals. +- Session keys allow automatic weapon/skin upgrades without signing transactions. + +### **2. Play-to-Earn (P2E) Games** + +- Earnings can be claimed without gas fees interrupting the experience. +- Players can stake and withdraw rewards seamlessly. + +### **3. On-Chain Strategy & Card Games** + +- Moves in turn-based strategy games can be auto-signed, keeping gameplay uninterrupted. +- Deck management, trades, and upgrades happen in real-time. + +--- + +## **Resources and further reading:** + +Start by integrating the Cartridge Controller into your Web3 game today! + +- Cartridge Controller Docs +- Getting Started with Cartridge Controller +- React Example Implementation + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/session-keys-on-starknet-unlocking-gasless-secure-transactions/ + +--- + +## How Session Keys on Starknet Revolutionize dApp UX with Gasless Transactions + +Home  /  Blog + +Apr 29, 2025 · 3 min read + +## **Introduction** + +As blockchain adoption grows, user experience remains one of the biggest hurdles. Interacting with decentralized applications (dApps) often requires signing multiple transactions, leading to frustrating delays and gas costs. + +Wouldn’t it be great if users could interact with dApps **seamlessly**, without signing every single transaction? + +This is where **Session Keys** come in. They offer a game-changing way to execute multiple transactions securely without requiring constant user approval. In this guide, we’ll explore the concept of Session Keys on Starknet, understand their benefits, and build a hands-on demo. + +## **What Are Session Keys?** + +A **Session Key** is a temporary key that grants limited transaction execution permissions to a dApp **without requiring user signatures for each action**. Instead of prompting for wallet confirmations on every interaction, session keys enable smooth and uninterrupted dApp usage for a specified period or under defined constraints. + +How Do Session Keys Work? + +1. **User Signs Once**: The user grants permission for a specific session key with predefined rules (e.g., limited to certain functions, time duration, or spending caps). +2. **dApp Executes Transactions**: The dApp uses this session key to sign transactions on behalf of the user within the given constraints. +3. **Session Expires**: After the session key expires (or reaches its limits), it can no longer sign transactions, ensuring security. + +### + +### Why are session keys useful? + +✅ **Gasless Transactions** – Users don’t need to pay for gas on every interaction. + +✅ **Seamless UX** – No need to sign each transaction manually. + +✅ **Fine-Grained Permissions** – Limited scope ensures security. + +✅ **Enhanced Gaming & DeFi** – Enables better automation and fluidity in games and trading platforms. + +> **Use Case Example:**Imagine a blockchain game where you need to approve every move or action. With session keys, the game can execute moves automatically within the approved parameters, improving the user experience! + +## **Session Keys on Starknet** + +Starknet leverages **Account Abstraction (AA)** to enhance smart contract wallets, making session keys possible. Starknet’s session keys operate through **smart contract-based authentication**, allowing fine-tuned access control. + +Key Features: + +- **Smart Contract-Based Access Control**: Permissions are embedded in the wallet’s contract. +- **Granular Constraints**: Developers can define specific function calls, time limits, and spending caps. +- **Enhanced Security**: Session keys have a controlled lifespan, preventing abuse. + +The **Argent Wallet** is a popular implementation of session keys on Starknet, offering developers an API to integrate session-based transactions seamlessly. + +## **Building a Session Key Demo on Starknet** + +Now, let’s build a demo that allows users to interact with a smart contract using session keys, similar to this demo + +**Step 1: Setting Up Your Starknet Environment** + +Ensure you have the following installed: + +``` +curl --proto '=https' --tlsv1.2 -sSf https://sh.starkup.sh | sh +``` + +### **Step 2: Deploying a Smart Contract with Session Key Support** + +We’ll write a simple **Counter Contract** where a session key can increment a counter without needing multiple signatures. + +**Counter Contract (Cairo)** + +``` +#[starknet::interface] +trait ITestSession { + fn increase_counter(ref self: TContractState, value: u128); + fn decrease_counter(ref self: TContractState, value: u128); + fn get_counter(self: @TContractState) -> u128; +} + +#[starknet::contract] +mod test_session { + use starknet::storage::StoragePointerWriteAccess; + use starknet::storage::StoragePointerReadAccess; + + #[storage] + struct Storage { + count: u128, + session_keys: Map<felt252, bool>, // Store session keys + } + + #[abi(embed_v0)] + impl TestSession of super::ITestSession { + fn increase_counter(ref self: ContractState, value: u128) { + assert!(self.session_keys.contains(&get_caller()), "Unauthorized session key"); + self.count.write(self.count.read() + value); + } + + fn decrease_counter(ref self: ContractState, value: u128) { + assert!(self.session_keys.contains(&get_caller()), "Unauthorized session key"); + let current = self.count.read(); + if current >= value { + self.count.write(current - value); + } else { + self.count.write(0); + } + } + + fn get_counter(self: @ContractState) -> u128 { + self.count.read() + } + + fn add_session_key(ref self: ContractState, key: felt252) { + assert!(is_admin(), "Only admin can add session keys"); + self.session_keys.insert(key, true); + } + + fn remove_session_key(ref self: ContractState, key: felt252) { + assert!(is_admin(), "Only admin can remove session keys"); + self.session_keys.remove(key); + } + } +} +``` + +### **Step 3: Generating and Using a Session Key** + +**Generating a Session Key** + +``` +import { starknet } from "starknet"; + +async function createSessionKey(wallet) { + const sessionKey = starknet.generatePrivateKey(); + const sessionPublicKey = starknet.getPublicKey(sessionKey); + + await wallet.addSessionKey(sessionPublicKey); + + console.log("Session Key Created: ", sessionPublicKey); + return sessionKey; +} +``` + +**Using the Session Key** + +``` +async function useSessionKey(sessionKey, contractAddress) { + const provider = new starknet.Provider(); + const contract = new starknet.Contract(contractAddress, provider); + + await contract.increase_counter(10, { from: sessionKey }); + console.log("Counter incremented using session key!"); +} +``` + +**Session Keys on Starknet**, allows users to interact with a smart contract without manually signing every transaction. By introducing **Session Keys**, we improved UX while maintaining security. + +### **What We Achieved:** + +✅ Implemented a **Session Key-enabled Counter Contract** in Cairo 2.9.2. + +✅ Allowed **temporary access** to session keys with controlled permissions. + +✅ Ensured **security** by restricting actions session keys can perform. + +✅ Demonstrated how **session keys** can enhance gasless transactions and smooth dApp interaction. + +## **Final Thoughts and Resources on Session Keys** + +Session keys provide a robust way to improve blockchain usability by reducing friction in user interactions. With **Account Abstraction (AA) and Session Keys**, developers can build **decentralized applications that feel as smooth as Web2 apps** while maintaining blockchain security and decentralization. + +🚀 **Want to try it out?** + +Deploy your session-key-enabled dApp and share your experience! + +Here is the link to the GitHub repository to follow along: https://github.com/reetbatra/session-keys-demo + +Argent’s guide on session keys: https://docs.argent.xyz/aa-use-cases/session-keys + +More on understanding session keys on starknet: https://starkware.co/blog/session-keys-unlocking-better-ux/#session-keys + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-foundation-announces-support-program-for-payment-applications/ + +--- + +## Starknet Foundation Launches Support Program for Payment Apps + +Home  /  Blog + +Apr 4, 2025 · < 1 min read + +A vibrant Web3 ecosystem isn’t a byproduct of mere speculation. It’s built on real usage. That’s why Starknet Foundation is supporting initiatives and campaigns launched by Starknet projects designed to accelerate this future. + +Let’s take a closer look at how Starknet Foundation is supporting payments applications with this program. + +Apply for a grant now → + +## How is Starknet Foundation supporting payment applications? + +Under this new grants program the Starknet Foundation will provide monthly STRK grants to eligible builders to help them with their acquisition and to bring their application or new application features to their end users. + +## What a successful payments ecosystem looks like + +Success isn’t doing things the same way they have always been done in crypto. It’s seeing people use Starknet applications in every day settings with the best underlying user experience. + +With this initiative, Starknet Foundation envisions both wallets and fintech apps integrating Starknet payments. We see real economic activity driving on-chain transaction volume instead of only speculative trades. The Starknet Foundation also foresees more strategic partnerships across the payment stack, from stablecoin issuers to payment processors and DeFi rails. + +The ultimate goal is for more people to use crypto the way it was always meant to be used: to power economic growth and develop emerging markets. + +## Get involved + +If you’re a wallet, card provider, or payment protocol ready to build the future of crypto payments, Starknet Foundation wants to hear from you! + +Crypto’s next era won’t be powered by hype but by habits. + +Apply for a grant now → + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/going-beyond-limits-bitcoin-ethereum-and-a-new-foundation-for-the-digital-world/ + +--- + +## Going beyond limits: Bitcoin, Ethereum, and Starknet + +Home  /  Blog + +Mar 11, 2025 · 3 min read + +**_By James Strudwick, Executive Director, Starknet Foundation._** + +## A system in need of reinvention + +At Starknet Foundation, our vision is a world where power is shared, creativity is rewarded, and opportunity is accessible to all. As the Starknet L2 moves towards becoming the first protocol to settle on both Bitcoin and Ethereum, I thought it was important to take a moment to talk about this vision, how it has brought us here, and how we see Bitcoin helping us realize it. + +The limits of the current digital world are clear: money, data, and power are concentrated in the hands of the few, limiting opportunity and participation for most, and leaving the internet as a whole a less diverse, creative, and innovative space. It was never meant to be like this. But, as with so many things, we get so used to the way things are that we often stop seeing them. That is, until they break. + +## The rise of digital gold + +The financial crisis of 2008 was exactly this kind of breaking point. We saw with painful clarity the limits of our current financial system, the impossibility of fully trusting financial institutions, and the need to be able to be custodians of our money in a way that was accessible to everyone. Enter Bitcoin. + +With Bitcoin’s launch in 2009 a new, imagined but previously unrealized, horizon opened up. We were presented with a truly global currency that required no intermediaries, no bank account, and no government intervention or regulation. It was a community driven currency open to everyone regardless of wealth, social status, or national origin. + +Unfortunately, as with many young technologies, a combination of technical limitations and bad actors led Bitcoin’s adoption to remain limited early on. Slow transactions, complicated UX, and limited ways to use the token, along with its early reputation for being primarily for illicit activities, proved to be challenging hurdles for Bitcoin. So, while it remained in the popular imagination it did not reach the mainstream or its world changing potential. + +## The birth of the global commons + +Six years after Bitcoin’s initial launch, the second major player in the blockchain space came into being. Unlike Bitcoin, Ethereum wasn’t meant to only be about money, it was intended to be a global commons where people could build everything from currency to identity and governance systems. It was, in a sense, a global computer, but much like Bitcoin, one that was initially held back by its own technological limitations. The UX was equally complicated, and it required learning new conceptual frameworks and programming languages. + +If we fast forward to today, numerous other layer 1 blockchains, as well as layer 2s and layer 3s have arisen, but Bitcoin and Ethereum remain the largest and most important projects in the Web3 space, and in many ways the greatest hopes for bringing this world changing technology to everyone. And this is where Starknet comes in. + +## Web3 at scale + +Although it was originally launched on Ethereum, Starknet wasn’t built only for Ethereum. Starknet was built to be able to scale any chain using STARK proofs in order to create a digital world with integrity thanks to full verifiability. The idea that this would be possible for Bitcoin as well has been there from the very beginning of the project. Now, after countless hours of research and development, we are in a place to begin making this idea a reality. + +That this is now possible, and that Starknet is building the infrastructure and partnerships needed to make this happen is a massive step forward, and a reason to be excited. But what is perhaps even more exciting is what this will enable and what it can mean for the digital world as a whole. + +## A new foundation for the digital world + +By enabling developers to create applications that only need to be built once, using the same code, but that can settle on either Bitcoin or Ethereum, we will enable greater utility for Bitcoin and continue to make Ethereum’s digital commons more accessible to everyone through faster transactions, increased scale, and lower costs. For the first time developers will have true optionality between the leading chains, and can access the strengths of both Ethereum and Bitcoin depending on the application being built. + +Satoshi’s original vision was a digital peer-to-peer payment system that can operate without the need for centralized authority, at scale. Until now, only part of that was possible. By bringing STARK technology to Bitcoin, we are helping to make the full vision a reality. This can bring about a sea change in financial accessibility and inclusion, open up new markets, and create a new foundation for reimagining and reinventing the digital world from the ground up, something that resonates with both Satoshi’s vision as well as our own at Starknet Foundation. + +We are on the precipice of something amazing, and Starknet is leading the way. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Introducing Garden on Starknet: A direct path for BTC bridging + + Garden is live on Starknet, offering a direct path for Bitcoin liquidity. Bridge Bitcoin to Starknet with Garden for fast, low-fee DeFi. + + April 29, 2025 + +- #### Atomiq brings wBTC to Starknet, enabling Bitcoin DeFi + + BTC-to-wBTC swaps are now live on Starknet using onchain escrows and Bitcoin PoW validation, with no bridges or custodians. + + April 16, 2025 + +- #### Starknet over Bitcoin: Vitalik, Dan Held, and Jeremy Rubin react + + Starknet will become the first Layer 2 to settle on Bitcoin. Learn what Vitalik Buterin and two Bitcoin OGs think about the move. + + March 30, 2025 + +- #### Bitcoin Lightning Network payments with STRK—now live on Starknet via Braavos + + Braavos now enables Bitcoin Lightning Network payments with STRK on Starknet—no BTC, no extra setup, just tap and pay + + March 13, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/begin-your-startup-journey-with-founder-basecamp/ + +--- + +## Begin your startup journey with Founder Basecamp | Starknet + +Home  /  Blog + +Mar 5, 2025 · 2 min read + +Starting your own business can seem challenging, especially if you’re new to entrepreneurship. You might have a great idea, but figuring out where to start can be overwhelming. Founder Basecamp is here to help you turn those initial thoughts into a real, actionable startup plan. Through four interactive weekly sessions and a final pitch competition, Founder Basecamp will help you shape your idea, craft a compelling pitch, and confidently engage potential customers and investors. + +Whether you’re starting from scratch, have a basic concept, or need guidance shaping your vision, Founder Basecamp is the perfect place to begin your journey. + +Apply now → + +## Why join Founder Basecamp? + +Every successful startup begins with a simple idea. But making that idea clear, convincing, and appealing to customers and investors is tough. Many entrepreneurs stumble due to unclear messaging, poor market validation, or ineffective go-to-market strategies. Founder Basecamp offers you practical support and expert advice to help you transform your initial thoughts into a strong business concept. You’ll learn how to clearly communicate your idea, prove its value to real people, and gain the skills needed to attract funding. + +By participating, you will: + +- Turn your initial idea into a clear and compelling business concept. +- Learn how to validate your idea with real-world insights. +- Build the skills needed to successfully fundraise. +- Gain confidence and clarity to take your startup forward. + +## Who should apply? + +Founder Basecamp is perfect if you: + +- **Are an aspiring entrepreneur** — You’re driven to create something great but need structured guidance to figure out exactly what that could be. +- **Have an existing idea** — You’re clear about what you want to build but need help communicating it effectively to customers and investors. +- **Want to brush up on your entrepreneurial skills** — You’re interested in entrepreneurship and want to sharpen your startup knowledge and pitching abilities. + +## Program Overview + +### Week 1: Idea Refinement & Market Validation + +- Clearly define the problem your startup solves. +- Validate your solution through research and user feedback. +- Set clear, achievable goals to measure your progress. + +### Week 2: Go-To-Market Strategy & Marketing + +- Discover what makes your idea unique and appealing. +- Create a simple plan to attract your first customers. +- Develop clear messaging that excites your target audience. + +### Week 3: Fundraising Fundamentals + +- Understand the fundraising landscape. +- Create an impressive pitch deck to convince investors. +- Practice confidently answering common investor questions. + +### Week 4: Crafting and Perfecting Your Pitch + +- Refine your storytelling techniques to clearly share your startup idea. +- Learn how to use visuals effectively in presentations. +- Practice your pitch with peer feedback for refinement and confidence. + +### Week 5: Pitch Competition + +- Present your idea live to a panel of judges. +- Receive valuable feedback. +- Build confidence for future investor conversations. + +## After the program + +Completing Founder Basecamp isn’t the end! It’s just the beginning. The strongest pitches will earn the opportunity to team up with top technical co-founders from the Starknet ecosystem, entering a product-focused hackathon. This is your chance to rapidly prototype, validate your concept, and lay a solid foundation for your startup’s success. + +## Ready to get started? + +Now is the perfect time to move forward with your startup idea. Founder Basecamp provides the support, community, and practical steps you need to turn your idea into reality. + +Apply now → + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### DeFi Spring Program 2.0 + + Discover how to earn additional yield as a liquidity provider on Starknet with DeFi Spring 2.0. + + October 20, 2024 + +- #### Leadership transition at Starknet Foundation + + Diego Oliva, who has served as the first CEO of the Starknet Foundation will be stepping down and James Strudwick will be assuming the… + + August 6, 2024 + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/what-its-like-to-work-at-the-starknet-foundation/ + +--- + +## What It’s Like to Work at the Starknet Foundation | Starknet + +Home  /  Blog + +Jan 29, 2025 · 3 min read + +## A different kind of foundation, a different kind of job + +Working at the Starknet Foundation isn’t like any other job. It’s a chance to do something that matters, challenge yourself, leave your mark on an ecosystem that is out to reinvent the digital world, and work with some of the brightest minds in the field. + +With a leadership team with nearly 40 years of collective experience in Web3 ranging from lecturers in blockchain technology, to DeFi experts, to startup founders, to government advisors, to some of the most experienced product people in the field, the Starknet Foundation is a truly unique place to grow a career. + +## Not just another protocol + +Founded by pioneers in cryptography including Eli Ben-Sasson who developed groundbreaking innovations including zk-STARKs and Cairo — the L2 smart contract language — Starknet was launched in 2021 to not only overcome the current technical limitations of Web3, but open new ways to build impactful products that solve real world problems with integrity. This allows founders and developers to think beyond the boundaries of both Web2 and Web3 to bring their most ambitious and creative ideas to life, while making widespread adoption a real possibility through native account abstraction and improved UX. + +Starknet doesn’t simply make Web3 better by making it faster, more efficient, more scalable, and more cost effective, though it does all of those things as well, it fundamentally does something different. Starknet provides a future proof, fully verifiable development platform with its own complete programming language, with the aim of allowing founders and developers unmatched creativity and opportunity. Think of it as a new platform for the digital world, built on verifiability, that can push back against ever growing corporate control and the centralization of power, so we can once again trust the products we use and information we receive. + +Currently the digital world is built to benefit the few by centralizing opportunity and creating a divide between builders and users. Starknet is helping to turn this on its head. Founders get new paths to monetization, distribution, and discovery that build relationships with users and invite them into the life of their projects. Developers get access to a technology stack that unlocks new ways to imagine app development. While users get a range of experiences that aren’t available anywhere else. And all of this is backed by a supportive ecosystem filled with bright and creative minds, funding opportunities, and everything founders and developers need to turn their ideas into sustainable businesses. + +Starknet is the platform for those looking to reinvent everything. From gaming to finance, Starknet’s vision is to build the foundation for a new digital world that increases creativity, opportunity, and participation. + +## Life at the Foundation + +To work at the Foundation is to go beyond the traditional borders of a company. Our impact and reach extends across an entire ecosystem of entrepreneurs and builders, each of whom are at the forefront of their fields, giving everyone who works with us the chance to engage with a broad range of projects that are laying the groundwork for a new digital world. + +We understand that what we are aiming for isn’t small, and that there is no quick path to success, But, by living our values of integrity, long-term thinking, transparency, collaboration, creativity, and purpose in everything we do, we are well positioned to ensure this happens. + +Aligned with our ecosystem entrepreneurs, the culture at the Foundation is dynamic, entrepreneurial, and always evolving. To work here is to know you are making a real difference, having impact, not just on one project or company, but on an entire continually evolving ecosystem. + +Interested in making an impact on an entire ecosystem, and helping to reinvent the digital world? Find your place on the team. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/dont-stop-hodling-introducing-asset-runes/ + +--- + +## Don’t stop HODLing - Introducing Asset Runes | Starknet + +Home  /  Blog + +May 27, 2025 · 2 min read + +### **TL;DR** + +**You can now get native exposure to USDC on Bitcoin, unlocking trust-minimized interaction with the largest and most traded currency.** + +Bitcoiners face a dilemma: the security of Bitcoin vs. the expressibility and composability of other chains. Bitcoiners who sought financial functions such as exposure to other assets were thus forced to explore the broader blockchain sphere, thus compromising in leaving Bitcoin to other, less secure networks to achieve that. + +Enter Asset Runes – a new class of Bitcoin-native assets that are redeemable 1:1 for real-world assets, natively available within Bitcoin, starting with USDC. Explore Asset Runes: + +## **HODL Bitcoin, Use Asset Runes** + +With Asset Runes, HODLers can now diversify their portfolios without leaving the Bitcoin network, starting with USDC and expanding in the future to USDT, ETH, SOL, STRK and many more. Asset Runes are powered by: + +1. Starknet, Ethereum’s leading ZK rollup +2. The Bitcoin<>Starknet Runes Bridge – enabling a secure connection between Bitcoin and Starknet + +## **How it works:** + +In a nutshell, Asset Runes can be bridged to Starknet and then redeemed via smart contracts for the underlying assets in a 1:1 ratio. Let’s give a slightly more detailed overview. + +- Users hold USDC•Starknet directly on Bitcoin. +- USDC•Starknet acts like any other rune, which can be traded trustlessly on Bitcoin mainnet. You can try them out on DotSwap. +- Full reserves: each Asset Rune is backed 1:1 by an actual asset on Starknet. For example, each USDC Rune has a locked counterpart on Starknet. By design, it is impossible for the supply of Asset Runes on Bitcoin to exceed the reserves on Starknet. +- The Bitcoin<>Starknet Runes Bridge, secured by a federation of Bitcoin OGs (you can read all about the validators here), facilitates the secure transfer of funds between the networks. +- Once bridged to Starknet, users can redeem the wrapped Runes for the underlying asset at a 1:1 ratio without any trusted intermediaries. +- In the upcoming weeks, the StarkGate UI will abstract the intermediate wrapper from users, allowing for direct redemption from Bitcoin. Various applications will also integrate with StarkGate, providing the same UX. All are to be announced soon. + +## **More than Asset Runes** + +With ZK tech infrastructure, scale, native account abstraction, and a vibrant ecosystem, Starknet is the ideal candidate for enriching the financial offering for Bitcoiners. + +Asset Runes are an example, with Starknet providing a redemption layer. However, Starknet is also ideally positioned as an arena for asset and value creation: whether you want launchpads or DeFi. + +## **Try Asset Runes Today** + +Open your Xverse wallet, or try them on DotSwap!  + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-foundation-delegation-program/ + +--- + +## Starknet Foundation Delegation Program: How to apply + +Home  /  Blog + +Jul 17, 2025 · 3 min read + +As Starknet continues its decentralization journey and moves closer towards a Proof of Stake (PoS) protocol, contributors across the ecosystem are working together to support the growth of a strong, decentralized validator set. This is a critical bootstrapping moment: wide participation in staking and validation is imperative to safeguarding the network against the undue influence of any single entity, which is essential for a strong, permissionless, and truly decentralized system. + +Delegation programs play a key role in this process by lowering the barrier to entry for validators, encouraging broader participation, and improving decentralization. + +## The Starknet Foundation Delegation Program + +This week, the Starknet Foundation launched the Starknet Foundation Delegation Program (SFDP), a strategic initiative designed to enhance staking distribution, support validator growth and diversity, and strengthen network resilience. + +The program creates new opportunities for both new and existing validators to participate in securing the network. As such, there is clear, meaningful support and well-defined performance benchmarks. + +Let’s take a closer look at how the program works, who it supports, and what to expect. + +## Program details + +At its core, the Starknet Foundation Delegation Program is about broadening participation and improving resilience. Starknet’s validator set has grown, but we can and should do better for the health of the network and ecosystem. The program addresses the growth of staking delegation by introducing delegation mechanics and targeted validator support. + +The program’s goals are clear: distribute stake across a more diverse validator set; increase the number of active validators securing the network; upgrade overall staking participation to improve network security in the long-term. + +And it does this with a design philosophy built around three principles: + +- **Fair** – Balance decentralisation goals with responsible treasury management +- **Targeted** – Prioritise measurable, meaningful outcomes +- **Flexible** – Built to evolve alongside the network and its needs + +## How it works + +The Foundation will match validator stake 1:1, up to a maximum of 5 million STRK per participant, subject to performance criteria, such as: + +- **Stake Matching:** For STRK staked by a validator, the Foundation will delegate the same amount (up to 5M STRK), excluding any amount received from other Delegation Programs. +- **Residual Delegation**: Any remaining STRK in the delegation pool may be distributed evenly amongst qualified participants, i.e. + +- Stake 30M STRK → receive 5M delegated STRK matched + residual share. +- Stake 1M STRK → receive 1M delegated STRK matched + residual share. + +- **Program Cap:** If the delegation pool is exhausted, the Foundation will reduce stake matching allocations to all validators by the same proportional percentage. + +These mechanisms support validators who have secured meaningful stake independently, while also encouraging new participants to grow with the ecosystem. + +### Who is eligible? + +To receive matched delegation, validators must: + +- Run a full Starknet validator node. +- Maintain high uptime (>99%) and responsiveness. +- Respond to Foundation inquiries within 48 hours. +- Set commission rates at 10% or less. +- Meet regulatory compliance requirements + +**Validators remain eligible even if they participate in other Delegation Programs; however, any delegation received through those programs will be excluded from the matched stake calculation**. Validator performance will be monitored continuously, and delegated amounts will be adjusted regularly. + +### Application + +To apply, fill out the Starknet Foundation Delegation Program application form. Reviews will take place on a rolling basis. + +## Designed with adaptability in mind + +The program is built to adapt. During the program’s rollout, community feedback will be ensured with clear, transparent communication from the Foundation. + +## What are the next steps? + +The Starknet Foundation Delegation Program is an important moment in Starknet’s path toward deeper decentralization. It’s not just a validator incentive, it’s a strong signal to our ecosystem that STRK is here to do more. + +If you’re a validator – or ready to become one – now is the time to join us in building a more diverse and resilient Starknet. + +If you apply to the Starket Foundation Delegation Program, stay tuned to your inbox for updates from the Starknet Foundation. + +Let’s build a more resilient Starknet, and reshape the digital world together. + +_Note: This program does not constitute a grant, investment, or form of compensation. Delegated STRK remains under Foundation custody and is subject to revocation based on validator behavior. The program operates at the sole discretion of the Foundation and may be modified at any time to promote broader inclusion, fairness, and alignment with ecosystem goals._ + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/blurb-on-liquidity/ + +--- + +## Blurb on Liquidity: Understanding DeFi Market Dynamics | Starknet + +Home  /  Blog + +Written By: Ilia Volokh + +Aug 10, 2025 · 12 min read + +This post attempts to organize a basic understanding of liquidity, oriented at DeFi. We’ll define liquidity and its key metrics, and analyze it for constant-product AMMs. Then we’ll touch on impermanent loss and end with a brief overview of concentrated liquidity. + +# Liquidity + +Liquidity is a property of markets, crucial for capital efficiency. Folklore intuition can be summed up in one line: + +> A market is liquid if it can quickly execute trades with minimal price changes. + +For example, major stock exchanges are liquid markets for commonly traded stocks. + +It is typical to abuse terminology and say an asset is liquid, meaning “this asset is quickly convertible into money with minimal loss”. Formally, this statement asserts the liquidity of an implicit market between the asset and money. For examples, a house is an illiquid asset because it takes a while both to discover the market price and to sell it at that price. + +One sometimes encounters the term “funding liquidity”, referring to the ease of obtaining credit (i.e., borrowing). Thus an asset has high funding liquidity if it can serve as collateral for money at a good rate. + +For some history see e.g. this stackexchange answer. + +Liquidity is measurable by a few key metrics: + +| Metric | Meaning | Consequence | Cause | +| ------------ | --------------------------------------------------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| Spread | Lowest sell price (best ask) minus highest buy price (best bid). | Wide spread → high cost to initiate trade | Insufficient market-making | +| Depth | What asset amount can be traded within some price range? | Shallow depth → volatility | Insufficient supply | +| Price impact | How does my trade impact the current market state? | High price impact → I get less | App-level: depth & spread | +| Slippage | What I expected when placing my trade vs what I got when it executed. | High slippage → I get less | Core-level: market state discrepancy between simulation & execution, e.g. due to competition, latency, MEV | + +Spread is a threshold cost which dominates small trades. Larger trades begin to consume depth, which outweighs the initial spread. + +Before diving a bit deeper, we record a common unit of measurement in finance: + +**Definition.** A basis point (plural bps) is a hundredth of a percent $0.01\%=\frac{1}{10,000}$. + +## Spread + +Assuming the market price is within spread interval, a taker must pay a premium to immediately initiate a trade. Wider spread → higher premium. + +[highest bid,lowest ask] + +A narrow spread thus increases capital efficiency, especially for small trades. A spread of 10 bps means the highest bid and lowest ask differ by $0.10\%$. + +## Depth + +High depth around an exchange rate leads to price stability: even large trades will not cause volatility. The statement “there’s 10K USD of BTC buy-side depth per bp at the current price” means you can buy 10K USD-worth of BTC and incur a price change of at most one basis point, i.e $0.01\%$. + +The depth of liquidity in a price interval should be thought of as the supply of capital deployed there. High depth at exorbitantly high/low prices is wasted capital. We’ll unpack this later for constant-product AMMs. + +Depth is also crucial for stable capital-efficient loan markets because it ensures liquidations are profitable to liquidators. We illustrate the opposite extreme: how shallow depth triggers a liquidation death spiral. The loan market in question is borrowing USD against BTC collateral. + +- Suppose Alice loaned 1M USD to Bob against 10 BTC. Suppose Bob defaults, so that Alice seizes 10 BTC. Now suppose Alice wishes to liquidate the loan i.e. sell the BTC for USD. If the BTC/USD market in question has shallow liquidity, the exchange rate would dip against Alice: she may sell 1 BTC at a good price, but any larger amount would sell at an increasing loss to her. In case of an over-collateralized loan, Alice can make a quick profit even if she sells some of her BTC underpriced. Such a sale would lower the BTC/USD exchange rate against BTC, potentially triggering more liquidations. +- Depth is the dampener of liquidations, defending against chain-reactions and death spirals. + +## Price impact + +Products sold in stores typically have posted prices, which trivialize economic calculation. The naive approach to buying some amount of an asset would be to multiply its market price-per-unit by the amount. + +If the market price is a 1 USD/unit, I naively expect 100 USD to buy me 100 units. _Price impact_ is any deviation from this expected outcome. Such deviations are deterministic in the current market state, and determined entirely by trade size, spread, and depth. Price impact can be mitigated at the application level, e.g. via aggregators and routers which traverse multiple markets. + +## Slippage + +Even if I have perfect knowledge of the market mechanism (e.g. AMM curve) and its current state, I do not know the future market state at the execution of my order. Despite my ability to perfectly simulate my trade, I cannot predict the market conditions at execution: reality can differ from my expectations, resulting in _slippage_. Such slippage can be honest, e.g. competitors pay higher priority fees and overtake me, or manipulative, e.g. sequencers manipulating ordering. + +# Market-makers + +Markets are not in a constant state of equilibrium, and organic activity (or lack thereof) can result in occasional wide spreads. + +1. Buyers and sellers need not show up together. There can be waves of one-sided demand, in terms of both time and volume. +2. Price discovery takes time: buyers would initially post low bids and sellers would initially post high asks. +3. Liquidity may not arise organically, due to wide spreads or shallow depth. + +Market makers (henceforth MMs) streamline market operations by providing supply & demand counterparties and optimizing price discovery. + +## Order-book market-makers + +In order-book markets, MMs act by posting trades that bring the market closer to equilibrium. The naive business model is simple: manufacture spread and profit off it. Specifically, MMs manufacture spread by maintaining a gap between their highest bids and lowest asks. They aim for a narrow spread when competition is high and risk is low, and conversely. Let’s make this a bit more explicit. Assume Alice and Bob are competing MMs. If Alice quotes (posts orders) slightly tighter than Bob, then her orders are more attractive to traders, and they’ll get executed first. This is obviously good if she profits, but a volatile market may actually cause tight spread to incur losses. + +Although MMs profit off of wider spread, a competitive market also incentivizes them to provide _depth_ around their _tightest_ quotes. Indeed, once demand depletes Alice’s tightest quotes, she no longer has any competitive advantage over Bob. The more depth she provides, the more orders she will be able to capture from Bob at her tighter spread (despite profiting less per unit exchanged). + +To summarize, order-book market-makers are precisely liquidity providers! + +## AMMs; impermanent loss + +An AMM is an implementation of a market that: + +1. Automatically computes exchange rates based on its state. +2. Automatically distributes supply across the exchange-rate curve to create liquidity. + +Since AMMs automatically manage capital, the only _required_ making is the deployment of capital. It so happens that AMM terminology refers to these capitalists as liquidity providers. As we shall see below, more refined AMM designs actually involve makers who choose where to deploy capital, i.e. where to create depth. In this sense, they are indeed liquidity providers as opposed to “mere capitalists”. + +Before continuing, we’ll define an important concept that is often overcomplicated by only looking at examples. + +**Definition.** A pair (LP position, initial deposit) is at _impermanent loss_ if the current the value of the LP position is lower than the current value of the initial deposit (i.e. at current exchange rates). + +To emphasize – impermanent loss is only defined with respect to an initial deposit; it’s not an intrinsic property of an LP position. Put succinctly, impermanent loss is the opportunity cost of being an LP instead of holding on to the capital in a wallet. This opportunity cost if offset by expected profit from trading fees. + +Impermanent loss is so-called because it may be transient. It is caused by arbitrage traders reacting to market shifts: + +1. The market outside the AMM shifts, affecting the market exchange rate between the AMM assets. +2. Arbitrage traders buy the appreciated asset from the AMM for cheaper than on the external market. +3. The AMM supply of the appreciated asset decreases until the AMM discovers market price. +4. If an LP redeems their share of each asset, they end up with a smaller amount of the appreciated asset than they deposited, but a larger amount of the depreciated asset. +5. The current value of the redeemed LP position is lower than the current value of the original deposit. + +Risk of impermanent loss vanishes once AMM exchange rates return to the neighborhood of the initial deposit. For this reason, it is customary for volatile pair LPs to charge higher fees. + +The above formulation should make it clear there is no “impermanent gain” – arbitrage traders buy whichever asset is undervalued by the AMM. + +# Worked example: constant-product AMMs + +We now illustrate the abstract nonsense above in the setting of a constant-product AMM. We start out **without fees**, and address them later. + +## Basics + +Fix two assets $X,Y$ and denote by $x,y$ their respective supplies. The AMM curve is $xy=k$ for some constant $k$. Evidently the curve is symmetric in $x,y$. As a function of $x$, we see $y=\tfrac kx$ is not only monotone decreasing but also _subadditive_, which enforces diminishing marginal utility. Conceptually, this is the only required property of an AMM curve. In our constant-product case, marginal diminution is visualized by the hyperbola curve: As the supply $x$ grows, a fixed change of supply $\Delta x$ causes a diminishing change of supply $\Delta y$. + +Let us quantify supply changes. Suppose the present state of AMM supply is $x,y$. How does a change in supply $\Delta x$ affect the supply of $Y$? By definition, the next state of the AMM supply is $x+\Delta x, y+\Delta y$, so the invariant constraint gives us + +Hence + +Thus we see how $\Delta y$ inversely depends on the initial supply $x$. + +The exchange rate (price) charged by the AMM is just the ratio of supplies. The fraction $\frac{y}{x}$ is the supply of $Y$ fitting into a unit supply of $X$. That is, the $Y$-price of a unit of $X$. Price change is easily computable: + +Note the $Y$-price of a unit of $X$ obeys an inverse square law w.r.t to the supply of $X$: price decays quadratically as supply grows. This super-linear decay also exhibits diminishing marginal utility. + +Prices are not encoded by the AMM equation, but rather discovered by the market. The equation merely constrains the supplies to satisfy diminishing marginal utility, which is necessary for price discovery. (Play around with a constant-sum equation and see how the resulting market is severely misbehaved. Hint: the exchange ratio must be 1:1, so no diminishing marginal utility and therefore no price discovery and the pool is easy to drain.) + +## Depth analysis + +In this section we’ll quantitatively analyze the depth in constant-product AMMs. Our goal is to answer questions like “what percent of the supply is employed for trading within a given price range”. + +We can express supply $x$ as a function of the $Y$-price per unit of $X$: $p=\frac yx$. + +Note a larger constant $k$ means more depth: the market sustains a larger supply of $X$ at a given price. + +By definition, depth is the supply change required to move between given prices. + +Depth is nonnegative iff $p\_1\leq p\_2$: supply decreases iff price increases (in this AMM). Evidently depth is antisymmetric, so the price interval determines a unique number – the absolute value of the associated depth. Note also how depth scales with the interval: + +> Constant-product AMM depth decays slowly as $\frac1\surd$. + +Equipped with the depth formula, we can analyze the capital efficiency of constant-product AMMs. Specifically, we’ll analyze how the constant product curve causes supply to be inefficiently allocated to price bands with low trading activity. + +### Depth on the tail + +Assume a current supply of $x\_0$ at a price-per-unit of $p\_0$. This supply is distributed over the price range $[p\_0,\infty)$ precisely according to depth. + +- A divergent increasing sequence of prices $p\_0<p\_1<p\_2<\cdots$ partitions the interval $[p\_0,\infty)$. +- Current supply is partitioned by the depths of the associated price bands. (The infinite sum makes sense because $x(p)\overset{p\to \infty}{\longrightarrow}0$.) + +> The partition of total current supply by depth specifies the amount of current supply allocated to each price band. + +How much supply is “wasted” on exorbitantly high prices? Consider a $\overbrace{\text{USDC}}^Y/\overbrace{\text{ETH}}^X$ pool with $k=10^{10}$. As of July 2025, 1 ETH ≈ 3000 USD, so $p\_0=3000$ whence $x\_0=\sqrt\frac{10^{10}}{3000}\approx 1825$. A high USD-price of ETH is denoted $p\_\top$. The depth formula gives + +Some example computations show the extreme capital inefficiency of the constant-product curve. + +### + +### Depth in general + +How to interpret $D\_X(p\_1\to p\_2)$ if the current price $p\_\text{now}$ satisfies $p\_\text{now}>p\_1$? In this case, reaching $p\_1$ would require an increase in supply, so we can’t use the partition trick above. Or can we? Math shows the way. The equation + +interprets the LHS as the amount of supply required for a price increase $p\_1\nearrow p\_\text{now}$, plus the (familiar) depth starting from the current price. + +### Depth concentration + +We can write an explicit formula for the relative depth concentration in a price band within a larger band $[p\_1,p\_2]\subset [p\_\perp,p\_\top]$, notably independent of the constant $k$. + +Let’s analyze the capital efficiency of a constant-product AMM for a **stable pair** USDC/USDT. by looking at the relative concentration of a bp interval vs a 1% interval (factor of 100) + +So assuming the entire market lives within a 10% band, merely 10% of capital is allocated to trading within a %1 band, and merely 1% is allocated to trading within a basis point! + +## Impermanent loss + +Consider an ETH/USDC pool with initial supply of 100 ETH and 100K USDC, so initial ETH price is 1000 USDC and the constant is $k=10^7$. Now assume ETH price doubled to 2000 USD on the outside. Traders flock in to buy the underpriced ETH from the AMM. We compute the ETH reserves at the end of price discovery, when the AMM price has stabilized at 2000 USDC per ETH: + +Suppose Alice initially owned 10% of the pool. + +- Her initial deposit was 10 ETH and 10K USDC. Current value = 30,000 USD. +- Her current LP position is 7.071 ETH and 14,142 USDC. Value $\approx$ 28,284 USD. + +## What about fees? + +Percentage fees are crucial for LP revenue. They slightly increase price impact, especially for larger trades. + +# Concentrated liquidity + +Classically, there is a clear distinction between capitalists, who passively provide capital, and those who actively employ capital (often delegated to them). In DeFi terminology, capitalists are the _passive_ liquidity providers. However, _active_ liquidity providers are superior market makers, who have strong potential to enhance capital efficiency. We illustrate this with a case study: Uniswap v2 vs Uniswap v3. + +Uniswap v2 is a constant-product AMM. LP UX is roughly: choose pair → deposit assets → receive LP token → earn fees → exit. LPs must supply equal value of both tokens (to preserve pool price). Since LP positioned are fully determined by deposited capital, LP tokens are just fungible ERC-20 tokens. + +Uniswap v3 is a “piecewise-constant-product” AMM. LP UX is roughly: choose pair → choose fee tier → choose price range → deposit assets → receive LP token → earn fees → reposition/exit. Each pool partitions the allowed price range via _ticks_, via which LPs can specify their desired price bands for deploying capital (adding depth). Due to the added complexity of the liquidity position, LP tokens are (currently) NFTs, encoding more than the ERC-20 standard allows. + +The ability to concentrate capital in a chosen price range precisely means LPs are free to choose where to provide depth. Let’s illustrate how beneficial this design is for capital efficiency by examining a stable pair, e.g. USDC/USDT (I wonder how well this will age). The vast majority of LPs will choose to provide depth in a narrow band about the 1:1 rate, so liquidity will be deep in the center and shallow at de-pegged exchange rates. If Alice deposits in tick range $[t\_1,t\_3]$ and Bob deposits in $[t\_2,t\_4]$, both are active in $[t\_2,t\_3]$, and both provide liquidity to the constant-product AMM associated to this small interval. The locality of each piece in Uniswap v3 mitigates the slow $\frac1\surd$ decay of depth in constant-product AMMs to small intervals. + +Unfortunately the piecewise design has a significant drawback: it exacerbates the risk of impermanent loss. For example, assume Alice concentrates her capital at in the range $[2900,3100]$ USD per ETH. Suppose ETH begins tp appreciate with respect to USD in the outside market. As usual, arbitrage traders buy the strong asset (ETH) from the pool. However, since Alice concentrated all her capital in this narrow range, if ETH appreciates beyond the interval, her entire initial deposit of ETH would be depleted and exchange for USD due to arbitrage. In other words, the narrow price range makes Alice more susceptible to impermanent loss. As usual, if the price moves back in range, the impermanent loss vanishes, and Alice can continue her plans for world domination. + +In a sense, piecewise-constant-product AMMs interpolate between a constant-product AMM on one end, and an order-book in the other: liquidity providers act as market makers by choosing where to deploy capital. Concentrated liquidity assists price discovery due to aligned incentives: LPs earn trading fees when their deployed capital is used, so they naturally want to provide depth near market prices. Order-books still have some advantages: market-makers have room for more capital efficient strategies, and they’re not exposed to impermanent loss! + +The article was originally posted by Ilia on GitHub’s Unthoughts. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-grinta-the-architecture-of-a-more-decentralized-future/ + +--- + +## Starknet Grinta: Advancing Decentralization & L2 Performance + +Home  /  Blog + +Sep 1, 2025 · 3 min read + +## Introduction + +The newly released version of Starknet – previously referred to by its numerical version name v0.14.0 and now known as ‘Grinta’ – marks a major milestone in Starknet’s decentralization journey by distributing the sequencer architecture. While Starknet previously operated with a single sequencer, it now has three independent sequencers running consensus and taking turns building blocks. + +This version of Starknet also includes some important user-facing features, including subsecond pre-confirmations, a mempool, a fee market, and a standardized integration to paymaster, all of which are discussed below. + +## Strides toward Decentralization + +The biggest change introduced by Starknet Grinta is a decentralized sequencing architecture consisting of three sequencers running consensus. Trust minimization is one Starknet’s core values and decentralized sequencing is essential to ensuring neutral transaction inclusion and ordering. Together with Staking v2, which was introduced in June 2025, this version of Starknet is a significant step toward putting the necessary technical infrastructure in place for the next phases of decentralization. + +During this version, the operation and control of the sequencers is still centralized under StarkWare; however, according to Starknet’s decentralization roadmap, block validation and production are distributed between several nodes operated by StarkWare, with fully decentralized sequencing and proving to come in the future. Decentralization is a core requirement for a public blockchain, and for Starknet this will mean that protocol security is managed through transparent, community-driven mechanisms. + +## Additional Features + +### Pre-Confirmations + +Starknet Grinta introduces incredibly fast, subsecond pre-confirmations, which means users receive the transaction status much earlier than block publication. In other words, pre-confirmation is a promise by the block proposer that a transaction is part of the proposal submitted to the consensus. The advantages of pre-confirmations for users are significantly reduced latency and the ability to act on transactions before L2 finality. + +### Mempool + +Mempools are also being introduced to Starknet with Grinta. Mempools store transactions waiting to be added to a block. They are continuously updated by adding, holding, deleting, and replacing transactions that are received. Starknet’s sequencers’ mempools are connected in a p2p network, so they are synced about transactions within a fraction of a second when there is no congestion. + +### Fee Market + +Another new feature focused on future-proofing Starknet is a fee market on l2_gas. Prior to Grinta, the price of l2 gas was dependent on Ethereum’s gas price and, as a result, also affected by fluctuations on Ethereum. In addition, gas fees covered the “marginal” onchain cost of verification. However, due to significant technological improvements on Starknet, including advances in its proving stack and the introduction of blobs, onchain costs have become almost negligible. + +As Starknet moves toward decentralization, we are striving for a fee policy that incentivizes the participation of many sequencers. With this in mind, and together with feedback from the community, the minimum l2_gas base price is set at 3 gFri. This base price ensures that fees cover the operational costs when gas prices on Ethereum are low, while improving the scale and costs when gas prices on Ethereum are high. + +### Standardized Paymaster + +Another new feature introduced by Grinta is a standardized paymaster interface. While Starknet had a paymaster in earlier versions, the interface was not standardized. The standardized interface brings compatibility across different dapps and crypto wallets, allowing devs to integrate with any paymaster without the need for custom logic which would vary on a per-vendor basis. + +## What’s Coming Next? + +The remainder of 2025 will see Starknet continue on its journey of becoming a better-performing and more decentralized network. On the decentralization track, decentralized validation is planned. This means that stakers will participate in the consensus and will vote on blocks. At least two-thirds of the stake will be required to sign off on blocks in order for them to be finalized. Only sequencers operated by StarkWare will propose blocks at that stage, with full decentralization set for a future version. + +As for performance, Starknet will move beyond 1000 TPS with the introduction of Cairo Native and will significantly reduce proving costs through improvements to S-two. Additional features, including faster L1 finality, better block times, and more are currently under discussion with the community. + +The name Grinta – meaning grit, resolve, or determination – captures our resolve to make Starknet the manifestation of the blockchain vision: a high-performance and widely-adopted economic hub that doesn’t compromise on security or decentralization. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/global-payments-settled-fast-on-starknet-powered-by-due/ + +--- + +## Global Payments, Settled Fast on Starknet - Powered by Due + +Home  /  Blog + +Sep 4, 2025 · 2 min read + +## Introducing Due + +We’re thrilled to announce the launch of Due on Starknet! Due is a cost-effective global payments solution on top of interoperable blockchains and stablecoins, enabling anyone globally to send and receive funds and make payments as if they were local. + +Due can be seamlessly connected to your Braavos and Ready wallets on Starknet or to dapps via Due’s API for on- and off-ramps, cross-border payments, remittances, and more. It is available in over 80 countries and supports more than 30 fiat currencies, as well as USDC, EURC, and USDT stablecoins, with more in the pipeline. + +Due offers multi-currency virtual accounts for businesses and individuals in USD, GBP, EUR, MXN, and more to send and receive funds directly between local or foreign fiat currencies and stablecoins. It also provides access to multiple local payment rails, including ACH, SEPA, and Brazilian Pix, among others. + +As for security, Due is built with SOC 2-grade controls, provides real-time risk monitoring, and automated KYC/KYB, and is operated through licensed and regulated partners globally. + +This integration enables Starknet users globally to on- and off-ramp funds from USDC or USDT and send funds to bank accounts, mobile wallets, or directly to stablecoins. All Due transactions settle in under 24 hours, and, in the case of stablecoins, instantly, removing friction and unlocking new levels of financial inclusion. + +## What Sets Due Apart + +**Due offers incredibly low fees [1]:** + +- 0.2-0.5% on average vs the standard 4-6% for conversion rates. +- Wires that are 5-10 times cheaper than traditional wires. +- Free USDC transfers. +- USDC <> USDT 1:1 swaps with zero slippage. + +**In addition to being cheap, Due offers users virtual local accounts at no cost:** + +- Virtual accounts provide local payment details unique to each user’s account that can be used to receive payments locally. +- This allows individuals and businesses to receive payments without ever having to open a local bank account. + +**While Due users can easily connect their Starknet wallets, Due also allows users to open digital non-custodial crypto wallets with biometric key access.** + +- The wallets function like onchain accounts and instantly convert fiat payments to stablecoins that can then be held in the wallet. +- Users can manage multiple digital currencies no matter where they are. + +## Start Using Due Today + +- Sign up at app.due.network +- Create your Vault or connect an existing wallet to store your funds +- Verify your account +- Start moving your money! + +For more information, visit https://www.opendue.com/. + +This is not investment advice and this information is subject to change. Please do your own research and see terms and conditions here. + +--- + +[1] https://www.gsma.com/solutions-and-impact/connectivity-for-good/mobile-for-development/wp-content/uploads/2024/12/Cross-border-Mobile-Money-Remittance-Cost-Survey.pdf?utm\_source=chatgpt.com + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-starter-pack/ + +--- + +## Starknet Starter Pack: Your Guide to the ZK Rollup Ecosystem + +Home  /  Blog + +The Starknet ecosystem is evolving fast. With Starktember live and the BTCfi campaign launching soon, it's easy to feel overwhelmed by everything happening at once. + +Written by: Lyskey + +Sep 4, 2025 · 20 min read + +This starter pack is here to guide you: a complete overview of what you can do on Starknet today, and how to get started on mainnet right now. + +It covers everything you need, and even includes some alpha on how to make the most of Starknet. Whether you’re into **DeFi, gaming, content creation, or yield farming**, this guide is designed for you. + +## **Why Starknet?** + +What makes Starknet different from other Layer 2s? Before diving into this starter pack, let’s quickly cover **why Starknet exists**. I’ll keep it short, I’ve already written a full article on this topic if you want to go deeper. Most blockchains force you to choose: + +- Fast and cheap **or** decentralized and secure +- Easy to use **or** truly trustless + +Starknet exists to **end that trade-off**. Built from scratch with a new VM, a new proof system, and a new UX model, it delivers **all three pillars of the blockchain trilemma at once.** + +### **Scale without compromise** + +High throughput, low latency, and fees that decrease as usage grows; all while inheriting Ethereum-level security. + +Today, Starknet handles **1,000+ TPS**, with average confirmations in **~500 ms** and fees as **low as $0.002**. + +And this is only the beginning: capacity will scale beyond **10,000 TPS**, while latency keeps dropping over time. + +### **Decentralization & Security by Design** + +As a Layer 2 that settles on Ethereum, Starknet naturally inherits Ethereum’s decentralization and security. But unlike other L2s, Starknet achieves this **without compromise**: + +- It is the only ZK Rollup in production with zero trust assumptions, powered by STARK proofs, a quantum-resistant system with no trusted setup, and already battle-tested on billions of transactions. +- Recognized by L2Beat as a Stage 1 Rollup, Starknet is on track to reach Stage 2 and become fully trustless. +- Progressive decentralization is already underway through STRK staking, soon to be complemented by BTC staking, positioning Starknet as the most decentralized and secure L2 stack. So, beyond inheriting Ethereum’s security and delivering high performance, Starknet is also on the path to becoming fully decentralized. + +### **Web2-grade UX** + +From day one, Starknet was built with **native Account Abstraction (AA)** at its core. + +That means users on Starknet don’t face the usual crypto friction. Here’s how that translates in practice: + +- **1-click everything** → Bundling transactions (approvals + actions) into one click saves time and confusion. No more “approve → confirm → sign again.” +- **Gasless transactions** → Users don’t need to juggle ETH or STRK for gas. Fees can be abstracted away or sponsored by apps, removing one of the biggest onboarding barriers. +- **2FA / 3FA security** → Multilayer authentication is native on Braavos and Ready wallets. So even if one device or key is compromised, your funds stay protected. +- **Social logins** → Forget seed phrases. With account abstraction, you can spin up a wallet using your Google, Discord, or other familiar logins, making wallets as easy to create as any Web2 account. +- **Session keys** → Enable smoother gameplay and dapp interactions by letting apps temporarily sign transactions on your behalf. That means zero pop-ups while interacting onchain, perfect for gaming and social use cases. + +### **Long-term alignment** + +Backed by a team (StarkWare) with a multi-cycle track record of shipping industry-defining tech. As the saying goes: a picture is worth a thousand words, so here’s one: + +In short, Starknet delivers the performance developers need, the UX users expect, and the integrity blockchains promise, all at once. + +--- + +## **How to Get Started on Starknet** + +If you already have a Starknet-compatible wallet with funds on it, you can skip this part and jump to the next Section. For everyone else 👇 + +### **1. Starknet Wallets** + +The first step to join the Starknet ecosystem is to download a crypto wallet. You have several options here, but note that Starknet is not EVM-compatible, which means downloading a native Starknet wallet will unlock the full power of the network: 2FA/3FA security, gasless UX, Session Keys, and more. + +Currently, you have 3 native Starknet wallet options: + +- **Ready** **(formerly Argent)** → Session Keys, 2FA, gasless UX on browser, gasfree on mobile, plus a debit card for real-world payments +- **Braavos** → 2FA/3FA for enhanced security, gasfree UX on mobile, an integrated DeFi hub, Lightning Network integration for real-world payments, and more +- **Cartridge Controller** → a gaming-focused wallet that delivers a Web2-like UX when playing most games on Starknet (no gas fees, no popups, social logins via Discord/Gmail, invisible wallet) + +In addition to native wallets, you can also use some leading wallets from other ecosystems: + +- **Xverse** → the leading Bitcoin wallet, allowing you to manage Bitcoin, Starknet, and other Bitcoin L2s from a single UI. Note: Starknet integration on this wallet is still in its early stages and not yet fully connected to the ecosystem, but it’s coming! +- **Keplr** → the leading Cosmos wallet +- **MetaMask Snap\*\***,\*\* **Bitget Wallet\*\***, and\*\* **Ledger** + +Finally, the ecosystem is actively working to remove the EVM bottleneck by making all EVM wallets (MetaMask, Rabby, Phantom, etc.) compatible with Starknet. The solution is Rosetta, not yet production-ready but hopefully coming soon, which will enable a **native Starknet experience directly inside MetaMask and other wallets.** + +Pick one of these available wallets, and you’re already halfway through your Starknet journey. + +Once your wallet is ready, the next step is to fund it. There are two possible situations: either you have no funds onchain and need to deposit fresh capital, or you already hold funds on other chains and want to bridge them over. + +Let’s start with the first case: on-ramping. + +### **2. Buy Crypto on Starknet with Credit Card or Deposit from CEX** + +You’ve got two options 👇 + +#### **a. Buy with Credit Card** + +The easiest option is to purchase crypto directly inside your wallet using a credit or debit card. + +- On **Braavos**, you can use **Transak, Ramp Network, and Banxa**. +- On **Ready**, you can use **Banxa**. + +This method is fast and simple: all you need is a wallet and a card. Funds usually arrive within minutes. + +#### **b. Deposit from a Centralized Exchange (CEX)** + +If you already hold crypto on a CEX, you can transfer it to your Starknet wallet. Supported CEXs include **Binance, KuCoin, OKX, Bybit, Biget, HTX,** **Crypto.com\*\***, Bithumb, Upbit, Gate, & MEXC.\*\* + +This option is often cheaper than buying with a credit card, especially for larger amounts. + +### **3. Bridge Crypto to Starknet (Ethereum, Bitcoin, Solana & more)** + +If you’re already an onchain trencher, you can bridge your funds from all other ecosystems directly into Starknet using the following options: + +- **StarkGate** → the canonical Starknet bridge, supporting: Ethereum ↔ Starknet, Bitcoin ↔ Starknet (for Runes assets), Solana ↔ Starknet +- Bitcoin-focused bridges: **Garden** and **Atomiq Labs**, connecting Starknet and Bitcoin. +- For all chains: **RocketX Exchange** connects Starknet with 180+ chains, offering deep liquidity via CEX routing (great for large transfers). Other options: **LayerSwap**, **Orbiter Finance**, **Rango**, **RhinoFi**, **RetroBridge**, **Owlto**, **Minibridge**. + +Note that other bridges are coming: + +- **Hyperlane** is now integrated with Starknet; new bridges are under development using this technology. +- Two major interoperability protocols are expected to launch in **Q4 2025**. + +--- + +## **Starknet DeFi Ecosystem** + +Starknet has one of the most diverse and fast-growing DeFi ecosystems in crypto. Whether you’re here to trade, farm yield, or experiment with new primitives, you’ll find advanced tools already live on mainnet. + +Let’s break it down 👇 + +_Note: A few other options exist (mySwap, 10kSwap, Hashstack…), but I won’t cover them here since they are essentially inactive or abandoned. Instead, I’ll focus on the projects that are active and delivering real value on Starknet._ + +### **1. Spot trading** + +If you want to trade spot on Starknet, you have plenty of options. + +#### **AVNU (Aggregator)** + +In my opinion, the best option is **AVNU**, a DEX aggregator that pulls liquidity from all available sources on Starknet: AMMs, CLOB DEXs, and market makers. It’s also the most integrated trading hub in the ecosystem, powering much of Starknet’s trading UX. + +By trading on AVNU, you get access to all pairs on Starknet and the best available rates in one place. You can trade with a simple swap interface or use **DCA (Dollar-Cost Averaging)** to spread your orders across time. Limit orders are also in the works as far as I know. + +AVNU additionally provides chart views with up to one year of history. + +#### **Fibrous (Aggregator)** + +Another aggregator is Fibrous Finance, also live on Base and Scroll. Like AVNU, it aggregates all liquidity sources on Starknet for best execution. In addition to a classic swap, Fibrous offers a batch trading feature that lets you swap multiple tokens (more than two) at once, in a single transaction. + +If you prefer trading directly on DEXs rather than aggregators, Starknet offers three options. + +#### **Ekubo (AMM)** + +Ekubo is the most advanced and efficient AMM in crypto. It lets you trade using: + +- **Swaps** for simplicity +- **DCA** to spread your orders over time +- **Limit orders** for precise execution + +#### **Layer Akira (CLOB DEX)** + +Layer Akira is a spot CLOB DEX that allows traders to swap with access to price charts, order book history, and visibility into how much liquidity sits at each price level. Limit orders are coming soon, enabling traders to buy or sell assets at very precise prices. + +#### **Remus (CLOB DEX)** + +Remus DEX is another spot CLOB DEX, aiming to provide the full spectrum of features usually available on CEXs. Traders can view detailed charts for each pair, consult a transparent order book to see liquidity on both sides, and place either market or limit orders. As a reminder, limit orders allow you to buy or sell at exact target prices. + +This is basically all the relevant options you have for spot trading on Starknet. But what if you want leverage? Starknet now has two strong Perp DEXs live: one built natively on Starknet, and another operating as a Starknet appchain. + +### **2. Perp trading** + +When it comes to Perps, Starknet now has a truly **ultra-efficient Perp DEX** built directly on its chain (not as an appchain) by former Revolut executives: **Extended**. + +On Extended, you can trade with leverage across a wide range of markets: + +- Up to **50x** on ~50 crypto pairs +- Up to **100x** on traditional markets such as **EUR/USD, Gold, Oil and the S&P 500** + +But Extended isn’t only for traders. You can also become a liquidity provider by depositing into its vault, which currently yields over **25% APR in USDC**. Returns come from a mix of team-driven market making, trading fees, and liquidations. + +Note that Extended is running an **incentive campaign** where you can earn points by trading, providing liquidity, or referring new users. Just saying. + +Extended isn’t the only Perp DEX on the Starknet ecosystem. **Paradex**, built as a separate appchain closely connected to Starknet, offers similar features to Extended but without TradFi markets. + +Since this guide focuses on the **public Starknet chain only**, I won’t go into detail here. If you’d like to learn more, you can check out my full deep dive on Paradex + +Trading is great, but if yield farming is more your thing, Starknet also offers plenty of ways to put your assets to work. + +### **3. Yield farming** + +In addition to Extended’s vault, Starknet offers plenty of options for yield hunters. Whether you prefer lending, LPing, or liquid staking, there’s a growing ecosystem to put your assets to work. + +#### **Vesu (Lending & Borrowing)** + +Vesu is Starknet’s leading money market. Users can lend assets to earn yield or borrow against them. Lenders earn from two sources: + +1. Interest paid by borrowers +2. Incentives from the Starknet Foundation’s **DeFi Spring** program + +What makes Vesu attractive is its simplicity: + +- Earn passive yield by lending your assets +- Borrow additional assets to fuel your DeFi strategies + +A standout feature offered by Vesu is **Multiply**, which lets you create advanced looping strategies in a single click (though it also increases liquidation risk). + +**Example strategy I use:** + +- Lend ETH +- Borrow USDC at <2% +- Deploy USDC into Paradex’s vault (~25% yield) and Extended’s vault (~30% yield) + +Alpha: right now you’re essentially being paid to use your assets as collateral and borrow stablecoins. Just saying again 😉 + +#### **Nostra Finance (Lending, Borrowing & AMM Pools)** + +Another money market on Starknet is Nostra Finance. Like Vesu, it allows lending and borrowing, but currently Vesu offers better rates and more innovative features. Still, Nostra is worth watching for rate differences and opportunities. + +Beyond lending & borrowing, Nostra also offers **AMM pools**, where LPs can earn from both swap fees and DeFi Spring incentives. + +#### **FixedLend (Lending & Borrowing)** + +FixedLend is a smaller protocol, but with a powerful feature: an **Order Book of Yield.** + +- Lenders set both the **rate** and the **duration** of loans +- Borrowers choose whether to accept +- Once matched, loans are locked with a **fixed rate** and **defined maturity** + +This solves a key issue in classic money markets: variable rates that force constant monitoring. + +#### **Ekubo (AMM)** + +Beyond lending, Starknet has Ekubo, arguably the most efficient AMM in crypto. Thanks to ultra concentrated liquidity, gas-optimized execution, and its singleton design, every dollar of liquidity works harder: + +- Tighter spreads +- Lower slippage +- Higher fee capture + +For LPs, this means unmatched capital efficiency: earn more fees with less capital at risk. Proof? With only ~$20m TVL, Ekubo is already a top 2 DEX by volume on Ethereum. + +Ekubo also supports spot trading with swaps, DCA, and limit orders. + +If you want to dive deep into Ekubo, here is the most complete article to date about it + +#### **Troves (Automated Yield Optimizer)** + +Troves lets you deploy capital into advanced strategies with a single click. Examples include: + +- Lending on Vesu while auto-rebalancing to the best rates +- Weekly auto-claim and compounding of DeFi Spring rewards +- Looping strategies (lend → borrow → re-lend → repeat) +- Managing LP positions on Ekubo to maximize yield + +Troves handles it all automatically, meaning you can access these strategies and benefit from them passively with a single click. + +#### **Opus (Starknet Native Stablecoin)** + +Opus is the protocol behind Starknet’s only native stablecoin: **CASH**. You can mint CASH by depositing 7 types of collateral: ETH, STRK, wBTC, xSTRK, wstETH, Ekubo, and LORDS. + +CASH is particularly attractive because you can **stack three yield sources at once** with this stablecoin: + +1. Provide liquidity in the CASH/USDC pool on Ekubo +2. Stake the LP NFT on Opus to receive 75% of protocol revenue +3. Earn additional yield from U.S. Treasury exposure (T-bills) + +As of August 2025, the APY is ~**18%**. + +#### **Endur (Liquid STRK & BTC staking)** + +Endur currently offers **liquid STRK staking.** You stake STRK to secure the Starknet’s network, earn rewards (~6.5% APR), and receive a liquid token (xSTRK) you can use across DeFi. Example strategy: + +- Stake STRK on Endur (~6.5% APR) +- Lend xSTRK on Vesu (~3% APR) +- Borrow USDC against it +- Deploy USDC into Extended or Paradex vaults for high yield (~25%) + +This dual benefit makes Endur a cornerstone of Starknet’s DeFi stack. + +Soon, Endur will also support liquid BTC staking once Bitcoin staking goes live on Starknet (expected in the coming weeks). + +### **4. Other DeFi Primitives on Starknet** + +Starknet’s DeFi stack doesn’t stop at lending, DEXs, and staking. A growing set of other DeFi primitives are live, covering savings, payments, prediction markets, options, and token launches. + +#### **Bountive (No-Loss Prize Savings)** + +Bountive introduces a **no-loss savings mechanism** that turns yield farming into a lottery-style game. + +How it works: + +- Users deposit assets into a pool +- Funds are deployed into DeFi strategies by Bountive +- Yield is used to fund **lottery prizes**, distributed among winners +- Deposits remain withdrawable at any time + +This model blends **savings + gamification**, replacing fixed APR with the chance to win **much bigger rewards**. + +#### **Raize Club (Prediction Markets)** + +Prediction markets have historically been one of the few DeFi primitives with real traction, and Starknet has its own: **Raize Club**. + +- Bet on outcomes ranging from crypto prices to real-world events +- Place a bet in one click +- Choose from **four different tokens to place your bets** (not just USDC, unlike most prediction markets) + +The mix of simplicity and flexibility makes Raize Club stand out. + +### **Payments on Starknet** + +When it comes to payments, three main products are currently live on Starknet. + +The first is **Pulsar Money**, which makes crypto payments as simple as sending a tweet. + +Integrated directly with **X (Twitter)**, Pulsar enables frictionless transfers between users. It’s perfect for tipping your favorite creators or boosting the reach of your posts by attaching a prize pool for those who engage. + +The second is the **Ready Card**, a crypto debit card by Ready, Starknet’s native wallet. You can pay anywhere Mastercard is accepted using your onchain USDC, with no FX fees, and even earn up to **10% cashback** on daily spending. It’s the perfect bridge between your onchain assets and real life. + +Finally, there’s **Braavos**, the second Starknet’s native wallet, which integrates the **Bitcoin Lightning Network**. + +This lets you use Lightning payment terminals directly from Starknet. In practice, you just open your Braavos mobile wallet and scan a QR code to pay instantly anywhere Lightning is accepted. + +#### **Carmine Options (European-style options)** + +**Carmine Options** is the first options protocol live on Starknet, bringing **European-style options** fully onchain. + +For context: **European options** are financial contracts that give you the right, but not the obligation, to buy (call) or sell (put) an asset at a set price, but only on the option’s expiry date. + +Carmine makes this powerful primitive accessible on Starknet, enabling users to: + +- Speculate on price moves with limited downside risk +- Protect against sharp drops in asset prices +- Hedge impermanent loss for LP positions +- Provide liquidity to earn fees on options markets + +Currently, Carmine supports calls and puts on **ETH, STRK, wBTC, and Ekubo.** + +#### **Unruggable (Token Launchpad)** + +**Unruggable is Starknet’s native token launchpad, built to make memecoin launches safer and fairer.** + +For **creators**, it offers a **no-code interface**, so anyone can launch a memecoin in just a few seconds, with no technical skills required. + +For **traders**, every launch comes with built-in protections: + +- Liquidity locked for at least **6 months** (or forever if none is added) +- Team allocation capped at **10%** (max 5% per member) +- **Anti-whale rules** in the first 24 hours to ensure fairer distribution + +Tokens certified as **“Unruggable”** can be verified directly on the official site or through platforms like AVNU, where a badge confirms the certification. + +--- + +## **Onchain Gaming on Starknet** + +Starknet hosts the most advanced **fully onchain gaming ecosystem** in crypto. Unlike the “Web2.5” experiences other chains brand as onchain gaming, most Starknet titles run entirely onchain: every mechanic, every asset, every interaction. + +Why does this matter? Because being fully onchain means true **ownership** of everything you create or earn, and games that cannot simply vanish. We’ve already seen the opposite with _Pirate Nation_ on Arbitrum, which shut down its instances; something impossible when a game is entirely onchain. + +#### **Realms (Age of Empires Onchain)** + +The flagship game on Starknet is **Realms** (formerly Eternum). It captures the spirit of Age of Empires, Civilization, and Travian, but fully onchain. + +Realms is a grand strategy game where you expand your realm, manage resources, trade, form alliances, betray, and wage wars for dominance. + +In recent months, Realms has rolled out major improvements, not only in design and gameplay, but also in accessibility: players can now log in via the **Cartridge Controller** using Discord or Gmail accounts, and even connect with EVM wallets. + +The team has also introduced two distinct modes: + +- **Eternum** → the full, long-form version, where matches last several weeks. +- **Blitz** → a fast-paced mode designed for quick 2-hour sessions. + +The first Eternum seasons launched in the past months, and new seasons are coming soon, this time featuring the brand-new Blitz mode. + +#### **BlobArena (Pokémon-Inspired Battles)** + +**BlobArena** is a playful, onchain reinterpretation of Pokémon, focused entirely on **fighting**. Players control Blobs in fast-paced duels, with every move executed onchain. + +A recent partnership with **AMMA (Armored Mixed Martial Arts)** brought BlobArena into the real world, distributed and showcased at AMMA’s live events. This makes it the first fully onchain game with real-world competitive integration. Powered by Starknet. + +#### **Art Peace (r/Place Onchain)** + +One of the most creative experiments on Starknet is **Art Peace**, a **shared onchain canvas** built by StarkWare and inspired by Reddit’s iconic _r/Place_. Just like on Reddit, anyone can place pixels on the canvas, but here, every action is recorded fully onchain. + +The concept transforms creativity into gameplay: users collaborate (or compete) to design mosaics, leave messages, or build collective masterpieces. Beyond being a playground for creativity, **Art Peace has become a tool for community engagement**. Projects and DAOs regularly use the canvas to launch mini-competitions with prize pools lasting several days. + +Follow the project closely, you might win something, and you’ll definitely have fun. + +#### **PonziLand (token-agnostic DeFi metagame)** + +The concept behind PonziLand is simple, and very degen: you **buy land** on the PonziLand grid, set a resale price in any token (STRK, PAPER, LORDS…), and the game begins. + +Each day, you pay a **small tax** (based on your land’s price) to your **neighbors**. You pay in your token but receive taxes in theirs. If their tokens pump harder, you profit; if not, you get rugged. It’s a constant battle of **strategy, speculation, and neighbor wars**. Conquer plots, optimize your exposure, and climb the map to become a true **PonziLord**. + +The game runs in **seasons**, so you’ll need to wait for the next one to begin (coming soon 👀). + +#### **Jokers of Neon (Poker strategy)** + +Jokers of Neon is THE game for poker lovers. + +In this game, you start with a deck of cards, and each round you have a limited number of plays to score as many points as possible. Points come from forming classic poker hands (pairs, straights, flushes, full houses…), and stacking them with in-game combos and bonus multipliers. + +The strategy lies in choosing whether to play the cards in your hand or discard them to draw new ones, chasing that perfect combination before you run out of moves. + +And of course, every single move happens fully onchain. + +#### **Force Prime Heroes (Heroes of Might and Magic Onchain)** + +Force Prime Heroes is a strategy game where you explore the map with your hero, gather resources, recruit units, and grow your army to ultimately defeat the **Bone Dragon** or other bosses. Each move consumes movement points (structured in days and weeks), income flows from captured buildings, and your final score depends on both **efficiency and speed**. + +Victory requires balancing hero progression, smart recruiting, and efficient map control. + +Oh, and you can even **design your own maps** here: Force Prime Editor + +#### **Pistols at Dawn (Cowboy Duels Onchain)** + +Pistols at Dawn is a 1v1 showdown where you face another Lord in a classic Western-style pistol duel to defend your honor. The rules are simple: challenge a friend or any opponent, and step into a high-stakes standoff. + +Every shot, every victory, every defeat is recorded fully **onchain.** + +#### **Dark Shuffle (Roguelike Deck-Builder)** + +Dark Shuffle is a fully onchain card-based strategy game. + +At the start of each run, you draft 20 cards to define your initial strategy. From there, you dive into **randomly generated maps** filled with branching paths. Every choice, which path to take, which card to play, or which battle to risk, shapes your journey and determines how far you can go. + +#### **Dope Wars (Hustle & Empire Building)** + +Dope Wars is a fully onchain strategy and role-playing game. + +Players start as hustlers in a gritty world, with one simple goal: **buy low, sell high, build your empire, and outsmart your rivals.** + +#### **zKube (Onchain Puzzle Challenge)** + +zKube is a fully onchain **puzzle game**, blending **Tetris** with sliding-block mechanics. You manipulate patterned blocks on a grid to solve challenges step by step, blockchain logic makes every move verifiable. + +#### **ByteBeasts (Tamagotchi)** + +ByteBeasts is **Tamagotchi reborn**, fully onchain on Starknet. Mint your digital pet, feed it, nurture it, bond and play with it. + +#### **Evolute (Carcassonne Meets Mage Duels)** + +Two sorcerers face off on an 8×8 grid, shaping Cities, Roads, and Fields with each tile they place. Tiles must connect logically, and control is gained by completing constructions, but territory can always be contested. Points from Cities and Roads decide which mage emerges victorious. + +Evolute is onchain, but settling on Celestia. + +--- + +## **Best tools on Starknet** + +DeFi and gaming are cool, but you need solid tooling to really get the most out of Starknet. Here’s the list of the most important ones. + +#### **Ready Portfolio (Portfolio tracker)** + +Beyond its role as one of Starknet’s native wallets, Ready also offers a **portfolio dashboard**. It allows you to track your (or someone else 👀) assets, positions, and DeFi allocations across the network in a simple and intuitive interface. + +#### **AVNU Market** + +AVNU launched a **DEXscreener-like platform**: AVNU Market. It lists all available markets on Starknet and offers a wide range of analytics for each asset, price charts, liquidity depth, trading volumes, and more. + +A must-have for traders tracking tokens in real time on Starknet, and a great complement to Dexscreener and GeckoTerminal. + +#### **StarkPulse** + +StarkPulse is a **Telegram bot** designed to monitor Starknet’s onchain activity. It lets you: + +- Track specific wallets and receive instant alerts when they buy or sell assets. +- Get notified when a new token is created on Starknet. + +In practice, StarkPulse puts the onchain trenches directly in your Telegram feed. It’s still relatively unknown on Starknet, so here’s the alpha. + +#### **Cartridge Arcade** + +Imagine having one single interface that brings together most of the games on Starknet, with a point system and a leaderboard to compete against all other Starknet gamers. + +That’s exactly what Cartridge Arcade offers. It showcases all the games built on the Cartridge/Dojo ecosystem (which powers most of Starknet’s gaming scene), lets you jump in, play easily, and track your progress compared to other players. + +Think of it as Steam for Starknet gaming. + +#### **Voyager** + +Voyager is one of the first and most widely used **block explorers** on Starknet. Similar to Etherscan on Ethereum, it provides transparency into every transaction, contract, and wallet on the network. It also offers high-level insights into Starknet’s activity in real time. + +#### **Starkscan** + +Starkscan is another major block explorer on Starknet, providing a different UI/UX. + +#### **Focus Tree** + +Focus Tree is a productivity app designed to help you win back your attention. It lets you: + +- Set focus timers + +- Block distractions on your phone + +- Earn items by completing sessions + +- Build your digital garden + +In practice, Focus Tree turns deep work into a game, making discipline visible, distractions costly, and progress rewarding. + +--- + +## **Bonus: How to Contribute to Starknet with the Wolf Pack League** + +The **Wolf Pack League (WPL)** is StarkWare’s flagship community program, created to accelerate Starknet’s growth. The vision is simple: just like wolves are stronger together when they hunt in packs, Starknet thrives when its community of builders, creators, and contributors moves forward as one. **To turn this vision into reality, the WPL connects projects and contributors through two complementary programs:** the WPL Platform and WPL Attested Creators. + +#### **a. WPL Platform** + +The WPL Platform is **open to everyone**. It acts as a **marketplace of collaboration** where projects and community members meet: + +- **Projects** can create missions (specific bounties/tasks) and open them to the whole Starknet community. +- **Contributors** can browse these missions, pick the ones that fit their skills (content, design, development, research, etc.), and submit their proposals. +- **Rewards** are then distributed by the projects to the winning submissions, ensuring fair recognition and value exchange. + +This system gives projects a way to boost their visibility and growth while empowering contributors with opportunities to showcase their talent, earn rewards, and become more deeply involved in Starknet. + +#### **b. WPL Attested Creators** + +The second pillar of the WPL highlights long-term contributors: the **Attested Creators**. These are individuals who have been consistently pushing Starknet forward with **high-quality content and meaningful contributions**. + +- The more they contribute, the more they **grow in reputation** within the program. +- In addition to the rewards available on the open WPL platform, attested creators receive **extra recognition and benefits** for their sustained impact. + +In other words, **Attested Creators are the pack leaders,** trusted voices who inspire others while being rewarded for their consistency and dedication. And if you keep contributing, you might soon join them. + +Starknet is the best place to start contributing and gain recognition for it. And the right time to start is now. + +--- + +## **Conclusion** + +The foundations of Starknet are stronger than ever, with all the core primitives now in place to build increasingly advanced use cases on top. Yet it’s still **day one** for the ecosystem: there’s plenty of room for anyone to make their mark, and programs like the **Wolf Pack League** make it easier than ever to get involved. + +But don’t wait too long: momentum is accelerating, with **Starktember now live and BTCfi only a few weeks away. The best time to join is NOW.** + +In the meantime, make sure to follow the full Starknet crew to stay up to date with everything happening across the ecosystem. **See you on the other side.** + +This article was also publishes on Lyskey’s blog. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-incident-report-september-2-2025/ + +--- + +## Starknet Incident Report — September 2, 2025 | Starknet + +Home  /  Blog + +Sep 11, 2025 · 4 min read + +On September 2, 2025, shortly after upgrading to version 0.14.0 (Grinta), Starknet experienced an outage during which block production was halted and two chain reorganizations (reorgs) were required to restore normal operation. + +We recognize the impact this had on our users and partners, and we are committed to providing full transparency into what happened, how it was resolved, and what steps we are taking to prevent recurrence. + +This incident occurred in the immediate aftermath of a historic milestone: **Starknet became the first Validity (ZK) rollup to decentralize its sequencer architecture, moving from one to three sequencers operating the network.** That shift was the core change that exposed this new challenge – one that is inherent in pioneering the path toward decentralization, a path that only Starknet has taken so far. + +Since the incident ended on September 2 at 13:41 UTC, Starknet has been fully operational. We are continuing to push the boundaries of proving and advancing toward becoming the first decentralized Validity (ZK) Rollup, while also applying the key insights from this incident to further strengthen Starknet’s resilience going forward. + +## **Summary** + +Between **02:20 and 13:40 UTC**, Starknet was intermittently unavailable. During that time, two reorgs were required: + +- The first reverted roughly **one hour of transactions**. +- The second reverted roughly **20 minutes of transactions**. + +The downtime was caused by a sequence of three interconnected incidents, beginning with a failure in Ethereum RPC providers at the node logic level. + +A deeper investigation identified the following contributing factors: + +**1. Ethereum node failures** – The three Starknet sequencers, which operate as part of its decentralized architecture, observed different states of Ethereum. This divergence disrupted the block-proposing process: one sequencer proposed transactions triggered by Ethereum messages that the others could not validate. As a result, network progression slowed significantly. + +**2. Manual intervention gap** – To address the sequencer failures discussed above, a manual intervention was required. In this manual process, certain validations that are performed automatically were skipped, which resulted in the creation of two conflicting blocks in the L2 layer by the different Starknet sequencers. To restore correctness, a reorg was performed. + +**3. Blockifier bug in v0.14.0 –** After the first reorg, transactions were discarded but L1→L2 messages were reprocessed. Some of these messages assumed that earlier Starknet transactions had already been executed, and when that assumption failed, they reverted. This triggered a bug in the blockifier – the component responsible for updating Starknet’s state based on transaction execution. The bug affected how reverted transactions initiated by L1→L2 messages were handled. This compounded the earlier disruptions and required both a hotfix and a second reorg to fully resolve. + +When analyzing the failures, we identified issues in the **consensus mechanism** and **blockifier logic**, which will be detailed further below. + +It is important to note that throughout the incident, **Starknet’s proving layer acted as the safeguard** that prevented these inconsistencies from compromising the integrity of the blockchain. This design reflects a core principle of Starknet: to preserve correctness and security regardless of any undesired sequencer behavior-whether caused by software bugs or by malicious activity. + +## **Impact** + +- **Downtime**: Approximately 9 hours of degraded or halted service. +- **Reorgs**: All transactions in the affected blocks reflecting ~1.5 hours of activity were not processed and needed to be resubmitted. + +## **Timeline** + +At **02:20 UTC**, initial issues were detected when sequencers failed to sync L1 events, preventing new blocks from being approved. An investigation was initiated immediately. By **03:57**, after several manual attempts to reset individual sequencers, L1 synchronization succeeded and Starknet resumed. + +At **04:10 UTC**, an alert indicated that the proving layer had detected an inconsistency, marking the beginning of the second incident. Apparently, different sequencers were building blocks on top of different versions of a certain block, and this was a result of our previous manual intervention. Starknet, as a validity rollup, first sequences blocks, and later proves them. When the proving layer detects an inconsistency (or any other invalid logic), it cannot generate a valid proof. By **04:37 UTC**, Starknet was manually halted, since it became clear that a reorg might be required in order to fix this issue. This approach is based on the principle that when a reorg is anticipated, halting the system helps to minimize potential transaction loss. + +At **06:05**, we identified the block where the inconsistency occurred, and thus decided to re-org back to the block before (1,960,612), , reverting approximately one hour of activity. Block production resumed at **07:42** and by **09:08** all full node clients were synced and Starknet operations were fully restored. + +The third incident began at **10:28**, when the proving layer identified another inconsistent batch. At **10:43**, Starknet was halted again as the probability for a second reorg became high. By **12:05**, the root cause was identified, and at **12:37** a bug fix was implemented, tested and deployed. At **13:29**, a second reorg was executed from block **1,962,681**, reverting roughly 20 minutes of activity. Finally, at **13:41**, block production and full network activity were restored. + +## **Key learnings and Prevention Measures** + +In addition to detecting, analyzing, and rapidly fixing the bugs that caused this failure, and adding safeguards that will automatically prevent such failures from recurring, we are also implementing a set of measures designed to further reduce the likelihood of similar issues in the future: + +- **Increase the number of nodes** participating in the internal consensus protocol to improve fault tolerance and resilience. +- **Introduce additional safety mechanisms** to protect against disruptions when external dependencies, such as Ethereum nodes, experience issues. +- **Minimize the need for manual interventions** and ensure that in the rare cases they are required, the process is reliable, well-documented, and resistant to human error. + +## **Closing** + +Starknet is back online and fully operational. While the incident was serious, the fixes applied have already increased network resilience, and additional long-term improvements and safeguards are being implemented. + +By identifying and addressing these bugs immediately upon detection, and with the proving layer serving as a backstop, Starknet emerges more robust. The fixes applied in response, together with additional safety precautions now being implemented, directly strengthen its reliability going forward. It is also worth noting that the Starknet dapp teams were well-prepared to handle reorgs, which ensured users were minimally affected at the application level throughout the incident. + +We are committed to full transparency with our users and partners, and will continue to share follow-up updates as improvements are rolled out. + +**Thank you, Starknet community, for your understanding and support as we worked through this issue.** + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Global Payments, Settled Fast on Starknet – Powered by Due + + Due offers cheap, fast global payments with low fees, virtual bank accounts, and instant USDC settlements through Starknet. + + September 4, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/why-bitcoin-staking-is-a-big-deal/ + +--- + +## Starknet Launches Bitcoin Staking + +Home  /  Blog + +Starknet now supports Bitcoin staking. It's a simple headline, but it has profound implications. + +Sep 30, 2025 · 4 min read + +Some 98.5% of Bitcoin sits idle on the Bitcoin network. This represents USD$ 2 trillion worth of value that is unutilized and locked away. It is no surprise then that an increasing number of projects are trying to unlock this value. In the world of DeFi, for example, Bitcoin value could drive deeper liquidity, more efficient markets and serve to unlock entire ecosystems and use cases. + +Value is equally important in the world of decentralization and distributed consensus. For Proof-of-Stake networks, like Ethereum and Starknet, the security of the network is directly correlated to the value staked. Enabling Bitcoin to stake and secure Starknet is a major milestone for both Starknet and Bitcoin. + +## How Starknet Immediately Benefits + +Starknet’s Bitcoin staking will immediately increase the value of the assets that are staked to secure Starknet. Today, there are 65,000+ delegators and 550 million+ STRK staked. The launch of Bitcoin staking will increase this number and thereby enhance the security characteristics of Starknet. Simply on those merits, Bitcoin staking is a significant development. + +Remember, Bitcoin is generally regarded as lower risk and a very attractive relative to other cryptocurrencies. As a result, Bitcoin holders require lower rewards than other cryptocurrencies to participate in similar programs. This means that in the long-term, Bitcoin staking is cheaper than STRK staking for an equivalent level of cryptoeconomic security. + +Starknet is uniquely positioned to rollout a successful Bitcoin staking protocol. Most networks, especially L2s, do not have a sufficiently adopted and decentralized staking program for their native token. If a network ends up with only Bitcoin stakers, it dilutes the role of its native token and its governance processes. The large adoption of STRK staking on Starknet enables the rollout of a successful Bitcoin staking program. The governance proposal that was approved is very detailed on how STRK and Bitcoin support each other. The consensus power of staked Bitcoin is limited to 25% of the network. STRK will hold the remaining consensus power, ensuring STRK staking maintains its centrality in securing starknet. + +## The Bitcoin Flywheel + +**But it gets better**: Bitcoin staking on Starknet kicks off a significant flywheel for the entire Starknet ecosystem. Here’s how: + +Bitcoin staking on Starknet will bring significant amounts of Bitcoin to the Starknet ecosystem, sustainably and perpetually. This will enhance the security characteristics of the network and the liquid TVL on Starknet. Enhanced security and increased liquidity in turn will attract more builders and assets to the entire Starknet ecosystem, further increasing the amount of STRK staked. By the mechanism designed and approved for Bitcoin staking, this increase in STRK staking will result in an increase in the rewards distributed to Bitcoin stakers, further incentivizing Bitcoiners to stake their Bitcoin, starting what is a powerful, reinforcing flywheel on Starknet. + +Let’s break down these components into more detail: + +Starknet’s Proof-of-Stake, like all PoS systems, rewards participants for securing the network by giving them newly created tokens, in this case STRK. These emissions are a naturally occurring part of PoS networks (and PoW networks too). They do not require special incentives. They are not one time programs. They do not depend on activity farming or other short-term behaviours. These rewards are part of a long-term, sustainable program. + +As already discussed, the more assets that are staked on a network, the more secure the network is. Enhanced security drives adoption. More Bitcoin staked also drives adoption in another meaningful way: liquid-staked tokens. Bitcoin stakers have the possibility to participate in liquid-staking programs, where they receive a derivative token representing their staked positions. Just like on other PoS networks, these liquid stake tokens themselves can be used to drive usage in DeFi. + +This in turn boosts STRK’s utility, as it is Starknet’s core asset: + +- Default token for gas and staking +- Governance token +- Main DeFi collateral +- Next up: a fee-burn (ETA TBD) aimed at reducing supply as usage scales. + +The amount of STRK staked is what determines emissions for both STRK staking and Bitcoin staking. This was implemented to make sure that STRK maintains its dominant position in securing Starknet. The mechanism for determining emissions increases emissions for both STRK and Bitcoin when more STRK is staked. This positive relationship is critical for securing Starknet with both BTC and STRK. + +## Why Should Bitcoiners Care? + +Bitcoin Staking (and the broader BTCFi rollout) is another step on Starknet’s journey of decentralization, innovation and security. + +Earlier this year, Starknet announced it became a Bitcoin and Ethereum L2. Starknet wants to leverage the security of both layers, and use its STARK-based zk-L2 to provide scale, security and low-cost transactions to both Ethereum and Bitcoin, without sacrificing decentralization. Last month, Starknet’s Grinta upgrade was yet another big step. Starkware has also released significant research and software on Bitcoin and zero-knowledge cryptography, including research on ColiderVM, providing a toy implementation of ColiderVM, setting up a $1m research fund on OP_CAT and setting a world record for proving Bitcoin mainnet with ZK proofs. And the roadmap is accelerating. + +Bitcoin staking presents an opportunity for Bitcoin holders to support a leading project promoting decentralization, cryptography, privacy and security, while also earning sustainable rewards. + +For the first time, Bitcoin holders can stake their Bitcoin to secure a Layer 2 and earn sustainable rewards. + +To learn how to stake your tokens, see the Bitcoin User Guide here. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +- #### Global Payments, Settled Fast on Starknet – Powered by Due + + Due offers cheap, fast global payments with low fees, virtual bank accounts, and instant USDC settlements through Starknet. + + September 4, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/introducing-the-re7-yield-aggregator-on-starknet/ + +--- + +## Re7 Labs Yield Aggregator Live on Starknet + +Home  /  Blog + +Sep 25, 2025 · 2 min read + +We are excited to share that the \***\*Re7 ALMM by Re7 Labs is now available** on Starknet\*\*. This new product is designed to make yield generation simple, sustainable, and accessible to anyone interested in DeFi. + +## **What Is the Re7 **ALMM**?** + +The Re7 ALMM is the Automated Liquidity Market Maker, built specifically for **Ekubo liquidity pools on Starknet**. It continuously monitors APRs and market activity and automatically rebalances LP positions. The result: your assets are always working. + +Instead of having to check and rebalance constantly, you simply deposit your assets once. From there, the ALMM does the work in the background, keeping your capital efficient. + +## **Turning DeFi Challenges into Opportunities** + +Starknet is rapidly becoming a leading destination for scalable DeFi. With this growth comes new opportunities, but also new challenges for users. One of the biggest pain points is managing liquidity positions effectively. + +Traditionally, this requires building complex strategies, keeping up with APR changes, and constantly adjusting positions. For many, that barrier is too high. Re7 set out to solve this problem: to give users the benefits of advanced yield strategies, without the complexity that usually comes with them. + +## **The How** + +Managing liquidity is often time-consuming, and even experienced users can struggle to capture optimal yield consistently. Re7 makes the process more straightforward: + +- - No strategy building required. + +- - No ongoing monitoring needed. + +- - Just deposit and earn. + +Vaults are built on top of Trove’s audited and tested on-chain infrastructure, combined with Re7 Labs’ proprietary rebalancing strategy. + +## **Re7 in Action: Features That Matter** + +The Re7 ALMM is designed with simplicity and performance in mind: + +- - **Focused on Ekubo liquidity pools** – ensures access to the highest APRs. + +- - **Active rebalancing in real time** – yield stays more optimized without relying on short-term incentives. + +- - **User-friendly experience** – deposit-and-earn model that requires no special knowledge. + +- - **Fully automated strategies** – no manual adjustments needed once you’ve deposited. + +## **Strengthening the Ecosystem** + +This launch is part of a broader effort to establish Starknet as the most capital-efficient DeFi ecosystem. By making sophisticated yield strategies accessible to everyday users, we are not only lowering barriers but also contributing to stronger liquidity and activity across the network. + +## **About Re7** + +Re7 Labs – a DeFi centric investment firm specialising in DeFi yield, liquid alpha strategies and on-chain vault management. With over 4 years of a consistent positive track record, Re7 is one of the most active DeFi liquidity providers globally, currently overseeing ~$1b. Re7 Labs is the innovation arm of Re7 Capital, focused on on-chain risk curation, vault management, and DeFi ecosystem design. Launched just over a year ago, it currently curates over $800 million in DeFi vaults across leading protocols. + +## **What’s Next** + +The **Re7 Labs | **ALMM** on Starknet** is now available – starknet.re7labs.xyz. + +Terms and Conditions apply, please review before engaging. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Starknet Foundation Introduces: BTCFi Season + + The Starknet Foundation launches BTCFi Season with 100M STRK to fuel BTC DeFi, stablecoin borrowing, and ecosystem growth. + + October 1, 2025 + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +--- + +Sources: + +- https://www.starknet.io/blog/starknet-foundation-introduces-btcfi-season/ + +--- + +## BTCFi Season: 100M STRK Incentives on Starknet + +Home  /  Blog + +Oct 1, 2025 · 3 min read + +## Useful Resources + +- BTCFi Season’s official website +- BTCFi on Starknet + +## Introduction + +The Starknet Foundation is committed to Starknet’s emergence as the leading destination for sustainable yield on BTC. After months of careful research, planning, and design, the Starknet Foundation is proud to announce the launch of BTCFi Season, a program designed to set a BTC-centric DeFi flywheel in motion that will unlock productive capital flows on Starknet and ensure its long-term ecosystem growth. + +In Starknet’s case, lending and borrowing will be the cornerstone of the DeFi flywheel. That’s why enabling borrowing sits at the heart of BTCFi Season’s design, positioning Starknet to become the cheapest place to borrow stablecoins against BTC collateral. + +BTCFi Season is part of the broader BTCFi initiative on Starknet, which focuses on making BTC productive in DeFi with a strong emphasis on sustainability while upholding its core principles of security and decentralization. Other important Starknet launches under this initiative include Re7’s new BTC Yield Fund, BTC Staking, and StarkWare’s upcoming Earn – One-click Yield aggregator. + +## Program Details + +BTCFi Season was officially launched on **Tuesday, September 30th** by the Starknet Foundation. + +Participating protocols also launched their incentive programs on the same date. + +BTCFi Season is a structured incentive program supporting eligible ecosystem protocols that enable highly liquid BTC pools on DEXs and Money Markets and borrowing of stablecoins against BTC collateral. + +Starknet Foundation has dedicated a budget of 100M STRK to this program. + +The program is set to run for a minimum of six months, with the potential to continue well beyond that. + +## How the program works + +The Starknet Foundation has partnered with OpenBlock Labs to design a program for the fair and equitable allocation & distribution of STRK tokens to participating DeFi protocols. + +The program runs on a weekly cycle, with any significant changes taking effect at the start of a new cycle. + +### Allocations + +Protocol allocations are determined on a daily basis. The allocations are based on methodologies that factor in important protocol performance metrics. Methodologies are designed to be robust and resistant to manipulation while allowing for continuous adjustments if needed to stay aligned with the evolving needs and contributions of protocols within the ecosystem. + +### Distributions + +At the end of a cycle, daily protocol allocations of the last 7 days are aggregated and reviewed by OpenBlock Labs. Once finalized and communicated to all relevant parties, STRK allocations are distributed to the participating protocols by the Starknet Foundation. + +Each participating protocol to the program is responsible for designing, announcing and implementing their own incentive programs to reward their users with STRK. Each protocol may determine its own criteria for rewarding users, deciding both which users qualify and how rewards are allocated on eligible activity and assets/pairs. + +Each protocol will be responsible for its own distribution of STRK to its users. + +Users can begin claiming their allocations from participating protocols for the first cycle of the program starting Friday, October 10th. + +## What’s next? + +More eligible assets and pairs for BTCFi Season and more participating protocols. + +More ecosystem products that align with the vision of BTCFi on Starknet. Stay tuned for more! + +## FAQs + +## General + +- What is BTCFi Season? + + BTCFi Season is an incentive program launched by the Starknet Foundation to bootstrap BTC liquidity and stablecoin borrowing activity against BTC on Starknet. + +- What is BTCFi Season’s purpose? + + BTCFi Season is an important piece of the broader BTCFi on Starknet initiative that is designed to enable the activities that will kickstart a flywheel effect for sustainable BTC yield -consistent, predictable and competitive, driven by real economic activity- and ecosystem growth on Starknet. + +- Which DeFi verticals does BTCFi Season support? + + BTCFi Season supports the DEX and Money Market verticals. + +- What activity will BTCFi Season support? + + BTCFi Season supports protocols that enable highly liquid BTC pools on DEXs and Money Markets and borrowing of stablecoins against BTC collateral. + +- What assets and pairs will be eligible for incentives? + + You can find an updated list of eligible assets and pairs on BTCFi Season’s website. + +- When does BTCFi Season launch? + + BTCFi Season launched on September 30th, 2025. + +- How long will BTCFi Season last? + + The program is set to run for a minimum of six months, with the potential to continue well beyond that. + +## I am a User + +- How do I know if a project is a participating protocol in BTCFi Season and will be distributing STRK rewards? + + You can find an updated list of eligible protocols on BTCFi Season’s website. + +- How do I know what actions are eligible for STRK rewards? + + You will need to explore the individual participating protocols and their terms of use to see how you can earn STRK through their programs. + +- How can I claim my STRK from BTCFi Season? + + You will need to follow the guidelines provided from the individual participating protocols as they are responsible for their own distribution of STRK to their users based on their terms of use and announced programs. + +- What happens if I don’t claim my STRK from BTCFi Season? + + You will be able to claim your STRK within each participating protocol. Any unclaimed STRK at the end of BTCFi Season will be returned back to the Foundation. + +## I am a Protocol + +- How can I participate in BTCFi Season? + + The Starknet Foundation determines the appropriateness of participating protocols in its absolute discretion and is focused solely on protocols that support the DEX and Money Market verticals. If you are interested in participating in BTCFi Season, please apply using this [form] and we will be in touch shortly. + +- What criteria should I use for my incentive program? + + Each protocol shall determine its own criteria for rewarding users, deciding both which users qualify and how rewards are allocated on eligible activity and assets/pairs. + +- Am I required to make the criteria of my incentive program public? + + Yes. Announcing your incentive program’s criteria and terms of use is a mandatory requirement to participate in BTCFi Season. + +## About the Starknet Foundation + +The Starknet Foundation is a non-profit organisation who oversees the growth and development of Starknet – a fast, scalable, future-proof, fully-verifiable tech platform. The Foundation oversees a broad range of educational, grant, and startup programs and partnerships that support developers and founders solving real world problems. + +The Starknet Foundation has allocated a total of 100 million STRK for BTCFi Season. + +## About OpenBlock Labs + +OpenBlock Labs is a quantitative research firm specializing in organic and sustainable ecosystem growth by providing data analytics and modeling to ensure that the chain is growing with real users. + +OpenBlock Labs will lead the recommendations of STRK allocations, the implementation and the analytics of the program. + +## Important Disclaimers & Disclosures + +The following disclaimers and risk disclosures apply: + +- The DeFi protocols mentioned in this blog post are independent from the Starknet Foundation and are not owned, operated or controlled by the Starknet Foundation. +- Users who engage with DeFi protocols do so at their own risk and subject to the terms and conditions set forth by each respective DeFi protocol. The Starknet Foundation has no relationship with the individual users. +- The Starknet Foundation does not endorse or recommend any specific DeFi protocol. Users are encouraged to conduct their own research and to exercise caution before engaging with any such protocol. +- Users are solely responsible for their own decisions and actions and assume all risks associated with utilising the respective DeFi Protocols. +- Users should be aware that DeFi, as a category, involves inherent financial risks, including the potential for total loss of invested assets. +- The Starknet Foundation disclaims any and all liability for losses that users may incur through their use of DeFi protocols. +- Users and DeFi Protocols are responsible for complying with any applicable laws, regulations, or restrictions applying to them in either availing of or providing DeFi services (as the case may be). +- The information provided in this post is for informational purposes only and should not be construed as financial, investment or legal advice. Users should consult with a qualified financial advisor before making any investment decisions. +- The Starknet Foundation reserves the right to discontinue BTCFi Season at any time. +- This blog should not be considered an offer to the public or to any particular DeFi protocol. + +#### Join our newsletter + +Receive notifications on Starknet updates + +--- + +#### May also interest you + +- #### Why Bitcoin Staking is a Big Deal + + Bitcoin holders can now stake BTC on Starknet, boosting security, DeFi liquidity, and earning sustainable rewards. + + September 30, 2025 + +- #### Starknet x Bitcoin: The Next Step – BTCFi on Starknet + + Starknet brings trustless BTC staking, 100M STRK incentives, and new DeFi opportunities to scale Bitcoin. + + September 30, 2025 + +- #### Starknet Incident Report — September 2, 2025 + + On September 2, 2025, Starknet faced a 9-hour outage after upgrading to v0.14.0, requiring two reorgs to restore service. Learn what caused the incident,… + + September 11, 2025 + +- #### Global Payments, Settled Fast on Starknet – Powered by Due + + Due offers cheap, fast global payments with low fees, virtual bank accounts, and instant USDC settlements through Starknet. + + September 4, 2025