Contratos Inteligentes Explicados: Una Guía No Técnica
Understand how code that runs by itself on a blockchain powers DeFi, NFTs and DAOs. No programming knowledge required: clear explanations, everyday analogies and practical takeaways.
¿Qué es un contrato inteligente?
Un contrato inteligente es un programa almacenado en una cadena de bloques que se ejecuta por sí solo cuando se cumplen condiciones específicas. Ethereum.org lo define como un programa desplegado en una dirección de la cadena: mantiene un saldo y ejecuta su código cuando recibe una transacción. A diferencia de un contrato tradicional, que depende de abogados, tribunales o intermediarios para hacer cumplir sus términos, un contrato inteligente hace exactamente lo que dice su código, cada vez, sin nadie en el medio.
The idea predates Bitcoin. Computer scientist Nick Szabo coined the term in the mid-1990s and described how digital protocols could enforce the terms of an agreement automatically (see Sources). Smart contracts became practical when Ethereum launched in July 2015, following the 2013 whitepaper by Vitalik Buterin that proposed a blockchain with a Turing-complete programming language.
La analogía de la máquina expendedora
La forma más sencilla de entender un contrato inteligente es la analogía que el propio Szabo utilizó, y que ethereum.org sigue usando: una máquina expendedora. Introduces una moneda (entrada), la máquina verifica el importe (condición) y dispensa tu snack (salida). No necesita un cajero. No le importa quién eres. Sigue su programación cada vez. Un contrato inteligente funciona de la misma manera, excepto que se ejecuta en una blockchain, gestiona activos digitales y nadie puede desenchufar la máquina ni cambiar sus reglas una vez desplegado.
At its core, a smart contract is if-then logic: if condition X is true, then execute action Y. For example: if Alice sends 1 ETH to this contract, then send 2,000 USDC from the contract's reserves to Alice's address. This predictable execution is what people mean by "trustless": you do not need to trust the other party, because the code determines the outcome.
Autoejecutable
No intermediaries. The code runs when its conditions are met, exactly as written.
Inmutable
Once deployed, the code cannot be edited. The rules stay as they were published, unless the contract was built with an upgrade mechanism.
Sin confianza
You rely on the code, not on a counterparty. Anyone can read a verified contract's logic on a public block explorer.
Cómo funcionan los contratos inteligentes
A smart contract follows a clear lifecycle: a developer writes the code, deploys it to a blockchain, and then users (or other contracts) interact with it by sending transactions. Here is what happens at each step, as described in the ethereum.org developer documentation.
Desplegado en una cadena de bloques
A developer writes the contract, usually in Solidity for Ethereum, and compiles it into bytecode. That bytecode is sent to the network in a special transaction. The network gives the contract its own address, just like a wallet address. From then on the contract lives on the blockchain and anyone can call it.
Deployment costs gas: the fee paid for processing the transaction and storing the contract code on every node. Larger contracts contain more bytecode and need more storage, so they cost more gas to deploy. See our gas fees guide for how the fee is calculated.
Inmutable una vez desplegado
Once a contract is on the blockchain, its code cannot be edited. This is a feature: it guarantees that the rules cannot be changed after the fact. If you deposit into a lending contract with a published interest formula, nobody can rewrite that formula or seize your funds by editing the code.
Immutability also means bugs are permanent. A logic error in deployed code cannot be patched in place. That is why testing, auditing and formal verification happen before deployment, and why some teams use upgradeable proxy patterns, which trade a little immutability for the ability to fix bugs (see the FAQ).
Activado por transacciones
Los contratos inteligentes no se ejecutan por sí solos. Permanecen inactivos hasta que alguien envía una transacción que llama a una de sus funciones. La transacción incluye el nombre de la función, sus parámetros y una tarifa de gas. Por ejemplo, llamar a la función swap() en un contrato de exchange DeFi activa la lógica de intercambio de tokens.
Los contratos también pueden llamar a otros contratos. Esta es la base de la composabilidad de DeFi: una sola transacción de usuario puede desencadenar una cadena de interacciones entre contratos a través de varios protocolos.
Ejecución determinista
Given the same inputs and the same blockchain state, a smart contract always produces the same output. Every node on the network executes the contract independently and reaches the same result. This determinism is what lets thousands of computers agree on an outcome without trusting each other, per the ethereum.org EVM documentation.
It also means a contract cannot fetch outside data on its own: it only knows what is on the blockchain. To use off-chain data such as asset prices or weather readings, contracts rely on oracles such as Chainlink, which bring that information on-chain.
Casos de Uso de Contratos Inteligentes
Smart contracts are behind almost every application in crypto. Here are the main categories where self-executing code has replaced a traditional intermediary.
DeFi (Finanzas Descentralizadas)
DeFi is the largest category of smart contract applications. Lending protocols such as Aave and Morpho use contracts to match lenders and borrowers without a bank. DEXs such as Uniswap enable token swaps without an order book or a centralized exchange. Staking contracts let users lock tokens and earn APY rewards automatically.
Every interaction (depositing collateral, borrowing, earning interest, liquidating undercollateralized positions) is handled by contract logic.
NFTs (Tokens No Fungibles)
Cada colección de NFT es un contrato inteligente. Los estándares ERC-721 y ERC-1155 definen cómo se crean, transfieren y poseen los activos digitales únicos en Ethereum. Los contratos gestionan la acuñación, los registros de propiedad y los listados en el mercado.
Creator royalties show both the promise and the limits. A contract can publish a royalty rate (the ERC-2981 standard exists for this), but the standard only signals the rate; whether it is paid depends on the marketplace honouring it.
DAOs (Organizaciones Autónomas Descentralizadas)
A DAO is an organization whose rules are enforced by smart contracts. Members hold governance tokens that give them voting rights on proposals. Contracts count votes, enforce quorum, execute approved proposals and hold the treasury, without a CEO or a board.
DAOs grandes como MakerDAO (ahora Sky), Uniswap DAO y Arbitrum DAO gestionan tesorerías sustanciales mediante votaciones on-chain. Consulta nuestra guía de DAO para saber cómo funciona la gobernanza.
Seguros & Cadena de suministro
Parametric insurance uses smart contracts to pay claims automatically from verifiable data. For example, a crop insurance contract can read a weather oracle, detect a drought and pay the farmer without a claims adjuster, paperwork or delay.
In supply chains, contracts can record goods moving from factory to consumer, verify provenance and release payment at each checkpoint. Several large companies have piloted such systems; results have been mixed, and adoption outside crypto remains limited.
Gana 7.50% APY en USDC
Los contratos inteligentes impulsan las estrategias on-chain detrás de Coinstancy Dollar Savings. Los intereses se acumulan cada segundo y se reinvierten automáticamente. Sin bloqueo, retira en cualquier momento.
Contratos inteligentes en Ethereum
Ethereum is where smart contracts became mainstream and it remains the largest platform for them. The 2013 whitepaper proposed a blockchain with a built-in Turing-complete language, so that it could run arbitrary programs rather than only transfer value as Bitcoin does. The network launched in July 2015, per the ethereum.org history page. Today it hosts the largest share of DeFi, NFT and DAO applications, with a growing part of that activity on its Layer 2 networks.
Solidity: El lenguaje de Ethereum
La mayoría de los contratos inteligentes de Ethereum están escritos en Solidity, un lenguaje de tipado estático diseñado para la Máquina Virtual de Ethereum (EVM). Su documentación lo describe como influenciado por C++, Python y JavaScript. Incluye tipos integrados para direcciones y saldos, así como acceso integrado a funciones criptográficas.
Vyper is the main alternative. It uses a Python-like syntax and aims for simplicity and auditability: per its documentation, it deliberately leaves out features such as inheritance, function and operator overloading and inline assembly, to reduce the attack surface. Some well-known DeFi protocols, including Curve, are written in Vyper.
La Máquina Virtual de Ethereum (EVM)
The EVM is the runtime that executes contract bytecode. Every Ethereum node runs the same EVM, so contract execution is identical across the whole network. When you send a transaction to a contract, every validator processes the same bytecode with the same inputs and reaches the same result, per ethereum.org.
The EVM has become a de facto standard. Layer 2 networks such as Arbitrum, Optimism and Base, and independent chains such as BNB Chain and Avalanche, are "EVM-compatible": they run the same Solidity contracts with little or no modification.
Costos de Gas y el Proceso de Despliegue
Every operation on Ethereum costs gas, a unit of computational effort. A simple ETH transfer costs 21,000 gas, per ethereum.org, while deploying a large contract can cost millions of gas units. The fee equals gas used multiplied by the gas price in gwei. When the network is busy, gas prices rise and deployment and interaction become expensive; live prices are on the Etherscan gas tracker (see our gas fees guide).
A typical workflow is: write the contract in Solidity, compile it, test it on a local network (with tools such as Hardhat or Foundry), deploy to a public testnet such as Sepolia, commission a security audit, then deploy to mainnet. Professional teams usually control deployment and admin functions through a multisignature wallet such as Safe.
Seguridad de contratos inteligentes
Security is the most important concern in smart contract development. Because contracts are hard to change and hold real value, a single vulnerability can cost millions of dollars with no way to reverse it. The industry has built up a set of practices to reduce that risk.
Auditorías de seguridad
Independent security firms review the code line by line, looking for reentrancy, access control flaws, arithmetic errors and logic mistakes. The time and cost depend on the size and complexity of the code; audit firms publish their scope and findings in a report that protocols usually make public.
Recompensas por errores
Protocols pay security researchers who report vulnerabilities responsibly. Platforms such as Immunefi host these programmes, with rewards scaled to severity; the largest critical-bug bounties run to millions of dollars. Each programme publishes its own reward table.
Verificación formal
Formal verification uses mathematical proofs to show that a contract satisfies specific properties for all possible inputs. It is stronger than a manual review for the properties it covers, but it only proves what is written in the specification: if the specification misses a case, so does the proof.
Well-Known Audit Firms
Los nombres consolidados incluyen Trail of Bits (herramientas de seguridad y auditorías), OpenZeppelin (mantenedor de las bibliotecas de contratos ampliamente utilizadas) y Certora (verificación formal). Una auditoría de una firma consolidada es una señal útil, pero lea el informe: el alcance, los hallazgos y si se corrigieron importan más que el logotipo.
Important: an audit is not a guarantee of safety. Audits are point-in-time reviews and can miss new attack patterns. Many exploited protocols had been audited. Look for several audits, an active bug bounty and a record of careful upgrades before you deposit.
Hackeos Famosos de Contratos Inteligentes
The history of smart contracts includes several large exploits that changed how the industry approaches security. Knowing them helps you judge the risk of any DeFi protocol. The figures below are the ones reported by the affected teams at the time.
El hackeo DAO
The DAO was the first large decentralized autonomous organization on Ethereum and raised a record amount of ETH in its 2016 token sale. An attacker exploited a reentrancy vulnerability: a flaw that let the attacker's contract call the withdrawal function again and again before the DAO updated its balance. About 3.6 million ETH was drained, per the ethereum.org history page, worth tens of millions of dollars at the time.
The community responded with a hard fork that returned the funds, which split the network into Ethereum (the forked chain) and Ethereum Classic (the original, unaltered history). The event made reentrancy the best-known smart contract vulnerability and led to the "checks-effects-interactions" pattern that the Solidity documentation now recommends.
Explotación del puente Wormhole
Wormhole, un puente entre cadenas que conecta Ethereum y Solana, fue explotado en febrero de 2022. El atacante encontró una falla en el contrato del lado de Solana que le permitió acuñar 120.000 ETH envueltos (wETH) en Solana sin bloquear el ETH correspondiente en Ethereum, según el informe de incidente del equipo de Wormhole.
The root cause was a signature verification bypass: the contract did not properly validate the "guardian" signatures that authorize cross-chain transfers. Jump Crypto, which backs the Wormhole development team, replaced the missing ETH so that users were made whole. The incident showed the specific risk of bridge contracts, which must keep state consistent across several blockchains.
Explotación de Euler Finance
Euler Finance, an Ethereum lending protocol, lost about $197 million in a flash loan attack in March 2023, per the team's own disclosures. The attacker abused a flaw in the donateToReserves function to manipulate a debt position and extract funds from the lending pools.
Unusually, the attacker returned the funds after negotiations with the Euler team, making it one of the largest recoveries in DeFi. The incident showed that audited protocols (Euler had several audits) can still contain exploitable logic errors, and that fast incident response can sometimes recover stolen assets.
Lecciones aprendidas
- Several audits are better than one. Different auditors catch different bugs.
- Bridges are high-value targets. Cross-chain contracts hold large sums and have a larger attack surface than single-chain protocols.
- Los préstamos flash lo amplifican todo. Un atacante puede pedir prestado un gran capital dentro de una sola transacción, por lo que incluso un pequeño fallo puede explotarse a escala.
- Immutability cuts both ways. It protects users from rule changes, but it also means bugs cannot be patched in place.
Gana 7.50% APY en USDC con Coinstancy
Los intereses se acumulan cada segundo y se reinvierten automáticamente. Sin bloqueo, retira en cualquier momento. Impulsado por contratos inteligentes on-chain.
Contratos inteligentes más allá de Ethereum
Ethereum made smart contracts mainstream, but many other blockchains now support them, often with different languages, execution environments and trade-offs. Here are the main alternatives.
| Cadena de bloques | Lenguaje | VM / Tiempo de ejecución | Key Characteristic |
|---|---|---|---|
| Ethereum | Solidity / Vyper | EVM | El ecosistema más grande, el historial más largo |
| Solana | Rust (Anchor framework) | Sealevel (SVM) | Ejecución paralela, comisiones bajas |
| Ecosistema Cosmos | Rust (CosmWasm) | CosmWasm VM | Comunicación intercadena (IBC), cadenas de aplicaciones |
| Arbitrum | Solidity (EVM) | Nitro (rollup optimista) | Ethereum security, much lower fees |
| Base | Solidity (EVM) | OP Stack (rollup optimista) | Creado por Coinbase sobre el OP Stack |
Solana: Programas, no contratos
Solana takes a different approach. Smart contracts on Solana are called "programs" and are usually written in Rust, often with the Anchor framework. Its runtime, Sealevel, can execute transactions in parallel as long as they do not touch the same accounts, whereas the EVM processes transactions one after another.
This design gives high throughput and very low fees, at the cost of a steeper learning curve for developers and a security model that differs from the EVM. Details are in the Solana developer documentation.
Cosmos: CosmWasm y contratos inteligentes intercadena
The Cosmos ecosystem uses CosmWasm, a WebAssembly-based contract platform where contracts are written in Rust. CosmWasm relies on Rust's memory safety and on an actor-style execution model that avoids several common attack patterns, including reentrancy.
The distinctive feature of Cosmos is IBC (Inter-Blockchain Communication), a protocol that lets contracts on different Cosmos chains exchange messages and assets without a third-party bridge. The result is a network of interoperable, application-specific blockchains.
Rollups de Capa 2: Arbitrum y Base
Arbitrum and Base are Ethereum Layer 2 networks that run the same EVM contracts as mainnet, execute transactions off the main chain and post compressed transaction data back to Ethereum. Developers get Ethereum's security guarantees with much lower gas costs and faster confirmations.
For developers, migration is simple: most Solidity contracts deploy to Arbitrum or Base with little or no change. For users, the experience is close to mainnet, with fees measured in cents rather than dollars. See our gas fees guide for how L2 fees are built.
El futuro de los contratos inteligentes
Smart contracts have matured a great deal since The DAO, and the technology keeps changing. Here are three developments shaping the next generation.
Abstracción de cuentas
Account abstraction (ERC-4337) turns a wallet into a smart contract. Instead of depending on a single private key, the wallet can enforce programmable rules: social recovery, spending limits, scheduled payments, session keys for games, and transactions whose gas is paid by an application.
This addresses two of the biggest usability problems in crypto, seed phrases and gas. Smart contract wallets such as Safe and several consumer wallets already offer these features.
AI-Assisted Development
Los modelos de lenguaje grandes se utilizan cada vez más para redactar, explicar y revisar el código de los contratos inteligentes. Pueden generar código repetitivo de Solidity, señalar patrones de vulnerabilidad comunes y traducir una especificación en lenguaje natural a un primer borrador.
AI-generated code still needs human review and a proper audit before it handles real funds. The realistic near-term effect is faster development and cheaper first-pass review, not contracts that write and verify themselves.
Interoperabilidad entre cadenas
Smart contracts increasingly span several chains. Protocols such as LayerZero, Chainlink CCIP and Cosmos IBC provide messaging layers that let contracts on different blockchains communicate.
El objetivo es que un contrato en Ethereum pueda desencadenar una acción en Solana, liquidarse en Arbitrum y reportar de vuelta dentro de una sola interacción del usuario. Eso reduciría la liquidez fragmentada y permitiría a los usuarios alcanzar los mejores precios y aplicaciones independientemente de la cadena en la que comiencen. Los puentes y las capas de mensajería siguen siendo una fuente importante de exploits, por lo que esta área merece precaución.
Preguntas frecuentes
¿Qué es un contrato inteligente en términos simples?
¿Se pueden cambiar los contratos inteligentes después del despliegue?
Are smart contracts legally binding?
How much does it cost to deploy a smart contract?
¿Necesito saber programar para usar contratos inteligentes?
¿Qué ocurre si un contrato inteligente tiene un error?
Continuar aprendiendo
Explora más guías sobre protocolos DeFi y fundamentos de criptomonedas.
Guía de Morpho
Learn how Morpho's smart contracts run isolated lending markets and curated vaults.
Leer Guía¿Qué es el APY en cripto?
Comprende el rendimiento porcentual anual, el interés compuesto y cómo evaluar los rendimientos DeFi de forma segura.
Leer GuíaGlosario Cripto
Consulta las definiciones de contratos inteligentes, DeFi, DAO, oráculos, ERC-20 y muchos otros términos cripto.
Explorar glosarioLos contratos inteligentes impulsan tu rendimiento
Gana un 7,50% de APY en USDC con Coinstancy Dollar Savings. Los intereses se acumulan cada segundo y se reinvierten automáticamente. Sin bloqueo, retira en cualquier momento. Los depósitos de ahorro primero ingresan en una cartera multifirma gestionada por el equipo de Coinstancy, y luego se asignan a la estrategia on-chain correspondiente, construida sobre la misma tecnología que acabas de conocer.
Comienza a ganar en CoinstancyFuentes y lecturas adicionales
Las cifras y afirmaciones de esta página se basan en los documentos que aparecen a continuación. Las cifras sensibles al tiempo (tasas, rendimientos, comisiones, datos de mercado) cambian: verifica el valor en vivo en la fuente antes de actuar en consecuencia.
- Ethereum.org, Introduction to smart contractsethereum.org
Definition of a smart contract, the vending machine analogy, deployment, immutability and the need for oracles.
- Whitepaper de Ethereum (Vitalik Buterin, 2013)ethereum.org
The original proposal for a blockchain with a Turing-complete scripting language for smart contracts.
- Nick Szabo, Smart Contracts: Building Blocks for Digital Markets (1996)fon.hum.uva.nl
The essay that coined the term and used the vending machine as the "primitive ancestor" of smart contracts.
- Documentación de Soliditydocs.soliditylang.org
Solidity as a statically typed language for the EVM, influenced by C++, Python and JavaScript.
- Documentación de Vyperdocs.vyperlang.org
Vyper design goals and the language features it deliberately leaves out for auditability.
- Ethereum.org, Ethereum Virtual Machine (EVM)ethereum.org
How the EVM executes contract bytecode deterministically on every node.
- Ethereum.org, History of Ethereumethereum.org
Timeline of the network, including the 2015 launch and the 2016 DAO attack and fork.
- OpenZeppelin documentationdocs.openzeppelin.com
Standard contract libraries and the Transparent and UUPS upgradeable proxy patterns.
- ERC-721: Non-Fungible Token Standardeips.ethereum.org
The token standard behind most NFTs on Ethereum.
- UK Law Commission, Smart legal contractslawcom.gov.uk
The 2021 advice to government on how existing law applies to smart legal contracts.
Última revisión: septiembre de 2026. Los enlaces externos se abren en una nueva pestaña; Coinstancy no es responsable de su contenido.
¿Listo para ganar con contratos inteligentes?
Gana un 7,50% de APY en USDC con Coinstancy Dollar Savings. Los intereses se acumulan cada segundo y se reinvierten automáticamente. Sin bloqueo, retira cuando quieras.