# Function insights

This page provides a behind-the-scenes look at the text-based token minting and contract deployment processes within the Xyxyx API. We will illustrate how the [Ethers v6 Library](https://docs.ethers.org/v6/getting-started/) is used under the hood, and why the wallet private key is critical to sign transactions autonomously — allowing calls to be made without user interaction via a front-end.

***

#### Overview

By leveraging Ethers, the API can:

1. **Connect to the blockchain** via a provider (e.g., `ethers.JsonRpcProvider`).
2. **Create a wallet** (signer) using the private key that you provide in each request.
3. **Deploy contracts** through the `ContractFactory`.
4. **Mint tokens** by calling contract methods.

Because the private key is included with every request (rather than stored server-side), you remain fully responsible for its confidentiality. However, this design still allows an entirely automated flow for contract deployment and token minting, without interactive wallet confirmations.

***

#### Mint Token

```js
const { ethers } = require("ethers");

const contractAbi = require("../utils/ERC-721F/abi.json");

// Load the contract
const contract = new ethers.Contract(contractAddress, contractAbi, wallet);

// Mint cost in wei (10000000000 WEI === 0.00000001 ETH)
const weiCost = ethers.parseUnits(mintCost.toString(), "wei");

// Execute the mint function on the contract
const tx = await contract.mint(tokenId, svgBody, { value: weiCost });

// Wait for the transaction to be mined
const receipt = await tx.wait();
```

**Explanation**

1. **Import Ethers:**\
   Using `require("ethers")` imports the core Ethers library.
2. **Load Contract ABI:**\
   The ABI (Application Binary Interface) `abi.json` describes the functions, events, and error signatures of the ERC-721F contract. It allows Ethers to understand how to encode calls to `mint()` and decode contract responses.
3. **Create Contract Instance:**

   ```js
   const contract = new ethers.Contract(contractAddress, contractAbi, wallet);
   ```

   * `contractAddress` is the on-chain address of the deployed contract.
   * `contractAbi` is the ABI loaded from the JSON file.
   * `wallet` is an instance of `ethers.Wallet`, which includes the private key (provided by the user in the request) and a provider.
   * Passing the `wallet` as the third parameter ensures that all contract calls are signed by the wallet.
4. **Calculate Mint Cost in Wei:**

   ```js
   const weiCost = ethers.parseUnits(mintCost.toString(), "wei");
   ```

   * `ethers.parseUnits()` converts a string or numeric value into a **BigInt** representing the smallest unit (in this case, wei).
   * This is crucial for Ethereum transactions, which require values in wei rather than ETH.
5. **Call the Mint Function:**

   ```js
   const tx = await contract.mint(tokenId, svgBody, { value: weiCost });
   ```

   * `mint(tokenId, svgBody, { value: weiCost })` executes the smart contract’s `mint()` method.
   * The `value` field indicates how much Ether (in wei) to send along with the transaction.
   * Behind the scenes, the wallet signs this transaction, requiring no additional user confirmation beyond providing the private key up front.
6. **Await Transaction Confirmation:**

   ```js
   const receipt = await tx.wait();
   ```

   * Ethers `wait()` method suspends execution until the transaction is mined on the blockchain.
   * The returned `receipt` includes details like block number, gas used, and transaction status.

**Reference Material**

* [Contracts in Ethers v6](https://docs.ethers.org/v6/getting-started/#contracts)
* [Signers and Wallets](https://docs.ethers.org/v6/getting-started/#accounts)

***

#### Deploy Smart Contract

```js
// Create the ContractFactory
const factory = new ethers.ContractFactory(deployData.abi, deployData.bytecode, wallet);

// Deploy the contract with the given parameters
const contractFactory = await factory.deploy(name, ticker, parseInt(supply), mintPrice, onlyOwnerMint);

// Wait for the contract to be mined
await contractFactory.deploymentTransaction().wait();

// Retrieve the deployed contract address
const contractAddress = await contractFactory.getAddress();
const deploymentHash = await contractFactory.deploymentTransaction().hash;
```

**Explanation**

1. **Initialize ContractFactory:**

   ```js
   const factory = new ethers.ContractFactory(deployData.abi, deployData.bytecode, wallet);
   ```

   * `deployData.abi` is the ABI for the contract being deployed.
   * `deployData.bytecode` contains the compiled contract bytecode.
   * The `wallet` signer is provided by the user on each request and used to sign the deployment transaction.
2. **Deploy the Contract:**

   ```js
   const contractFactory = await factory.deploy(name, ticker, parseInt(supply), mintPrice, onlyOwnerMint);
   ```

   * `factory.deploy(...)` sends a transaction to create a new contract on-chain.
   * The parameters (`name`, `ticker`, `supply`, `mintPrice`, `onlyOwnerMint`) are passed to the constructor of the contract.
   * Under the hood, Ethers automatically calculates the gas limit and constructs the transaction data required for deployment.
3. **Await Mining:**

   ```js
   await contractFactory.deploymentTransaction().wait();
   ```

   * Similar to the mint example, this waits until the deployment transaction is confirmed.
   * Once confirmed, the contract is live on the blockchain.
4. **Obtain Deployment Details:**

   ```js
   const contractAddress = await contractFactory.getAddress();
   const deploymentHash = await contractFactory.deploymentTransaction().hash;
   ```

   * `getAddress()` retrieves the newly deployed contract address.
   * `deploymentTransaction().hash` gives the transaction hash of the deploy transaction.
   * These details can be used for logging, user notifications, or subsequent on-chain interactions.

**Reference Material**

* [Contract Factories in Ethers v6](https://docs.ethers.org/v6/getting-started/#contracts%E2%80%93contractfactory)
* [Transaction Lifecycle](https://docs.ethers.org/v6/getting-started/#transactions)

***

#### Why the private key is necessary?

* **Automatic signing:** Without the private key provided in each request, every transaction would require interactive approval from a front-end wallet (e.g., MetaMask). This manual process is not suitable for automated or large-scale operations.
* **Autonomous execution:** Including the private key in the API call allows the service to sign and broadcast transactions programmatically, enabling continuous, unattended minting and deployment.

***

#### Security & Custody

* **User responsibility:** The Xyxyx API does not store or persist your private key. You are required to provide the private key each time you make a request. As a result, you have full responsibility for its security.
* **Protecting your key:** If your private key is compromised, unauthorized transactions could be performed on your behalf. Always use secure channels and best practices when transmitting private keys.
* **No server-side sustody:** Since the API does not manage or retain your private key, there is no server-side wallet custody. Every signed transaction is generated by you, on demand, within each request.

***

#### Summary

By integrating Ethers v6 and requiring the wallet private key on every request, the Xyxyx API lets you deploy contracts or mint tokens without building a separate front-end signing flow. This approach empowers full autonomy while keeping private key custody in your hands.
