Reach out for an audit or to learn more about Macro
or Message on Telegram

thirdweb 20

Security Audit

September 18th, 2024

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

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 August 26, 2024 to September 2, 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.

Overall Assessment

The following is an aggregation of issues found by the Macro Audit team:

Severity Count Acknowledged Won't Do Addressed
Medium 2 - - 2
Low 4 - - 4
Code Quality 6 - 1 5

thirdweb was quick to respond to these issues.

Specification

Our understanding of the specification was based on the following sources:

Source Code

The following source code was reviewed during the audit:

We audited the following contracts within the contracts-pay-gateway repository:

Contract SHA256
src/PayGateway.sol

ab939f88ab89ca88ca4b3a22f74653f2cd5258d400e361621d6798fc3145dbec

src/PayGatewayModule.sol

6be9d6785e0461ffef65d09e12b8c560b78d15a1b32d0961a608ea24531f5981

We audited the following contracts within the modular-contracts repository:

Contract SHA256
src/module/token/royalty/RoyaltyERC1155.sol

da674d302d9d8d743c117854b15ad381d87b9d8e1c6da878dfa195dfce2547d6

src/module/token/royalty/RoyaltyERC721.sol

e5c293447a409b2c81edc02e04008e2622ed6be29945da4bda35df1f686db9aa

src/module/token/transferable/CreatorTokenERC20.sol

cd3132e2e2f58ca0f232d2b12b3cecc1877bf446a1faec0a3ffc79ee2a407b7d

We audited the following contracts within the contracts repository:

Contract SHA256
contracts/prebuilts/account/non-upgradeable/Account.sol

9cbca7a210bf1064b5c072f4d19f702d006e0af57b946ca5c765d610f7ab47ca

contracts/prebuilts/account/non-upgradeable/AccountFactory.sol

a1ea8c1164053156d9e8532e53e4526b7d901525fd403078588695b5256807e5

contracts/prebuilts/account/managed/ManagedAccount.sol

a3c9e5587189eeb6df5dddd69875aaef046e02fa1a38a5b38d9fa0ad501e1302

contracts/prebuilts/account/managed/ManagedAccountFactory.sol

66c65fd1e99179013483250549fda4f5acd517a9d24f278bf91a0c6e610425d3

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.

Issue Descriptions and Recommendations

Click on an issue to jump to it, or scroll down to see them all.

Security Level Reference

We quantify issues in three parts:

  1. The high/medium/low/spec-breaking impact of the issue:
    • How bad things can get (for a vulnerability)
    • The significance of an improvement (for a code quality issue)
    • The amount of gas saved (for a gas optimization)
  2. The high/medium/low likelihood of the issue:
    • How likely is the issue to occur (for a vulnerability)
  3. The overall critical/high/medium/low severity of the issue.

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.

Issue Details

M-1

Missing return value check on low-level call

Topic
Best Practice
Status
Impact
High
Likelihood
Low

In PayGatewayModule’s initiateTokenPurchase, native tokens are directly forwarded to the forwardAddress when directTransfer is set.

if (req.directTransfer) {
    if (_isTokenNative(req.tokenAddress)) {
        req.forwardAddress.call{ value: sendValue }("");

Reference: PayGatewayModule.sol#L225

However, the return value is not checked on the .call function, which can lead to unwanted behavior in case the call function returns false.

Remediations to Consider

Consider checking the return value of the .call function accordingly or use SafeTransferLib.safeTransferETH

M-2

MANAGER_ROLE is not allowed to set transfer policy

Topic
Protocol Design
Status
Impact
Medium
Likelihood
Medium

In RoyaltyERC721, RoyaltyERC1155, and CreatorTokenERC20, the MANAGER_ROLE can set the validator address via the setTransferValidator function. However, the MANAGER_ROLE is not permissioned to set transfer policies, this is because of the validator’s implementation, where only the owner, admin, or contract itself is allowed to set policies, see _requireCallerIsNFTOrContractOwnerOrAdmin here. As a result, while the MANAGER_ROLE can set the validator’s address, only the Core’s owner can configure transfer policies on this validator, such as whitelisting or blacklisting accounts.

In particular, this can lead to problems where ownership wants to be renounced from the Core contract in order to remove upgradeability, but the possibility to configure transfer policies want to be maintained.

Remediations to Consider

hasRole function could be implemented in the modules so that it returns true for accounts having the MANAGER_ROLE assigned.

L-1

isProcessed function isn’t callable

Topic
Protocol Design
Status
Impact
Low
Likelihood
Low

In PayGatewayModule, the external isProcessed function is used to check if a given transactionId has been used. Given the modular contract pattern, a function needs to be set in the fallbackFunctions array in order to be callable. This is not the case with the isProcessed function and thus it can’t be called.

Remediations to Consider

Add isProcessed function to the fallbackFunctions array.

L-2

Native tokens might remain in the contract on initiateTokenPurchase

Topic
Protocol Design
Status
Impact
Low
Likelihood
Low

In PayGatewayModule’s initiateTokenPurchase, when directTransfer = true and _istTokenERC20 = true, tokens are transferred to the contract and approved to the forwardAddress. However, if native tokens are sent with the call (msg.value > 0), they won’t be forwarded and remain in the contract.

Remediations to Consider

When directTransfer = true and _istTokenERC20 = true, enforce that no native tokens are sent with the call (msg.value == 0).

L-3

PayGatewayMismatchedValue error is thrown with wrong parameters

Topic
Error Handling
Status
Impact
Low
Likelihood
Low

In PayGatewayModule’s initiateTokenPurchase, an error is thrown when sendValue is smaller than req.tokenAmount:

if (sendValue < req.tokenAmount) {
    revert PayGatewayMismatchedValue(sendValue, req.tokenAmount);
}

Reference: PayGatewayModule.sol#L219

The declaration of the error is:

error PayGatewayMismatchedValue(uint256 expected, uint256 actual);

As per above definition, the first parameter provided should be the expected value (= req.tokenAmount) and the second parameter provided should be the actual value (= sendValue). However, the error is thrown with the values in reverse order.

Remediations to Consider

Reverse the parameters to throw the error according to the defintion.

L-4

Wrong function selector returned for the transfer validation function

Topic
Interoperability
Status
Impact
Low
Likelihood
Low

In CreatorTokenERC20, the function getTransferValidationFunction() is implemented to return the function selector for the transfer validation function:

function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
    functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256, uint256)"));
}

Reference: CreatorTokenERC20.sol#L94

However, the string being used to calculate the signature contains a space between the last two parameters, causing to return an incorrect function selector.

Remediations to Consider

Remove the space between the last two parameters.

Q-1

Outdated storage position name

Topic
Consistency
Status
Quality Impact
Low

The PaymentsGateway has been recently renamed to PayGateway including its references. However, in PayGatewayModule.sol, the storage location is still referring to Payments instead of Pay.

library PayGatewayModuleStorage {
    /// @custom:storage-location erc7201:payments.gateway.module
    bytes32 public constant PAYMENTS_GATEWAY_EXTENSION_STORAGE_POSITION =
        keccak256(abi.encode(uint256(keccak256("payments.gateway.module")) - 1)) & ~bytes32(uint256(0xff));

Reference: PayGatewayModule.sol#L14-L16

Additionally, the error definition PaymentsGatewayMsgValueNotZero is still referring to the old name.

Remediations to Consider

For consistency sake, update all above mentioned occurrences to the new name.

Q-2

Redundant check for msg.value < tokenAmount

Topic
Readability
Status
Quality Impact
Low

In PayGatewayModule’s initiateTokenPurchase function, there is the following check for msg.value:

if (_isTokenNative(req.tokenAddress)) {
    if (msg.value < req.tokenAmount) {
        revert PayGatewayMismatchedValue(req.tokenAmount, msg.value);
    }
}

Reference: PayGatewayModule.sol#L202-L204

A few lines further down, there is a similar check:

if (_isTokenNative(req.tokenAddress)) {
    sendValue = msg.value - totalFeeAmount;

    if (sendValue < req.tokenAmount) {
        revert PayGatewayMismatchedValue(sendValue, req.tokenAmount);
    }
}

Reference: PayGatewayModule.sol#L215-L221

As the second check always covers the first one (they are the same when totalFeeAmount is 0), the first check is redundant and can be removed.

Remediations to Consider

To improve readability, remove the first check.

Q-3

Move interface identifier for ERC165 to Core

Topic
Best Practice
Status
Quality Impact
Low

All core token implementation (ERC20Core, ERC721Core, and ERC1155Core) support ERC165 and thus return true for the ERC165 interface id in their supportsInterface function:

function supportsInterface(bytes4 interfaceId) public view returns (bool) {
    return interfaceId == 0x01ffc9a7 // ERC165 Interface ID for ERC165
    ...

As the Core contract by itself already implements the supportsInterface function, this check can be moved to the Core’s supportsInterface function and removed from all the Core’s token implementations.

Remediations to Consider

Move the ERC165 interface ID check from the Core’s token implementations to the Core contract itself.

Q-4

Add encode functions to IInstallationCallback

Topic
Interfaces
Status
Wont Do
Quality Impact
Low

encodeBytesOnInstall and encodeBytesOnUninstall has been added to all modules implementing the onInstall/onUninstall functions.

Remediations to Consider

Consider adding those two functions to the IInstallationCallback interface to improve integration experience.

Response by thirdweb

encodeBytesOnInstall can have different function parameters across modules

Q-5

Royalty modules should inherit ICreatorToken interface

Topic
Interfaces
Status
Quality Impact
Low

RoyaltyERC721 and RoyaltyERC1155 both implement all necessary functions of ICreatorToken interface, but don’t inherit from it. This is in contrast to the CreatorTokenERC20 module, which inherits the ICreatorToken interface.

Additionally, for all three modules, consider adding ICreatorToken to the supportedInterfaces in getModuleConfig().

Remediations to Consider

Consider changing RoyaltyERC721 and RoyaltyERC1155 to inherit from ICreatorToken interface and add it to the supportedInterfaces array.

Q-6

Nitpicks

Topic
Documentation
Quality Impact
Low
  1. In PayGatewayModule.sol, incorrect comment on L53: the @param tag is still referring to feeBPS.
  2. In PayGatewayModule.sol, missing @param tag for newly added directTransfer flag on L81
  3. In the readme of the PayGateway, it refers to TransferStart and TransferEnd event, but it should be TokenPurchaseInitiated and TokenPurchaseCompleted events.
  4. In ERC20Core.sol, unused import of ReentrancyGuard on L8.
  5. When using “named return variables” as in the function definition of getTransferValidator() in RoyaltyERC721, RoyaltyERC1155, and CreatorTokenERC20, values need to be assigned to the return variable but there is no need to return the value itself, e.g. see here.

Disclaimer

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.