In blockchain systems, storing data directly on the blockchain (on-chain) is often more expensive than storing it outside the blockchain (off-chain). Why is this the case?
Think about how blockchain nodes keep copies of the data.
On-chain data is stored by every full node in the blockchain network. This means the data is duplicated many times, using more storage and bandwidth. This resource use is paid for by higher costs. Off-chain data is stored separately, so it does not require all nodes to store it.
Consider this simplified Python code that calculates cost based on data size and location:
def storage_cost(size_kb, location):
base_cost = 0.01 # base cost per KB
if location == 'on-chain':
multiplier = 10 # on-chain storage is 10x more expensive
else:
multiplier = 1
return size_kb * base_cost * multiplier
print(storage_cost(100, 'on-chain'))What is the output?
Multiply size by base cost and multiplier.
The size is 100 KB, base cost is 0.01 per KB, and on-chain multiplier is 10. So, 100 * 0.01 * 10 = 10.0.
Here is a Python function to calculate storage cost. It should return the cost for given data size and location. Find the error that causes it to always return size_mb * 0.05.
def calc_cost(size_mb, location):
cost_per_mb = 0.05
if location == 'on-chain':
cost_per_mb * 20
else:
cost_per_mb * 1
return size_mb * cost_per_mb
print(calc_cost(5, 'on-chain'))Look at how the multiplier is applied to cost_per_mb.
The lines 'cost_per_mb * 20' and 'cost_per_mb * 1' compute a value but do not store it back. So cost_per_mb remains 0.05, making the cost calculation incorrect.
Given this Solidity-like pseudocode snippet for storing data location:
mapping(address => string) public dataLocation;
function setDataLocation(address user, string memory location) public {
dataLocation[user] = location
}Which option below will cause a syntax error?
Check punctuation at the end of statements.
In Solidity, statements must end with a semicolon. Missing it after 'dataLocation[user] = location' causes a syntax error.
Imagine a blockchain where storing 1 KB on-chain costs 0.02 tokens, and storing 1 KB off-chain costs 0.001 tokens. A user wants to store 500 KB of data. They can choose to store all on-chain, all off-chain, or split 300 KB on-chain and 200 KB off-chain.
Which option results in the lowest total cost?
Calculate cost for each scenario by multiplying size by cost per KB.
All on-chain: 500 * 0.02 = 10 tokens.
All off-chain: 500 * 0.001 = 0.5 tokens.
300 on-chain + 200 off-chain: (300 * 0.02) + (200 * 0.001) = 6 + 0.2 = 6.2 tokens.
300 off-chain + 200 on-chain: (300 * 0.001) + (200 * 0.02) = 0.3 + 4 = 4.3 tokens.
Lowest cost is all off-chain at 0.5 tokens.