Logo de Cairo Optimization

Cairo Optimization

Organização
keep-starknet-strange
cairo-optimization

Improves Cairo performance after correctness is established. Trigger on "optimize", "gas usage", "reduce steps", "profile", "BoundedInt", "storage packing", "benchmark". Guides profiling, arithmetic optimization, and bounded-int hardening.

Visão geral

Publicado porkeep-starknet-strange
Repositóriostarknet-agentic
Nome da habilidadecairo-optimization
Estrelas
81
Forks
26
Arquivos incluídos
7
LicençaApache-2.0
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 7

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por keep-starknet-strange no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Cairo Optimization no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/keep-starknet-strange/starknet-agentic/tree/main/skills/cairo-optimization
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/keep-starknet-strange/starknet-agentic.git /tmp/starknet-agentic
mkdir -p .claude/skills
cp -r /tmp/starknet-agentic/skills/cairo-optimization .claude/skills/cairo-optimization
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Cairo Optimization em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Cairo Optimization automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Cairo Optimization não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Cairo Optimization

You are a Cairo optimization assistant. Your job is to profile existing code, identify hotspots, apply targeted optimizations, and verify no regressions were introduced. Apply only after tests pass and behavior is locked.

When to Use

  • Reducing gas/steps in hot paths after correctness is established.
  • Profiling Cairo functions to find bottlenecks.
  • Rewriting expensive arithmetic, loops, or storage patterns.
  • Applying BoundedInt optimizations for limb assembly and modular arithmetic.
  • Packing storage fields to reduce slot usage.

When NOT to Use

  • Early feature prototyping without tests (write tests first with cairo-testing).
  • Contract architecture decisions (cairo-contract-authoring).
  • Security audit (cairo-auditor).
  • Deployment operations (cairo-deploy).

Quick Start

  1. Confirm tests pass with snforge test.
  2. Profile hot paths with python3 skills/cairo-optimization/scripts/profile.py profile.
  3. Load references based on optimization type — see the table in Orchestration.
  4. Apply one optimization class at a time, re-test after each.
  5. Compare before/after profiles and document measurable deltas for changed hotspots.
  6. Encode stable optimization regressions in ../../evals/cases/contract_skill_benchmark.jsonl to prevent benchmark drift.
  7. Emit a handoff block using ../references/skill-handoff.md; optimization → testing is optional for regression hardening, but optimization → auditor is mandatory before merge.

Rationalizations to Reject

  • "Let's optimize before we have tests."
  • "We can skip re-profiling — the change is obviously better."
  • "BoundedInt types are too complex — let's use raw u128 math."
  • "We can calculate bounds by hand instead of using the CLI tool."

Mode Selection

  • profile: User wants to find bottlenecks. Run profiler, identify hotspots.
  • arithmetic: User wants to optimize math (DivRem, loops, Poseidon). Apply rules from legacy-full.md.
  • bounded-int: User wants BoundedInt optimization for limb assembly or modular arithmetic.
  • storage: User wants to pack storage fields or reduce slot usage.

Orchestration

Turn 1 — Baseline. Before optimizing anything:

(a) Determine mode: profile, arithmetic, bounded-int, or storage.

(b) Verify tests pass. Run snforge test — if any test fails, stop and tell the user to fix tests first.

(c) Read the target code. Use Glob to find .cairo files, then Read to inspect them. Identify:

  • Hot-path functions (called frequently or with expensive operations).
  • Current arithmetic patterns (division, modulus, loops, bitwise ops).
  • Storage layout (field types, packing opportunities).
  • BoundedInt usage or opportunities.

(d) Profile the baseline. Run python3 {skill_dir}/scripts/profile.py profile with the appropriate arguments. Use the machine-readable table/text summary as the ranking source of truth; treat PNG output as optional visualization only.

(e) Load references based on the optimization type:

Request involvesLoad reference
Arithmetic rules (DivRem, loops, Poseidon, integer types){skill_dir}/references/legacy-full.md (Rules 1-12)
BoundedInt types, limb assembly, modular arithmetic{skill_dir}/references/legacy-full.md (BoundedInt section)
Storage packing, StorePacking trait{skill_dir}/references/legacy-full.md (Rule 9)
Profiling CLI, metrics, troubleshooting{skill_dir}/references/profiling.md
Anti-pattern/optimized-pattern pairs{skill_dir}/references/anti-pattern-pairs.md

Where {skill_dir} is the directory containing this SKILL.md. Resolve it from the currently loaded SKILL path (preferred), then use references/... and scripts/... relative paths from that directory.

Turn 2 — Plan. Before changing any code, output a brief plan:

  1. Hotspots — list the top 3-5 functions by step cost from the profile.
  2. Optimizations — for each hotspot, identify which rule(s) apply (by number from legacy-full.md).
  3. Anti-patterns found — list any anti-pattern/optimized-pattern pairs detected in the code.
  4. BoundedInt opportunities — if applicable, list functions that would benefit from BoundedInt types.
  5. Expected impact — rough estimate of step reduction per optimization.

Keep the plan under 30 lines. Wait for user confirmation before implementing.

Turn 3 — Optimize. Apply changes following these rules:

Process rules:

  • Apply ONE optimization class per commit. Never mix arithmetic and storage optimizations.
  • Run snforge test after each change — if any test fails, revert and investigate.
  • Re-profile after each change to measure actual impact.

Arithmetic rules (from legacy-full.md):

  • Use DivRem::div_rem instead of separate / and % (Rule 1).
  • Use != instead of < in loop conditions (Rule 2).
  • Use match-based lookup tables instead of pow() (Rule 3).
  • Use pop_front / for / multi_pop_front instead of index loops (Rule 4).
  • Cache .len() before loops (Rule 5).
  • Use span.slice() instead of manual loop extraction (Rule 6).
  • Use DivRem for parity checks instead of bitwise ops (Rule 7).
  • Use the smallest integer type that fits the range (Rule 8).
  • Use hades_permutation for 2-input Poseidon hashes (Rule 11).

Storage rules:

  • Pack small fields into one slot with StorePacking trait (Rule 9).

BoundedInt rules:

  • Use BoundedInt types as function inputs AND outputs — never downcast at every call (Rule 10).
  • Use u128s_from_felt252 + upcast for bulk felt252 → BoundedInt conversions (Rule 12).
  • Always use python3 {skill_dir}/scripts/bounded_int_calc.py to compute bounds — never calculate manually.
  • Use the SHIFT pattern for negative dividends in bounded_int_div_rem: SHIFT = ceil(|min_possible_value| / modulus) * modulus, then reduce value + SHIFT.

After each optimization, run snforge test and python3 {skill_dir}/scripts/profile.py profile to verify improvement.

Turn 4 — Verify. After all optimizations:

  • Run full test suite: snforge test (all tests must pass).
  • Summarize before/after hotspot metrics and include step deltas in the PR description.
  • Suggest next steps: run cairo-auditor on touched files and update eval cases (contract_skill_benchmark.jsonl, contract_skill_generation_eval.jsonl) to lock gains.

For the full execution checklist, use workflows/default.md.

starknet.js Example

ts
import { Account, Contract, RpcProvider } from "starknet";

const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC! });
const account = new Account({ provider, address: process.env.ACCOUNT_ADDRESS!, signer: process.env.PRIVATE_KEY! });
const contract = new Contract({ abi, address: process.env.CONTRACT_ADDRESS!, providerOrAccount: account });

try {
  const before = await contract.call("hot_path_steps", []);
  const tx = await contract.invoke("apply_optimized_path", []);
  await provider.waitForTransaction(tx.transaction_hash);
  const after = await contract.call("hot_path_steps", []);
  console.log({ before, after });
} catch (err) {
  console.error("optimization check failed", err);
}

Error Codes and Recovery

CodeConditionRecovery
OPT-001Baseline tests failed before optimizationStop optimization work, fix failing tests, then rerun baseline profiling.
OPT-002Profiling artifacts missing (trace/pb.gz)Re-run profile.py with correct --mode/--package and validate tool availability.
OPT-003BoundedInt bounds invalid or unsafeRecompute bounds with bounded_int_calc.py; reject manual bounds and rerun tests.
OPT-004Post-change profile regressedRevert the change, isolate one optimization class, and measure again with identical inputs.

Security-Critical Rules

These are non-negotiable. Every optimization you apply must satisfy all of them:

  1. Tests pass before AND after every optimization. Never optimize untested code.
  2. One optimization class per commit. Never mix unrelated changes.
  3. BoundedInt bounds are computed with the CLI tool — never by hand.
  4. Re-profile after every change to confirm measurable improvement.
  5. Anti-pattern/optimized-pattern pairs are enforced — never write the anti-pattern.

References

Workflow

  • Main optimization flow: default workflow
  • Mandatory pre-merge chain: optimization → auditor (with optimization → testing only as an optional regression-hardening pass before auditor).

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Cairo Optimization faz?

Improves Cairo performance after correctness is established. Trigger on "optimize", "gas usage", "reduce steps", "profile", "BoundedInt", "storage packing", "benchmark". Guides profiling, arithmetic optimization, and bounded-int hardening.

Por que usar Cairo Optimization no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Cairo Optimization é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Cairo Optimization no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/keep-starknet-strange/starknet-agentic/tree/main/skills/cairo-optimization. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Cairo Optimization?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Cairo Optimization?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Cairo Optimization com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Cairo Optimization é gratuita?

Sim. A habilidade é publicada no GitHub por keep-starknet-strange sob a licença Apache-2.0. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇