In centralized finance (CeFi), a crypto service operator typically controls custody, account access, and trade execution. In decentralized finance (DeFi), users typically authorize transactions from a wallet, and smart contracts enforce the rules for actions such as swaps and loans. Neither label tells you who can pause withdrawals, change the rules, or block access to an interface. This guide follows a trade through both models and shows how to verify a narrow onchain claim without signing a transaction.
The practical difference between CeFi and DeFi
If you trade through a custodial exchange, the operator can generally execute the trade and update your account without publishing an individual blockchain transaction. If you swap through a decentralized exchange (DEX), the swap typically changes smart contract state onchain. A smart contract is code that runs on a blockchain under the network's rules.
To classify a service, trace one action from authorization to exit. Identify who signs, where the resulting balance is recorded, and who can stop the user from moving the assets afterward. An exchange can settle withdrawals onchain without settling every trade onchain. A wallet-connected app can settle swaps onchain while relying on an operator to run its website or an administrator to upgrade its contracts. Classify each step, not the brand.
Custody, execution, and access at a glance
| Dimension | Typical custodial CeFi service | Typical wallet-based DeFi protocol |
|---|---|---|
| Authorization | The user submits an account instruction; the service controls the custody keys | The user authorizes a wallet transaction or signed instruction; a contract checks the applicable rules |
| Execution and records | The operator may match orders and update a private ledger | Smart contracts enforce onchain execution or settlement; routing or matching may happen offchain |
| Access and recovery | Accounts may require identity checks; support and recovery depend on policy | Direct contract access may be open, but interfaces or contracts can impose restrictions; key recovery depends on wallet design |
| Costs | Trading fees, spread, and possible withdrawal fees | Protocol or liquidity fees, price impact, and network fees where applicable |
| Exit | The operator processes withdrawals subject to its policies and ability to pay | Exit depends on contract rules, available liquidity, and the network processing the transaction |
In crypto, CeFi usually refers to intermediaries such as custodial exchanges and lenders. Traditional finance (TradFi) is a broader category that includes institutions and markets such as banks and securities exchanges. The categories can overlap: a centralized crypto service might use banking rails for deposits and a public blockchain for withdrawals.
A trade from instruction to settlement
On a custodial exchange, a token deposit may appear onchain as a transfer to an exchange-controlled address. The exchange then credits its internal ledger. When a trade fills, the exchange can debit one account balance and credit another without moving tokens onchain. A later withdrawal can create an onchain transaction, but that transaction establishes what moved on the network, not how the earlier trade was priced or matched.
On an Ethereum-style DEX, a wallet may first authorize a router to spend a token. The swap then calls a contract that checks conditions such as the minimum acceptable output and transfers tokens if execution succeeds. Depending on the protocol, approval may be a separate transaction, part of a signed authorization, or unnecessary for the asset being sent. An included swap that reverts generally still incurs a network fee, even though the swap's state changes are undone.
Lending exposes a similar difference. A CeFi lender manages collateral and applies its liquidation terms. A DeFi lending contract can allow a liquidator to act once an oracle-fed collateral condition is met. The contract defines eligibility, but an eligible liquidation may still depend on someone submitting a transaction and the network including it.
Prerequisites for a read-only comparison
The example below checks a specific claim: an ERC-20 token contract reports a balance for a documented pool or vault address at a chosen block. Use Python 3, an Ethereum-compatible JSON-RPC endpoint that supports the finalized block tag and historical state reads at the selected height, and the expected chain ID from network documentation. Get the token and holder addresses from the protocol's deployment documentation for that exact network. No wallet, private key, token approval, or funds are needed.
Use the network directory to locate network information and the blockchain API service overview for endpoint context. Confirm support for the calls you need before using an endpoint in production. If the URL contains an API credential, keep it out of shared logs and notebooks. For a matching CeFi example, use an account export or statement you are authorized to access; the RPC checks cannot retrieve a private exchange ledger.
A finalized block as the reference point
Save this as pin_block.py. Set RPC_URL and EXPECTED_CHAIN_ID in your environment, then run python3 pin_block.py. The script checks the endpoint's chain ID and prints the block number and hash returned for finalized. Keep both values: a height alone does not identify a block across networks or competing histories. The meaning and availability of finalized are network-specific.
import json
import os
from urllib.request import Request, urlopen
def rpc(method, params):
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method,
"params": params}).encode()
request = Request(os.environ["RPC_URL"], data=body,
headers={"Content-Type": "application/json"})
with urlopen(request, timeout=20) as response:
reply = json.load(response)
if "error" in reply:
raise RuntimeError(f"{method}: {reply['error']}")
return reply["result"]
def check_chain():
expected = int(os.environ["EXPECTED_CHAIN_ID"], 0)
actual = int(rpc("eth_chainId", []), 16)
if actual != expected:
raise SystemExit(f"Wrong chain: expected {expected}, got {actual}")
return actual
if __name__ == "__main__":
chain_id = check_chain()
block = rpc("eth_getBlockByNumber", ["finalized", False])
if not block or not block.get("number") or not block.get("hash"):
raise SystemExit("Endpoint did not return a finalized block")
print(json.dumps({"chainId": chain_id, "BLOCK_NUMBER": block["number"],
"BLOCK_HASH": block["hash"]}, indent=2))Verification of a token balance at the pinned block
Save this as read_balance.py next to the first script. Set BLOCK_NUMBER and BLOCK_HASH to the values printed above and set TOKEN_ADDRESS and HOLDER_ADDRESS to the documented addresses. Run python3 read_balance.py. The script checks for contract code at the token address and calls the ERC-20 balanceOf(address) method. It compares the endpoint's block hash before and after the state reads to catch a visible mismatch; that check is not an independent proof of the endpoint's response.
A successful result contains the chain ID, block number, block hash, token address, holder address, and balance in raw token units. Zero is a valid result. To display a human-readable balance, confirm the token's decimals rather than assuming them. The output says what that token contract reports for that address at that block. It does not establish the pool's usable liquidity, your personal claim, or whether you can withdraw.
import json
import os
import re
from pin_block import check_chain, rpc
def address(name):
value = os.environ[name]
if not re.fullmatch(r"0x[0-9a-fA-F]{40}", value):
raise SystemExit(f"Invalid {name}: expected a 20-byte hex address")
return value.lower()
chain_id = check_chain()
height = os.environ["BLOCK_NUMBER"]
block_hash = os.environ["BLOCK_HASH"].lower()
token = address("TOKEN_ADDRESS")
holder = address("HOLDER_ADDRESS")
def check_block():
block = rpc("eth_getBlockByNumber", [height, False])
if not block or block["hash"].lower() != block_hash:
raise SystemExit("Block hash mismatch at pinned height")
check_block()
if rpc("eth_getCode", [token, height]) == "0x":
raise SystemExit("No contract code at the token address at this block")
data = "0x70a08231" + holder[2:].rjust(64, "0")
result = rpc("eth_call", [{"to": token, "data": data}, height])
check_block()
if not re.fullmatch(r"0x[0-9a-fA-F]{64}", result):
raise SystemExit("Unexpected balanceOf return data")
print(json.dumps({"chainId": chain_id, "blockNumber": height,
"blockHash": block_hash, "token": token, "holder": holder,
"balanceRaw": str(int(result, 16))}, indent=2))Evidence records for a fair comparison
Use the table as a worksheet for an existing trade, withdrawal, or balance observation. Mark unavailable evidence as unavailable rather than zero. Compare the same asset, trade direction, and size where practical. If you're measuring elapsed time, define the event at each end: an exchange's order fill, an onchain transaction's inclusion, and finality are different milestones. For an end-to-end exit comparison, use the same destination and the same confirmation criterion.
| Observation | CeFi evidence to record | DeFi evidence to record |
|---|---|---|
| Balance | Account export, timestamp, asset, available versus locked amount | Chain ID, block number and hash, token and holder addresses, raw balance |
| Execution | Order ID, fill time, amounts, and charged fees | Transaction hash, receipt status, block, and decoded amounts for the same action |
| Exit | Withdrawal request time, fee, and transaction hash if provided | Submission and inclusion times, received amount, and chosen confirmation or finality criterion |
A screenshot can help reconstruct what the interface displayed, but it is weaker evidence than an export or a pinned query. Likewise, a public wallet balance or a reserves snapshot is not enough to establish an operator's ability to cover liabilities. Record the claim each source actually supports.
Common failures and misleading signals
- Wrong chain, empty code, or surprising zero: Recheck the chain ID, token contract, holder address, and deployment block. The same-looking address can refer to a different asset or have no code on another network. A protocol may hold tokens in a separate vault rather than at its router.
- Unsupported block tag or missing historical state: Verify the chain's finality guidance and the endpoint's history capabilities. If you use a documented alternative block-selection rule, record it explicitly; do not silently switch to
latestand call the result finalized. - Revert or unexpected return data: Confirm the token interface for that deployment and check whether the address is a proxy. An RPC error, revert, or malformed response is not a zero balance.
- Successful receipt but unexpected output: Inspect the relevant token transfers and contract events. A successful outer transaction does not prove every intended action occurred, particularly when a router can tolerate a failed subcall.
- Missing exchange trade on a block explorer: An internal fill may have no transaction hash. For a pending withdrawal, distinguish the operator's status from the network's status; once a hash is available, check it on the specified chain.
Risk, convenience, and hybrid control
CeFi can simplify fiat access, account recovery, and support. In exchange, users depend on the operator's custody, security, solvency, and withdrawal policies. Identity checks or regulatory oversight do not automatically imply deposit insurance or guaranteed recovery. Review the terms for the specific product and jurisdiction.
DeFi can make execution and state easier to inspect, but self-custody does not eliminate third-party dependencies. When you deposit into a vault, the contract may control the deposited tokens while your wallet controls a position or receipt token. Upgrades, pause controls, price oracles, and token issuers can each affect whether that position is usable. A front end may go offline without stopping the contracts; a contract pause or token restriction can affect exit even if the website works.
For a hybrid service, trace the layers separately: a centralized on-ramp can fund a self-custodied wallet, which can then use a smart contract holding an issuer-controlled stablecoin. Each step has a different operator or set of rules. The most useful distinction is which dependency can prevent the specific action you need.
Next steps for users and integrators
Before choosing either model, map one entry path and one exit path. For CeFi, check withdrawal conditions, the custody terms, and the records you can export. For DeFi, verify the deployed contracts, permissions, and exit conditions. Decide which evidence you would need if the interface displayed an unexpected balance or a withdrawal stalled.
If you're building an integration, track account events and onchain settlement as separate states. Store the chain ID, block number, and block hash with observed balances, and report unavailable state separately from zero. Estimate read volume against the RPC pricing and plan details, and review dedicated node options if your operating requirements call for dedicated infrastructure. For related implementation and diagnostics, browse the OnFinality Learn technical guides.