Tokens, Digital Assets and DeFi Building BlocksIntroductionBlockchain networks become economically useful when they can represent, transfer and govern digital value. Tokens are programmable records associated with a blockchain account or smart contract. They may represent currency, ownership, access rights, voting power, collectibles, claims on assets or positions in financial protocols. Decentralized finance (DeFi) combines these representations with automated exchange, lending, collateral, escrow and governance. This chapter examines the principal token standards used in smart-contract systems, especially Ethereum-compatible systems. It also explains ownership, approvals, minting, burning, royalties, metadata and the components of common DeFi applications. The emphasis is practical: a developer must understand not only how a standard works, but also what can go wrong when tokens are integrated into wallets, marketplaces, exchanges and financial protocols. Learning ObjectivesBy the end of this chapter, students should be able to: - Distinguish fungible, non-fungible and multi-token assets.
- Explain the purposes and risks of balances, ownership, approvals and transfer functions.
- Apply the principal features of ERC-20, ERC-721 and ERC-1155-style standards.
- Analyse minting, burning, metadata, royalties and supply controls.
- Describe the smart-contract components of exchanges, lending systems, escrow, staking and DAOs.
- Identify security, governance, regulatory and ethical risks in token-based applications.
1. Digital Assets and Token ModelsA digital asset is a digitally represented item or right whose ownership, control or use can be recorded and transferred. A token is not necessarily the underlying legal asset. For example, a token may represent a claim on a physical commodity, while the commodity remains subject to separate custody and legal arrangements. This distinction between on-chain representation and off-chain reality is fundamental. Token systems generally use one of three models: | Model | Main characteristic | Typical examples |
|---|
| Fungible token | Each unit is interchangeable with another unit | Payment token, governance token, stablecoin | | Non-fungible token | Each token is individually identifiable | Artwork, certificate, in-game item | | Multi-token system | One contract manages many fungible and non-fungible types | Game inventories, membership systems |
Fungibility means substitutability. If one unit has the same rights and value as another unit, the units are fungible. Non-fungible tokens (NFTs) are distinguishable by an identifier, although two NFTs may still have similar economic value. A token ledger commonly maps accounts to balances or ownership records. In an ERC-20-style design, a balance is associated with an account address. In an ERC-721-style design, a unique token identifier is associated with an owner. In both cases, the contract must enforce valid state transitions: tokens should not be transferred by unauthorised parties, and total supply should change only through permitted operations. 2. Fungible Tokens: ERC-20-Style DesignThe ERC-20 standard specifies a common interface for interchangeable tokens on Ethereum-compatible networks. Its central functions include: totalSupply(): returns the number of token units in existence.balanceOf(account): returns an account’s balance.transfer(to, amount): transfers units from the caller to another account.approve(spender, amount): authorises a spender to use units from the caller’s balance.allowance(owner, spender): reports the remaining approved amount.transferFrom(from, to, amount): transfers units using an allowance.
The standard also defines Transfer and Approval events. Events are not the ledger itself; they are logs that help wallets, explorers and indexing systems observe state changes. A correct implementation updates state and emits events consistently. Ownership and allowancesAn ERC-20 token normally does not maintain an owner for every individual unit. Instead, it maintains balances. The contract may have an administrator, minter role or ownership mechanism controlling special functions, but ordinary token units belong economically to the accounts whose balances contain them. Allowances support contracts such as exchanges and lending protocols. If Alice approves a lending contract to spend 100 tokens, the lending contract can call transferFrom within the approved limit. This creates a delegated authority relationship: Remaining allowance = Approved allowance − Amount already spent The expression assumes that all spending is valid, that amounts use the token’s smallest unit, and that the result cannot become negative. Implementations must prevent arithmetic underflow and must define how an allowance is changed. A well-known integration risk occurs when a user changes a non-zero allowance directly to another non-zero allowance. Depending on transaction ordering, a spender may use the old allowance before the new one is recorded. Applications may mitigate this by first setting the allowance to zero, using increase/decrease allowance functions where available, or using signature-based approval mechanisms. The decimals value is a display convention, not a change to the underlying integer ledger. If a token uses 18 decimals, a displayed balance of 1 token is commonly represented internally as 10¹⁸ smallest units. The contract must perform calculations in integer units and user interfaces must format them carefully. Minting and burningMinting creates new units, while burning destroys units. A common supply identity is: Total supply = Initial supply + Cumulative mints − Cumulative burns This identity applies when all supply-changing operations are correctly recorded and no exceptional mechanism creates or destroys units outside the contract’s accounting. Minting should be restricted through roles, governance or clearly defined rules. Burning may be initiated by holders, a token contract, a redemption contract or an administrator, depending on the economic design. Unlimited or poorly governed mint authority can dilute existing holders. Conversely, an irreversible fixed supply may prevent necessary upgrades or redemptions. The design should document who may mint, under what conditions, whether limits exist, and how users can verify these rules. 3. Non-Fungible Tokens: ERC-721-Style DesignERC-721-style tokens identify each asset using a unique tokenId. The contract records the owner of each identifier and normally provides: ownerOf(tokenId);balanceOf(owner);transferFrom and safer transfer functions;approve for one token identifier;setApprovalForAll for an operator to manage all tokens of an owner;- metadata functions such as
tokenURI(tokenId).
Ownership is therefore identifier-specific. A user may own token 17 but not token 18, even though both were minted by the same contract. The token identifier does not automatically prove legal ownership of an off-chain object; it proves the on-chain relationship recorded by the contract. The safer transfer pattern checks whether the receiving address is a contract and, if so, whether it can properly receive the token. Without such checks, a token can be sent to a contract that has no method to return or manage it, creating an effectively inaccessible asset. MetadataMetadata describes an asset. It may include a name, description, image, attributes, creator information or external references. A URI can point to a central web server, content-addressed storage, or data stored directly on-chain. Each approach involves trade-offs: | Storage approach | Strength | Limitation |
|---|
| Centralised server | Easy to update and inexpensive | Server failure or alteration risk | | Content-addressed storage | Content changes produce a different address | Requires reliable pinning and retrieval | | On-chain metadata | Strong persistence and composability | Higher deployment and update cost |
A token contract should specify whether metadata is immutable, updateable by an administrator, or governed through a defined process. An image stored on a server is not made permanent merely because its URI is recorded on a blockchain. 4. Multi-Token Standards: ERC-1155-Style DesignAn ERC-1155-style contract manages multiple token types under one contract address. A token identifier may represent a fungible currency, a semi-fungible item such as a ticket class, or a unique collectible. The balance is indexed by both account and token identifier. The main advantages are batch transfers, shared logic and reduced deployment overhead. A game, for example, may transfer ten item types in a single transaction. However, the application must define the meaning of each identifier and must not assume that all identifiers have identical transfer, metadata or supply characteristics. Batch operations increase efficiency but also increase complexity. Contracts must ensure that arrays of identifiers and amounts have compatible lengths, that each item is authorised, and that receiver callbacks are handled correctly. A failed condition should normally revert the entire operation unless the standard explicitly supports another behaviour. 5. Approvals, Operators and Transfer SecurityApprovals are essential for composability but create a major attack surface. A user who grants unlimited approval to a malicious or compromised contract may lose all approved tokens. Wallet interfaces should clearly display the spender, asset and amount. Users should periodically revoke unnecessary approvals. Common risks include: - approving a counterfeit token or malicious spender;
- signing an unclear permit message;
- confusing a token contract with a trusted marketplace;
- using unlimited approvals when a limited amount is sufficient;
- failing to check chain identifiers and contract addresses;
- incorrectly handling tokens that do not return the expected Boolean value;
- reentrancy during token callbacks or external transfers.
A robust application uses audited libraries, checks return values, follows checks-effects-interactions, applies reentrancy protection where appropriate, and tests adversarial cases. Auditing does not eliminate economic or governance risk; it only reduces certain classes of implementation risk. 6. Royalties and Economic RightsNFT royalty mechanisms usually communicate a suggested payment to a creator when an asset is sold. A royalty standard can expose a recipient and a royalty amount, often calculated as a fraction of the sale price. It does not automatically force every marketplace or transfer to pay that amount. Enforceability depends on marketplace behaviour and, in some systems, transfer restrictions. A generic royalty calculation is: Royalty payment = Sale price × Royalty rate If the sale price is 2 ether and the royalty rate is 5%, the royalty is 0.1 ether. The formula assumes that the rate is represented consistently—for example, 500 basis points out of 10,000—and that the sale price and payment currency are clearly defined. Creators and buyers should distinguish between contractual royalty rules, marketplace policy and legal rights. A token’s royalty field alone does not establish copyright ownership, resale rights or an enforceable licence. 7. DeFi Building BlocksDeFi protocols replace or supplement intermediaries with contracts, tokens and transparent rules. Their main components are balances, collateral records, pricing mechanisms, interest calculations, liquidity pools, time locks and governance. Decentralised exchangesAn automated market maker (AMM) allows users to trade against a liquidity pool rather than a traditional order book. In the constant-product model, reserves of two assets satisfy: x × y = k Here, x and y are the quantities of the two reserve assets, and k is treated as constant during an idealised swap before fees. The formula assumes a two-asset pool, no external price intervention and an idealised transaction. Fees, rounding, arbitrage and price impact mean that real implementations require additional equations. If a trader adds asset X to a pool, the amount of asset Y received is determined by the new reserve relationship, less any fee. A large trade relative to pool reserves produces greater price impact, so liquidity providers face both fee income and inventory risk. Oracle-based or order-book systems use different mechanisms and risks. Lending and collateralA lending protocol records supplied assets, borrowed assets, collateral and health conditions. A simplified collateral ratio is: Collateral ratio = Value of collateral ÷ Value of debt Both numerator and denominator must use the same valuation currency and a defined price source. Liquidation may occur when the ratio falls below a protocol threshold. In practice, protocols include liquidation bonuses, close factors, oracle safeguards, interest accrual and sometimes multiple collateral factors. Price oracles are critical. A manipulated or stale price may allow under-collateralised borrowing or unfair liquidation. Reliable designs use decentralised data sources, update thresholds, time-weighted prices, circuit breakers and clear fallback procedures. EscrowAn escrow contract holds an asset until predetermined conditions are satisfied. A basic sequence is: - Buyer deposits payment.
- Seller deposits or identifies the asset.
- The contract records the conditions and deadlines.
- An authorised release, mutual confirmation or dispute process triggers settlement.
- The contract refunds or transfers assets according to the outcome.
Escrow does not remove the need to define subjective facts. If delivery quality cannot be verified on-chain, an oracle, arbitrator or trusted party may be required. StakingStaking contracts may lock tokens to secure a network, participate in governance or earn protocol rewards. A reward system should specify the reward source, emission schedule, eligibility, lock period and withdrawal rules. Apparent annual percentage yields can be misleading when token prices, emissions or compounding assumptions change. A simple proportional reward allocation is: User reward = Total distributable reward × (User eligible stake ÷ Total eligible stake) This assumes a single measurement period, proportional allocation and no time weighting. Real contracts commonly calculate user share over time, so deposits and withdrawals must be accounted for accurately. Decentralised autonomous organisationsA DAO combines token-based participation with proposals, voting and execution rules. Core components include proposal creation, voting eligibility, quorum, approval thresholds, timelocks and an executor. Governance tokens may represent voting power, but token voting can concentrate influence among wealthy holders or delegated representatives. A timelock gives participants time to inspect an approved action before execution. Emergency powers can protect users during an exploit but create centralisation and trust risks. Governance design must therefore balance responsiveness, transparency, resistance to capture and technical safety. 8. Applied Case: Illustrative Community Energy DAOBackgroundConsider a fictional community energy cooperative that installs solar equipment and issues tokens representing participation in its programme. It uses a fungible token for voting and rewards, NFTs for individual equipment certificates, and an escrow contract for supplier payments. ProblemThe cooperative must distribute rewards fairly, prevent unauthorised minting, record equipment ownership, and release supplier funds only after installation is verified. It also needs a governance process for maintenance and future expansion. Approach and solutionThe fungible token contract uses role-based minting. Rewards are distributed according to measured energy contributions, while a capped emission schedule limits dilution. The NFT contract assigns each equipment certificate a unique identifier and stores a content-addressed metadata reference. The escrow contract holds payment and releases it when an independent verifier submits an approved completion record. A DAO contract permits token holders to submit proposals. Proposals require a minimum participation level, pass only when quorum and approval conditions are met, and execute after a timelock. An emergency guardian may pause transfers temporarily, but cannot permanently withdraw cooperative funds without a separate governance action. Analysis and outcomeThe design separates concerns: token accounting, asset identification, payment settlement and governance are not placed in one monolithic contract. This reduces conceptual complexity and permits focused testing. Nevertheless, the system remains dependent on the energy meter, verifier and metadata storage. If the verifier submits false information, the blockchain will faithfully preserve an incorrect decision. Learning points- Token standards solve interface and accounting problems, not all real-world trust problems.
- Administrative roles must be visible, limited and governed.
- Oracles and off-chain data require explicit assumptions and dispute procedures.
- Timelocks, pause controls and independent audits improve operational resilience.
- Legal rights associated with equipment or energy revenue require agreements beyond token code.
9. Governance, Regulation and EthicsToken systems may raise questions about securities, payment services, consumer protection, anti-money-laundering controls, taxation, intellectual property and data protection. Classification depends on jurisdiction and facts; naming an asset a “utility token” does not determine its legal status. Ethically, designers should disclose risks, avoid misleading yield claims, protect users from deceptive approvals, and consider accessibility and unequal participation. Privacy is also important: public transaction histories can reveal financial behaviour. Personal data should not be placed on-chain without a clear legal and technical justification. AI can assist with code review, anomaly detection and user support, but generated code must not be deployed without expert review, testing and audit. AI systems may produce plausible but insecure contract logic or misunderstand token standards. Human accountability remains essential. 10. Professional Best PracticesA competent token or DeFi project should: - define the economic and legal purpose before selecting a standard;
- use established interfaces and carefully reviewed libraries;
- specify minting, burning, pausing and upgrade authority;
- limit approvals and explain them clearly to users;
- test boundary conditions, reentrancy, access control and failed transfers;
- use independent audits and public documentation;
- protect oracle inputs and monitor abnormal activity;
- separate contracts by responsibility where practical;
- introduce timelocks and emergency procedures appropriately;
- publish contract addresses, deployment chains and administrative roles;
- plan migration and recovery procedures before launch.
Chapter SummaryFungible tokens represent interchangeable units and are commonly implemented through ERC-20-style balances and allowances. Non-fungible tokens identify distinct assets through token identifiers, while multi-token standards manage many asset types in one contract. Minting and burning determine supply, approvals enable composability but create authority risk, and metadata connects on-chain identifiers with descriptive information. Royalties may express creator compensation but are not universally enforceable. DeFi applications combine token standards with pools, collateral records, oracles, escrow conditions, staking rules and governance. AMMs, lending protocols, DAOs and related systems automate economic functions but remain exposed to code defects, oracle manipulation, governance capture, liquidity risk and legal uncertainty. Sound design requires technical controls, transparent governance, careful testing and an honest distinction between blockchain records and off-chain rights. Key TermsToken: A blockchain-recorded representation of value, rights or access. Fungibility: Interchangeability of units with equivalent properties. Non-fungible token: A uniquely identifiable blockchain token. ERC-20: A widely used interface for fungible Ethereum-compatible tokens. ERC-721: A widely used interface for unique non-fungible tokens. ERC-1155: A multi-token interface supporting many token types. Allowance: The amount a spender is authorised to transfer from an owner. Operator: An address authorised to manage tokens on behalf of another account. Minting: The creation of new token units. Burning: The destruction of token units. Metadata: Descriptive information associated with a token. Royalty: A payment intended for a creator on a qualifying resale. AMM: An automated market maker using programmed liquidity and pricing rules. Liquidity pool: Contract-held reserves used to facilitate exchange. Oracle: A mechanism supplying external data to a smart contract. Collateral: Assets pledged to secure an obligation. Escrow: Contractual holding of assets until specified conditions occur. Staking: Locking or committing assets for security, governance or rewards. DAO: A decentralised organisation governed partly through smart contracts and voting. Timelock: A delay between approval and execution of a governance action. Review QuestionsShort Answer Questions- What is the principal difference between fungible and non-fungible tokens?
- What purpose does an ERC-20 allowance serve?
- Why is metadata storage an important design decision for NFTs?
- What is the role of an oracle in a lending protocol?
- Why are timelocks used in DAO governance?
Long Answer Questions- Compare ERC-20, ERC-721 and ERC-1155-style standards, including their data models, advantages and risks.
- Explain how minting, burning and administrative permissions affect token supply and user trust.
- Describe the operation of an automated market maker and discuss price impact and liquidity-provider risk.
- Analyse the main security risks associated with approvals, operators and token callbacks.
- Explain how a collateralised lending protocol uses valuations, collateral ratios and liquidation mechanisms.
Analytical / Application Questions- Design a token architecture for a digital game containing currency, unique characters and batches of interchangeable items. Justify the standards and approval mechanisms selected.
- A DAO plans to distribute rewards according to users’ eligible stake over time. Identify the accounting data and safeguards needed to prevent unfair rewards or manipulation.
- Evaluate the community energy DAO case. Identify two on-chain risks, two off-chain dependencies and a governance improvement for each category.
Multiple Choice Questions with AnswersQuestion 1Which token model is most appropriate when every unit is intended to be interchangeable with every other unit? A. ERC-20-style fungible token B. ERC-721-style non-fungible token C. Unique NFT with a separate identifier D. Metadata-only record Correct Answer: A. ERC-20-style fungible token Question 2What does an ERC-20 allowance primarily authorise? A. A spender to transfer tokens from an owner within a specified limit B. Anyone to mint unlimited tokens C. A marketplace to change token metadata D. A wallet to reverse completed transactions Correct Answer: A. A spender to transfer tokens from an owner within a specified limit Question 3Which statement about NFT royalties is most accurate? A. They are automatically enforceable on every blockchain transfer B. They usually communicate a suggested creator payment whose enforcement depends on implementation and marketplace behaviour C. They transfer copyright to the marketplace D. They prevent an NFT from being resold Correct Answer: B. They usually communicate a suggested creator payment whose enforcement depends on implementation and marketplace behaviour Question 4In the idealised constant-product AMM model, which relationship is maintained during a swap before fees and rounding? A. x + y = k B. x − y = k C. x × y = k D. x ÷ y = k Correct Answer: C. x × y = k Question 5What is the principal function of collateral in a lending protocol? A. To guarantee that token metadata is permanent B. To secure a borrower’s obligation and support liquidation if required C. To eliminate all oracle risk D. To make every loan interest-free Correct Answer: B. To secure a borrower’s obligation and support liquidation if required Question 6Why is a receiving-contract check useful during NFT transfers? A. It increases the token’s royalty rate B. It confirms that a contract recipient can handle the token, reducing accidental loss C. It automatically verifies copyright ownership D. It prevents the sender from paying gas Correct Answer: B. It confirms that a contract recipient can handle the token, reducing accidental loss Question 7If a token has an initial supply of 1,000 units, 250 units are minted and 100 units are burned, what is the resulting total supply? A. 850 units B. 1,150 units C. 1,250 units D. 1,350 units Correct Answer: B. 1,150 units Question 8What is a common purpose of a governance timelock? A. To delay approved actions so participants can inspect or respond before execution B. To hide proposals from token holders C. To guarantee that a proposal passes D. To convert NFTs into fungible tokens Correct Answer: A. To delay approved actions so participants can inspect or respond before execution Question 9Which component supplies external information such as an asset price to a smart contract? A. Allowance B. Oracle C. Burn function D. Token identifier Correct Answer: B. Oracle Question 10What is a major advantage of an ERC-1155-style multi-token contract? A. It can support multiple token types and batch transfers in one contract B. It guarantees that all tokens are legally securities C. It eliminates the need for access control D. It makes every token unique Correct Answer: A. It can support multiple token types and batch transfers in one contract
|