跳到主要内容

56 篇文档带有标签「智能合约」

查看所有标签

Alternatives to OpenZeppelin

While OpenZeppelin is a widely used and respected smart contract library, there are alternative libraries that offer improved gas efficiency. Two notable examples are Solmate and Solady. These libraries have been tested and recommended by developers for their focus on gas optimization.

Bytes32 与 String

在 Solidity 中,不同的数据存储类型的选择可能会在合约操作时带来不同的 gas 消耗,尤其是存储或修改状态变量时。 以太坊虚拟机(EVM)对所有操作收取燃气费,选择使用bytes32或 string类型会影响这些消耗。

Efficient Initialization

In Solidity, how you initialize state variables can have a impact on the deployment cost of your contracts, specifically in terms of gas usage. The Ethereum Virtual Machine (EVM) requires gas for every operation, including the initialization of variables.

Efficient Use of Storage Pointers

This tutorial explores how using storage pointers instead of copying data to memory can result in substantial gas savings. Storage pointers allow developers to directly reference storage without unnecessary copying of data, leading to more efficient smart contract execution.

ERC20 转账问题

ERC20 转账问题是智能合约中常见的漏洞来源。 这些问题源于 ERC20 标准实现的不一致性,特别是不同代币如何处理转账函数的返回值。

ERC20Permit

在标准的 ERC20 中,用户通常需要执行两个单独的交易:

Flashloan Governance Attacks

闪电贷是一种强大的去中心化金融(DeFi)功能,允许用户在无需抵押的情况下借入资产,前提是他们在同一交易中归还借入的金额。 This feature has enabled unique financial strategies, but it also poses significant risks for governance systems.

Memory 与 Calldata

1. memory : 通常用于修饰函数参数和函数内的临时变量。 此类变量存储在内存中,不会永久保存在区块链上。

MethodId Sort Optimization

In the contract, all functions are organized into an array and systematically sorted by their MethodID, a unique identifier for each function. This organization not only streamlines the management of function calls but also facilitates quick access by imposing a structured order that can be efficiently searched during function executions.

msg.value in Loops

在开发智能合约时,安全性是最关键的考虑因素之一。 本教程将深入探讨一个常见但危险的模式:在循环中使用msg.value。 We'll explain why this is dangerous and provide some best practices to avoid related vulnerabilities.

Optimize Timestamps and Block Numbers

In Solidity, the way data is stored can significantly impact the gas costs associated with deploying and interacting with smart contracts. Gas costs can quickly become a major concern, especially in applications that handle a large number of transactions.

Predicting Contract Addresses Using Account Nonce

In Solidity, predicting contract addresses before their deployment can save substantial gas, especially when deploying interdependent contracts. This method eliminates the need for setter functions and storage variables, which are costly in terms of gas usage. We can use the LibRLP library from Solady to deterministically compute the addresses based on the deployer's nonce.

ResetVariable

在Solidity中,使用delete关键字来移除状态变量将其重置为其类型的默认值。 默认值根据数据类型而异:

Selector Collision Attack

The selector collision attack was one of the key reasons behind the hacking of the Poly Network cross-chain bridge.

SSTORE2

The cost of executing transactions on the Ethereum network can be very high, especially when interacting with smart contract storage using the SSTORE opcode. To mitigate these costs, developers can leverage alternative methods like SSTORE2 for more efficient data handling.

Tx Origin Attacks

A transaction origin attack is form of phising attack that can drain a contract of all funds.In Solidity, tx.origin retrieves the address of the transaction originator, distinguishing it from msg.sender.

Uint 类型 Gas 比较

在Solidity中,通常认为使用较小的整数类型如 uint8, uint16, uint32, uint64, uint128, 和 uint256 可能会因为它们的尺寸较小而节省gas。 然而,情况并非总是如此。

Unchecked

We know that before the Solidity version 0.8, it was necessary to manually import the SafeMath library to ensure data safety and avoid overflow, thereby preventing overflow attacks.

Using Payable

In Solidity, leveraging the payable keyword can be a subtle yet effective way to optimize gas usage. In this article, we explore two distinct scenarios where using payable can lead to gas savings: in constructors and admin functions.

Using selfdestruct in Constructors

In Solidity, optimizing gas usage is crucial for creating efficient smart contracts. One technique involves using the selfdestruct function within the constructor for contracts designed for one-time use. This approach can reduce gas costs by eliminating the contract from the blockchain once its purpose is fulfilled.

UUPS vs Transparent Proxy

When designing upgradable smart contracts, gas efficiency is critical for users interacting with the contract. There are two common upgrade patterns: UUPS (Universal Upgradeable Proxy Standard) and the Transparent Upgradeable Proxy. While both enable upgradability, the UUPS pattern is generally more gas efficient for users.

不当的输入验证

如果访问控制是关于控制谁调用函数,那么输入验证就是要控制他们用什么参数来调用合约。 这一般归结为忘记放置恰当的require语句。

价格操纵

Price manipulation poses a significant risk to smart contracts that utilize decentralized exchanges (DEXs) like Uniswap, where asset prices are influenced by the liquidity within trading pools. These pools are vulnerable to manipulation by well-resourced entities capable of altering market balances to artificially influence prices. Such manipulative actions can severely undermine the functionality and security of financial applications that rely on this pricing data for essential operations.

位图和位运算

在区块链上存储数据的成本极高。 很多项目创新性地使用了一些巧妙的方法来降低gas费用。 我们今天将会讨论那些常见于龙头项目的源代码中的方法。

低成本重入保护

在智能合约中使用修饰符进行重入检查可以通过确认合约当前是否正在执行来提升安全性。 通常,布尔型标志用于控制访问权限,只有当合约尚未激活时才允许函数运行。

余额核算

Smart contracts often maintain state variables that track balances. However, direct transfers not mediated by contract functions (like direct Ether sends to a contract address or transfer calls for ERC20 tokens that bypass the contract's logic) can create discrepancies between the actual balance held by the contract and the balance recorded in the contract’s internal state variables.

使用单体合约架构

This tutorial explores how making the architecture of your smart contracts monolithic, rather than having several contracts that communicate with each other, can result in gas savings. 合约间的调用可能会非常昂贵,通过将逻辑整合到单个合约中,可以避免这些成本,尽管在复杂性和模块化方面会有一些权衡。

修饰符 vs 内部函数

In Solidity, the choice between using modifiers and internal functions can impact the gas costs associated with contract operations. 本文探讨了在执行典型操作时,修饰符和内部函数之间在燃气使用方面的差异。 了解这些差异可以帮助开发者优化他们的智能合约,以优化合约功能并控制成本。

固定大小/动态数组

In Solidity, the way you manage and interact with arrays can impact the gas cost of your smart contract operations. This tutorial demonstrates the difference in gas usage between fixed-size arrays and dynamic arrays when they are filled with values. This understanding can help developers make more cost-effective decisions when designing smart contracts.

在路由器类合约中实现多调用

在 Solidity 中,可以通过将多个状态修改调用批量处理为单个交易,以在路由器类合约中实现多调用功能,显著降低燃气成本。 这种技术在像 Uniswap 和 Compound 平台的合约中非常有价值。

安全的向下转换

在 Solidity 中,安全地将较大的整数类型向下转换为较小的类型可能会带来风险,尤其是在 0.8.0 之前的版本中,因为这些版本缺乏自动溢出检查。 本文将解释向下转换的风险,提供一个在旧版本 Solidity 中有问题的函数示例,并介绍如何使用诸如 SafeCast 之类的库来确保操作安全。 尽管 Solidity 0.8.0 及以后的版本已经内置了溢出检查,但使用 SafeCast 仍然可以提高代码的清晰度和安全性。

局部变量

在许多常见的DeFi项目中,我们经常遇到需要定义许多新的局部变量和更新现有全局变量的各种复杂计算。 众所周知,修改存储比在内存中进行更改的成本要高得多。

拒绝服务攻击

2022年4月,一家名为Akutar的热门NFT项目成功地进行了一次 荷兰式拍卖筹集了11,539.5个ETH。 However, when processing refunds for previous community pass holders, a flaw in their smart contract prevented operations, locking all funds within the contract due to a DoS vulnerability.

整数溢出

2018年4月,BeautyChain(BEC)代币上发生了一起涉及整数溢出漏洞的重大事件。 该漏洞使攻击者能够凭空生成大量的BEC代币,导致了巨额财务损失,并削弱了该代币的价值。

方法标识(MethodId)优化

当以太坊虚拟机(EVM)执行交易时,随附的调用数据(calldata)指定了要执行的合约函数,会产生 gas 费。 These fees are calculated based on the calldata size, with 0 bytes costing 4 gas units and non-0 bytes costing 16 gas units. 这种定价结构鼓励有效利用调用数据以减少交易成本,特别是在交易量大或操作复杂的合约中。

映射 vs 动态数组

在 Solidity 中,不同的数据结构会显著影响因合约操作而产生的 gas 成本。 本文探讨了在执行插入、删除和检索等典型操作时,映射 和 动态数组 在 gas 使用上的差异。 了解这些差异可以帮助开发者优化他们的智能合约,以优化合约功能并控制成本。

智能合约安全

确保智能合约的安全至关重要,因为它们涉及财产的直接处理与存储,并且一旦合约被部署在区块链上,就很难修改。 为了保护你的智能合约,遵循以下关键步骤和最优的实践方法:

更好的增量

在合约开发中,增量操作是基础操作,由于它们在计数和循环机制中经常使用。 Each method of incrementing has subtle nuances that may affect gas consumption and readability:

未经检查的低级调用

未经检查的低级调用在智能合约开发中是常见的漏洞来源。 这些调用包括call(),delegatecall(),staticcall()和 send(),当它们失败时不会回滚交易,而是返回布尔值false。 未检查这些返回值可能导致严重的安全问题。

比较运算符

在以太坊虚拟机(EVM)中,选择比较运算符会影响智能合约的效率和燃气消耗。 Opting for ` (greater than) over ≤ (less than or equal to) and ≥ (greater than or equal to) is notably more gas-efficient. 这是因为 EVM 的设计中没有直接的操作码指令支持 ≤ 和 ≥`,实现这些比较需要额外的操作。

短路运算

在Solidity中,每一个需要上链的操作都需要消耗gas,短路运算是一种编码技巧,它仅在第一个参数没有确定结果时才评估逻辑操作的第二个参数,从而显著减少不必要的gas消耗,提高效率。

私有变量安全性

When developing smart contracts, it's crucial to understand that marking variables as private does not make them confidential. This tutorial explains why private variables are still accessible and provides best practices for handling sensitive information in smart contracts.

绕过智能合约检测

许多免费铸造的项目使用 isContract() 方法限制对外部账户(EOAs)的访问以及限制智能合约的交互。 此方法使用 extcodesize 来决定地址运行时 bytecode 长度。 如果大于零,则被视为智能合约;否则,它被视为EOA。

访问控制漏洞

智能合约的访问控制漏洞是导致 Poly Network 跨链桥黑客攻击(损失 6.11 亿美元)的主要因素之一,并且也导致了在币安智能链(BSC)上的 ShadowFi DeFi 项目遭受 30 万美元的黑客攻击。

过多的函数限制

智能合约中过度的函数限制可能导致严重的问题,例如资金被锁定,甚至在必要情况下也无法正确访问。 一个著名的例子是Akutars NFT事件,由于为了保证安全而采用了过度限制的合约机制,导致3400万美元的以太坊被困。

重入攻击

重入攻击是针对智能合约最常见的攻击类型之一,攻击者利用合约的漏洞递归调用合约,使其能够从合约中转移资产或者铸造大量的代币。

错误

在Solidity中,开发者可以以三种主要形式定义错误: revert、 require 和 assert。 从功能角度来看,这些方法的主要区别有两个:

非零余额

Initializing a storage variable from zero to a non-zero value is one of the most gas-intensive operations a contract can perform. It requires a total of 22,100 gas, including 20,000 gas for changing the value from zero to non-zero and 2,100 gas for cold storage access.