Smart contracts are the foundation of DeFi.
Smart contracts are blockchain code which will self-execute a transaction when activated on the blockchain.
Contracts determine when, where and under what circumstances assets should be “moved” around on the blockchain ledger. They can work independently as long as they are funded and given enough gas to move around the network.
Once the user signs a transaction to agree on the destination and asset to be moved, the code will be executed trustlessly the way it is written. It is decentralised insofar as, by simply interacting with the contract, no centralised entity or intermediary is required to execute and record that transaction to the blockchain.
For instance, Uniswap swaps are smart contracts that exchange tokens between a user and the pool. The trader signs the transaction signalling their intent to make a trade at a designated price and allowing for a small percentage of deviation (known as slippage) on that trade for the expected outcome of the swap. If the price changes outside of the slippage allowed in the contract, or the contract runs out of gas to execute the transaction completely, then the transaction will fail and the trade will be reverted.
Many protocols have smart contracts for depositing, swapping, vesting or staking, minting NFTs and other user activities. For example, OpenSea, perhaps the most popular NFT marketplace, uses smart contracts for minting and swapping NFTs. The code of the smart contract ensures that it must be fulfilled once executed as long as it has sufficient gas to complete the network activity.