Skip to main content

5 posts tagged with "CODE"

View All Tags

· 4 min read
Loubna Benzaama

Welcome to our NFT generation and deployment tutorial! In just two clicks, you can create and deploy your own valuable NFTs. Our tutorial will guide you through the process of generating and deploying unique NFTs quickly and easily.

This tutorial will guide you on how to set up your environment to create an AI-generated NFT collection. You will learn how to configure your .env file, run the backend and frontend servers, and ensure that you have enough faucet funds.

You will need

  • A Starton API KEY
  • A Wallet with currency of your network
  • A DALL-E 2 API KEY

What is DALL-E 2?

DALL-E 2 is an artificial intelligence (AI) model developed by OpenAI. DALL-E 2 is designed to generate images from textual descriptions.

It is capable of generating complex and detailed images. It can create images that are up to 1024x1024 pixels in size, and can generate multiple objects and textures within a single image. DALL-E 2 can also create images that are animated and can be interacted with.

INSTALLING THE PROJECT

info

The project has been set up using a client-side and a server-side so that your API key is not exposed on client. You can also use the server-side to connect a database for metrics.

CREATING STARTON PROJECT

  1. Clone the project from Starton AI generative NFT collection GitHub.

SETTING UP ENVIRONMENT VARIABLES

Before you start setting up the project, you need to set the environment variables.

  1. In the backend folder of the project, set up an .env according to .env.example:
API_HOST=localhost
API_PORT=8000

## Put on the following line your Starton API key (available at https://app.starton.com)
STARTON_API_URL='https://api.starton.io/v3'
STARTON_API_KEY=

## Put on the following line your Signer wallet address
STARTON_SIGNER_WALLET=

## Put on the following line your OpenAI API key (available at https://platform.openai.com/account/api-keys)
OPEN_AI_API_KEY=
  1. In the frontend set up your .env file according to .env.example :
NEXT_PUBLIC_BACK_URL=http://localhost:8000

SETTING UP THE SERVER SIDE

Here we would like to enter the data needed to generate and deploy your collection as well as entering your API, so that you can authenticate safely to the API.

  1. Go to the backend folder of the project.
  2. Run the command yarn install to install the required dependencies.
  3. Start the server by running the command yarn dev.

SETTING UP OUR CLIENT SIDE

On the client side, we will set up all the information of your smart contract to connect your project to Web3Auth.

  1. Go to the frontend folder of the project.
  2. Run the command yarn install to install the required dependencies.

RUNNING THE PROJECT

To run your project, you will need to run commands both on server and client side.

  1. In server, run the command yarn dev
  2. In client, run the command yarn dev

Visit http://localhost:3000 to test your project.

GENERATING AND DEPLOYING YOUR COLLECTION

Once started, visit http://localhost:3000 to enter the following parameters:

  1. Enter the receiver wallet of the NFT (where you want to send the NFTs).
  2. Select the network on which you want to deploy your NFTs. If you are testing, then use the testnet network, and if you are ready to deploy, use the mainnet network (between Polygon, Avalanche, Binance, and Ethereum).
  3. Choose the number of NFTs that you want to create for your collection.
  4. Enter the prompt that will generate the images for your NFTs. You can use different prompts to create unique and personalised NFTs.
  5. Click Generate to display the assets for your NFTs.
  6. Review the generated assets.
  7. Once you are satisfied with the images, click Deploy.

Congratulations! You just deployed an NFT collection of images generated by AI.

· 4 min read
Loubna Benzaama
Learn how to receive ngrok-integrated webhooks to monitor blockchain activity locally.

You will need

  • A Starton API KEY
  • Ngrok Authentication Token
  • Basic comprehension of Node.js and Webhooks

Step 1

Creating Your Node.js Project

Set up your Node.js project environment:

  1. Create a Project Directory:

    mkdir my-starton-project
    cd my-starton-project
  2. Initialize Your Node.js Project:

    npm init -y
  3. Install Essential Packages:

    npm install express dotenv axios body-parser ngrok node-notifier
    • express: A minimal and flexible Node.js web application framework for building APIs and web servers.
    • dotenv: Loads environment variables from a .env file into process.env, managing configuration settings separately from the code.
    • axios: A promise-based HTTP client for making asynchronous HTTP requests to external resources, like REST APIs.
    • body-parser: Middleware for Express that parses incoming request bodies, making them available under the req.body property.
    • ngrok: Exposes local development servers to the Internet, useful for testing applications that interact with external services like webhooks.
    • node-notifier: A module for sending native desktop notifications, providing visual feedback from scripts or applications.

Understanding Webhooks

Webhooks dispatch automated HTTP POST requests activated by specific events in a source system. They relay data to a recipient system. With Starton, watchers utilize webhooks to send event notifications.

Step 2

Setting Up Environment Variables

  1. Configuring Variables: Create or update the .env file in your project's root directory:
STARTON_API_KEY=YOUR_STARTON_API_KEY
NGROK_TOKEN=YOUR_NGROK_AUTH_TOKEN
  1. Retrieving Your Ngrok Authentication Token

  2. Sign Up or Log In: Visit Ngrok's website and sign up or log in.

  3. Find the Token: In the dashboard, go to Your Authtoken and click Copy.

Step 3

Configuring the Watcher Integration

In your project's root directory, create a file named index.js and insert the following code: Tailor the watcher parameters and the rest of the code to suit your project's needs.

const express = require("express");
const bodyParser = require('body-parser');
const notifier = require('node-notifier');
const ngrok = require('ngrok');
const axios = require("axios");
require('dotenv').config();

const app = express();
app.use(bodyParser.json());

const axiosInstance = axios.create({
baseURL: "<https://api.starton.com>",
headers: {
"x-api-key": process.env.STARTON_API_KEY,
},
});
let watcherId = null;

app.post('/', (req, res) => {
if (req.body.data) {
notifier.notify({
title: 'New transaction',
message: `Hash: ${req.body.data.transaction.hash}`
})
}
res.send('ok')
})
const port = 30001
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
createNgrokTunnelAndWatcher()
})

const createNgrokTunnelAndWatcher = async () => {
const url = await ngrok.connect({
authtoken: process.env.NGROK_TOKEN,
addr: port
})
console.log(`NGROK listening on ${url}`)
axiosInstance.post("/v3/watcher", {
name: "Watcher test",
address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
network: "polygon-mainnet",
type: "EVENT_TRANSFER",
webhookUrl: url,
confirmationsBlocks: 0
}).then((response) => {
console.log("Watcher created", response.data)
watcherId = response.data.id
}).catch(e => console.log(e.response.data))
}

Tailor the watcher parameters to your needs like so :

name: "Watcher test",name of your watcher in Starton (learn more)
address:"0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",address watched on the blockchain (learn more)
network: "polygon-mainnet",network on which we are creating the watcher (learn more)
type: "EVENT_TRANSFER",Type of event returned by the watcher (learn more)
webhookUrl: url,Url of your webhook (learn more)
confirmationsBlocks: 0Number of confirmation blocks (learn more)

Step 4

Automating the deletion of our test watcher

After testing, ensure to delete the watcher to prevent unintended operations.

const deleteWatcher = async () => {
await axiosInstance.delete(`/v3/watcher/${watcherId}`).then(response => {
console.log("Watcher deleted")
})
process.exit();
}

process.on('SIGINT', deleteWatcher)
process.on('SIGTERM', deleteWatcher)

Step 5

##Running the Project**

  1. Server: Start your server using the command:

    node index.js

  2. Client: Access your application by visiting http://localhost:3000 in a browser.

Step 6

Setting Up Webhooks with Ngrok**

  1. Launching Ngrok:

    ngrok http 3000

    Document the provided URL for webhook testing.

  2. Webhook Examination: Use the Ngrok URL as the webhook endpoint when creating the watcher.

Congratulations! You've successfully integrated Starton's Monitor with webhook notifications using Ngrok. This setup allows you to monitor blockchain activities locally and in real-time. As you transition to a production environment, remember to use permanent and secure webhook endpoints.

· 4 min read
Loubna Benzaama

In this tutorial, we’ll use Starton Connect to create our own crypto token!

We will deploy a smart contract directly from code using the Relayer.

The contract will be an instance of an audited premade template available in Starton.

The language used will be Javascript but any language would work in a similar manner.

Get the list of available templates

Before deploying our contract let's get the list of templates in order to find one that suits our need.

To do this, we’ll need to query Connect’s API and to authenticate ourselves using an API key.

We can create an API key from the dashboard in the Developer section. Using this API key we can call the API with the following JS code:

const axios = require("axios")

const http = axios.create({
baseURL: "https://api.starton.com/v3",
headers: {
"x-api-key": "YOUR_API_KEY",
},
})
http.get("/smart-contract-template").then((response) => {
console.log(response.data)
})

Be sure to replace x-api-key value with your own api key! When querying the API, it should return a list of template items:

{
"id": "ERC20_META_TRANSACTION",
"name": "ERC20 Fungible Token with fixed supply",
"description": "An ERC20 token contract keeps track of fungible tokens: any one token is exactly equal to any other token",
"tags": ["..."],
"blockchains": ["..."],
"bytecode": "string",
"constructorParams": ["..."],
"abi": ["..."],
"compilerVersion": "string",
"source": "string",
"isAudited": true,
"isActivated": true,
"createdAt": "string",
"updatedAt": "string"
}

This is the object associated with the template we’ll use for our crypto token.

We’ll be using an ERC20 template as it is the standard for token creation on EVM based blockchains.

Choose a Network and fuel wallet

Now that we know which template to use, we also need to choose a network on which to deploy.

The compatible blockchains for this template can be seen inside the blockchain objects in the previously returned template object.

For example for the Ethereum blockchain there are multiple available networks such as ethereum-mainnet or ethereum-sepolia (testnet).

We’ll choose to deploy our contract on the ethereum-sepolia network.

It is now important that we fuel our wallet with some Ether faucet otherwise the blockchain will reject our smart contract’s deployment as we will lack funds to cover the gas fees.

In order to claim test faucets we need to go on the Wallet section on Connect’s dashboard and find the address associated to the network we are interested in.

Here, it is the ethereum-sepolia network.

We can now claim free faucet on the official Ethereum faucet website. Enter your address, click Send me test Ether and wait for the transaction to complete.

Deploying the contract

Everything is now in place so we can create an instance of the smart contract template we picked.

We’ll use the ID of the template we got in order to tell Deploy which template to use for the contract creation.

We also need to provide values for the parameters of our smart contract’s constructor.

For our ERC20, we’ll need to provide:

  • a name for our token
  • a ticker
  • the initial supply

Let’s call our token the DemoToken, with DEMO as its ticker and an initial supply of 1.000.000 tokens.

Here is the code to deploy the contract (Axios being configured as before):

http.post("/smart-contract/from-template", {
network: "ethereum-sepolia",
templateId: "ERC20_META_TRANSACTION",
name: "DemoToken",
description: "Our own crypto token.",
params: ["1000000", "DemoToken", "DEMO"],
}).then((response) => {
console.log(response.data)
})

The expected result:

{
"id": "sc_24dce9e26a7d46a7b707e257a6a6cfb2",
"name": "DemoToken",
"description": "Our own crypto token.",
"network": "ethereum-sepolia",
"bytecode": " … ",
"abi": ["..."],
"projectId": "prj_f2108b28949d47898a39939cbc7277c3",
"address": "0xDA96a733ec2C3eC1142A5A1Ef31cfd7755CAE037",
"creationHash": "0xef4313209959d6441e14db5d43905f674a78adba2173b522b7fe37311e135c05",
"createdAt": "Tue Jun 29 2021 13:09:17 GMT+0000 (Coordinated Universal Time)",
"updatedAt": "Tue Jun 29 2021 13:09:17 GMT+0000 (Coordinated Universal Time)"
}

If it worked, congrats! You just created your own crypto token in a few minutes and with a minimal amount of code.

Checking the contract creation

Most blockchains propose a blockchain explorer so we can inspect the state and history of the blockchain.

We can thus use the previously returned address and creation hash to check for our contract’s status on the blockchain.

The summary of the transaction created for the deployment of our contract (using the creationHash in the url) is available. We can also track here our new DEMO token.

Result

Or more generally, we can use the address of the contract to find out how it interacted with the world.

Congratulations for completing this tutorial!

You can also deploy your smart contract from our web application.

· 4 min read
Loubna Benzaama

WHAT IS WEB3AUTH?

Web3auth is an open-source authentication library for web3 applications. It allows users to authenticate with wallets using a social login flow. Similarly, Web3auth offers a solution of wallet address from social login, allowing users to discover Web3 while using a login system they are most likely used to.

This tutorial will cover how to create meta transactions with Starton and Web3auth. Meta transactions are a useful way to onboard users to the Web3 ecosystem by allowing them to use their familiar social login system, and execute transactions without having to pay gas fees or have Ether in their wallets.

By using two routes on Starton, you can create meta transactions. This use case is handy when you want to onboard users to web3.

PREREQUISITES

You will need :

  • A smart contract that implements ERC20 interface. Starton Smart contract templates support Metatransactions. To deploy an ERC20 with Starton, go to How to create your own crypto currency.
  • A Starton API key

Installing the project

The project has been set up using a client-side and a server-side so that your API key is not exposed on client. You can also use the server-side to connect a database for metrics.

Creating Starton Project

  1. Clone the project from Starton Metatransactions GitHub.

Setting up the server side

Here we would like to enter the data needed to request funds and set up your metatransactions as well as entering your API, so that you can authenticate safely to the API.

  1. In server, add your Starton API key in .env.
  2. In src > config > startonconfig.ts, set the following parameters:
    • the route to interact with your smart contract call URL (ex: /smart-contract/avalanche-fuji/0xcEB17Bf0E3d198ec985370f456332f10f373CdB3/call)
    • the speed of your transaction (ex: low, average, fast, fastest)
    • the signer wallet
    • the amount of requested funds

Let’s continue with our config files in client.

Setting up our client side

On the client side, we will set up all the information of your smart contract to connect your project to Web3Auth.

  1. Install the client side.

  2. In client, add the port where your server is running in .env.

  3. In src > config >smart-contract go to smartContract.config.ts and set the following parameters:

    • the version of your smart contract
    • the name of your smart contract
    • the chainId of the network on which you deployed your contract
    • the address of your smart contract

    USING FUNCTIONS TO RETRIEVE YOUR SMART CONTRACT INFORMATION

    You can retrieve all of this information using the Interact tab of your smart contract. Learn more

  4. In src>config > smart-contractABI.config.ts, enter the ABI of your contract.

  5. In starton, go to starton.config.ts, enter the value of the meta transaction.

  6. In src > services> ethersRPC.ts, enter the wallet from which to transfer.

  7. In src > hooks> useWeb3AuthInit.ts:

    1. In chainId, replace the value in Number(43113) with the chainId of your network.
    2. In rpcTarget, enter the address of your node, such as 'https://api.avax-test.network/ext/bc/C/rpc'.

    info

    You can find public nodes on https://chainlist.org/

Now that we’re all set, let’s run our project.

Running the project

To run your project, you will need to run commands both on server and client side.

  1. In server, run the command npm run build

  2. Then, run npm run start

  3. In client, run the command npm run build

  4. Then, run npm run start

    Visit http://localhost:3000 to test your project.

Now that you have used our project, visit this guide to learn more about the project How did we build a Meta-Transaction Site with Web3Auth and Starton.

· 6 min read
Loubna Benzaama
When creating and selling a collection, you can allow only a few chosen people to buy them for a defined price. This system is called a whitelist sale and it is what we are going to see today.

You will need

  • nodejs (version 16 or over)
  • npm
  • ethers v5
  • merkletreejs
  • a deployed ERC721 NFT contract

note

To deploy a Sale contract, you must have deployed your NFT by deploying an ERC721 contract first. Learn how to Deploy your NFT with Starton

In this tutorial, we will:

    Create a merkle root from all approved addresses
    Deploy the Sale contract from API
    Interact with the contract
To deploy this contract, you need to compute a special parameter called definitiveMerkleRoot.

Step 1

Creating a merkle root from all approved addresses

The best way to create a whitelist in solidity is by generating a merkle tree. It is a data structure that can store many data in a limited space which ends up being a merkle root.

To be able to generate this parameter, you will need to use this code snippet:

import { ethers } from "ethers"
import { MerkleTree } from "merkletreejs"

// Compute the root of the merkletree
const addresses = [
/* The addresses of the wallets allowed to mint */
]
const leaves = addresses.map((addr) => ethers.keccak256(addr))
const merkleTree = new MerkleTree(leaves, ethers.keccak256, { sortPairs: true })
const rootHash = merkleTree.getRoot()

caution

Don’t forget to replace addresses with the actual wallet addresses of the whitelisted accounts.

Step 2

Deploying the Sale contract from API

After you computed the root of the Merkle Tree, you can deploy the contract:

const axios = require("axios")

const axiosInstance = axios.create({
baseURL: "https://api.starton.com",
headers: { "x-api-key": "PUT HERE YOUR API KEY" },
})

axiosInstance
.post("/v3/smart-contract/from-template", {
network: "",
signerWallet: "",
templateId: "ERC721_SALE",
name: "My first NFT Whitesale",
description: "This is my first NFT Whitesale ",
params: [
"", // definitiveTokenAddress
"", // definitiveMerkleRoot
"", // definitivePrice
"", // definitiveStartTime
"", // definitiveEndTime
"", // definitiveMaxTokensPerAddress
"", // definitiveMaxSupply
"", // definitiveFeeReceiver
],
speed: "average",
})
.then((response) => {
console.log(response.data)
})
  • definitiveTokenAddress: The address of the previously deployed ERC721
  • definitiveMerkleRoot: The merkle root
  • definitivePrice: The price to sell each token
  • definitiveStartTime: The time when the sale will start
  • definitiveEndTime: The time when the sale will end
  • definitiveMaxTokensPerAddress: The max amount of tokens a single address can buy
  • definitiveMaxSupply: The total amount of tokens that can be sold
  • definitiveFeeReceiver: The address that will receive all the price paid to mint

Step 3

Granting role on your base contract

For the whitelist sale contract to be able to mint new tokens, you are going to need to grant the newly created contract the MINTER_ROLE over the base contract deployed.

You will need

  • the address of the base ERC721 contract
  • the address of the Sale contract
  • the data of the Minter Role (in bytes)

Retrieving the MINTER_ROLE

First, let's get the minter role:

const axios = require("axios")

const axiosInstance = axios.create({
baseURL: "https://api.starton.com",
headers: {
"x-api-key": "PUT HERE YOUR API KEY",
},
})

axiosInstance
.post("/v3/smart-contract/{network}/{YOUR_BASE_CONTRACT}/read", {
functionName: "MINTER_ROLE",
params: [],
})
.then((response) => {
console.log(response.data)
})

Granting the minter role to your Sale contract

To grant the minter role to your contract, you can use the following request:

const axios = require("axios")

const axiosInstance = axios.create({
baseURL: "https://api.starton.com",
headers: { "x-api-key": "PUT HERE YOUR API KEY" },
})

axiosInstance
.post("/v3/smart-contract/${network}/${YOUR SMART CONTRAT ADDRESS}/call", {
functionName: "grantRole(bytes32,address)",
params: [
"0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6", // MINTER_ROLE
"", // account
],
signerWallet: "",
speed: "average",
})
.then((response) => {
console.log(response.data)
})
  • account: The whitelist sale contract address

Step 4

Interacting with the contract

You can access different parameters of the contract using these functions:

priceGet the price to mint one token
startTimeGet the start time of the sell
endTimeGet the end time of the sell
maxTokensPerAddressGet the max tokens per address
leftSupplyGet the total amount of tokens that can still be minted
tokensClaimed(address)Get the total amount already minted by an address

And finally you can use the withdraw function to withdraw all the fees earned to the definitiveFeeReceiver.

  • definitiveMaxTokensPerAddress: The max amount of tokens a single address can buy
  • definitiveMaxSupply: The total amount of tokens that can be sold
  • definitiveFeeReceiver: The address that will receive all the price paid to mint

Minting a NFT

Now that the contract is deployed, every user can mint a token.

To be able to do this, every user will need to specify two parameters while minting:

  • the address of the receiver of the NFT
  • the merkle proof

This proof is also linked to the merkle tree and it can prove that an address is inside the merkle tree To be able to generate it, you can use this code snippet:

import { keccak256 } from "ethers/lib/utils"
import { MerkleTree } from "merkletreejs"

// Compute the root of the merkletree
const addresses = [
/* The addresses of the wallets allowed to mint */
]
const leaves = addresses.map((addr) => keccak256(addr))
merkleTree = new MerkleTree(leaves, keccak256, { sortPairs: true })

// replace MINTER_ADDRESS with the address of the account that will mint the NFT
const proof = merkleTree.getHexProof(keccak256(MINTER_ADDRESS))

Users will then be able to mint a new token using their wallet such as metamask with the right parameters.

Step 5

Integrating the Sale to your application

Congrats! You're now all set for your NFT Sale. You can connect this smart contract using the mint function to a button. By, using etherjs/web3js, call the mint function of the sale contract with the desired address.

You can also give more information on this mint page such as NFT left to mints or end time of the sale.

Shall we continue ?

How to create your own cryptocurrency (ERC20)
How to sell an NFT collection in an auction