AI coding assistants are useful for Solidity in the same way they are useful elsewhere: they scaffold boilerplate, explain unfamiliar code, suggest tests and spot typos quickly. They are also a risky fit, because smart contracts are unforgiving. Code is public, it holds value, and often it can't be patched after deployment. A bug that would be a minor incident in a web app can mean permanently lost funds.
This post is a practical guide to using assistants on Solidity projects without letting plausible-looking code become your security model. It includes two real bugs, with tests that exploit them and the fixes. I wrote these bugs by hand: they are common mistakes made by people and tools alike, and I'm not claiming any particular product writes them. The lesson is about your process, not about blaming a tool.
What assistants are good for here
- Scaffolding. Boilerplate such as an ERC-20 or ERC-721 skeleton that you'd otherwise copy from documentation, as long as you then compare it with the library's current API. OpenZeppelin 5 changed several things from version 4 (for example
Ownabletakes an initial owner, and token hooks became_update), and an assistant trained on older code can suggest outdated patterns that don't even compile. - Explaining code. Paste a function and ask what it does and which assumptions it makes. Useful for reading, and always worth checking against the source.
- Drafting tests. Ask for edge cases you haven't thought of: zero amounts, the maximum value, reentrancy, a caller that isn't the owner.
- Reviewing a diff. As a second reader before the human one, not instead of it.
Why review matters more than usual
Three things make the stakes in Solidity different. Deployed code is typically immutable. The environment is adversarial: anyone can call your public functions, with any contract as their caller. And the failures are silent: a contract with a logic bug compiles, deploys and passes the happy-path test. Plausible code is exactly the dangerous kind, because it looks right to a quick reviewer. Let me show two examples.
Bug 1: authorising with tx.origin
The wallet below sends Ether when called by its owner. It checks tx.origin == owner, which looks natural: "was this transaction started by the owner?" The problem is that tx.origin is the account that started the whole call chain, even if the owner's call went through another contract on the way. The Solidity documentation's security chapter is blunt about it: never use tx.origin for authorization.
AssistantBugs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// BUG 1 (VULNERABLE): authorises with tx.origin, which is whoever started the transaction.
contract TxOriginWallet {
address public owner;
constructor() payable {
owner = msg.sender;
}
function transferTo(address payable to, uint256 amount) external {
require(tx.origin == owner, "not owner");
(bool ok, ) = to.call{value: amount}("");
require(ok, "send failed");
}
}
/// Fix: authorise the direct caller.
contract SafeWallet {
address public owner;
constructor() payable {
owner = msg.sender;
}
function transferTo(address payable to, uint256 amount) external {
require(msg.sender == owner, "not owner");
(bool ok, ) = to.call{value: amount}("");
require(ok, "send failed");
}
}
/// A contract the owner is tricked into sending ETH to ("claim your airdrop").
contract Phisher {
TxOriginWallet public immutable target;
address payable public immutable thief;
constructor(TxOriginWallet target_) {
target = target_;
thief = payable(msg.sender);
}
receive() external payable {
target.transferTo(thief, address(target).balance);
}
}
interface IWallet {
function transferTo(address payable to, uint256 amount) external;
}
/// A token that signals failure by returning false instead of reverting.
/// ERC-20 allows this, and some real tokens behave this way.
contract FalseReturnToken {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function mint(address to, uint256 amount) external { balanceOf[to] += amount; }
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
if (balanceOf[from] < amount || allowance[from][msg.sender] < amount) return false;
allowance[from][msg.sender] -= amount;
balanceOf[from] -= amount;
balanceOf[to] += amount;
return true;
}
function transfer(address to, uint256 amount) external returns (bool) {
if (balanceOf[msg.sender] < amount) return false;
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
return true;
}
}
/// BUG 2 (VULNERABLE): ignores the return value, so a failed transfer still credits the user.
contract BadDeposits {
mapping(address => uint256) public credit;
function deposit(IERC20 token, uint256 amount) external {
token.transferFrom(msg.sender, address(this), amount); // return value ignored
credit[msg.sender] += amount;
}
}
/// Fix: SafeERC20 reverts when the token reports failure.
contract GoodDeposits {
using SafeERC20 for IERC20;
mapping(address => uint256) public credit;
function deposit(IERC20 token, uint256 amount) external {
token.safeTransferFrom(msg.sender, address(this), amount);
credit[msg.sender] += amount;
}
}
In the file, TxOriginWallet is the vulnerable version and SafeWallet authorises msg.sender, the direct caller. Phisher is a contract that the owner is tricked into paying (an "airdrop claim"); in its receive function it calls the wallet. The wallet sees tx.origin equal to the owner and sends everything to the thief.
The tests demonstrate both sides. The first sends a 1 wei payment from the owner to the phisher and checks that the wallet's 3 ETH is gone. The second runs the same attack against the safe wallet, where the call reverts and the balance stays at 3 ETH. They passed on Hardhat's simulated network.
Bug 2: ignoring an ERC-20 return value
The ERC-20 standard says transfer and transferFrom return a boolean. Some tokens signal failure by returning false instead of reverting. BadDeposits calls transferFrom, ignores the result, then credits the user. If the transfer failed, the user is credited for tokens that never arrived and can later withdraw something real. This pattern is easy for a human or a tool to write because the line looks complete.
The fix is OpenZeppelin's SafeERC20. Its documentation describes wrappers that revert on failure when the token returns false, and that also handle tokens that return nothing at all. GoodDeposits uses safeTransferFrom. The tests show the bad contract giving 100 units of credit while holding zero tokens, and the good one reverting with OpenZeppelin's SafeERC20FailedOperation error.
AssistantBugs.ts
import { expect } from "chai";
import { network } from "hardhat";
const { ethers } = await network.create();
describe("tx.origin authorisation", function () {
it("lets a phishing contract drain the wallet when the owner interacts with it", async function () {
const [owner, thief] = await ethers.getSigners();
const wallet = await ethers.deployContract("TxOriginWallet", [], { value: ethers.parseEther("3"), from: owner.address });
const phisher = await ethers.deployContract("Phisher", [await wallet.getAddress()], thief);
const before = await ethers.provider.getBalance(thief.address);
// The owner is lured into sending a tiny payment to the phisher's contract.
await owner.sendTransaction({ to: await phisher.getAddress(), value: 1n });
expect(await ethers.provider.getBalance(await wallet.getAddress())).to.equal(0n);
expect(await ethers.provider.getBalance(thief.address)).to.be.gt(before);
});
it("msg.sender authorisation is not fooled", async function () {
const [owner, thief] = await ethers.getSigners();
const safe = await ethers.deployContract("SafeWallet", [], { value: ethers.parseEther("3"), from: owner.address });
// Point the same phishing logic at the safe wallet (cast through the shared function selector).
const phisher = await ethers.deployContract("Phisher", [await safe.getAddress()], thief);
await expect(owner.sendTransaction({ to: await phisher.getAddress(), value: 1n })).to.revert(ethers);
expect(await ethers.provider.getBalance(await safe.getAddress())).to.equal(ethers.parseEther("3"));
});
});
describe("ignored ERC-20 return values", function () {
async function setup() {
const [user] = await ethers.getSigners();
const token = await ethers.deployContract("FalseReturnToken");
const bad = await ethers.deployContract("BadDeposits");
const good = await ethers.deployContract("GoodDeposits");
return { user, token, bad, good };
}
it("BadDeposits credits a deposit even though no tokens moved", async function () {
const { user, token, bad } = await setup();
// The user has no tokens and no allowance, so transferFrom returns false.
await bad.deposit(await token.getAddress(), 100n);
expect(await bad.credit(user.address)).to.equal(100n); // phantom credit
expect(await token.balanceOf(await bad.getAddress())).to.equal(0n);
});
it("GoodDeposits reverts instead", async function () {
const { token, good } = await setup();
await expect(good.deposit(await token.getAddress(), 100n))
.to.be.revertedWithCustomError(good, "SafeERC20FailedOperation");
});
});
A review checklist for AI-generated contracts
When an assistant gives me Solidity, I read it against a short list before I run anything:
- Who can call this? Every external function needs an explicit answer. Look for missing access control and for authorisation based on
tx.origin. - What happens to external calls? Are return values checked? Is state updated before the call (checks-effects-interactions)? Could the callee re-enter?
- Which library version is this written for? Compare imports and constructors with the current documentation. Hallucinated function names and outdated signatures are common failure modes of any text generator.
- Is it using a library or hand-rolling? Prefer audited libraries for tokens, access control and math. Treat "custom implementation" of any of them as a red flag.
- What are the unchecked assumptions? Token decimals, fee-on-transfer tokens, rebasing tokens, zero addresses, a price oracle that can be manipulated.
- Where are the tests for the sad paths? Not just "mint works", but "a stranger can't mint" and "this reverts for zero".
Turn every review finding into a test
The tests above are the most important part. A written bug description fades; a failing test doesn't. When you find a flaw in generated code, write the exploit as a test first, watch it succeed against the bad version, then apply the fix and watch it fail. Keep both in the repository. Assistants are also quite good at drafting these exploit tests once you describe the attack, so use them for that, and then read what they wrote.
Use tools that don't rely on your attention
- Run the compiler with warnings treated seriously. The Solidity docs recommend taking warnings seriously.
- Measure test coverage. Hardhat 3 supports
--coverage. Uncovered branches are where bugs hide. In my ERC-20 example, coverage showed 100% line and statement coverage for the token. - Add a static analyzer to your CI as a second opinion. It will find some of what you miss, and will miss some of what you find.
- Keep contracts small and modular, built from well-known pieces. Less code, less to review.
What to never delegate
- Final security sign-off. An assistant's "looks good" is not an audit. For anything holding real value, get an independent review; the audit preparation checklist covers how to be ready.
- Secrets. Never paste private keys or seed phrases into any chat or tool, whatever the assistant promises.
- Deployment decisions. Constructor arguments, owners and upgrade rights deserve a human double-check on a testnet first.
The short version
Treat an AI assistant like a fast junior colleague: great at producing a first draft, wrong in confident ways, and in need of review. For Solidity, that review should be driven by questions about callers, external calls and library versions, and every finding should become a test that stays in your repository.
Building a smart contract project?
I write and review Solidity, Hardhat and dApp front ends, with tests for the failure paths. If you'd like help preparing a contract for review, get in touch.
See services Get in touchWhat I ran this against
- I wrote the two bugs below by hand. They are classic mistakes that appear in tutorials and in human-written code, and I am not claiming that any specific assistant produced them. I did not run an experiment to measure how often assistants write insecure Solidity, so I make no such claim.
- Hardhat 3.22.0 (Mocha + ethers template), @openzeppelin/contracts 5.6.1, ethers 6.17.0, solc 0.8.34, Node.js 24.22.1, run on 17 November 2026 on Hardhat's in-process simulated network. In the full project, 38 tests passed. The ones shown here are two sets of two tests each: one demonstrating the bug, one showing the fix. Nothing was deployed to a testnet or mainnet, and the contracts are teaching examples that have not been audited.
Sources checked
- Solidity documentation, Security Considerations: "Never use tx.origin for authorization", with the attack wallet example: docs.soliditylang.org.
- OpenZeppelin Contracts 5.x, ERC-20 utilities:
SafeERC20wraps ERC-20 operations so they revert on failure when a token returns false, and also supports tokens that return no value: docs.openzeppelin.com.