Security Audit
October 7th, 2024
Version 1.0.0
Presented by 0xMacro
This document includes the results of the security audit for thirdweb's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team from September 18, 2024 to September 25, 2024.
The purpose of this audit is to review the source code of certain thirdweb Solidity contracts, and provide feedback on the design, architecture, and quality of the source code with an emphasis on validating the correctness and security of the software in its entirety.
Disclaimer: While Macro’s review is comprehensive and has surfaced some changes that should be made to the source code, this audit should not solely be relied upon for security, as no single audit is guaranteed to catch all possible bugs.
The following is an aggregation of issues found by the Macro Audit team:
Severity | Count | Acknowledged | Won't Do | Addressed |
---|---|---|---|---|
High | 3 | - | - | 3 |
Medium | 2 | - | - | 2 |
Low | 1 | - | - | 1 |
Code Quality | 2 | - | - | 2 |
thirdweb was quick to respond to these issues.
Our understanding of the specification was based on the following sources:
The following source code was reviewed during the audit:
c121e8eb762b9b85eb45aaca1f65345a236669ff
60c8b9baee0f032933db43b4307799b20377df91
We audited the changes related to PR 163 on the following contracts within the modular-contracts repository:
Source Code | SHA256 |
---|---|
src/Core.sol |
|
src/callback/BeforeMintCallbackERC1155.sol |
|
src/callback/BeforeMintCallbackERC721.sol |
|
src/callback/BeforeMintWithSignatureCallbackERC1155.sol |
|
src/callback/BeforeMintWithSignatureCallbackERC20.sol |
|
src/callback/BeforeMintWithSignatureCallbackERC721.sol |
|
src/callback/BeforeTransferCallbackERC1155.sol |
|
src/callback/UpdateMetadataCallbackERC1155.sol |
|
src/callback/UpdateMetadataCallbackERC721.sol |
|
src/callback/UpdateTokenIdERC1155.sol |
|
src/core/token/ERC1155Base.sol |
|
src/core/token/ERC1155Core.sol |
|
src/core/token/ERC1155CoreInitializable.sol |
|
src/core/token/ERC20Base.sol |
|
src/core/token/ERC20Core.sol |
|
src/core/token/ERC20CoreInitializable.sol |
|
src/core/token/ERC721Base.sol |
|
src/core/token/ERC721Core.sol |
|
src/core/token/ERC721CoreInitializable.sol |
|
src/module/token/metadata/BatchMetadataERC1155.sol |
|
src/module/token/metadata/BatchMetadataERC721.sol |
|
src/module/token/metadata/OpenEditionMetadataERC721.sol |
|
src/module/token/minting/ClaimableERC1155.sol |
|
src/module/token/minting/ClaimableERC20.sol |
|
src/module/token/minting/ClaimableERC721.sol |
|
src/module/token/minting/MintableERC1155.sol |
|
src/module/token/minting/MintableERC20.sol |
|
src/module/token/minting/MintableERC721.sol |
|
src/module/token/tokenId/SequentialTokenIdERC1155.sol |
|
We audited the changes related to non-standard token decimals handling on the following contracts within the contracts repository:
Source Code | SHA256 |
---|---|
contracts/prebuilts/account/token-paymaster/TokenPaymaster.sol |
|
Note: This document contains an audit solely of the Solidity contracts listed above. Specifically, the audit pertains only to the contracts themselves, and does not pertain to any other programs or scripts, including deployment scripts.
Click on an issue to jump to it, or scroll down to see them all.
baseURI
to incorrect token ids
We quantify issues in three parts:
This third part – the severity level – is a summary of how much consideration the client should give to fixing the issue. We assign severity according to the table of guidelines below:
Severity | Description |
---|---|
(C-x) Critical |
We recommend the client must fix the issue, no matter what, because not fixing would mean significant funds/assets WILL be lost. |
(H-x) High |
We recommend the client must address the issue, no matter what, because not fixing would be very bad, or some funds/assets will be lost, or the code’s behavior is against the provided spec. |
(M-x) Medium |
We recommend the client to seriously consider fixing the issue, as the implications of not fixing the issue are severe enough to impact the project significantly, albiet not in an existential manner. |
(L-x) Low |
The risk is small, unlikely, or may not relevant to the project in a meaningful way. Whether or not the project wants to develop a fix is up to the goals and needs of the project. |
(Q-x) Code Quality |
The issue identified does not pose any obvious risk, but fixing could improve overall code quality, on-chain composability, developer ergonomics, or even certain aspects of protocol design. |
(I-x) Informational |
Warnings and things to keep in mind when operating the protocol. No immediate action required. |
(G-x) Gas Optimizations |
The presented optimization suggestion would save an amount of gas significant enough, in our opinion, to be worth the development cost of implementing it. |
ClaimableERC20 and MintableERC20 modules were recently updated to calculate the mint price by dividing pricePerUnit
by 1e18.
function beforeMintWithSignatureERC20(address _to, uint256 _amount, bytes memory _data, address _signer)
external
payable
virtual
override
returns (bytes memory)
{
...
>> _distributeMintPrice(msg.sender, _params.currency, (_amount * _params.pricePerUnit) / 1e18);
}
Reference: ClaimableERC20.sol#L216
This approach works correctly if the specified currency uses 18 decimal representation. However, the price calculation becomes inaccurate when dealing with currencies that have a different number of decimals.
Consider a scenario where the specified currency is USDC, which only has 6 decimals. The pricePerUnit
will be expressed using the 6-decimal representation, but it's still divided by 1e18. Consequently, the calculated mint price will be significantly lower than intended.
Remediation to Consider
Instead of using a hardcoded 1e18 divisor, consider using the decimals value of the specified currency.
Modules use the “Namespaced Storage Layout” to prevent collisions between different modules as well as between the modules and the core contracts. However, this doesn’t protect against storage collisions between different version upgrades of the same module.
ClaimableERC20/721/1155 were recently updated to include a maxMintPerWallet
param in the ClaimCondition struct:
struct ClaimCondition {
uint256 availableSupply; // slot 1
bytes32 allowlistMerkleRoot; // slot 2
uint256 pricePerUnit; // slot 3
address currency; // slot 4
>> uint256 maxMintPerWallet; // slot 5
uint48 startTimestamp;
uint48 endTimestamp;
string auxData;
}
Reference: ClaimableERC20.sol#L75
The ClaimCondition is set in the storage using the following layout:
struct Data {
// sale config: primary sale recipient, and platform fee recipient + BPS.
ClaimableERC20.SaleConfig saleConfig;
// claim condition
ClaimableERC20.ClaimCondition claimCondition;
// UID => whether it has been used
mapping(bytes32 => bool) uidUsed;
// address => how many tokens have been minted
mapping(address => uint256) totalMinted;
}
Reference: ClaimableERC20.sol#L21-L30
This change is considered an unsafe storage layout change, since an upgrade would overwrite subsequent parameters. This can lead to severe vulnerabilities such as unintentionally setting wrong values for claim conditions or breaking the module’s functionality at all.
Remediation to Consider
Consider changing the storage layout so that upgrades can be made in a safe way. E.g. only add new params at the end of the storage layout or define a new storage layout for each version that reads from a separate storage slot.
The contracts are not deployed to mainnet/prod yet, so restructuring the storage layout will not lead to storage collisions as of now.
baseURI
to incorrect token ids
ERC721Base and ERC1155Base added support for updateMetadataERC721
and updateMetadataERC1155
callbacks, respectively. This allows for setting the baseURI
on the mint
and mintWithSignature
functions.
The callback and thus the respective BatchMetadata module is called when a baseURI
is provided, otherwise the callback is skipped:
function mint(address to, uint256 amount, string calldata baseURI, bytes calldata data) external payable {
uint256 tokenId = _nextTokenId();
>> if (bytes(baseURI).length > 0) {
_updateMetadata(to, tokenId, amount, baseURI);
}
_beforeMint(to, tokenId, amount, data);
_safeMint(to, amount, "");
}
Reference: ERC721Base.sol#L191
This approach allows minting tokens without invoking the BatchMetadata module by leaving the baseURI
empty. In such cases, the tokenId
in ERC721Base or ERC1155Base increments, while the nextTokenIdRangeStart
in the module's storage remains at 0
. As a result, when a token is subsequently minted with a provided baseURI
, the metadata is incorrectly applied to tokenId = 0
instead of the newly minted tokenId
.
For example, imagine 100 NFTs are minted for ERC721Base without a baseURI
. Then, 1 NFT is minted with a baseURI
of ipfs://base/
, intended to apply to tokenId = 100
. However, this doesn't happen as expected. Because the module wasn't informed of the 100 previously minted NFTs and the nextTokenIdRangeStart
is still 0, it mistakenly applies the provided baseURI
to tokenId = 0
.
Remediation to Consider
Consider changing the logic in the BatchMetadata modules, so that the metadata is correctly applied to the provided token range.
SequentialTokenIdERC1155 increments the tokenId
when a value of uint.max
is passed to updateTokenIdERC1155
. This works well when the module is installed before minting the first token, but can lead to unwanted behavior if installed at a later point.
Consider a scenario where 10 tokens (range 0-9) have been already minted by ERC1155Core, and only then the SequentialTokenIdERC1155 is installed. The nextTokenId
in SequentialTokenIdERC1155 would start from id 0 (instead of 10), which is not the desired behavior. Instead, it should increment the value from the most recent tokenId.
Remediation to Consider
Add a onInstall
function to the module to allow setting the nextTokenId
accordingly.
In TokenPaymaster’s _postOp
function, refillEntryPointDeposit
is called to refill the deposit on EntryPoint with the Paymaster’s token balance. If the EntryPoint balance falls below the minEntryPointBalance
threshold, tokens are swapped to wei using Uniswap:
if (currentEntryPointBalance < tokenPaymasterConfig.minEntryPointBalance) {
uint256 swappedWeth = _maybeSwapTokenToWeth(token, _cachedPrice);
unwrapWeth(swappedWeth);
entryPoint.depositTo{value: address(this).balance}(address(this));
}
Reference: TokenPaymaster.sol#L178-L182
In _maybeSwapTokenToWeth
, the amountOutMin
is calculated to provide slippage protection for the Uniswap swap operation.
uint256 amountOutMin = addSlippage(tokenToWei(tokenBalance, quote), uniswapHelperConfig.slippage);
Reference: UniswapHelper.sol#L55
The TokenPaymaster’s implementation has been recently changed to support tokens with decimals < 18. However, this is not considered in the calculation of the amountOutMin
value. Consequently, the amountOutMin
calculated might be significant lower than what is required for sufficient slippage protection.
Let’s consider a scenario where USDC is used (decimal: 6) for the payment token. In this case, the calculated amountOutMint
would be by a magnitude of 10^12 (10^18-6) smaller than what is required, effectively removing slippage protection.
This makes the swap operation vulnerable to a sandwich attack, meaning that the Paymaster potentially receives much less WETH for the amount of tokens provided.
Remediation to Consider
Consider the token’s decimal value when calculating the amountOutMin
value.
The TokenPaymaster contract was modified to accommodate tokens with decimals other than 18:
uint256 tokenAmount = weiToToken(preChargeNative, cachedPriceWithMarkup) / (10 ** (18 - _tokenDecimals));
Reference: TokenPaymaster.sol#L131
While this implementation works for tokens with decimals ≤ 18, it fails for tokens with decimals > 18. In such cases, the transaction would revert, rendering the Paymaster contract non-functional.
Remediation to Consider
For ClaimableERC20/721/1155, the FallbackFunction array is defined with a size of 5, but only needs to hold 4 elements. Consider reducing the size of the array to 4.
Natspec is missing or incorrect on the following occurrences:
_startTokenId
param here and here_id
param heredeadline
, v
, r
, s
params hereClaimSignatureParamsERC20
hereClaimParamsERC20
herebeforeMintWithSignatureERC20
here. It misses natspec for all the params and incorrectly says “for the ERC20Core.mint” instead of “ERC20Core.mintWithSignature”Macro makes no warranties, either express, implied, statutory, or otherwise, with respect to the services or deliverables provided in this report, and Macro specifically disclaims all implied warranties of merchantability, fitness for a particular purpose, noninfringement and those arising from a course of dealing, usage or trade with respect thereto, and all such warranties are hereby excluded to the fullest extent permitted by law.
Macro will not be liable for any lost profits, business, contracts, revenue, goodwill, production, anticipated savings, loss of data, or costs of procurement of substitute goods or services or for any claim or demand by any other party. In no event will Macro be liable for consequential, incidental, special, indirect, or exemplary damages arising out of this agreement or any work statement, however caused and (to the fullest extent permitted by law) under any theory of liability (including negligence), even if Macro has been advised of the possibility of such damages.
The scope of this report and review is limited to a review of only the code presented by the thirdweb team and only the source code Macro notes as being within the scope of Macro’s review within this report. This report does not include an audit of the deployment scripts used to deploy the Solidity contracts in the repository corresponding to this audit. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. In this report you may through hypertext or other computer links, gain access to websites operated by persons other than Macro. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such websites’ owners. You agree that Macro is not responsible for the content or operation of such websites, and that Macro shall have no liability to your or any other person or entity for the use of third party websites. Macro assumes no responsibility for the use of third party software and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software.