Treasure Chests with AI Minting
Learn how to build a web3 application using React with AI-generated loot from treasure chests. Utilize an Embedded Wallet for authentication, Cloudflare workers for transaction ease, and Sequence Stack tools.
Time to complete: 50-60 minutes
In this guide, we will create a web3 application built in React, leveraging tools from the Sequence Stack to mint AI generated loot from treasure chests using an Embedded Wallet for authentication, and Cloudflare workers for easy, no-confirmation transactions.
We’ve wrapped this in a dungeon crawler game to showcase these features in a game environment that you can play and earn rewards.
The full code can be found in the respective repositories:
The tools will enable you to perform:
- Sequence Builder Console Signup & Project Creation: Create a project with the Builder
- Access Key Management: Claim a public, secret access key, and waas config key to interact with the Sequence stack
- Embedded Wallet Integration: Integrate an Embedded Wallet into the application
- Deploy a Contract & Sponsor gas: Deploy an items contract and sponsor gas
- Deploy a Cloudflare Worker: Deploy a Cloudflare worker for gasless and no-confirmation transactions
- Generating AI Prompts & Images: Craft AI prompts from an API and generate images to be uploaded
- Store Media to Sequence Metadata service: Upload collection and token metadata to Sequence
- Securing your Cloudflare Worker: Prevent outside requests to your Cloudflare worker by restricting the referrer URL
- (Optional) Native Mint Restriction Per Wallet: Restrict daily mints per wallet
1. Sequence Builder Console Signup & Project Creation
First start by following this walkthrough for how to sign up to the Sequence Builder Console and to learn how to create a project.
To use certain features, like Gas Sponsoring
and the use of the Transactions API
, you’ll need to upgrade your project plan to Developer
using this walkthrough
2. Access Key Management
Now that you have a project, you’ll need to acquire 3 different Access Keys for your project in order to authenticate your application with the Sequence Stack:
Waas Config Key
used for the Embedded Wallet, which can be learned about herePublic Access Key
used for the Embedded Wallet & Transactions API, which can be done hereSecret Access Key
used for the Metadata Service, with the following steps
Secret Access Key Creation
Access Settings
First start by accessing settings, and selecting the API Keys
Add Service Account
Scroll down and select + Add Service Account
Select Write Permission
Then change the access to Write
and Confirm
Finally copy
the key and store it in a safe location, as you will not have access to this in the future from the Builder Console.
3. Embedded Wallet Integration
You can view and clone the template repository here
We’ll start from scratch building up the project with the necessary pieces, to enable the use of a Sequence Embedded Wallet which enables users to be onboarded to your application using web2 authentication providers.
First start by creating a project folder with mkdir <project>
, then cd <project>
and create a vite
project using React:
Next, we’ll install the correct Wallet-as-a-Service (Waas) package to use the Embedded Wallet:
For all of the new files created in the follows steps, have them be created in /src
First, create a file called something like SequenceEmbeddedWallet.ts
with the following initialization code:
Then create another file called useSessionHash.ts
that generates a session hash from the SDK unique to the user:
Finally, to implement Google auth, you will need the GoogleOAuthProvider
to wrap your application. The following command will install it and Apple Auth sign in, which will be used later:
Then, the starter code is implemented with the previous imported files, in the following code within the main.tsx
file:
Once your main.tsx
is ready, lets create the login buttons, which will look like this:
In App.tsx
use the following code that checks to see if a user is connected and presents a wallet address based on the signed in user, with the various social auth buttons and handlers:
Then, include a .env
file in the root of your project, adding it to .gitignore
, and updating the file with the following values from the Sequence Builder:
All environment variables must start with VITE_
to be included in the environment of a vite application
Run your code with the following command in the root folder and give it a try:
4. Deploy A Contract & Sponsor Gas
We will deploy an token contract so we are able to link the AI-generated images to the metadata for any given token. When deploying your contract, the recommended approach is to use an ERC1155
over an ERC721
. The benefits of using an ERC1155
- Semi-Fungible: which is ideal for game assets that can have multiple copies of the same underlying item.
- Gas Savings: for projects that require multiple tokens as a single ERC1155 can hold many different varieties.
In terms of the gas savings benefit, instead of deploying a new contract for each token type, a single ERC1155 token contract can hold the entire system state, reducing deployment costs and complexity.
To deploy a contract, you can follow this guide to deploy your ERC1155, and update your wrangler.toml
with the CONTRACT_ADDRESS
.
Then, for the minting function to work programmatically so that transactions are gasless for your relayer, you will need to make the Transactions API draw from your account credits on your upgraded billing plan by sponsoring your deployed smart contract address.
To allow the Transactions API to relay transactions without a fee, sponsor gas by following this guide for the deployed contract.
All Sequence testnets are free
5. Deploy Transactions API on a Cloudflare Worker
Following the previous step, the Sequence Transactions API can be implemented on a serverless Cloudflare worker so a game or app user interaction is seamless without a confirmation signature or gas payment. In this case, the worker will leverage the Sequence Transactions API to mint tokens to the user’s address. You’ll also benefit from not having to be worried about transaction speed, throughput or re-orgs, and experience automatic scaling with Cloudflare.
Minting A Token
If you want to learn how to deploy a Cloudflare Worker from scratch, you can follow this guide on minting a serverless NFT minting service with your deployed ERC1155
contract or simply clone the template specific to this guide.
Ensure that if you’re using a Sequence Standard ERC1155 Items Contract, you grant the MINTER_ROLE
for your relayer account address.
Once setup, we will call the endpoint of the cloudflare instance to mint our NFTs in a later step.
6. Generating AI Prompts & Images
When beginning your journey into AI image generation, you will require a source of AI model prompts to produce media. For this guide and demo, we’ve sourced prompts from the items contained in the Diablo game.
In the template, we’ve included code to call an already deployed API and code to parse the response.
With this API, we will showcase how to generate images using the prompt from the deployed Diablo API within the generate
function within the Cloudflare worker:
Then complete the getInferenceWithItem
function in order to get the instantiated inference reference from the Scenario API and pass in a prompt
which is the generated loot name
and type
, as well as some additional parameters model parameters, which can be customized via the Scenario API docs:
For this guide, we landed on the EulerDiscreteScheduler
scheduler type from the Scenario API based on quality and time, but if you want to experiment with using additional schedulers, you can use this custom local cli and check the results in the Scenario.gg dashboard
Then we simply implement the above functions in the react code:
Once we have the inferenceId
we can call poll the inference status and return when complete, signified by the succeeded
status descriptor:
Again, we add the above function to the react code and pass the inferenceId. When you receive the response, you can obtain the image url with resObject.inference.images[0].url
:
It should be noted, that you can design applications that return mulitple images per prompt, and allow the user in userspace to choose the correct generation
7. Store Media to Sequence Metadata Service
With our media url
from the Scenario API in hand, we can move onto storing the asset to the Sequence Metadata Service
. This enables you to link the AI-generated image to the specific token metadata - all through REST-API calls.
Each Dungeon Minter treasure chest reward follows the same process where metadata is first stored using the Sequence Metadata API, the url
and the randomly generated tokenID
(which allows for parallel requests) is returned to the client. The user then consents, after collectible inspection, to mint the token where the tokenID
and the user’s address
passed back to the worker created in Step 5.
Implementation
Complete and integrate this guide in order to build your serverless Media Service leveraging the Sequence Metadata API that uses Cloudflare workers or simply clone our cloudflare template for this guide.
Once complete, pass the stored media tokenID
and url
to the frontend to be rendered, to allow a user to mint after first viewing what they’re minting:
8. Minting with your Cloudflare Worker
The last step is to finally mint the corresponding tokenId that you linked the metadata to previously to the user’s address. Here we post a request to the Cloudflare Worker we created in Step 5 which will mint the token to the user.
One important note is that you will likely want to ensure that your Cloudflare workers only process requests from a certain frontend origin, you can simply check the request.headers
for the Referrer
value and compare it against the CLIENT_URL
in the wrangler.toml
:
Conclusion
Let’s recap what we’ve done during this tutorial:
We’ve covered how to create a Sequence project and obtain access to our suite of APIs. We’ve deployed and setup an embedded wallet to ensure smooth gameplay for an example dungeon crawler game. Additionally, we’ve used the Sequence platform to deploy a contract, sponsor gas for that contract to simplify the user experience. We also deployed a serverless NFT minter using the Sequence Transaction API which enables your game to scale to millions of players and handle complex blockchain interactions like reorgs. Furthermore, we’ve leveraged the scenario.gg API to dynamically create game assets as rewards for players. These images are then linked to the metadata of an NFT using the Sequence Metadata API. You should now understand how to mint AI art for your Scenario.gg and Sequence powered game.
It’s clear how many components go into creating a scalable, secure, and fun blockchain-enabled game, but the Sequence platform with Scenario has you covered.
Lastly, you can see all the steps above incorporated in a complete experience with our dungeon crawler game to brave the maze and get your own dungeon loot.
Happy building!
9. (Optional) Native Mint Restriction Per Wallet
As an option to prevent overuse of the treasure chest minting from specific wallets, a parameter called DAILY_MINT_RESTRICTION
can be set in the wrangler.toml
as a maximum mint allowance per day. And, if you feel it’s necessary to add an ADMIN
to your protocol to be able to mint an infinite amount.
These features can be implemented in the code with the following steps:
Where hasDailyMintAllowance
is broken down into 2 functions:
fullPaginationDay
of transactions of the usersaddress
mintCount
that corresponds to thefrom
being the0x
address
Full Pagination Of Indexer For A Day
As an aside, the Sequence Indexer stack only holds 30 days of transactions for this period, so you can extend the time frame from a day up to this max
In order to use the Sequence Indexer, we’ll need to pnpm install @0xsequence/indexer
Then, to implement we use a while loop that gets the first batch of transactions and the page.after
value from the indexer, and continuously checks if the timestamp is less than 24 hours appending to a temporary array for each pass. This ensures we get all of the available transactions:
Mint Count For A Day
All collectibles minted from the ERC721
and ERC1155
standard Sequence contracts are from
the 0x
address:
Has Daily Mint Allowance
Was this page helpful?