AI 资讯
Reading an Audit Contest Scope Like an Auditor: Invariants First, Code Second
The first time I audited seriously, I opened the biggest contract in the repo and started reading line one. Two hours later I had a headache and zero findings. I had memorized how the code worked without ever asking what it was supposed to guarantee. That is backwards, and it took me a while to unlearn it. Now I do not read Solidity first. I read the scope, and before I look at a single function body I write down what must always be true. Bugs are violations of those truths. If you do not know the truths, you are just admiring the code. Step one: write the invariants before you read An invariant is a property the protocol claims will always hold, no matter who calls what in what order. For a contest, I start with money and control, because that is where severity lives. Two questions cover most of it: Who can move funds, and under what conditions? What must always hold about the accounting? For a lending-pool-shaped protocol my starting invariant list looks like this, written in plain language before I care how any of it is implemented: The sum of all user deposits minus all borrows equals the pool's available liquidity plus outstanding debt. Accounting must reconcile. A user can only withdraw up to their own balance, never more, never someone else's. A position can only be liquidated when it is actually under the health threshold. Interest accrues monotonically, it never goes backwards in a way that lets someone repay less than they owe. Only the borrower, or a liquidator on an unhealthy position, can reduce a debt. Nobody except governance can change interest rate parameters or the oracle. Notice none of that mentions a function name. These are the promises. Now my job for the rest of the contest is simple to state: find an ordering of calls that breaks one of these. Step two: map the external entry points Funds do not teleport. Something has to be called from outside for state to change. So I list every externally reachable function, because the attack surface is
AI 资讯
Shipping a Solidity contract to mainnet? Do this 20-minute self-check first
You built something. Tests pass. You're days from mainnet. Before you either skip security entirely (please don't) or spend weeks lining up a full audit, here's a self-check you can run in 20 minutes that catches the mistakes I see most often in first-time deployments. I run security reviews for small and new protocols, and the same handful of issues come up again and again. None of these need a tool — just your eyes and this list. 1. Who can call what? Open every external / public function that moves funds, mints, pauses, or upgrades. For each, ask: should a random address be able to call this? If not — is there an onlyOwner / onlyRole / require(msg.sender == ...) guarding it, in the function itself or in every internal function it calls? The classic bug isn't a missing modifier. It's a function that looks unguarded but delegates to a guarded internal one (fine), or one that looks guarded but the guard is in a branch a caller can skip (not fine). Trace the call, don't trust the signature. 2. The first-depositor trap (if you have a vault) If you mint shares from deposits (ERC-4626 or anything share-based), the first depositor can sometimes donate assets directly to the contract to inflate the share price, so the second depositor rounds down to zero shares and loses funds. Fix: virtual shares, a dead-shares mint at deploy, or a minimum-liquidity lock. OpenZeppelin's ERC-4626 handles this out of the box — a hand-rolled vault usually doesn't. 3. Reentrancy — but only the real kind Not every external call is reentrancy. It's a bug when an attacker-controlled call can re-enter and corrupt shared storage before you've updated it. Quick checks: Do you update state before the external transfer (checks-effects-interactions)? Is there a nonReentrant on functions that move value? Is the call target a trusted, immutable contract, or an arbitrary address the attacker supplies? A call to a protocol-owned contract, or a memory /local variable written after the call, is usually not
AI 资讯
I almost reported a critical bug that didn't exist. One constant saved me.
Last week I was reviewing the staking engine of a protocol before its mainnet launch. Deep in a 1,400-line contract, I found what looked like a serious bug. The reward math multiplied three values before dividing: uint256 delta = (lot.amount * rBase * midpointRate) / (RAY * RAY); Multiply-before-divide. If that intermediate product overflows uint256 , the whole epoch settlement reverts — and since every stake , withdraw , and setStake runs it, the post's funds get permanently frozen . That's a High-severity, fund-locking DoS. I had the finding half-written. lot.amount can reach 10M tokens ( 1e25 ). rBase grows with elapsed time. midpointRate can hit RAY . Multiply those and you blow past 2^256 ... I was ready to send it. Then I did the one thing that separates a real audit from false-positive spam: I checked the actual constants before writing the claim. uint256 private constant RAY = 1e18; // I'd assumed 1e27 RAY was 1e18 , not the 1e27 I'd been carrying in my head. And the interest rate had a hard cap — MAX_RATE_MAX_RAY = 5e18 , enforced even against a fully-captured timelock. I ran the numbers with the real values: For that multiplication to overflow, the protocol would need to go 2.3 × 10¹⁵ years without a single state update. Not reachable. The bug didn't exist. I deleted the finding. Why this matters more than the bug would have If I'd sent that report, here's what happens: the team's engineer clones the repo, plugs in the real constants, and realizes in ten minutes that I flagged an overflow that can't happen. Every other finding in my report now gets read with a raised eyebrow. My credibility — the entire product — is gone. This is the dirty secret of automated smart-contract auditing: the bottleneck isn't finding issues. It's not drowning the real ones in false positives. Anyone can run a scanner and paste 40 "criticals." A team that has to triage 40 flags to find the 2 that matter will — correctly — stop trusting you. The bar I hold: zero false positives o
AI 资讯
The Hidden Technical Problems That Break DAOs in Production
Decentralized Autonomous Organizations are often presented as simple governance systems: token holders create proposals, vote, and execute decisions on-chain. In practice, building a production-grade DAO is far more difficult. A DAO is not only a smart contract. It is a distributed coordination system that combines governance logic, treasury security, token economics, identity, off-chain infrastructure, and human decision-making. A failure in any one of these layers can compromise the entire organization. Below are some of the most important technical problems DAO developers must solve. 1. Governance Attacks Through Borrowed Voting Power Many DAOs calculate voting power based on the number of governance tokens held at a specific moment. This creates a serious attack surface when tokens can be borrowed through lending protocols or flash loans. An attacker may temporarily acquire a large amount of voting power, submit or approve a malicious proposal, and return the borrowed assets shortly afterward. The standard defense is snapshot-based voting power. Instead of checking a user’s current balance, the governance contract reads historical balances from a previous block. function getVotes( address account, uint256 blockNumber ) public view returns (uint256) { return token.getPastVotes(account, blockNumber); } However, snapshots alone do not solve every problem. Developers should also consider proposal delays, minimum token-holding periods, quorum requirements, and vote-delegation risks. 2. Dangerous Proposal Execution The most sensitive part of a DAO is usually the executor. A successful proposal may call arbitrary contracts, transfer treasury assets, upgrade protocols, or change governance parameters. If proposal calldata is incorrectly validated, a governance action can execute unintended operations. A DAO should clearly separate: Proposal creation Voting Proposal queuing Timelock execution Emergency cancellation Using a timelock gives token holders and security teams
AI 资讯
Chainlink Functions Is Serverless Compute With Oracle Guarantees. Here's the Full Request Lifecycle.
The mental model most people have is too simple "Chainlink Functions lets smart contracts call APIs." That's true the same way "Ethereum lets people send money" is true. Technically accurate, misses almost everything that makes the product interesting and almost everything that matters for security. Chainlink Functions is better understood as a decentralized serverless compute platform: arbitrary JavaScript runs across every node in a DON, each node executes independently, OCR aggregates the results, and the aggregated output gets delivered back to the consumer contract through a verified callback. The "API call" is just one of the things that JavaScript can do inside that environment. The DON consensus and the threshold-encrypted secrets model are what make it meaningfully different from a centralized API proxy. This is day 9 of the 28-day Chainlink architecture series. Today covers the full request lifecycle, every contract in the chain, how threshold encryption protects secrets without exposing them to any individual node, and the integration mistakes that come from misunderstanding how billing and callbacks actually work. The four contracts you need to understand Before tracing the full lifecycle, it helps to know exactly which contract does what. FunctionsRouter : the stable, immutable entry point for consumers. Manages subscriptions and authorized consumer contracts. Its interface doesn't change when the underlying implementation upgrades, consumer contracts call sendRequest here and only here. Also handles billing: estimates fulfillment cost at request time and finalizes it at response time. FunctionsCoordinator : the interface between the Router and the DON. Emits the OracleRequest event that DON nodes watch for. Handles fee distribution to transmitters via a fee pool. Inherits from OCR2Base , meaning the full OCR consensus machinery runs here. This contract can be upgraded independently of the Router, which is why the Router exists as a stable facade in fro
AI 资讯
Precision Loss and Rounding Exploits in Financial Smart Contracts
A smart contract does not need an overflow, reentrancy bug, or broken access-control check to lose money. Sometimes, the exploit is hidden inside an ordinary division: uint256 result = amount * rate / SCALE; The expression looks harmless. It may even produce the expected answer in every unit test. But financial smart contracts operate with integer arithmetic. Fractions are discarded, rounding direction changes who receives value, and an error of one unit can be repeated across thousands of transactions. In a financial protocol, rounding is not merely a mathematical implementation detail. Rounding is a value-transfer policy. Every division should therefore answer three questions: Which direction does the calculation round? Which party benefits from that direction? Can the rounding advantage be repeated or amplified? This article examines the most dangerous precision problems in Solidity and the engineering patterns used to prevent them. Solidity Does Not Have Native Fixed-Point Arithmetic Most financial formulas use fractions: interest = principal × rate × time fee = amount × fee percentage shares = assets × total shares ÷ total assets collateral value = token amount × oracle price Solidity primarily performs these calculations with integers. For unsigned integers: uint256 result = 5 / 2; The result is: 2 The fractional component is discarded. For positive values, this behaves like rounding down: 2.5 → 2 This appears insignificant until the result represents: vault shares; debt; collateral; protocol fees; interest; rewards; liquidation bonuses; exchange rates; token prices. The lost fraction does not disappear economically. One party receives less value, while another party retains the remainder. Precision Loss Is Not Always Small Consider a protocol calculating a percentage: function calculateFee( uint256 amount, uint256 feeBps ) public pure returns (uint256) { return amount * feeBps / 10_000; } For a 0.3% fee: amount = 100 feeBps = 30 fee = 100 × 30 ÷ 10,000 fee =
AI 资讯
General Token Economics: The Core System Behind a Sustainable Web3 Project
Token economics is not only about token price. It is about designing the rules, incentives, and long-term logic of a Web3 ecosystem. When people start building a Web3 project, they usually focus on the visible parts first. They think about the smart contract, the frontend, the wallet connection, the token launch, the whitepaper, and maybe the community. All of those are important. But there is one part that can decide whether the project survives or fails: Token economics. A project can have clean smart contracts, a nice UI, and strong marketing, but if the token economy is weak, the project can slowly collapse. Users may come only for rewards, early investors may dump, inflation may destroy value, and the token may lose its reason to exist. That is why token economics should not be treated as just a “crypto finance” topic. For developers and Web3 builders, token economics is closer to system design . It defines how value moves inside the ecosystem, how users are rewarded, how supply is controlled, how governance works, and how the project can grow without depending only on hype. What Is Token Economics? Token economics, often called tokenomics , means the design of how a token works inside a project. It answers questions like: Why does this token exist? Who receives the token? How is the token used? How many tokens will exist? How are rewards distributed? When can team and investor tokens unlock? How does the project treasury work? What creates real demand for the token? In simple words, token economics is the rule system behind a token. A token is not only something people buy and sell. In a real Web3 product, a token can be used for payments, staking, governance, access, rewards, collateral, or network fees. If the token has no clear role, it becomes only a speculative asset. That is dangerous because speculation can bring attention, but it cannot support a project forever. Why Developers Should Care Some developers think token economics is only for founders, eco
AI 资讯
A .NET Dinosaur in Web3. Day 18 - Automated Market Maker
🏦 Day 6 of 7: Building a Mini Uniswap in 80 Lines of Solidity Imagine a vending machine. It has 1,000 coffee beans and 1,000 coins. No menu, no cashier — just one iron rule: the product of the two numbers inside must never decrease. That's it! This is how Uniswap works — and this is what I built on Day 6, coming from .NET. Here's how, why it's elegant, and where you can step on a rake. Why an Order Book Doesn't Work on a Blockchain Traditional exchanges — Binance, NYSE, any CEX — run on an order book . Market makers post bids and asks. A matching engine pairs them. Millions of updates per second, all in a centralised database. In a blockchain, this is impossible. Transactions take 12 seconds. Every state change costs gas. Storing millions of constantly changing orders would eat all the profit before a single trade completes. Uniswap's solution: replace the order book with a liquidity pool — a smart contract holding two tokens — and replace the matching engine with pure math. Just a formula — below. x · y = k — The Formula That Broke Finance The Constant Product Invariant : x · y = k Where x is the reserve of Token0, y is the reserve of Token1, and k is a constant that must never decrease during swaps. When a trader sells Token0 into the pool, x increases. To keep k constant, y must decrease — the contract sends out Token1. The price is determined automatically by the ratio of reserves. Live example with numbers: Pool: 1,000 Token0, 1,000 Token1. k = 1,000,000. Trader sells 100 Token0: amountOut = (reserveOut × amountIn) / (reserveIn + amountIn) amountOut = (1000 × 100) / (1000 + 100) amountOut = 100,000 / 1,100 amountOut ≈ 90.9 Token1 The trader gets ~90.9, not 100. That gap is slippage — and it's not a bug. It's the formula protecting the pool. The more you buy relative to pool size, the worse your price gets. Naturally. Mathematically. After the swap: pool has 1,100 Token0 and ~909.1 Token1. k ≈ 1,000,000. Invariant holds. The Contract: SimpleAMM Three functions.