Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

In this article, I explore the BAYC contract using Bunzz's DeCipher feature, a service that uses AI to generate smart contract documentation.

DeCipher was in closed beta when this article was originally published in July 2023.

The BAYC contract is available here:

I will translate, summarize, and expand on the generated documentation, referring to the contract code where appropriate.

Overview

Bored Ape Yacht Club (BAYC) is an NFT collection implemented as an ERC-721 smart contract on Ethereum. ERC-721 is the token standard; BAYC is a particular implementation.

NFTs can represent distinct digital or physical assets, ranging from sports cards and virtual real estate to digital sneakers.

Each BAYC token represents a collectible Bored Ape with its own combination of attributes. The contract defines rules governing minting, token ownership, and the original sale.

Contract functionality

The contract provides NFT transfer and approval functionality, together with owner-restricted operations, minting, sale configuration, pricing, and provenance information. Transfers can support secondary sales, although the ERC-721 interface does not itself implement a marketplace.

BoredApeYachtClub()

The constructor executes once when the contract is deployed. It initializes the ERC-721 name and symbol, sets the maximum NFT supply, and calculates the reveal timestamp from the supplied sale-start timestamp.

solidity
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) {
	MAX_APES = maxNftSupply;
	REVEAL_TIMESTAMP = saleStart + (86400 * 9);
}

The reveal timestamp is set nine days after the supplied sale-start time. This assignment does not itself activate the sale.

reserveApes()

The contract owner can call reserveApes() to mint reserved NFTs to the owner's address.

The function loops 30 times, assigning consecutive token IDs starting from the current total supply. It attempts to mint exactly 30 tokens per successful invocation, not a variable quantity up to 30.

solidity
function reserveApes() public onlyOwner {        
	uint supply = totalSupply();
	uint i;
	for (i = 0; i < 30; i++) {
	    _safeMint(msg.sender, supply + i);
	}
}

The excerpt does not impose a separate maximum-supply check for this reservation function. Its behavior must be assessed together with the rest of the contract.

withdraw()

The contract owner can withdraw the contract's entire ETH balance, including ETH collected during the NFT sale.

solidity
function withdraw() public onlyOwner {
        uint balance = address(this).balance;
        msg.sender.transfer(balance);
}

setProvenanceHash

The owner can use setProvenanceHash() to record a collection-level provenance commitment.

A provenance hash can help verify that an ordered collection of assets corresponds to a previously published commitment. It is not itself proof of NFT ownership or ownership transfers, and this setter does not enforce immutability of the commitment.

solidity
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
        BAYC_PROVENANCE = provenanceHash;
}

Reference

Other functionality

Sale and pricing

The contract defines an NFT price of 0.08 ETH through apePrice, a maximum purchase quantity of 20 per transaction through maxApePurchase, and a Boolean saleIsActive indicating whether the original sale is active.

These values describe the original contract's sale configuration, not the current secondary-market price.

Transferring contract ownership

The contract owner can manage administrative ownership through the inherited functions:

  • transferOwnership()
  • renounceOwnership()

transferOwnership()

Transfers the contract's administrative ownership to another address.

renounceOwnership()

Relinquishes administrative ownership by assigning the owner role to the zero address. Owner-only functions then become inaccessible under the conventional Ownable implementation.

These operations are distinct from transferring an individual NFT.

How to use the contract

The BoredApeYachtClub contract implements ERC-721 functionality and collection-specific minting and sale logic.

The following describes the original deployment and operation process, rather than instructions for purchasing an NFT from the existing collection today.

Deploying the contract

A new instance can be deployed to a public or private Ethereum-compatible network. The original article mentioned Ethereum mainnet and Ropsten; Ropsten is a historical, retired testnet.

The constructor runs once during deployment and accepts the collection name, symbol, maximum supply, and sale-start timestamp used to calculate the reveal timestamp.

Reserving NFTs

The reserveApes() function is used to mint reserved NFTs. Only the contract owner can execute it.

Managing ownership

The owner can transfer administrative privileges to a new account through transferOwnership() or relinquish them through renounceOwnership().

Sale and transfers

The maxApePurchase value defines the maximum number of apes that may be purchased in one mint transaction. The mintApe() function accepts the requested quantity and implements the original public minting process.

Managing funds

While the administrative owner exists, it can call withdraw() to withdraw the contract's ETH balance.

Reveal and provenance

REVEAL_TIMESTAMP records the configured reveal time. The actual availability of revealed artwork also depends on the metadata and reveal implementation.

BAYC_PROVENANCE stores a provenance commitment associated with the collection.

Administrative functions such as withdraw(), reserveApes(), transferOwnership(), and renounceOwnership() are restricted to the contract owner.

Constructor parameters

The following parameters are supplied when deploying the contract.

  • name
    • Collection name.
  • symbol
    • Collection symbol.
  • maxNftSupply
    • Configured maximum NFT supply.
  • saleStart
    • Sale-start timestamp used to calculate the reveal timestamp.

Functions

The preceding sections introduced the core functionality. This section covers additional functions and state variables associated with BAYC.

For standard ERC-721 functionality, see the following article.

https://chaldene.net/erc721

Write operations

flipSaleState

Toggles the Boolean saleIsActive to its opposite value.

For example, when saleIsActive is true, the contract owner can call this function to deactivate the original sale.

The function does not return a value and directly updates the state variable.

The implementation uses the onlyOwner modifier. Ordinary NFT holders and approved token-transfer operators do not receive permission to call this function merely by holding or being approved for an NFT.

solidity
function flipSaleState() public onlyOwner {
        saleIsActive = !saleIsActive;
}

setStartingIndex

Sets the collection's starting index using the hash of a designated block. The index can be used in the collection's provenance and reveal arrangement to associate token IDs with the ordered artwork.

The function has two explicit preconditions:

  • startingIndex must still be zero.
  • startingIndexBlock must have been set to a nonzero value.

Unlike the administrative functions above, this function is public and does not have an onlyOwner modifier. The excerpt also does not require the sale to be inactive.

solidity
function setStartingIndex() public {
        require(startingIndex == 0, "Starting index is already set");
        require(startingIndexBlock != 0, "Starting index block must be set");
        
        startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES;
        // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
        if (block.number.sub(startingIndexBlock) > 255) {
            startingIndex = uint(blockhash(block.number - 1)) % MAX_APES;
        }
        // Prevent default sequence
        if (startingIndex == 0) {
            startingIndex = startingIndex.add(1);
        }
}

The function uses the designated block hash and reduces it modulo MAX_APES. If the designated block is outside the available block-hash window, it falls back to the preceding block's hash. It also replaces a resulting zero index with one.

This historical block-hash-based mechanism should not be regarded as a general-purpose cryptographically secure random-number generator.

emergencySetStartingIndexBlock

Allows the contract owner to set the starting-index block to the current block number in exceptional circumstances, provided the starting index has not already been assigned.

Because the function changes the block used in the reveal-related calculation, its administrative privileges are relevant when evaluating the collection's fairness assumptions.

solidity
function emergencySetStartingIndexBlock() public onlyOwner {
        require(startingIndex == 0, "Starting index is already set");
        
        startingIndexBlock = block.number;
}

Read operations

startingIndex

A public state variable storing the collection's starting index.

solidity
uint256 public startingIndex;

startingIndexBlock

A public state variable identifying the block whose hash is intended to be used when calculating the starting index.

solidity
uint256 public startingIndexBlock;

This variable is not the starting position used by ERC-721 enumeration functions such as tokenByIndex() or tokenOfOwnerByIndex(). Those functions enumerate tokens using their own data structures.

tokenOfOwnerByIndex

Returns the token ID at a specified index in the collection of NFTs owned by a particular account.

It accepts an owner address and a uint256 index.

solidity
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        return _holderTokens[owner].at(index);
}

The index represents a position in that owner's token collection, not necessarily the token ID itself. Enumeration order can change when tokens are transferred.

Events

The generated documentation also describes the contract's events.

OwnershipTransferred

Records the previous and new administrative owners when contract ownership changes.

  • previousOwner
    • Previous contract owner's address.
  • newOwner
    • New contract owner's address.

Approval

Emitted when an approval associated with an individual NFT changes.

  • owner
    • Token owner's address.
  • approved
    • Address approved to transfer the token, or the zero address when approval is cleared.
  • tokenId
    • Identifier of the NFT whose approval changed.

ApprovalForAll

Emitted when an owner grants or revokes an operator's authorization over all of the owner's NFTs in the contract.

  • owner
    • Token owner's address.
  • operator
    • Address receiving or losing operator authorization.
  • approved
    • Boolean indicating whether authorization was granted or revoked.

Code

The contract code is also available through the original DeCipher link:

The Solidity excerpts are preserved from the Japanese article. They have not been independently compiled or audited as part of this translation. The historical service link is retained without asserting its current availability.

Conclusion

I explored the BAYC contract using Bunzz DeCipher. The generated documentation was more detailed than I expected.

Some individual functions still require additional explanation and direct inspection of their implementation, but the documentation provides a useful starting point. Reading it before examining the source code helped me understand the contract more efficiently.

Developers familiar with Solidity and NFTs may find this approach especially useful. I would like to continue exploring other NFT collections and smart contracts in future articles.

I also publish articles about blockchain and AI through the following sites:

https://chaldene.net/