Smart contracts written in Plutus can be divided in two: an
on-chain part and an
off-chain part. What's the main difference between these two?
I think the Plutus core specification gives pretty good explanation.
Plutus Core code (and code intended for execution on a blockchain in general) can be executed in two different environments: off-chain and on-chain. As the name suggests, off-chain execution doesn’t happen on the blockchain itself, but in some other environment, such as in an electronic wallet on a smartphone or PC. In contrast, on-chain execution takes place on core nodes, machines which are actually maintaining the blockchain.
Not only the environment is different though. The purpose is also different:
- On-chain code is used to validate transactions. It will be run every time somebody wants to submit a transaction to the blockchain. If validation succeeds, most likely the transaction will be written to the chain. Fees also should be paid for running the on-chain code to prevent DoS of the blockchain (if there are no fees, anybody can submit an infinite loop to the blockchain and then every node running this code will be stuck and thus blockchain won't be able to operate)
- Off-chain code is used to build and submit transactions and also query the blockchain. Say, you want to participate in online auction running on Cardano. In order to do so, you need to make a bid. To make a bid, you need to send specific data to the auction smart contract, say the ID of the lot and amount of Ada. Off-chain code builds such a transaction, runs off-chain validation (so you can avoid spending fees for invalid transactions), calculates the fees and submits the transaction to the blockchain
The on-chain and off-chain code are written in Plutus language which is basically Haskell. The on-chain part is compiled using PlutusTx to "Plutus Core" which are executed by the nodes on the blockchain. The off-chain part is compiled using Haskell compiler to run on user's machine (wallet, pc, mobile ...)