ethereum-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEthereum Development Skill
以太坊开发技能
Master Ethereum development including EVM internals, gas optimization, transaction mechanics, and client interactions.
精通以太坊开发,涵盖EVM内部原理、Gas优化、交易机制及客户端交互。
Quick Start
快速开始
python
undefinedpython
undefinedInvoke this skill for Ethereum development
调用该技能进行以太坊开发
Skill("ethereum-development", topic="gas", network="mainnet")
undefinedSkill("ethereum-development", topic="gas", network="mainnet")
undefinedTopics Covered
涵盖主题
1. EVM (Ethereum Virtual Machine)
1. EVM(以太坊虚拟机)
Understand the execution environment:
- Stack Machine: 256-bit words, 1024 depth
- Memory: Linear byte array, expansion costs
- Storage: Persistent key-value, 32-byte slots
- Opcodes: Costs, effects, gas consumption
了解执行环境:
- 栈式虚拟机:256位字长,栈深度1024
- 内存:线性字节数组,扩容产生成本
- 存储:持久化键值对,32字节插槽
- 操作码:成本、影响及Gas消耗
2. Gas Optimization
2. Gas优化
Reduce transaction costs:
- Storage Packing: Fit multiple values in one slot
- Calldata vs Memory: Choose efficiently
- Loop Optimization: Cache storage reads
- Custom Errors: Save gas on reverts
降低交易成本:
- 存储打包:将多个值放入单个插槽
- Calldata与Memory:高效选择使用场景
- 循环优化:缓存存储读取结果
- 自定义错误:在回滚时节省Gas
3. Transaction Mechanics
3. 交易机制
Master transaction lifecycle:
- Types: Legacy (0), Access List (1), EIP-1559 (2)
- Fee Estimation: Base fee, priority fee, max fee
- Nonce Management: Sequential ordering
- Receipts: Status, logs, gas used
精通交易生命周期:
- 交易类型:传统型(0)、访问列表型(1)、EIP-1559(2)
- 费用估算:基础费用、优先费用、最高费用
- Nonce管理:顺序排序规则
- 交易收据:状态、日志及Gas使用量
4. Client Interactions
4. 客户端交互
Work with Ethereum nodes:
- RPC Methods: eth_, debug_, trace_
- State Queries: Storage slots, code, balance
- Event Subscriptions: Filter logs, topics
与以太坊节点协作:
- RPC方法:eth_、debug_、trace_系列
- 状态查询:存储插槽、合约代码、账户余额
- 事件订阅:过滤日志、主题匹配
Code Examples
代码示例
Gas-Efficient Storage
高效Gas存储
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Optimized {
// Pack into single slot (32 bytes)
struct User {
uint128 balance; // 16 bytes
uint64 lastUpdate; // 8 bytes
uint32 nonce; // 4 bytes
bool active; // 1 byte
// 3 bytes padding
}
mapping(address => User) public users;
}solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Optimized {
// 打包进单个32字节插槽
struct User {
uint128 balance; // 16字节
uint64 lastUpdate; // 8字节
uint32 nonce; // 4字节
bool active; // 1字节
// 3字节填充位
}
mapping(address => User) public users;
}Read Storage Slot
读取存储插槽
typescript
import { createPublicClient, http, keccak256, encodePacked, pad } from 'viem';
import { mainnet } from 'viem/chains';
const client = createPublicClient({ chain: mainnet, transport: http() });
// Read mapping value: balances[address]
async function getBalance(contract: `0x${string}`, user: `0x${string}`) {
const slot = keccak256(encodePacked(['address', 'uint256'], [user, 0n]));
return await client.getStorageAt({ address: contract, slot });
}typescript
import { createPublicClient, http, keccak256, encodePacked, pad } from 'viem';
import { mainnet } from 'viem/chains';
const client = createPublicClient({ chain: mainnet, transport: http() });
// 读取映射值:balances[address]
async function getBalance(contract: `0x${string}`, user: `0x${string}`) {
const slot = keccak256(encodePacked(['address', 'uint256'], [user, 0n]));
return await client.getStorageAt({ address: contract, slot });
}EIP-1559 Transaction
EIP-1559交易
typescript
import { createWalletClient, http, parseEther } from 'viem';
const client = createWalletClient({ transport: http() });
const hash = await client.sendTransaction({
to: '0x...',
value: parseEther('0.1'),
type: 'eip1559',
maxFeePerGas: parseGwei('30'),
maxPriorityFeePerGas: parseGwei('2'),
});typescript
import { createWalletClient, http, parseEther } from 'viem';
const client = createWalletClient({ transport: http() });
const hash = await client.sendTransaction({
to: '0x...',
value: parseEther('0.1'),
type: 'eip1559',
maxFeePerGas: parseGwei('30'),
maxPriorityFeePerGas: parseGwei('2'),
});Gas Optimization Cheatsheet
Gas优化速查表
| Technique | Savings | Example |
|---|---|---|
| Storage packing | ~20k/slot | |
| Calldata vs memory | ~3/byte | Use |
| Unchecked math | ~80/op | |
| Custom errors | ~200+ | |
| Short-circuit | Variable | Cheap checks first |
| 技巧 | 节省量 | 示例 |
|---|---|---|
| 存储打包 | ~20000 Gas/插槽 | 单个插槽中存储 |
| Calldata替代Memory | ~3 Gas/字节 | 只读场景使用 |
| 无检查数学运算 | ~80 Gas/操作 | |
| 自定义错误 | ~200+ Gas | |
| 短路判断 | 变量 | 先执行低成本检查 |
Common Pitfalls
常见陷阱
| Pitfall | Issue | Solution |
|---|---|---|
| Storage in loops | Expensive reads | Cache in memory first |
| String storage | Uses multiple slots | Use bytes32 when possible |
| Zero value storage | Full refund gone | Don't rely on SSTORE refunds |
| 陷阱 | 问题 | 解决方案 |
|---|---|---|
| 循环中读取存储 | 读取成本高昂 | 先缓存到内存中 |
| 字符串存储 | 占用多个插槽 | 尽可能使用bytes32 |
| 零值存储 | 全额退款机制已取消 | 不要依赖SSTORE退款 |
Troubleshooting
故障排查
"Transaction underpriced"
"交易定价过低"
bash
undefinedbash
undefinedCheck current gas prices
查看当前Gas价格
cast gas-price --rpc-url $RPC
cast basefee --rpc-url $RPC
Set `maxFeePerGas` to at least 2x current base fee.cast gas-price --rpc-url $RPC
cast basefee --rpc-url $RPC
设置`maxFeePerGas`至少为当前基础费用的2倍。"Out of gas"
"Gas耗尽"
bash
undefinedbash
undefinedTrace transaction to find issue
追踪交易定位问题
cast run --trace $TX_HASH --rpc-url $RPC
undefinedcast run --trace $TX_HASH --rpc-url $RPC
undefined"Nonce too low"
"Nonce值过低"
bash
undefinedbash
undefinedGet current nonce
获取当前Nonce
cast nonce $ADDRESS --rpc-url $RPC
undefinedcast nonce $ADDRESS --rpc-url $RPC
undefinedCLI Commands
CLI命令
bash
undefinedbash
undefinedFoundry essentials
Foundry核心命令
forge build --sizes # Contract sizes
forge test --gas-report # Gas consumption
forge snapshot # Gas snapshots
cast storage $ADDR $SLOT # Read storage
cast call $ADDR "fn()" # Simulate call
undefinedforge build --sizes # 查看合约大小
forge test --gas-report # 生成Gas消耗报告
forge snapshot # 生成Gas快照
cast storage $ADDR $SLOT # 读取存储插槽
cast call $ADDR "fn()" # 模拟合约调用
undefinedTest Template
测试模板
solidity
contract GasTest is Test {
function test_GasOptimization() public {
uint256 gasBefore = gasleft();
target.optimizedFunction();
uint256 gasUsed = gasBefore - gasleft();
assertLt(gasUsed, 50000, "Too much gas used");
}
}solidity
contract GasTest is Test {
function test_GasOptimization() public {
uint256 gasBefore = gasleft();
target.optimizedFunction();
uint256 gasUsed = gasBefore - gasleft();
assertLt(gasUsed, 50000, "Gas使用量过高");
}
}Cross-References
交叉引用
- Bonded Agent:
02-ethereum-development - Related Skills: ,
solidity-developmentweb3-frontend
- 关联Agent:
02-ethereum-development - 相关技能: ,
solidity-developmentweb3-frontend
Version History
版本历史
| Version | Date | Changes |
|---|---|---|
| 2.0.0 | 2025-01 | Production-grade with viem, gas optimization |
| 1.0.0 | 2024-12 | Initial release |
| 版本 | 日期 | 变更内容 |
|---|---|---|
| 2.0.0 | 2025-01 | 生产级版本,集成Viem,新增Gas优化内容 |
| 1.0.0 | 2024-12 | 初始版本 |