M07-L02 · Tokens Nfts And Ecosystem

Allowances and delegated transfers

Allowances and delegated transfers

Problem: Approve, transferFrom, allowance decrement, overspending prevention.

Model: Every public transaction changes a deterministic state machine. Distinguish token balances from native gas coin, transaction submission from finality, and contract permissions from off-chain operator policy.

BSC vs Ethereum: Both execute EVM-compatible contracts, but chain ID, native gas asset, RPC and network finality assumptions differ. ERC-20/BEP-20 interface compatibility does not move balances across networks.

Safety: Training implementations are intentionally minimal. For deployed tokens/NFTs prefer audited OpenZeppelin contracts, access control, testing and independent review.

Allowances and delegated transfers — executable lab

Bài toán → Vấn đề → Giải pháp

Approve, transferFrom, allowance decrement, overspending prevention. A centralized implementation cannot assume on-chain transfers and application accounting are automatically synchronized. Implement the contract with explicit validation, accounting and revert behavior.

Setup

  1. Install Foundry (forge --version) and Solidity compiler 0.8.24 (Foundry can download it when online).
  2. cd solution && forge build && forge test -vvv.
  3. Read src/AllowanceToken.sol and test/Lab.t.sol, then implement your own version in starter/.

Test plan

Expected output

forge test exits 0 with [PASS] for each included test. This is an expected result, not a verified runtime log.

Exercises

  1. Add tests for two distinct actors and zero addresses.
  2. Explain the trust boundary and identify missing production controls.
  3. Extend the contract using OpenZeppelin in a separate production-style branch.

Interview

Q: Why is an event not enough to prove final payment? A: Logs can be removed by chain reorg; verify receipt, confirmations/finality, chain ID, token address, and log identity. Q: Is this contract production ready? A: No; the examples omit standards compliance, audits, upgrade and operational controls.

Interview — Allowances and delegated transfers

  1. What does on-chain state guarantee? Deterministic execution under consensus, not truthful off-chain inputs.
  2. Can a transaction be considered final immediately? No; account for inclusion, reorg and chain-specific finality.
  3. Why avoid homegrown token contracts in production? Missing standard methods, approvals, security review and integration edge cases.