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?
3 Answers
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
-
Since the off-chain part runs on the wallet, would be possible to hang it with an infinite loop? or there's a mechanism to prevent this behaviour? May 1, 2021 at 19:48
I'm not sure how specific you want the answer to be, but essentially on-chain
means that the contract is executed on the block-chain. Whereas, off-chain
means that this part of the contract is executed off of the block-chain (ie. on the user's machine).
-
Are the following clarifications correct? By "on the user's machine", you mean the code is executed using computation power provided by a 3rd-party/user interacting with the contract (the results of which will potentially not be verified in any way). By "on the block-chain", you mean the code is executed using compute power provided by validator nodes (the results of which will be statistically verified).– mathandyOct 2, 2021 at 3:53
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 ...)