# What is Ternoa Chain ?

Ternoa is a next-generation PayFi Layer 2 designed for maximum capital efficiency, combining advanced cryptographic security with seamless programmability. Built on a modular architecture, Ternoa integrates zkEVM, Polygon CDK, Avail DA, a private DAC for redundancy, Polygon AggLayer, and a decentralized keystore to enable secure and scalable financial operations.

What sets Ternoa apart is its **TEE Integrity Proof technology**, which ensures the security and decentralization of traditionally centralized infrastructure within the Layer 2 ecosystem. This allows Ternoa to provide **trust-minimized, high-performance financial applications** without sacrificing decentralization or security.

This document explores the core innovations behind Ternoa, how its unique tech stack strengthens the PayFi ecosystem, and why it stands out in the evolution of blockchain-based finance.


# Polygon CDK zkEVM

### **What is Polygon CDK?**

Polygon CDK (Chain Development Kit) is a modular framework for building custom Layer 2 blockchains powered by Ethereum. It enables developers to launch high-performance chains with **scalability, low fees, and seamless interoperability**, all while inheriting Ethereum’s security.

### **Why Ternoa Chose Polygon CDK**

Ternoa leverages **Polygon CDK** to build a capital-efficient, **zkEVM-powered** Layer 2 tailored for high-performance financial applications. With CDK, we unlock:

🟧 **Scalability** – Massive throughput and low gas fees without compromising decentralization.\
🟧 **Interoperability** – Seamless interaction with Ethereum, Polygon, and other zkEVM-based chains.\
🟧 **Ethereum-Grade Security** – Transactions are secured by Ethereum’s finality.\
🟧 **EVM Compatibility** – Full smart contract equivalence with Ethereum for effortless migration.\
🟧 **Modular Flexibility** – Customizable components to optimize efficiency and performance.

### **How Polygon CDK Enhances Ternoa’s Ecosystem**

By integrating **Polygon CDK**, Ternoa benefits from:

✔️ **Customizable Data Availability** – Choose between on-chain, off-chain, or hybrid DA solutions.\
✔️ **Optimized Settlement Layers** – Faster finality with built-in cross-chain communication.\
✔️ **Seamless Rollup Infrastructure** – Native zkEVM support for privacy, security, and efficiency.\
✔️ **Bridging-Ready Architecture** – Instant asset and liquidity movement across networks.

### **Empowering Developers with CDK**

With **Polygon CDK**, developers building on Ternoa gain:

🔸 **EVM-Equivalent Smart Contracts** – No need to rewrite or modify existing Solidity code.\
🔸 **High Throughput & Cost Efficiency** – Scale without congestion or excessive fees.\
🔸 **Composable Infrastructure** – Build modular dApps that integrate seamlessly with DeFi, gaming, and more.


# Polygon AggLayer

## **Polygon AggLayer: Unifying Liquidity & Connectivity Across Chains**

### **What is Polygon AggLayer?**

Polygon AggLayer is an **aggregation and interoperability layer** designed to seamlessly connect multiple Layer 2s, rollups, and appchains into a unified network. It enables **instant cross-chain execution, shared liquidity, and seamless interoperability**, solving the fragmentation issues that hinder blockchain scalability.

### **Why Ternoa Integrates AggLayer**

Ternoa leverages **Polygon AggLayer** to provide **a seamless, low-latency, and highly liquid environment** for financial applications. This integration enables:

🟧 **Instant Cross-Chain Transactions** – Execute cross-rollup interactions without waiting for slow bridging mechanisms.\
🟧 **Unified Liquidity** – Aggregate liquidity across multiple chains, reducing slippage and inefficiencies.\
🟧 **Interoperability by Default** – Smart contracts can interact across different Layer 2s without additional modifications.\
🟧 **Ethereum-Backed Security** – Transactions settle with Ethereum’s finality, maintaining high security standards.

### **How AggLayer Powers Ternoa**

With **Polygon AggLayer**, Ternoa enhances:

✔️ **Capital Efficiency** – Assets and liquidity can freely move across integrated chains.\
✔️ **Composable dApps** – Developers can build applications that interact seamlessly across multiple Layer 2s.\
✔️ **Faster Settlements** – Near-instant finality across ecosystems without relying on slow legacy bridges.\
✔️ **Scalability Without Fragmentation** – Connects multiple rollups without compromising decentralization.

### **Empowering Developers with AggLayer**

With **AggLayer**, developers building on Ternoa gain:

🔸 **Seamless dApp Interoperability** – No need for custom bridges; smart contracts interact natively across chains.\
🔸 **Shared State & Liquidity** – Deploy applications that access a larger liquidity pool across different Layer 2s.\
🔸 **Optimized Cross-Chain Execution** – Leverage AggLayer’s infrastructure to create **fluid, multi-chain experiences**.


# Avail DA

### **What is Avail DA?**

Avail DA (Data Availability) is a **highly scalable and decentralized data availability layer** designed to ensure that blockchain transactions remain verifiable, even in high-throughput environments. It provides **efficient data posting, retrieval, and verification**, allowing rollups and Layer 2s to scale without sacrificing security.

### **Why Ternoa Uses Avail DA**

Ternoa integrates **Avail DA** to optimize **data storage, retrieval, and availability** for its Layer 2 network. This enables:

🟧 **Scalability Without Compromise** – High data throughput without increasing on-chain storage costs.\
🟧 **Reliable Data Verification** – Ensures that transaction data remains publicly available and verifiable.\
🟧 **Optimized Rollup Infrastructure** – Reduces dependency on Ethereum L1 for data storage.\
🟧 **Decentralized and Trust-Minimized** – Avoids centralized dependencies for data availability.

### **How Avail DA Strengthens Ternoa**

By leveraging **Avail DA**, Ternoa benefits from:

✔️ **Modular Design** – Enables seamless integration with zkEVM rollups and Layer 2 architectures.\
✔️ **Data Availability Sampling (DAS)** – Ensures verifiability while keeping costs low.\
✔️ **Ethereum & Multi-Chain Compatibility** – Works across multiple blockchain ecosystems.\
✔️ **Cost-Efficient Storage** – Reduces data posting expenses while maintaining security.

### **Empowering Developers with Avail DA**

For builders on Ternoa, **Avail DA** provides:

🔸 **Trustless Data Storage** – No reliance on centralized entities for data availability.\
🔸 **Low-Cost Scaling** – Efficiently handles large volumes of data without congestion.\
🔸 **High Availability** – Guarantees that transaction data remains accessible and verifiable.


# Trusted Execution Environments 

### **What is a Trusted Execution Environment (TEE)?**

A **Trusted Execution Environment (TEE)** is a secure enclave within a processor that enables confidential computing by isolating sensitive computations from the rest of the system. It ensures that even if the operating system, hypervisor, or other software is compromised, the data and code inside the TEE remain protected.

### **Why Ternoa Uses Intel SGX?**

Ternoa integrates **Intel SGX (Software Guard Extensions)** to enhance **confidentiality, integrity, and security** for its Layer 2 network. This enables:

🟧 **End-to-End Data Protection** – Sensitive computations run in isolated enclaves, shielded from external threats.\
🟧 **Verifiable Integrity** – Code inside SGX enclaves can be remotely attested, proving it hasn’t been tampered with.\
🟧 **Decentralized Security for Layer 2** – Protects critical operations such as transaction validation and key management.\
🟧 **Defense Against Insider Attacks** – Even privileged system administrators cannot access the encrypted enclave data.

### **How Intel SGX Powers Ternoa’s Infrastructure**

By leveraging **Intel SGX**, Ternoa ensures:

✔️ **Tamper-Proof Execution** – Even compromised servers cannot alter or leak enclave-protected data.\
✔️ **Secure Key Management** – Cryptographic operations and key storage are protected inside the enclave.\
✔️ **Privacy-Preserving Computation** – Enables zk-proof generation and verification without data exposure.\
✔️ **Remote Attestation** – Verifiable proofs that Ternoa’s integrity-sensitive components remain unaltered.


# Wallets

## **Ternoa Wallet Compatibility**

### **Seamless Access with Any EVM-Compatible Wallet**

Ternoa is fully compatible with **all EVM wallets**, allowing users to seamlessly interact with the network using their preferred wallet applications. Whether you’re using **MetaMask, Rabby, Trust Wallet, Ledger, or any other EVM-supported wallet**, connecting to Ternoa is simple and secure.

### **How to Connect to Ternoa**

To manually add **Ternoa’s zkEVM network** to your wallet, use the following details:

🔸 **Network Name:** Ternoa zkEVM\
🔸 **RPC URL:** <https://rpc-mainnet.zkevm.ternoa.network/>\
🔸 **Chain ID:** `752025`\
🔸 **Currency Symbol:** `$CAPS`\
🔸 **Block Explorer URL:** <http://explorer-mainnet.zkevm.ternoa.network>

### **Why Use Ternoa?**

🟧 **Full EVM Compatibility** – No need to switch wallets; Ternoa works seamlessly with existing EVM setups.\
🟧 **Secure & Scalable** – Built on zkEVM technology for faster, low-cost transactions.\
🟧 **PayFi-Optimized** – Designed for **next-gen programmable finance** and seamless DeFi integrations.

### **Getting Started**

1️⃣ Open your wallet (MetaMask, Rabby, etc.).\
2️⃣ Navigate to **Networks** and click **Add a Custom Network**.\
3️⃣ Enter the **Ternoa RPC details** above and save.\
4️⃣ Start transacting securely on **Ternoa’s zkEVM Layer 2**.

🟠 **Ternoa is ready for you—connect and explore the future of finance today!**


# RPC

## **Ternoa RPC: Connect to the Network with Ease**

### **What is an RPC?**

An **RPC (Remote Procedure Call)** is the gateway that allows wallets, dApps, and developers to interact with the Ternoa blockchain. It enables users to send transactions, query data, and execute smart contracts seamlessly on **Ternoa’s zkEVM Layer 2 network**.

### **Ternoa Mainnet RPC Details**

To connect to **Ternoa’s zkEVM network**, use the following RPC information:

🔸 **RPC URL:** <https://rpc-mainnet.zkevm.ternoa.network/>\
🔸 **Chain ID:** `752025`\
🔸 **Network Name:** Ternoa zkEVM\
🔸 **Currency Symbol:** `$CAPS`


# API

## **Ternoa API: Unlock Seamless Blockchain Integration**

### **What is the Ternoa API?**

The **Ternoa zkEVM+ API** provides developers with a powerful suite of RESTful endpoints to interact seamlessly with the **Ternoa blockchain**. It enables easy access to blockchain data, token management, and network interactions—allowing developers to build robust applications on **Ternoa’s zkEVM Layer 2**.

### **Key Features**

🟧 **Blockchain Data Access** – Query information on blocks, transactions, and addresses in real-time.\
🟧 **Token Management** – Retrieve balances, execute transfers, and track token activity.\
🟧 **Smart Contract Interactions** – Read contract states and execute calls directly from your app.\
🟧 **Network Monitoring** – Access real-time network status, gas fees, and key blockchain metrics.

### **API Endpoints Overview**

🔸 **Blocks & Transactions:** Fetch details about blocks, transactions, and confirmations.\
🔸 **Accounts & Balances:** Retrieve account details, token balances, and transfer history.\
🔸 **Contract Calls:** Interact with deployed smart contracts via read operations.\
🔸 **Network Status:** Get real-time network health, gas price estimates, and sync status.

### **How to Use the API**

1️⃣ **Explore API Docs:** Visit the full documentation [here](https://explorer-mainnet.zkevm.ternoa.network/api-docs).\
2️⃣ **Integrate in Your App:** Use RESTful API calls to fetch blockchain data and execute transactions.\
3️⃣ **Deploy & Scale:** Leverage **Ternoa’s zkEVM+ API** to build scalable, blockchain-powered applications.


# Explorer

### **What is the Ternoa Explorer?**

The **Ternoa Explorer** is the official blockchain explorer for **Ternoa’s zkEVM Layer 2**, providing real-time access to **transactions, blocks, accounts, smart contracts, and network analytics**. It enables users, developers, and validators to **verify and track all on-chain activities** in a transparent and user-friendly interface.

🔗 **Access the Explorer:** [Ternoa Explorer](https://explorer-mainnet.zkevm.ternoa.network/)

### **Key Features**

🟧 **Transaction Tracking** – Search and monitor transaction details, statuses, and gas fees.\
🟧 **Block Exploration** – View block confirmations, validators, and timestamps.\
🟧 **Account & Token Lookup** – Check wallet balances, token holdings, and activity history.\
🟧 **Smart Contract Insights** – Analyze deployed contracts, method calls, and interactions.\
🟧 **Network Health Monitoring** – Access real-time network status, gas price updates, and validator activity.

### **Why Use the Ternoa Explorer?**

🔸 **Full Transparency:** Verify every on-chain action with open access to transaction data.\
🔸 **Developer-Friendly:** Essential insights for debugging smart contracts and tracking gas usage.\
🔸 **User-Focused:** Easily check wallet balances, token transfers, and dApp interactions.\
🔸 **Security & Trust:** A **verifiable ledger of on-chain transactions**, ensuring decentralized integrity.

### **How to Use the Ternoa Explorer**

1️⃣ **Search by Transaction Hash, Address, or Block Number** – Instantly access relevant blockchain data.\
2️⃣ **Monitor Network Status** – Check gas fees, block confirmations, and validator performance.\
3️⃣ **Verify Smart Contracts** – Inspect deployed contracts and interaction histories.


# Staking

## T**ernoa Staking: Earn the Best Yield on $CAPS**

### **What is Ternoa Staking?**

Ternoa Staking allows $CAPS holders to **secure the network and earn high-yield rewards** while benefiting from additional incentives across the **Ternoa ecosystem**. By staking your $CAPS, you gain access to **the best yields, sustainable rewards, and exclusive ecosystem benefits**.

🔗 **Start Staking Now:** [staking.ternoa.network](https://staking.ternoa.network/)

### **Why Stake $CAPS?**

🟧 **Best Yield for $CAPS** – Maximize your returns with the most competitive APY.\
🟧 **Secure the Network** – Strengthen Ternoa’s blockchain while earning passive rewards.\
🟧 **Ecosystem Rewards** – Unlock additional incentives, including airdrops and exclusive perks.\
🟧 **Simple & Instant Staking** – One-click staking with no complex delegation process.

### **How to Stake $CAPS**

1️⃣ **Connect Your Wallet** – Open [staking.ternoa.network](https://staking.ternoa.network/) and connect your wallet.\
2️⃣ **Click “Stake”** – Enter the amount of $CAPS you want to stake.\
3️⃣ **Earn Rewards** – Start accumulating rewards instantly!

### **Unlock Extra Benefits from the Ternoa Ecosystem**

Staking $CAPS doesn’t just earn you yield—it also grants access to **exclusive ecosystem rewards**, including:

🔸 **Future Airdrops** – Be eligible for rewards from upcoming Ternoa projects.\
🔸 **Exclusive Access** – Priority participation in governance and ecosystem initiatives.\
🔸 **Sustainable Staking Model** – Designed to optimize long-term yield and network security.


# Ternoa Safe

### **What is Ternoa SAFE?**

Ternoa SAFE is a **multi-signature smart contract wallet** that enables secure asset management and transaction approvals. Built on **Ternoa zkEVM**, SAFE ensures **trustless, multi-party control over funds** while providing robust security through **smart contract verification and decentralized execution**.

🔗 **Contract Address & Verification:**

* **Safe.sol** – [View Contract](https://explorer-mainnet.zkevm.ternoa.network/address/0x7bAd89D2270cEFa698834b7c6E7532eFA6546e42?tab=contract)
* **SafeProxyFactory.sol** – [View Contract](https://explorer-mainnet.zkevm.ternoa.network/address/0x7C982d79d9B14500F1d1C114BB3779028B935d28?tab=contract)
* **MultiSend.sol** – [View Contract](https://explorer-mainnet.zkevm.ternoa.network/address/0xF6DCd634ABA8e0Ec891C3A6C2e240001F2cdF83c?tab=contract)
* **MultiSendCallOnly.sol** – [View Contract](https://explorer-mainnet.zkevm.ternoa.network/address/0x628c91FF2A8A99C767E09A84c21f62c9b423CC95?tab=contract)
* **SafeL2.sol** – [View Contract](https://explorer-mainnet.zkevm.ternoa.network/address/0xdC856ED68Dfb09129e7b1Ea393098b487ddf3047?tab=contract)
* **SignMessageLib.sol** – [View Contract](https://explorer-mainnet.zkevm.ternoa.network/address/0x677Aa661BD551Af5c563A40176Cd9E25c9394fa6?tab=contract)

### **How to Use Ternoa SAFE**

#### **1️⃣ Deploy Your Multi-Sig Wallet**

* Use **SafeProxyFactory** to create a new multi-signature wallet.
* Specify the list of signers and the required approval threshold.

#### **2️⃣ Securely Store & Manage Assets**

* Deposit funds into your SAFE wallet.
* All transactions require multi-signature approval, reducing single-point failure risks.

#### **3️⃣ Execute Multi-Sig Transactions**

* Transactions must be signed by the required number of approved signers.
* Use **MultiSend** and **MultiSendCallOnly** libraries to batch-process multiple transactions efficiently.

#### **4️⃣ Sign & Verify Messages**

* Utilize **SignMessageLib** to securely sign messages and verify signatures within the contract.

### **Why Use Ternoa SAFE?**

🟧 **Multi-Signature Security** – Transactions require multiple signers for execution.\
🟧 **Trustless Asset Management** – No single party has unilateral control.\
🟧 **Smart Contract Verified** – Fully audited, transparent, and accessible on-chain.\
🟧 **Batch Transactions** – Save on gas fees using the MultiSend feature.\
🟧 **Seamless Integration** – Works across Ternoa’s zkEVM Layer 2.


# TIP

### **What is TEE Integrity Proof?**

Tee Integrity Prover (TIP) is an innovative solution designed to ensure that Web3 applications and tools operate securely and as intended. By leveraging Trusted Execution Environments (TEEs), TIP provides real-time integrity monitoring, ensuring that applications remain unaltered and free from tampering.

🚧 **Current Status:** **In Development**\
TIP is actively being developed to bring **verifiable computation** to blockchain-based ecosystems, ensuring **secure execution of critical processes** in a trust-minimized manner.

🔗 **Learn More:** [t-i-p.network](https://t-i-p.network/)

### **Concept: How TIP Works**

TEE Integrity Proof enables **continuous integrity checks** of smart contracts, applications, and off-chain processes running inside **Intel SGX-powered enclaves**. It operates by:

1️⃣ **Secure Execution** – Critical operations run inside TEEs, isolated from external threats.\
2️⃣ **Cryptographic Attestation** – Enclaves generate proof that their code hasn’t been tampered with.\
3️⃣ **On-Chain Verification** – TIP records these proofs on the blockchain, ensuring transparency.\
4️⃣ **Decentralized Validators** – A network of independent nodes verifies these integrity proofs.

### **Why TIP Matters?**

🟧 **Ensures Code Integrity** – Verifies that executed code matches its open-source counterpart.\
🟧 **Protects Against Tampering** – Even privileged system administrators cannot alter enclave-protected computations.\
🟧 **Decentralizes Trust** – Shifts security from centralized verification models to cryptographic proofs.\
🟧 **Optimized for Web3** – Works with dApps, sequencers, provers, and indexers to enhance security.

### **Use Cases**

🔸 **Decentralized Finance (DeFi)** – Secure execution of financial transactions without centralized risk.\
🔸 **On-Chain Governance** – Verifiable execution of governance mechanisms.\
🔸 **Data Provenance & Storage** – Proof that off-chain data has not been altered.\
🔸 **Verifiable zk-Provers** – Secure computation of zk-SNARKs and zk-STARKs inside TEEs.

### **What’s Next?**

TIP is under active development, with ongoing work to refine its **architecture, attestation mechanisms, and decentralized verifier network**. Stay tuned for updates on its rollout and integration into **Ternoa’s zkEVM ecosystem**.

🔗 **Follow the Progress:** [t-i-p.network](https://t-i-p.network/)

🟠 **The future of verifiable computation is coming—be part of it.**


# Wallets

To start your journey in our ecosystem you will need to use a wallet. Here you will find a list of different wallets compatible with Ternoa Chain and their documentation:

* [Ternoa Wallet](/getting-started/wallets/ternoa-wallet)
* [Polkadot Extension](/getting-started/wallets/polkadot-extension)
* [Nova Wallet](https://docs.novawallet.io/nova-wallet-wiki/welcome-to-nova-wallet/about-nova-wallet)
* [Subwallet](https://docs.subwallet.app/main/)
* [Talisman](https://docs.talisman.xyz/talisman/introduction/welcome-to-talisman)
* [Fearless Wallet](https://wiki.fearlesswallet.io/)


# Polkadot Extension

### Download the Polkadot{.js} extension

The Polkadot{.js} browser extension does one thing: it manages accounts and allows the signing of transactions with those accounts. It does not inject providers for use by dApps at this early point, nor does it perform wallet functions, e.g send funds.

{% hint style="info" %}
Download the Polkadot{.js} browser extension [here](https://polkadot.js.org/extension/). \
\
The Polkadot{.js} extension is only available for **Chrome & Firefox** and *is not compatible with mobile browsers*. To connect your wallet to the extension, you will need to use a desktop browser.
{% endhint %}

<figure><img src="/files/sUqNgSWwdg377ilXwMVb" alt=""><figcaption></figcaption></figure>

For developers wanting to use the accounts from the extension in a Dapp, head to the Polkadot{.js} [developer documentation](https://polkadot.js.org/docs/extension/) or look at the corresponding [build/handling wallets & accounts ](/build-1/javascript/wallets)section.

### **How to connect your Ternoa account on Polkadot{.js}**

To interact with your Ternoa Wallet from your browser to any dApp, you need to get your Ternoa account imported in the Polkadot{.js} [**browser extension**](https://polkadot.js.org/extension/).\
\
A video tutorial is available below:

{% embed url="<https://youtu.be/sDut4eICNBk>" %}

If you already have Polkadot{.js} installed, you can either import account from pre-existing seed from your Ternoa Wallet or connect your Substrate address from a hardware wallet.

You can import your Ternoa Wallet directly on the extension by clicking the '+'. **It will be necessary to have your wallet connected to validate transactions.**

<figure><img src="/files/h7iQZSHYdezQyJQk6f30" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="/files/D9hphO4BJASQjk12DC52" alt="" width="375"><figcaption></figcaption></figure>


# Ternoa Wallet

The Ternoa Wallet application is a recommended crypto wallet to manage your CAPS and access dApps powered by Ternoa Chain. The application provides functionality that enables you to view your CAPS balance, send or receive CAPS to another Ternoa wallet, and view your transaction history in real-time.

{% hint style="success" %}

#### Download Ternoa Wallet:

[On the PlayStore](https://play.google.com/store/apps/details?id=com.ternoa.wallet.prod###)\
[On the App Store](https://apps.apple.com/us/app/ternoa-wallet/id1562180877#?platform=iphone/)
{% endhint %}

### How to create your Ternoa Wallet

To get started, please download the Ternoa Wallet app. It is available in the [**Google Play Store**](https://play.google.com/store/apps/details?id=com.ternoa.wallet.prod) and the [**iOS App Store**](https://apps.apple.com/us/app/ternoa-wallet/id1562180877#?platform=iphone).

Once you’ve downloaded Ternoa wallet you can open it and start creating your Ternoa account:

<figure><img src="/files/UVgK2OcvdX6jTLgPBbZS" alt="" width="563"><figcaption></figcaption></figure>

On the next screen, the app will prompt you to write and store the mnemonic key (12 Random Words) offline just to have it handy.

{% hint style="warning" %}
*In case your phone is lost, stolen, or damaged you must have the key penned down to retrieve your Ternoa account. **(Very Important!)***
{% endhint %}

<figure><img src="/files/wdRmeVbz4OnnlD00KA1j" alt="" width="563"><figcaption></figcaption></figure>

After re-entering and confirming your mnemonic key, a user must enter their details to finish the account creation. In the next step, you will be navigated to the wallet page where you can see your CAPS balance, last transactions, the option to **Send/Receive** caps, and your NFTs under the **My NFTs** tab.

<figure><img src="/files/ULxmmZDISZazBf11sDzG" alt="" width="563"><figcaption></figcaption></figure>

### Account settings & features

You can find your **Ternoa Wallet Address** in the **Profile**

<figure><img src="/files/DIn9u5uC3r2TudOmqWeT" alt="" width="563"><figcaption></figcaption></figure>

### Change Password

Here you can change the **App Password.**

<figure><img src="/files/Y7g9Eu37Hi3nBacxc3tk" alt="" width="540"><figcaption></figcaption></figure>

### Check your Mnemonic Key

Here you can check your **Mnemonic Key.**

<figure><img src="/files/yZl9WAlCpObl0AlVyYRI" alt="" width="540"><figcaption></figcaption></figure>

### Contact

From your **Address Book**, you can add and review recent contacts, and observe other accounts.

<div><figure><img src="/files/dcMg8RpNVGh1iQkLer30" alt="" width="375"><figcaption></figcaption></figure> <figure><img src="/files/SP8RztaI4kPZgKRttuuh" alt="" width="375"><figcaption></figcaption></figure></div>

### Observe Contacts

<div><figure><img src="/files/oj5X8lnePkij98rLmAvQ" alt=""><figcaption></figcaption></figure> <figure><img src="/files/vvVknGdimSl2fevqN8zW" alt=""><figcaption></figcaption></figure></div>


# \[Solidity Smartcontracts]

COMING SOON 👀


# Networks


# Substrate Layer 1

The Ternoa chain is available through two distinct Substrate networks: the **Mainnet,** official Ternoa production network, and the **Alphanet,** official testing network with all the newest features available for testing purposes. <br>

## **Mainnet endpoints**

|                 | Public Endpoints                        |
| --------------- | --------------------------------------- |
| Network         | Mainnet                                 |
| Chain Websocket | wss\://mainnet.ternoa.network           |
| Indexer         | <https://indexer-mainnet.ternoa.dev>    |
| Dictionary      | <https://dictionary-mainnet.ternoa.dev> |
| Explorer        | <https://explorer.ternoa.com>           |
| IPFS node       | <https://ipfs-mainnet.trnnfr.com>       |

##

## **Alphanet endpoints**

|                 | Public Endpoints                         |
| --------------- | ---------------------------------------- |
| Network         | Alphanet                                 |
| Chain Websocket | wss\://alphanet.ternoa.com               |
| Indexer         | <https://indexer-alphanet.ternoa.dev>    |
| Dictionary      | <https://dictionary-alphanet.ternoa.dev> |
| Explorer        | <https://explorer-alphanet.ternoa.dev>   |
| IPFS node       | <https://ipfs-dev.trnnfr.com>            |

The Alphanet faucet provides you with some free test CAPS tokens to start building or interacting with the Ternoa chain on the Alphanet network.

It is accessible via the [Ternoa website](https://faucet.ternoa.network/).

### Alphanet CAPS Faucet

Paste your fresh Ternoa account address [created previously ](/getting-started/wallets/ternoa-wallet)(it starts with the number `5` e.g. `5DFAg6g9n3fNT2...VDSt5a1psr7BFJ1`), verify the captcha, and click on the `Claim` button.

You will receive alpha CAPS tokens within a few minutes.

<figure><img src="/files/ePEavhiYCLUBCr2A9I3c" alt="" width="563"><figcaption></figcaption></figure>

*If the daily 100 alphanet $CAPS allowance is not enough, feel free to reach out to our dev community team on* [*Discord*](https://discord.com/invite/mQeEWQj46a)*.*


# Chain fees


# Fees calculation

Here’s how the fees are calculated:&#x20;

*WEIGHT + BYTES\_LENGTH\_FEE*

### Example for a 100K CAPS balance transfer

The signed transaction is 152 bytes:

> `0x590284001a40e806c28a32dbac60f2b088c77a9ac3d3702011ac0e13579402ddcc21430801065848e44986dfdd3c82c45915650d2ea8b29a934c3578069a1f19ec3c1d530452c04bc8b3a4c4b02f831ee743cf1d696660ab3ea4fe82aea23a3c25c3f31a8a6502e50a00040000cc8c895b436901396bd1d43adb8fdd33e29da56765fe460eac9d9c7f027bff021b000080f64ae1c7022d15`

{% hint style="success" %}
*BYTES\_LENGTH\_FEE is calculated as 152 \* PER\_BYTES\_FEE (where PER\_BYTES\_FEE is fixed by the chain at 10^14).*&#x20;
{% endhint %}

BYTES\_LENGTH\_FEE = 152\*10^14 and a WEIGHT of 223,375,000.&#x20;

The total fees are therefore 152,000,000,223,375,000. (*Approximately **0.152 CAPS***)


# Fixed fees & Commission fees

### Mainnet fixed fees:&#x20;

* NFT mint fee: 10 CAPS
* Secret NFT mint fee: 50 CAPS
* Caspule NFT mint fee: 100 CAPS
* Marketplace mint fee: 10 000 CAPS
* Bridge fee: 1000 CAPS
* Transmission Protocols - At block fee: 20 CAPS
* Transmission Protocols - At block with reset fee: 40 CAPS
* Transmission Protocols - On consent fee: 30 CAPS
* Transmission Protocols - On consent at block fee: 40 CAPS

### Commission fees:&#x20;

Marketplace owners have the option to set some commission fees on every NFT sale conducted within their marketplace. Similarly, NFT creators can set some 'royalty fees' on every secondary sale of their NFTs. Based on these settings, the following rule applies:&#x20;

{% hint style="info" %}
Marketplace commission fees take precedence over royalties. Initially, the marketplace commission is subtracted from the sale amount, and then the royalty fees are calculated and deducted from the remaining sale price.
{% endhint %}


# zkEVM+ Layer 2

## zkEVM+ Testnet <a href="#ternoa-chain-substrate-l1" id="ternoa-chain-substrate-l1"></a>

Ternoa zkEVM+ official testing network on SEPOLIA is available to EVM developers.&#x20;

Below is the reference list of each endpoint:

| Service  | URL                                                                      |
| -------- | ------------------------------------------------------------------------ |
| RPC      | [https://rpc.zkevm.ternoa.network ](<https://rpc.zkevm.ternoa.network >) |
| Bridge   | <https://bridge.zkevm.ternoa.network>                                    |
| Explorer | <https://explorer.zkevm.ternoa.network>                                  |
| Faucet   | <https://faucet.zkevm.ternoa.network>                                    |

### **RPC**

| Chain ID     | 752024                             |
| ------------ | ---------------------------------- |
| Endpoint     | <https://rpc.zkevm.ternoa.network> |
| Network name | Ternoa zkEVM+ Testnet              |

### Faucet <a href="#alphanet" id="alphanet"></a>

To start using Ternoa zkEVM+ TestNet, enter your Ternoa zkEVM public address (starting by 0x...), and claim Testnet CAPS

![](/files/WLkzAPxsyW7sZ3aiKAvr)

### Key Smart Contracts

<table><thead><tr><th width="306">Contract Name</th><th>Address</th></tr></thead><tbody><tr><td>PolygonZKevm Contract</td><td>0x1F9942BfAB4f7a19d1e857dA8e60F98b23E15B4B</td></tr><tr><td>Bridge Contract</td><td>0xF157F1f41eb8e161Dfa82E8792c740e9de2Ae5C8</td></tr><tr><td>Rollup Manager Contract</td><td>0x82f45dB8503a9a73CcaDAd37741105930dDc563a</td></tr><tr><td>Gas Token Contract</td><td>0xe4a18Ae2258727e636eeE1290761895016644342</td></tr><tr><td>DA Contract</td><td>0xbc6c6513DE3aC2b0E947998ea4fAE626914E935b</td></tr><tr><td>ProxyAdmin</td><td>0x95cC8654C48CA78e3Dd341253D9422FADBb77Af1</td></tr><tr><td>PolygonZkEVMDeployer</td><td>0x28AFA5B864Be24109BF2360319D81e850C00c73B</td></tr><tr><td>PolygonZkEVMGlobalExitRootL2</td><td>0xa62Bd3c5665a17F240E646127aDC0a1bBFDa5a05</td></tr><tr><td>PolygonZkEVMTimelock</td><td>0x44B8092e8E98bDc449312dcD4718686f4a477DAd</td></tr></tbody></table>

&#x20;

### &#x20;API Documentation

<https://explorer.zkevm.ternoa.network/api-docs>

&#x20;

&#x20;

&#x20;

&#x20;

&#x20;

&#x20;

&#x20;


# Javascript SDK


# Ternoa-js library

### Overview ⚙️[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#overview-%EF%B8%8F) <a href="#overview" id="overview"></a>

Welcome to the Ternoa-js developer documentation. Ternoa-js's main objective is to be: **one of the most user-friendly tools to build web3 projects** on top of the Ternoa Chain. Based on Polkadot{.js} API and Javascript, it offers developers the ability to query and interact with substrate chains like the Ternoa chain. It provides a seamless experience and allows you to start building at a glance: an extra short init and just a few lines of code, and your first NFT will be live on the chain.

#### What is the Ternoa-Js library?

Ternoa-Js is an isomorphic Node js library integrating the custom Ternoa [Primitives](/learn/ternoa-wasm-chain/primitives-features)/FRAMEs to interact with the chain.

#### Forward Together[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#forward-together) <a href="#forward-together" id="forward-together"></a>

Ternoa-js is an open-source project. Feel free to interact and move forward with us. If you have questions about anything related to Ternoa, need help, or want to request features, you can open a discussion on our [GitHub Discussions](https://github.com/capsule-corp-ternoa/ternoa-js/discussions) And if you find an issue, let us know in our [GitHub Issues](https://github.com/capsule-corp-ternoa/ternoa-js/issues) section.


# Installation

The Ternos-js npm library can be found [here](https://www.npmjs.com/package/ternoa-js).

> Prerequisites: [NodeJS v.14+](https://nodejs.org/en/download/) & NPM

Install the latest stable version of the ternoa-js library in your existing project by running:

{% code fullWidth="false" %}

```
npm install ternoa-js
```

{% endcode %}

> This package provides TypeScript types, but you will need TypeScript version 4.2 or higher to use them properly.

{% hint style="info" %}

You can test out our upcoming features in our *Alpha or Release candidate* versions. These versions aren't stable and might contain some technical errors. @alpha versions are for internal and testing only whereas @rc releases tend to be the closest to its production version.

You can check out our version list over [npm](https://www.npmjs.com/package/ternoa-js?activeTab=versions). Installing a specific version is as easy as replacing the @`1.6.0-rc0` with your desired version:
{% endhint %}

```
# for version 1.6.0-rc0
npm i ternoa-js@1.6.0-rc0
```


# Initialization

> Prerequisites: [Install the ternoa-js library.](/getting-started/javascript-sdk/ternoa-js-library/installation)

To initialize the library, add the following code to your dApp:

```typescript
import { initializeApi } from "ternoa-js";

await initializeApi();
```

Once the Ternoa-JS library is initialized, you will be able to use all the powerful NFT FRAMEs designed by Ternoa to build your dApps.

{% hint style="info" %}
The default network used is **Alphanet**. To connect to the Mainnet network it is as simple as passing the desired WSS endpoint:
{% endhint %}

```typescript
import { initializeApi } from "ternoa-js";

// The endpoint here will make the init API on the Ternoa Mainnet network
await initializeApi("wss://mainnet.ternoa.io");
```

That's it! You're ready to build your dApp on Ternoa.

### Accessing the Ternoa API

Ternoa SDK provides **a powerful** function named `getRawApi()` to interact with the API. If the API is connected, it will be directly returned. You can use it all throughout your development experience to access passed data, subscribe to blockchain events, and access real-time blockchain info outside of extrinsics, constants, or queries.&#x20;

```js
  ...
   //we assume that API has been initiated before
   const api = await getRawApi()

   // Do something
   // example: To get the last block
   const signedBlock = await api.rpc.chain.getBlock();
  ...
}
```


# Architecture

### API Architecture[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#api-architecture) <a href="#api-architecture" id="api-architecture"></a>

The Ternoa SDK facilitates access to the main functionalities offered by the Ternoa chain. It enables you to execute all transactions from the chain pallets/primitives, perform queries, or access constant storage. Additionally, the SDK includes various helpers and utility functions to enhance your overall experience.

#### On-chain handlers architecture[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#handlers-architecture) <a href="#handlers-architecture" id="handlers-architecture"></a>

For those who have experience with Polkadot, the architectural design of the features in Ternoa SDK will be familiar. If you are new to this, there's no need to worry as the fundamental concepts are straightforward to grasp. Based on the specific pallet or handler category, you can access the following:

* ***Constants*** to request the chain runtime.
* ***Storage*** to query the chain state.
* ***Extrinsics*** to execute the transactions.
* ***Utils & Helpers:*** Some powerful functions to assist you in interacting with the chain or performing off-chain operations.

{% hint style="info" %}
If you need to perform custom storage calls, constant calls, or extrinsic calls that are not readily available as dedicated helpers in the SDK, you can execute them directly through the [API using `getRawApi()`](/getting-started/javascript-sdk/ternoa-js-library/initialization). Further instructions on executing custom calls can be found in the  [Build section.](/build-1/javascript)
{% endhint %}

#### Off-chain handlers architecture[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#handlers-architecture) <a href="#handlers-architecture" id="handlers-architecture"></a>

* ***Helpers:*** Some user-friendly functions to facilitate performing off-chain operations like interacting with TEE SGX Clusters, connecting and storing data in the IPFS Ternoa client, and managing encryption with keys (...).

#### The main handlers are the ones below:[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#the-main-handlers-are-the-ones-below) <a href="#the-main-handlers-are-the-ones-below" id="the-main-handlers-are-the-ones-below"></a>

* [blockchain](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/blockchain): the CORE blockchain function. The API brain that randomly: init the API, executes transactions, queries data, batch transactions, etc.
* [account](https://github.com/capsule-corp-ternoa/ternoa-js/blob/main/src/account/): the functions that allow you to generate a new seed and a keyring
* [auction](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/auction): the Auction pallet with its extrinsics, query, and storage to create auctions and manage bids.
* [assets](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/assets): the Auction pallet with its extrinsics, query, and storage.
* [balance](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/balance): the Balance pallet with its extrinsics, query, and storage.
* [nft](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/nft): the NFT pallet with its extrinsics, query, and storage.
* [marketplace](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/nft): the Marketplace pallet with its extrinsics, query, and storage.
* [protocols](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/protocols): the Transmission protocols pallet with its extrinsics, query, and storage.
* [rent](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/rent): the Rent pallet with its extrinsics, query, and storage.
* [helpers](https://github.com/capsule-corp-ternoa/ternoa-js/tree/main/src/helpers): the helpers' folder that contains all the functions to perform off-chain operations:&#x20;
  * Crypto utilities
  * Encryption helpers
  * The Ternoa IPFS client
  * Some end-to-end NFT, secret NFT & Capsule NFT helpers
  * Some TEE helpers interact with clusters
  * The Utility helpers as formatters, file converters, and other useful helpers.
* [events](https://github.com/capsule-corp-ternoa/ternoa-js/blob/main/src/events.ts): the [events list ](/getting-started/javascript-sdk/ternoa-js-library/blockchain-events)returned when the `submitTxBlocking` function is triggered

#### Response Format[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/introduction#response-format) <a href="#response-format" id="response-format"></a>

In our effort to offer the most accessible tools for building on the Ternoa chain, we have also endeavored to simplify the response formats of our functions where possible. Depending on whether you can use the automated approach or the customizable one to run your extrinsics, we suggest selecting the appropriate function. Some functions will directly provide events and featured data, while others will return only the transaction hash in hexadecimal format to be signed and submitted by the external user of your dApp. *More about this automated or customizable approach in the* [*Workflow section.*](/getting-started/javascript-sdk/ternoa-js-library/workflow)


# Blockchain events

### Overview: What are chain events?

**Events are objects containing decoded values (data)** provided by the chain in the result of any transaction triggered using the `submitTxBlocking` function. At least one of these two `ExtrinsicSuccessEvent` or `ExtrinsicFailedEvent` events is provided for any transaction depending on its success or failure. While `submitTxBlocking` provides the SDK handlers' main events list of ***BlockchainEvents*** available, we also allow you to filter this list to get the ones you need. *An example to filter only the events list of a balance transfer transaction:*

```javascript
const balanceTransfertEvents = BlockchainEvents.findEvents(
	BalancesTransferEvent
);
```

**note:** *BlockchainEvents is the result of the `submitTxBlocking` function. It can be stored in a constant for example.*

To better understand Events, we already jumped a bit deeper than the first and easiest option to get the extrinsics events list. In case you do not need to manually sign or send your transaction, each of the Ternoa extrinsics features comes with two functions to execute a transaction and an easy one to directly get the required events list. See the example below :\
*When the `balancesTransferTx` function creates an unsigned unsubmitted transaction hash, the `balancesTransfer` function signs and submits the transaction to provide the events list.*

***

### About the Event Design Format:

To make the returned events data useful, we provide both the native format and a more friendly, ready-to-use format:

* a string as an AccountId32 corresponds to a classic user-valid address.
* a string as u128 is a BN value as a string natively used under the hood by the chain.
* rounded data (ex: amoutRounded) is the "human" version of data, (usually a BN) that can be directly used.
* some events from the utility pallet do not return any data.

***

### The events below are the Events handled in the Ternoa SDK sorted by categories

* [Assets](#assets-events)
* [Auctions](#auctions-events)
* [Balances](#balances-events)
* [Capsule](#capsule-events)
* [Collection](#collection-events)
* [Marketplace](#marketplace-events)
* [NFT](#nft-events)
* [Rent](#rent-events)
* [System](#system-events)
* [Tee](#tee-events)
* [Transmission protocols](#transmission-protocols-events)
* [Treasury](#treasury-events)
* [Utility](#utility-events)

***

### Assets events

* #### AssetTransferredEvent
  * **Summary:** Gtoken transfer succeeded.

***

### Auctions events

* **AuctionCreatedEvent**
  * **Summary:** An auction has been created.
* **AuctionCancelledEvent**
  * **Summary:** An existing auction has been canceled.
* **AuctionCompletedEvent**
  * **Summary:** An auction has been completed.
* **BidAddedEvent**
  * **Summary:** A bid has been added to an auction.
* **BidRemovedEvent**
  * **Summary:** A bid has been removed from an auction.

***

### Balances events

* #### BalancesWithdrawEvent
  * **Summary:** Some amount was withdrawn from the account
* #### BalancesDepositEvent
  * **Summary:** Some amount was deposited.
* #### BalancesTransferEvent
  * **Summary:** Transfer succeeded.
* #### BalancesEndowedEvent
  * **Summary:** An account was created with some free balance

***

### Capsule events

* ***NFTConvertedToCapsuleEvent***
  * **Summary:** An existing NFT has been converted to a Capsule NFT
* **CapsuleOffchainDataSetEvent**
  * **Summary:** The capsule metadata has been set or updated.
* **CapsuleKeyUpdateNotifiedEvent**
  * **Summary:** The blockchain has been notified that the capsule owner requests new keys.&#x20;
* **CapsuleRevertedEvent**
  * **Summary:** The Capsule NFT assets have been reverted from an NFT.

***

### Collection events

* #### CollectionCreatedEvent
  * **Summary:** A Collection has been created.
* #### CollectionLimitedEvent
  * **Summary:** The collection's limit has been set.
* #### CollectionClosedEvent
  * **Summary:** A collection has been closed.
* #### CollectionBurnedEvent
  * **Summary:** A collection has been burned.
* **CollectionOffchainDataSetEvent**
  * **Summary:** The collection metadata has been set or updated.

***

### Marketplace events

* #### MarketplaceCreatedEvent
  * **Summary:** A marketplace has been created.
* #### MarketplaceOwnerSetEvent
  * **Summary:** The marketplace owner has been set.
* #### MarketplaceKindSetEvent
  * **Summary:** The marketplace kind has been set.
* #### MarketplaceConfigSetEvent
  * **Summary:** The marketplace configuration has been updated. Parameters can be unchanged (Noop), Removed, or Set
* #### MarketplaceMintFeeSetEvent
  * **Summary:** The marketplace mint fee has been set.
* #### NFTListedEvent
  * **Summary:** An NFT has been listed for sale on a marketplace.
* #### NFTUnlistedEvent
  * **Summary:** An NFT has been unlisted from a marketplace.
* #### NFTSoldEvent
  * **Summary:** An NFT has sold.

***

### NFT events

* #### NFTCreatedEvent
  * **Summary:** An NFT has been created.
* ***SecretAddedToNFTEvent***
  * ***Summary:*** An NFT has been converted to a Secret NFT.
* #### NFTBurnedEvent
  * **Summary:** An NFT has been burned.
* #### NFTDelegatedEvent
  * **Summary:** An NFT has been delegated.
* #### NFTRoyaltySetEvent
  * **Summary:** The NFT's royalty has been set.
* #### NFTTransferredEvent
  * **Summary:** An NFT has been transferred.
* #### NFTAddedToCollection
  * **Summary:** An NFT has been added to a collection.

***

### Rent events

* **ContractCreatedEvent**
  * **Summary:** A rental contract has been created.
* **ContractCanceledEvent**
  * ***Summary:*** A rental contract has been canceled.
* **ContractStartedEvent**
  * **Summary:** A rental contract has started.
* **ContractRevokedEvent**
  * **Summary:** A rental contract has been revoked.
* **ContractOfferCreatedEvent**
  * **Summary:** An offer for a rental contract has been created.
* **ContractOfferRetractedEvent**
  * **Summary:** An offer for a rental contract has been created.
* **ContractSubscriptionTermsChangedEvent**
  * **Summary:** The rental contract owner has requested new conditions.
* **ContractSubscriptionTermsAcceptedEvent**
  * **Summary:** The new rental contract conditions have been accepted by the rentee.
* **ContractEndedEvent**
  * **Summary:** The rental contract has ended.
* **ContractSubscriptionPeriodStartedEvent**
  * **Summary:** The rental contract's new subscription period has started.
* **ContractExpiredEvent**
  * **Summary:** The rental contract has expired.

***

### System events

* #### ExtrinsicFailedEvent
  * **Summary:** An extrinsic failed.
* #### ExtrinsicSuccessEvent
  * **Summary:** An extrinsic was completed successfully.
* #### NewAccountEvent
  * **Summary:** A new account was created.

***

### Tee events

* **MetricsServerReportSubmittedEvent**
  * **Summary:** The metric server has submitted a report.
* **RewardsClaimedEvent**
  * **Summary:** The enclave owner has claimed his rewards.&#x20;

***

### Transmission protocols  events

* **ProtocolSetEvent**
  * **Summary:** A transmission protocol has been set.
* **ProtocolRemovedEvent**
  * ***Summary:*** A transmission protocol has been removed.
* **TimerResetEvent**
  * **Summary:** A transmission protocol's timer has been reset.
* **ConsentAddedEvent**
  * **Summary:** A consent has been given to a transmission protocol.
* **ThresholdReachedEvent**
  * **Summary:** The transmission protocol's threshold has been reached.
* **TransmittedEvent**
  * **Summary:** The NFT has been transmitted through a transmission protocol.

***

### Treasury events

* #### TreasuryDepositEvent <a href="#treasurydepositevent" id="treasurydepositevent"></a>
  * **Summary:** Some funds have been deposited.

***

### Utility events

* #### ItemCompletedEvent
  * **Summary:** A single item within a Batch of dispatches has been completed with no error.
* #### BatchInterruptedEvent
  * **Summary:** The batch of dispatches was not completed fully. Index of first failing dispatch given, as well as the error.
* #### BatchCompletedEvent
  * **Summary:** Batch of dispatches completed fully with no error.

###


# Workflow

> This section will go through the main workflow process to execute a transaction. In just a few steps, you will be able to understand how the Ternoa SDK works.

### API initialization

It's optional, but it's good practice to initialize the API as soon as possible. If this call is omitted, the first SDK call will return an exception. The default chain endpoint is `wss://alphanet.ternoa.com`. It can be modified by passing a new endpoint as the first argument to the *initializeApi()* function.&#x20;

{% hint style="info" %}
Find more information & examples [here](/getting-started/javascript-sdk/ternoa-js-library/initialization) about how to connect to the Ternoa chain and access specific or custom data.
{% endhint %}

### How to execute a transaction[​](https://docs.ternoa.network/for-developers/developer-tools/ternoa-js/sdk-workflows#lets-create)? <a href="#lets-create" id="lets-create"></a>

Now that we know how to init our SDK API, let's get into a feature example. The Ternoa-js provides *the most friendly way to build* on the chain and execute transactions.&#x20;

{% hint style="info" %}
To know what transaction to do with the Ternoa SDK, please look at our [primitives/features list](/learn/ternoa-wasm-chain/primitives-features) or the full [events list](/getting-started/javascript-sdk/ternoa-js-library/blockchain-events).
{% endhint %}

It is expected three steps to execute every transaction (also called "tx" or "extrinsic").&#x20;

1. **Create** an unsigned transaction
2. **Sign** the transaction hash returned when creating the unsigned transaction
3. **Submit** the transaction to the Ternoa chain.&#x20;

#### **To build applications within the Ternoa SDK, we provide two approaches for each primitive/extrinsic:**&#x20;

* An **automated & user-friendly single-ligne function** manages this three-step process seamlessly. It is the recommended method for executing transactions **when you can access the transaction signer's account seed.** With this approach, you should be able to generate a keyring from your seed. *To prevent public exposure and theft, the seed must be kept in an environment variable.* The following helper creates an NFT directly on the chain. It returns a blockchain event specifying the information registered on the chain.&#x20;

  ```js
  createNft(Offchain data, royalty, collectionId, soulbound, keyring, WaitUntil.BlockInclusion)
  ```

* A **customizable function** that provides an unsigned transaction hash from the extrinsic execution. It is the recommended method for executing transactions **when you need a user to sign the transaction.** According to your needs and the platform you are building, you will ask the user to sign the transaction with a wallet or an extension like the Polkadot extension. Instead of signing the transaction with a keyring as you do in the first approach, you will provide an injector that connects to your wallet or extension.  The following helper creates an *unsigned NFT*. It returns a blockchain hash you will ask the user to **sign** to confirm the transaction and **submit** to the chain.

  ```js
  createNftTx(Offchain data, royalty, collection id, souldbound)
  ```

{% hint style="info" %}
When unsure about which function to select, consider whether you have access to the seed for signing the transaction. Looking at the [SDK code repository](https://github.com/capsule-corp-ternoa/ternoa-js/blob/main/src/nft/extrinsics.ts) will clarify this distinction. Each extrinsic function in the repository has a variant ending with "Tx". For instance, `createSecretNftTx()` versus `createSecretNft()`, `burnNft()` versus `burnNftTx()`, and so on.&#x20;
{% endhint %}

Opting for the unsigned version, denoted by the `Tx()` suffix, demands to handle more pieces of code, but unlocks additional flexibility and functionalities like batching transactions. This is particularly beneficial for creating and managing a large volume of NFTs without the need to sign and send each one separately.\
\
You can find more details about transactions, signing, keyring, injectors and submitting a tx, in the [Build](/build-1/javascript) section of this documentation.<br>


# Ternoa indexer

### Overview⛓️ <a href="#overview" id="overview"></a>

The indexer is an open, flexible, and fast tool based on the [**SubQuery Framework**](https://doc.subquery.network/)**.** It is used to transform blockchain data into a **graphql queryable database**.

#### How it works:

The indexer scans through each block and their events to see what happened on the Ternoa Blockchain. It then parses all that data into entities and inserts it in a Postgres DB. Ternoa deploys its indexer, and anybody can run his own.

> You can get more information on the [**SubQuery official documentation**](https://doc.subquery.network/faqs/faqs.html)

> You can also check out [**our repository**](https://github.com/capsule-corp-ternoa/ternoa-subql) to see how we set up the subquery project to connect to the ternoa blockchain.

#### The most important files are:

* Project.yaml: set up the endpoint, the genesis hash, the types file, and the different filters to get only the specific events / extrinsics needed. We can also filter on the success status of the event / extrinsic.
* Schema.graphql: specifies the custom data we need to record in our Postgres db.
* The Mappings folder: Your mappingHandlers will handle the functions to transform the blockchain data into the needed GraphQL entities contained in the Schema.graphql. More info [here](https://academy.subquery.network/build/mapping/polkadot.html)


# Entities

The entities listed below are all the entities handled in the indexer you can query, sorted by categories with the corresponding data:

#### **TransferEntity:**&#x20;

* id
* blockId
* blockHash
* extrinsicId
* isSuccess
* timestamp
* from
* to
* currency
* amount
* amountRounded

***

#### **CollectionEntity:**

* id
* collectionId
* owner
* offchainData
* nfts
* nbNfts
* limit
* hasReachedLimit
* isClosed
* timestampCreated
* timestampBurned
* timestampClosed
* timestampLimited

***

#### **NftEntity:**

* id
* nftId
* auction
* collection
* owner
* creator
* offchainData
* secretOffchainData
* capsuleOffchainData
* royalty
* isCapsule
* isCapsuleSynced
* isSecret
* isSecretSynced
* delegatee
* isDelegated
* isSoulbound
* isListed
* typeOfListing
* isRented
* rentee
* rentalContract
* price
* priceRounded
* marketplace
* isTransmission
* transmissionRecipient
* transmissionProtocol
* createdAt
* updatedAt
* timestampCreated
* timestampBurned
* timestampListed
* timestampRented
* timestampSecretAdded
* timestampConvertedToCapsule

***

#### RentEntity

* id
* nftId
* hasStarted
* hasEnded
* hasBeenCanceled
* isExpired
* renter
* rentee
* startBlockId
* creationBlockId
* durationType
* blockDuration
* maxSubscriptionBlockDuration
* isSubscriptionChangeable
* nextSubscriptionRenewalBlockId
* nbSubscriptionRenewal
* newTermsAvailable
* nbTermsUpdate
* acceptanceType
* acceptanceList
* renterCanRevoke
* revokedBy
* rentFeeType
* rentFee
* rentFeeRounded
* rentOffers
* nbRentOffers
* totalRentOffersReceived
* renterCancellationFeeType
* renterCancellationFee
* renterCancellationFeeRounded
* renteeCancellationFeeType
* renteeCancellationFee
* renteeCancellationFeeRounded
* timestampCreated
* timestampStarted
* timestampLastSubscriptionRenewal
* timestampLastTermsUpdate
* timestampLastOffer
* timestampEnded
* timestampCancelled
* timestampRevoked
* timestampExpired

***

#### MarketplaceEntity

* &#x20;id
* marketplaceId
* owner
* kind
* commissionFeeType
* commissionFee
* commissionFeeRounded
* listingFeeType
* listingFee
* listingFeeRounded
* accountList
* offchainData
* collectionList
* createdAt
* updatedAt
* timestampCreated

***

#### AuctionEntity

* id
* nftId
* marketplaceId
* creator
* startPrice
* startPriceRounded
* buyItNowPrice
* buyItNowPriceRounded
* startBlockId
* endBlockId
* isCompleted
* isCancelled
* isExtendedPeriod
* bidders
* nbBidders
* topBidAmount
* topBidAmountRounded
* typeOfSale
* timestampCreated
* timestampEnded
* timestampLastBid
* timestampCancelled

***

#### AccountEntity

* id
* capsAmount
* capsAmountFrozen
* capsAmountTotal
* capsAmountRounded
* capsAmountFrozenRounded
* capsAmountTotalRounded
* createdAt
* updatedAt

***

#### TransmissionEntity:

* id
* nftId
* from
* to
* isActive
* isThresholdReached
* protocol
* endBlock
* consentList
* currentConsent
* threshold
* cancellation
* cancellationBlock
* createdAt
* updatedAt
* timestampCreated
* timestampRemoved
* timestampUpdated
* timestampTransmitted


# Start to query


# Using a playground

### Use it from the playground

Depending on the data you are looking for, you can directly query any data needed on:

* [**The Alphanet indexer**](https://indexer-alphanet.ternoa.dev/)
* [**The Mainnet indexer**](https://indexer-mainnet.ternoa.network/)

You just need to create the graphql request, for example, a simple request to get the 10 last listed nft:

```graphql
{
	nftEntities(first: 10, offset: 0, orderBy: TIMESTAMP_LIST_DESC) {
		totalCount
		nodes {
			nftId
			owner
			creator
			collectionId
			offchainData
		}
	}
}
```

**The same example in the playground:**

<figure><img src="/files/Cau5yvZ0IInhn6S5LvwJ" alt=""><figcaption></figcaption></figure>

**You can access the whole schema in the right panel of the playground:**

<figure><img src="/files/d7lpMqWn9Azqw6I8IPZK" alt=""><figcaption></figcaption></figure>


# In a dApp

Here is the simplest example to request indexer data from a node application. We'll use the simple request used in the [playground section.](/getting-started/javascript-sdk/ternoa-indexer/start-to-query/using-a-playground)

#### First of all, in a new folder, create 2 files:

{% code title="package.json" %}

```json
{
  "name": "indexer-request-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "graphql-request": "^5.0.0"
  }
}
```

{% endcode %}

{% code title="index.js" %}

```javascript
import { request } from "graphql-request"

const getLastListedNFTs = async () => {
	const gqlQuery = `{
	  nftEntities(
		first: 10, 
		offset: 0, 
		orderBy: TIMESTAMP_LIST_DESC
	  ) {
		totalCount
		nodes {
			nftId
			owner
			creator
			collectionId
			offchainData
    	}
	  }
	}`
	const response = await request("https://indexer-alphanet.ternoa.dev/", gqlQuery)
	if (response.nftEntities){
		console.log("Total count", response.nftEntities.totalCount)
		response.nftEntities.nodes.forEach(x => console.log(x))
	}
}

getLastListedNFTs()
```

{% endcode %}

Now open a terminal in this folder and run the following commands:

```bash
npm install
node index.js
```


# Dictionary

Ternoa Dictionary records all the native substrate on-chain data of the Ternoa blockchain: blocks, extrinsics, and events. It is a glossary of data that pre-indexes chain events, drastically improving the overall indexing performance. Unlike the Indexer, no data relating to the Ternoa pallets is covered by the Dictionary.

If you already looked at our documentation, you should now understand that the indexing data provided by the chain can be retrieved both on our ([**alphanet indexer**](https://indexer-alphanet.ternoa.dev/) or [**mainnet indexer**](https://indexer-mainnet.ternoa.network/)) and also on our [dictionary](https://dictionary-mainnet.ternoa.dev/).

Since the Dictionary is focused on native substrate on-chain data contained in **blocks**, (instead of being focused on listening events like the indexer), you can use it for :

* Installing it into your own indexer as we do to improve performance.
* Use it to query data exactly like on the indexer

*If you want to know which tool suits you the best, look at the official* [*documentation*](https://academy.subquery.network/academy/tutorials_examples/dictionary.html)*.*


# Add the dictionary to the indexer

You can improve the performance of the indexation part by using a dictionary endpoint instead of targeting directly the blockchain to get data. Under the hood, the Dictionary provides a list of relevant block heights containing the specific events and extrinsics.

*Example*: If you look at a createNft event, not every block will contain this event since it depends on users' usage of the Ternoa chain. When looking at events, the dictionary will provide the list that contains the createNft event we are looking for instead of every event of each block.

* You can see in [**our repository**](https://github.com/capsule-corp-ternoa/ternoa-subql/blob/mainnet/project.yaml) what is the dictionary endpoint and how to add it.

**Code snippet example:** look at line 7

```yaml
...
  schema:
    file: ./schema.graphql
  network:
    genesisHash: '0x6859c81ca95ef624c9dfe4dc6e3381c33e5d6509e35e147092bfbc780f777c4e'
    endpoint: wss://mainnet.ternoa.network
    dictionary: https://dictionary-mainnet.ternoa.dev/
  dataSources:
    - kind: substrate/Runtime
      startBlock: 1
      mapping:
        file: "./dist/index.js"
        handlers:
          - handler: handleEvent
            kind: substrate/EventHandler
            filter:
              module: balances
              method: Transfer
...
```


# Make queries on the dictionary

### **Use the dictionary as an explorer**

*The main interest of the dictionary is to have a middleman database between the blockchain and the indexer. Again, this database will allow the indexer to query block metadata directly from the dictionary. This means that if we want to get only NFT creation events, the indexer will ask the dictionary for the corresponding blocks. (So, for example, instead of fetching blocks 0 to 100, it will fetch only the numbers 5, 16, and 94 because that’s where NFTs are created.)*

Another use of the dictionary is to record all generic data that can be used for an explorer. For example, block, transaction (extrinsic), and event data. This data is then used to display chain information. (See the [**ternoa scan**](https://explorer.ternoa.com/)) You can also compare the basic dictionary template provided by the Subquery team and the dictionary used by Ternoa which also records data for its explorer.

* [Subquery dictionary template](https://github.com/subquery/subql-dictionary)
* [Ternoa dictionary](https://github.com/capsule-corp-ternoa/ternoa-subql-dictionary)

[The dictionary playground](https://dictionary-mainnet.ternoa.dev/) will work the same as the Indexer. You will be able to perform queries the same as you do on the indexer, with the same syntax.


# Run a local indexer

## Install Indexer

{% hint style="info" %}
Have **yarn** installed, **docker,** and **docker-compose installed** and running on your machine.
{% endhint %}

### Installation process

```bash
git clone https://github.com/capsule-corp-ternoa/ternoa-subql.git
cd ternoa-subql
git checkout alphanet
yarn install
yarn codegen
yarn build
```

Every time the graphQl Schema changes, you need to run the yarn codegen command. Every time the code changes, you need to build it again with the yarn build command. Now everything is built, you can launch it with docker.

```bash
docker-compose pull
docker-compose up
```

docker-compose pull needs to be run to pull the last version and does not need to be run again unless you change any docker image.

> After a few seconds, the indexing starts. You can see in the shell every block indexed. To check the blockchain data stored, run a query in your local graphql playground in a browser (default [**localhost:3000**](http://localhost:3000)).

### Common errors on containers start

#### Database connection failed

```bash
ERROR Unable to connect to the database SequelizeConnectionRefusedError: connect ECONNREFUSED XX.XX.XX.XX:YYYY
```

The subquery-node container tends to be ready before the Postgres one. No worries, it will automatically restart until the database is ready.

#### Outdated .data

```bash
ERROR Node failed to start AssertionError: Specified project manifest chain id/genesis hash does not match database stored genesis hash, consider cleaning project schema using --force-clean
```

Remember to delete the `.data` folder at root on the network changes. Also, make sure to use the correct network genesis hash in the `project.yaml` file.

## Install Dictionary

{% hint style="info" %}
**Prerequisite**: have **yarn installed**, **docker,** and **docker-compose installed** and running on your machine.
{% endhint %}

You can set up your own dictionary to define what data you want to record for the chain. The dictionary will be used by the indexer to get only blocks that match the defined filter (for example, you can index only NFTs-related transactions (extrinsic).

Check [our repository](https://github.com/capsule-corp-ternoa/ternoa-subql-dictionary) here.

```bash
git clone https://github.com/capsule-corp-ternoa/ternoa-subql-dictionary
cd ternoa-subql-dictionary
git checkout v43/alphanet # The branch mechanism follows the one in the indexer repo, the indexer and dictionary should be on the same version.
yarn install
yarn codegen
yarn build
docker-compose pull
docker-compose up
```

> After a few seconds, the indexing starts. You can see in the shell every block indexed. To check the blockchain data stored, run a query in your local graphql playground in a browser (default [**localhost:3000**](http://localhost:3000)).


# Practice & learn from examples

Start interacting with the indexer following this tutorial: [Learn from examples](https://github.com/capsule-corp-ternoa/ternoa-subql/discussions/185).

{% hint style="info" %}
Our **active community of builders** has created this tutorial and is not maintained by Ternoa directly. *Feel free to reach out to us on* [*Discord*](https://discord.com/invite/cNZTGtGJNR) *or initiate a discussion in the corresponding* [*repository*](https://github.com/capsule-corp-ternoa)*, if you are interested in contributing to the development of a detailed showcase or tutorial for any of Ternoa's features.*
{% endhint %}


# Quickstart - Node JS

### Introduction

This tutorial is designed to guide you through the process of setting up a server-side dApp that enables you to **mint, retrieve, and sell an NFT** from a NodeJS application. We will achieve this by leveraging the tools provided in our SDK:

* **Ternoa-JS library**: An isomorphic NodeJS [package](https://www.npmjs.com/package/ternoa-js) that seamlessly integrates custom Ternoa FRAMEs for interacting with the blockchain. Find more information about it [here](https://github.com/capsule-corp-ternoa/ternoa-js).
* **Ternoa Indexer**: A GraphQL Indexer responsible for parsing Ternoa's on-chain data, which can be directly used in your project or accessed via our [playground](https://indexer-mainnet.ternoa.dev/) instance.

### Prerequisites

Before getting started, please ensure that you have the following prerequisites in place:

1. [Create a Ternoa account](/getting-started/wallets/ternoa-wallet) with [Alphanet CAPS](broken://pages/ej9gceaLIhCN2PgUBh42) from the [faucet.](https://faucet.ternoa.network/)
2. Install and configure your preferred code editor (for this tutorial, we will be using Visual Studio Code \[VSC]).
3. Install [NodeJS v.14+](https://nodejs.org/en/download/), along with NPM.
4. Generate an *IPFS Key* from the [Ternoa IPFS Key manager](https://ipfs-key-manager-git-dev-ternoa.vercel.app/)

{% hint style="info" %}
We assume you have already created a new wallet for development purposes with no CAPS on Ternoa Mainnet. You must use a development wallet with *NO REAL MONEY* in it when learning, practicing, and testing.
{% endhint %}

### Getting Started

The simplest way to quickstart jumping into Ternoa SDK and begin building on the blockchain, is to download the starter repository [here](https://github.com/capsule-corp-ternoa/ternoa-sdk-starter), and start our tutorial:

```bash
  git clone https://github.com/capsule-corp-ternoa/ternoa-sdk-starter.git
  cd ternoa-sdk-starter
```

We already installed the Ternoa-JS, you can directly run the following command:

```bash
  npm install
```

In the `.env.example` file, you will find the expected environment variables. Copy and paste them into a `.env` file at the root of the project.

* `SEED_TEST_FUNDS`: The Ternoa account *seed* you will use to sign transactions.
* `IPFS_API_KEY`: An IPFS KEY generated with the Ternoa [IPFS Key manager](https://ipfs-key-manager-git-dev-ternoa.vercel.app/). *After being generated, the IPFS key may need a few minutes to become effective for use with the Ternoa client.*

In the `src/basics/` folder we will find the following files:

* `01_mintNFT.ts`: In this 1st step, you will understand how to initialize the API and run your first on-chain transaction to create an NFT. Keep the NFT id from the log with you as you will need it later.
* `02_getNFT.ts`: In the 2nd step, you will see how to use our Indexer to retrieve your NFT data.
* `03_sellNFT.ts`: In the 3rd and last step, you will learn how to list your NFT for sale on a marketplace.

Run the following command to execute each script once you have read carefully the comments (replace FILENAME with the correct file name):

```bash
  npm run start src/basics/FILENAME.ts
```

Impressive, isn't it? Just one line of code to create an NFT and another single line to list it on a marketplace. Exciting, isn't it? Now, you're all set to kickstart your dApp development journey using our toolkit. Let's get started!

### Looking for a more advanced use case?

Just follow the advanced guide:

* `01-mintSecretNFT.ts`: In this 1st advanced step you will see how to create a secret NFT, upload metadata on IPFS, encrypt content, and send some private key shares on a TEE/SGX Cluster.

```bash
  npm run start src/advanced/01_mintSecretNFT.ts
```


# Ink! Smartcontracts

### Overview&#x20;

This tutorial provided on developing smart contracts walks you through utilizing the [ink! programming language](https://use.ink/) to construct smart contracts for execution on a blockchain built with Substrate.

To maintain a focus on the fundamental aspects of smart contract development, these tutorials utilize a [substrate-contracts-node](https://github.com/paritytech/substrate-contracts-node) that has been preconfigured for convenience.

Should you opt for the [standard node template](https://github.com/paritytech/substrate-contracts-node), it will be necessary for you to manually incorporate the [Contracts pallet](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/contracts) into your development setup, along with making several other modifications. You may review and compare their runtime codes for further insights into the distinctions between the two nodes.

* Let's [start building your first smart-contract](/getting-started/ink-smartcontracts/start-building-your-first-smart-contract): The Flipper smart contract.


# Start building your first smart-contract

This tutorial demonstrates how to build a basic smart contract to run a Substrate-based chain.

In this tutorial, you'll explore using ink! as a programming language for writing Rust-based smart contracts.

### Prerequisites

Before getting started, make sure you have the following ready:

1. You are generally familiar with command-line interfaces (CLI).
2. You have **installed Rust** and set up your development environment as described in one of the sources below:
   1. [Rust learn documentation](https://doc.rust-lang.org/book/ch01-01-installation.html)
   2. [Substrate documentation](https://docs.substrate.io/install/)
   3. [Rust-lang](https://www.rust-lang.org/tools/install)

### Update your Rust environment <a href="#update-your-rust-environment" id="update-your-rust-environment"></a>

For this tutorial, you need to add some Rust source code to your Substrate development environment.

To update your development environment:

1. Open a terminal shell on your computer.
2. Update your Rust environment by running the following command:

   ```bash
   rustup component add rust-src
   ```
3. Verify that you have the WebAssembly target installed by running the following command:

   ```bash
   rustup target add wasm32-unknown-unknown --toolchain nightly
   ```

   \
   If the target is installed and up-to-date, the command displays output similar to the following:

   ```
   info: component 'rust-std' for target 'wasm32-unknown-unknown' is up to date
   ```

### Install `cargo-contract` CLI Tool <a href="#install-cargo-contract-cli-tool" id="install-cargo-contract-cli-tool"></a>

`cargo-contract` is a command-line tool that you will use to build, deploy, and interact with your ink! contracts.

Note that in addition to Rust, installing `cargo-contract` requires a C++ compiler that supports C++17.

Modern releases of `gcc`, `clang`, as well as Visual Studio 2019+ should work.

1. Add the `rust-src` compiler component:

```bash
rustup component add rust-src
```

2. Install the latest version of `cargo-contract`:

```bash
cargo install --force --locked cargo-contract --version 2.0.0-rc
```

3. Verify the installation and explore the commands available by running the following command:

```bash
cargo contract --help
```

### Install the Substrate Contracts Node <a href="#install-the-substrate-contracts-node" id="install-the-substrate-contracts-node"></a>

To simplify this tutorial, you can [download](https://github.com/paritytech/substrate-contracts-node/releases) a precompiled Substrate node for Linux or macOS.

The precompiled binary includes the FRAME pallet for smart contracts by default.

To install the contracts node on macOS or Linux:

1. Open the [Releases](https://github.com/paritytech/substrate-contracts-node/releases) page.
2. Download the appropriate compressed archive for your local computer.
3. Open the downloaded file and extract the contents to a working directory.

If you can't download the precompiled node, you can compile it locally with a command similar to the following. You can find the latest tag on the [Releases](https://github.com/paritytech/substrate-contracts-node/releases) page:

```bash
cargo install contracts-node --git https://github.com/paritytech/substrate-contracts-node.git --tag <latest-tag> --force --locked
```

You can find the latest tag to use on the [Tags](https://github.com/paritytech/substrate-contracts-node/tags) page.

You can verify the installation by running `substrate-contracts-node --version`.

### Create a new smart contract project <a href="#create-a-new-smart-contract-project" id="create-a-new-smart-contract-project"></a>

You are now ready to start developing a new ink! smart contract project.

To generate the files for an ink! project:

1. Open a terminal shell on your computer.
2. Create a new project folder named `flipper` by running the following command:

   ```bash
   cargo contract new flipper
   ```
3. Change to the new project folder by running the following command:

   ```bash
   cd flipper/
   ```
4. List all of the contents of the directory by running the following command:

   ```bash
   ls -al
   ```

   You should see that the directory contains the following files:

   ```
   -rwxr-xr-x   1 dev-doc  staff   285 Mar  4 14:49 .gitignore
   -rwxr-xr-x   1 dev-doc  staff  1023 Mar  4 14:49 Cargo.toml
   -rwxr-xr-x   1 dev-doc  staff  2262 Mar  4 14:49 lib.rs
   ```

Like other Rust projects, the `Cargo.toml` file is used to provide package dependencies and configuration information.

The `lib.rs` file is used for the smart contract business logic.

#### Explore the default project files <a href="#explore-the-default-project-files" id="explore-the-default-project-files"></a>

By default, creating a new ink! project generates some template source code for a very simple contract.

This contract has one function — `flip()` — that changes a Boolean variable from true to false and a second function — `get()` — that gets the current value of the Boolean.

The `lib.rs` file also contains two functions for testing that the contract works as expected.

As you progress through the tutorial, you'll modify different parts of the starter code. By the end of the tutorial, you'll have a more advanced smart contract - See more examples [here](https://use.ink/examples/smart-contracts/).

To explore the default project files:

1. Open a terminal shell on your computer, if needed.
2. Change to project folder for the `flipper` smart contract, if needed:
3. Open the `Cargo.toml` file in a text editor and review the dependencies for the contract.
4. Open the `lib.rs` file in a text editor and review the macros, constructors, and functions defined for the contract.
   * The `#[ink::contract]` macro defines the entry point for your smart contract logic.
   * The `#[ink(storage)` macro defines a structure to store a single boolean value for the contract.
   * The `new` and `default` functions initialize the boolean value to false.
   * There's a `#[ink(message)` macro with a `flip` function to change the state of the data stored for the contract.
   * There's a `#[ink(message)` macro with a `get` function to get the current state of the data stored for the contract.

#### Test the default contract <a href="#test-the-default-contract" id="test-the-default-contract"></a>

At the bottom of the `lib.rs` source code file, there are simple test cases to verify the functionality of the contract. These are annotated using the `#[ink(test)]` macro. You can test whether this code is functioning as expected using the **off-chain test environment**.

To test the contract:

1. Open a terminal shell on your computer, if needed.
2. Verify that you are in the `flipper` project folder, if needed.
3. Use the `test` subcommand to execute the default tests for the `flipper` contract by running the following command:<br>

   ```bash
   cargo test
   ```

   \
   The command should compile the program and display output similar to the following to indicate successful test completion:<br>

   ```
   running 2 tests
   test flipper::tests::it_works ... ok
   test flipper::tests::default_works ... ok

   test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
   ```

#### Build the contract <a href="#build-the-contract" id="build-the-contract"></a>

After testing the default contract, you are ready to compile this project to WebAssembly.

To build the WebAssembly for this smart contract:

1. Open a terminal shell on your computer, if needed.
2. Verify that you are in the `flipper` project folder.
3. Compile the `flipper` smart contract by running the following command:<br>

   <pre class="language-bash"><code class="lang-bash"><strong>cargo contract build
   </strong></code></pre>

   \
   This command builds a WebAssembly binary for the `flipper` project, a metadata file that contains the contract Application Binary Interface (ABI), and a `.contract` file that you use to deploy the contract.

   \
   For example, you should see output similar to the following:

   ```
   Original wasm size: 35.5K, Optimized: 11.9K

   The contract was built in DEBUG mode.

   Your contract artifacts are ready. You can find them in:
   /Users/dev-doc/flipper/target/ink

   - flipper.contract (code + metadata)
   - flipper.wasm (the contract's code)
   - flipper.json (the contract's metadata)
   ```

   \
   The `.contract` file includes both the business logic and metadata. This is the file that tooling (e.g UIs) expect when you want to deploy your contract on-chain.

   The `.json` file describes all the interfaces that you can use to interact with this contract. This file contains several important sections:

   * The `spec` section includes information about the functions—like **constructors** and **messages**—that can be called, the **events** that are emitted, and any documentation that can be displayed. This section also includes a `selector` field that contains a 4-byte hash of the function name and is used to route contract calls to the correct functions.
   * The `storage` section defines all the **storage** items managed by the contract and how to access them.
   * The `types` section provides the custom **data types** used by the contract.

### Start the Substrate Contracts Node <a href="#start-the-substrate-contracts-node" id="start-the-substrate-contracts-node"></a>

If you have [successfully installed the `substrate-contracts-node`](https://docs.substrate.io/tutorials/smart-contracts/prepare-your-first-contract/#install-the-substrate-contracts-node), it's time to start a local node.

1. Start the contracts node in local development mode by running the following command:<br>

   ```bash
   substrate-contracts-node --log info,runtime::contracts=debug 2>&1
   ```

   \
   The extra logging is useful for development.

   \
   You should see output in the terminal similar to the following:

   ```
   2023-01-30 23:08:49.835  INFO main sc_cli::runner: Substrate Contracts Node
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: ✌️  version 0.23.0-87a3d76c880
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: ❤️  by Parity Technologies <admin@parity.io>, 2021-2023
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: 📋 Chain specification: Development
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: 🏷  Node name: profuse-grandmother-6287
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: 👤 Role: AUTHORITY
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: 💾 Database: ParityDb at /tmp/substrateCu3FVo/chains/dev/paritydb/full
   2023-01-30 23:08:49.836  INFO main sc_cli::runner: ⛓  Native runtime: substrate-contracts-node-100 (substrate-contracts-node-1.tx1.au1)
   2023-01-30 23:08:54.570  INFO main sc_service::client::client: 🔨 Initializing Genesis block/state (state: 0x27d2…a1d8, header-hash: 0x6a05…1669)
   2023-01-30 23:08:54.573  INFO main sub-libp2p: 🏷  Local node identity is: 12D3KooWG4h1FpwAhybzyMxoEGQgY8SbrLb4F5FB6mCBZCY6u7W1
   2023-01-30 23:08:58.643  INFO main sc_service::builder: 📦 Highest known block at #0
   2023-01-30 23:08:58.643  INFO tokio-runtime-worker substrate_prometheus_endpoint: 〽️ Prometheus exporter started at 127.0.0.1:9615
   2023-01-30 23:08:58.644  INFO                 main sc_rpc_server: Running JSON-RPC HTTP server: addr=127.0.0.1:9933, allowed origins=None
   2023-01-30 23:08:58.644  INFO                 main sc_rpc_server: Running JSON-RPC WS server: addr=127.0.0.1:9944, allowed origins=None
   2023-01-30 23:09:03.645  INFO tokio-runtime-worker substrate: 💤 Idle (0 peers), best: #0 (0x6a05…1669), finalized #0 (0x6a05…1669), ⬇ 0 ⬆ 0
   2023-01-30 23:09:08.646  INFO tokio-runtime-worker substrate: 💤 Idle (0 peers), best: #0 (0x6a05…1669), finalized #0 (0x6a05…1669), ⬇ 0 ⬆ 0
   ```

   \
   Note that no blocks will be produced unless we send an extrinsic to the node. This is because the `substrate-contracts-node` uses `Manual Seal` as its consensus engine.

### Deploy the contract <a href="#deploy-the-contract" id="deploy-the-contract"></a>

At this point, you have completed the following steps:

* Installed the packages for local development.
* Generated the WebAssembly binary for the `flipper` smart contract.
* Started the local node in development mode.

The next step is to deploy the `flipper` contract on your Substrate chain.

However, deploying a smart contract on Substrate is a little different than deploying on traditional smart contract platforms.

For most smart contract platforms, you must deploy a completely new blob of the smart contract source code each time you make a change.

For example, the standard ERC20 token has been deployed to Ethereum thousands of times.

Even if a change is minimal or only affects some initial configuration setting, each change requires a full redeployment of the code.

Each smart contract instance consumes blockchain resources equivalent to the full contract source code, even if no code was actually changed.

In Substrate, the contract deployment process is split into two steps:

* Upload the contract code to the blockchain.
* Create an instance of the contract.

With this pattern, you can store the code for a smart contract like the ERC20 standard on the blockchain once, and then instantiate it any number of times.

You don't need to reload the same source code repeatedly, so your smart contract doesn't consume unnecessary resources on the blockchain.

#### Uploading the ink! Contract Code <a href="#uploading-the-ink-contract-code" id="uploading-the-ink-contract-code"></a>

For this tutorial, you use the `cargo-contract` CLI tool to `upload` and `instantiate` the `flipper` contract on a Substrate chain.

1. Start your node using `substrate-contracts-node --log info,runtime::contracts=debug 2>&1`
2. Go to the `flipper` project folder.
3. Build the contract using `cargo contract build`.
4. Upload and instantiate your contract using:<br>

   ```bash
   cargo contract instantiate --constructor new --args "false" --suri //Alice --salt $(date +%s) -x   
   ```

   \
   Some notes about the command:

   * The `instantiate` command will do both the `upload` and `instantiate` steps for you.
   * We need to specify the contract constructor to use, which in this case is `new()`
   * We need to specify the argument to the constructor, which in this case is `false`
   * We need to specify the account uploading and instantiating the contract, which in this case is the default development account of `//Alice`
   * During development, we may want to upload the instantiate of the same contract multiple times, so we specify a `salt` using the current time. Note that this is optional.

   After running the command confirming that we're happy with the gas estimation we should see something like this:<br>

   ```
   Dry-running new (skip with --skip-dry-run)
     Success! Gas required estimated at Weight(ref_time: 328660939, proof_size: 0)
   Confirm transaction details: (skip with --skip-confirm)
   Constructor new
         Args false
    Gas limit Weight(ref_time: 328660939, proof_size: 0)
   Submit? (Y/n):
       Events
        Event Balances ➜ Withdraw
          who: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
          amount: 98.986123μUNIT
        Event System ➜ NewAccount
          account: 5GRAVvuSXx8pCpRUDHzK6S1r2FjadahRQ6NEgAVooQ2bB8r5
        ... snip ...
        Event TransactionPayment ➜ TransactionFeePaid
          who: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
          actual_fee: 98.986123μUNIT
          tip: 0UNIT
        Event System ➜ ExtrinsicSuccess
          dispatch_info: DispatchInfo { weight: Weight { ref_time: 2827629132, proof_size: 0 }, class: Normal, pays_fee: Yes }

     Contract 5GRAVvuSXx8pCpRUDHzK6S1r2FjadahRQ6NEgAVooQ2bB8r5
   ```

We will need the `Contract` address to `call` the contract, so make sure you don't lose it.

### Calling the Deployed ink! Contract <a href="#calling-the-deployed-ink-contract" id="calling-the-deployed-ink-contract"></a>

We can not only `upload` and `instantiate` contracts using `cargo-contract`, we can also `call` them!

#### `get()` Message <a href="#get-message" id="get-message"></a>

When we initialized the contract we set the initial value of the `flipper` to `false`. We can confirm this by calling the `get()` message.

Since we are only reading from the blockchain state (we're not writing any new data) we can use the `--dry-run` flag to avoid submitting an extrinsic.

```bash
cargo contract call --contract $INSTANTIATED_CONTRACT_ADDRESS --message get --suri //Alice --dry-run
```

Some notes about the command:

* The address of the contract we want to call has to be specified using the `--contract` flag. Replace `$INSTANTIATED_CONTRACT_ADDRESS` with the contract address created at the end of the build.
* This can be found in the output logs of the `cargo contract instantiate` command
* We need to specify the contract message to use, which in this case is `get()`
* We need to specify the account calling the contract, which in this case is the default development account of `//Alice`
* We specify `--dry-run` to avoid submitting an extrinsic on-chain

After running the command should see something like this:

```
Result Success!
Reverted false
    Data Tuple(Tuple { ident: Some("Ok"), values: [Bool(false)] })
```

We're interested in the `value` here, which is `false` as expected.

#### `flip()` Message <a href="#flip-message" id="flip-message"></a>

The `flip()` message changes the storage value from `false` to `true` and vice versa.

To call the `flip()` message we will need to submit an extrinsic on-chain because we are altering the state of the blockchain.

To do this we can use the following command:

```bash
cargo contract call --contract $INSTANTIATED_CONTRACT_ADDRESS --message flip --suri //Alice
```

Notice that we changed the message to `flip` and removed the `--dry-run` flag.

After running we expect to see something like:

```
Dry-running flip (skip with --skip-dry-run)
    Success! Gas required estimated at Weight(ref_time: 8013742080, proof_size: 262144)
Confirm transaction details: (skip with --skip-confirm)
     Message flip
        Args
   Gas limit Weight(ref_time: 8013742080, proof_size: 262144)
Submit? (Y/n):
      Events
       Event Balances ➜ Withdraw
         who: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
         amount: 98.974156μUNIT
       Event Contracts ➜ Called
         caller: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
         contract: 5GQwxP5VTVHwJaRpoQsK5Fzs5cERYBzYhgik8SX7VAnvvbZS
       Event TransactionPayment ➜ TransactionFeePaid
         who: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
         actual_fee: 98.974156μUNIT
         tip: 0UNIT
       Event System ➜ ExtrinsicSuccess
         dispatch_info: DispatchInfo { weight: Weight { ref_time: 1410915697, proof_size: 13868 }, class: Normal, pays_fee: Yes }
```

If we call the `get()` message again we can see that the storage value was indeed flipped!

```
Result Success!
Reverted false
    Data Tuple(Tuple { ident: Some("Ok"), values: [Bool(true)] })
```


# Introduction

In this section, you will find a high level overview of Ternoa's architecture, networks and purpose.

##

##

##


# What is Ternoa

[Ternoa](https://www.ternoa.network/) is a  multi-network and cross-layer protocol leveraging confidential computing technologies to make blockchain more secure, private and scalable.

Our tech stack combines distributed ledger and confidential computing technologies to provide decentralized yet private development environments for next generation applications. Ternoa comprises of 3 independent, yet interconnected networks:

* **Ternoa Chain**: A WASM Layer 1 blockchain network built on Substrate where builders can deploy ink! smartcontracts coded in Rust, C, C++ or Typescript, and call pre-coded primitives through a JavaScript SDK (mainnet since April 2022)
* **Ternoa Fortress**: A decentralized TEE-powered coprocessor network, implemented as a key management system, enabling users to encrypt off-chain data with on-chain encryption keys (mainnet since September 2023)
* **Ternoa zkEVM**: A Layer 2 validium secured with TEE multi-proofs, offering a full EVM equivalent environment where builders can deploy solidity smartcontracts (mainnet planned for 2024)

Since the beginning Ternoa has been envisioned as a comprehensive protocol enabling new privacy and security use cases. Our TEE-powered tech stack has been live and available as a mainnet L1 since 2022, prompting us to develop a multi-layer and multi-chain architecture, set for delivery in 2024.


# Why build on Ternoa

**ACCESSIBILITY**

Our tech stack has been designed to cater to the needs of the greatest number of developers. Regardless of your background, or of the type of application you are looking to build, you will find a suitable dev environment to launch your project.

* On Ternoa, **new developers** making their first steps in web3 don’t need to learn how to write smart contracts to develop blockchain applications. Our javascript SDK enables this and makes Ternoa suitable for web2 audiences just entering web3, including corporations & organizations.
* **Seasoned Web3 developers** can deploy WASM smartcontracts on Ternoa Chain written in Rust, C, C++, or Typescript. And will soon be able to build EVM dapps in Solidity. Our smartcontract environments enable the most complex use cases to be built on our infrastructure, and take advantage of our built-in confidentiality features and security.

**BUILT-IN CONFIDENTIALITY FEATURES**

For developers and dapps with a need to secure, control access and transmit confidential data without relying on 3rd parties or tech platform. Ternoa natively offers privacy features through the Fortress, our decentralized key management system. Enabling developers to create and compose private yet trustless applications very easily. Builders and users can interact with the Fortress via Ternoa Chain today. The Fortress will also become accessible from Ternoa zkEVM once launched.<br>

**SECURITY**

Ternoa Chain is built with  Substrate, an open-source, thoroughly audit framework powered by state of the art Proof of Stake consensus. Our network is decentralized by hundreds of nodes and validators. And our architecture makes us natively compatible to rely upon Polkadot's network security.

Ternoa zkEVM combines zero knowledge proofs with additional TEE proofs to achieve enhanced levels of network security.

## Networks Purpose

Each of Ternoa's network serve the shared goal of making internet a more decentralized and private place , and play a specific role in this grand scheme:

<table><thead><tr><th width="162">Network</th><th>Purpose</th><th>Specifics</th></tr></thead><tbody><tr><td>Ternoa Fortress</td><td>Enable data privacy and decentralized security</td><td>The Fortress is a TEE coprocessor network, fully open source, with native key management features</td></tr><tr><td>Ternoa Chain</td><td>Facilitate the onboarding of web and web2 builders in Web3</td><td>Ternoa Chain brings in a WASM deployment environment for smartcontracts, as well as pre-coded primitives accessible with Javascript</td></tr><tr><td>Ternoa ZKEVM</td><td>Bring in enhanced TEE security to zkEVM, and make Ternoa ecosystem accessible natively from ethereum</td><td>Ternoa ZKEVM is a validium using TEE proofs to add a layer of security to zkEVM, and is fully ethereum equivalent</td></tr></tbody></table>


# What to build on Ternoa?

With Ternoa Chain , you can build anything and create your first web3 project without developing single, smart contracts.&#x20;

On Ternoa Chain, our pallets and Javascript SDK facilitate the creation and management of any sort of NFT-based applications, including private-content NFTs,  in no time.

This page lists examples of projects or companies who run, or plan to launch applications using our Technology

**Data Privacy**

* [Time Guardian](https://www.time-guardian.app/en)
* Hereditas

**Marketplaces**

* [Secret Stash](https://secret-stash.io/)

**Gaming**

* [Mafiafoot](https://www.mafiafoot.com/)
* [Virtual Regatta](https://www.virtualregatta.com/en/)


# Security

By Integrating Storage and Computing protocols, we've designed our network to provide cutting-edge decentralized tech for NFTs. We ensure true ownership of data and assets via decentralization of key encryption management. Ternoa protocol handles Key re-encryption and registration requests from the Computing protocol.

### Ternoa Protocol

Sealed Secret keys are stored on both the Ternoa and Computing protocols by their enclaves using Trusted Execution Environments (TEEs). Only the enclave can claim ownership of the keys at any given point in time.

No individual or entity {even a central one} can access the NFT Encryption Key apart from the current owner. The *EncKey* of the NFT can be wiped after each upload/download.

### Storage Protocol

Our Storage Layer is a decentralized storage network that can be used to store {secure} encrypted private data if {needed/the need arises}. We currently support Inter Planetary File System (IPFS) and Arweane whereas support for other storage networks on the Polkadot ecosystem such as Crust will be accessible soon.

As Ternoa doesn't support native file storage, the need for dedicated, decentralized storage {network/layer} became paramount. Ternoa's chain architecture being developed on the Polkadot substrate framework allows interoperability with existing {networks/blockchains}. This allows Data ownership management on decentralized storage networks along with Seamless data storage experience. This approach to storage is the most advantageous in terms of security and resilience. This functionality also opens the doors for a variety of B-to-B and B-to-C use cases.

### Computing Protocol

functions like Key generation, Key agreement, and Shamir secret sharing are executed in enclaves to make sure that the Keys are never available to anyone outside of the enclave.

Enclaves are in a nutshell, private regions which can protect their contents in such a way that they can't be read or saved by any outside processes. This ability of an enclave to protect its environment in such a way is called Trusted Execution Environment (TEE). TEE is essentially Hardware-level privacy with a low runtime overhead {which makes sure it doesn't take a huge computational hit}.

TEEs encrypt the enclaves and then decrypt them on the fly, but only within the CPU, and even then only for code and data running from within the enclave itself. The processor thus protects the code from being spied on or examined by other code.

This capability in today’s processors is called Secure Execution Environment for AMD, Software Guard Extension for Intel, and Secure Execution for IBM.

Certified master nodes on our network will take advantage of the inbuilt capabilities of these processors to establish TEEs. This, in turn, sheild the nodes from malicious code. It offers a secure environment within the processor which protects both the confidentiality and Integrity of the Data inside of it which is especially important for zero-trust networks like ternoa. We've named them **Secret nodes** due to obvious reasons.


# Privacy

Key components of the Ternoa private data protocol include:

1. Layer 1 blockchain running on Polkadot technology
2. On-chain protocol that includes rules for state management and access of encrypted NFTs, on-chain registration for secret node operators, and rewards management
3. Secure enclaves running in Trusted Execution environments for distributed key management, organized in clusters that sync data among themselves in real-time for data redundancy,
4. In-enclave oracles to communicate keyshare receipt to blockchain.
5. Ternoa Javascript SDK to build DApps
6. Ternoa IPFS gateway to allow decentralized storage of encrypted private data
7. Ternoa indexer and dictionary for DApps to access historical on-chain data
8. Attestation server for remote attestation of enclaves
9. Metrics server to record performance of secret nodes and submit scores to blockchain
10. Dashboard for secret node operators to claim rewards

<figure><img src="/files/j2fyybjQMyknRBjMsKfA" alt=""><figcaption></figcaption></figure>


# Roadmap

**COMPLETED**

* Substrate Layer 1 (2022)
* Native NFT features (2022)
* Ternoa Fortress (2023)
* Native Privacy features (2023)
* WASM Smartcontracts (2024)

**PLANNED**

* zkEVM
* TEE prover
* EVM Ternoa Fortress


# Ternoa WASM Chain

In this section, discover core concepts and features underlying Ternoa Chain, our Substrate-built Layer 1 WASM blockchain


# Substrate

Ternoa is built on Substrate. Therefore it's naturally interoperable with the Polkadot ecosystem. We plan to become a Polkadot Parachain, which can serve the entire Polkadot Parachain ecosystem.

Substrate is a development environment created to facilitate the creation of Blockchains thanks to a modular architecture that considerably reduces the development cost and time of a Blockchain.

The ecosystem formed by the Substrate and the Polkadot Blockchain stood out in 2020 as the first project not based on the Ethereum Blockchain to integrate Chainlink, a leading decentralized Oracle network solution. And enabling it to become « the main provider of oracles for all Substrate-based blockchains and, ultimately, for the entire Polkadot network »

The Ternoa Blockchain is based on the substrate framework to offer:

* The use of delegated proof of stake (Nominated-Proof-of-Stake abbreviated to NPOS) to validate transactions and thus secure the data.
* The possibility to connect to other Blockchains to be able to store the data on specialized infrastructures.
* The creation of Smart Contracts to create the different protocols allowing data to be transmitted/to transmit the data.
* The management of Non-Fungible Tokens (NFT) which acts as a time capsule and allows the management of time capsules;

### The importance of multi-chain

Blockchains, because of their necessary overhead for things like consensus and encryption, suffer from congestion and slow transaction times. This results in higher transaction fees, poor user experience, and ultimately lower user adoption.

For blockchain technology to become widely adopted, blockchains must become faster. One good way to speed things up is to develop purpose-built blockchains, rather than try and build dApps and smart-contracts on a do-it-all blockchain like Ethereum.

Because it only has to do one thing, targeted protocols can be developed on a purpose-built blockchain which is designed to optimize throughput. Purpose-built blockchains sound like the ideal solution, but they too come with a big hurdle.

Purpose-built blockchains are not natively interoperable. That means an ecosystem of purpose-built blockchains would be an ecosystem of blockchains that can’t talk to each other. Perhaps the one impediment to user adoption worse than slow blockchains is blockchains that don’t communicate with each other. For a blockchain ecosystem to work, the individual blockchains must be interoperable and form a cohesive user experience.


# Governance

### What is Governance?

In plain terms, governance is the management or structure a participant in a system agrees to when entering into that system. Governance is not only the rules that a user has to follow but also the punishments for not following the rules.

Governance tends to fall into two different categories: direct and representative. Direct governance is like a democracy, where users determine decisions and actions with no intermediary. Representative governance systems have users create representatives that submit votes on their behalf instead.

For blockchain systems, governance is mostly how the blockchain ecosystem decides on which improvements to enact. Users of the blockchain ecosystem create proposals, which then receive votes from the rest of the community based on the participation rules created.

### Why Do Blockchains Rely on Governance?

The main reason why blockchains need governance is the same reason any software or computer system does: they need rules to function.

When developers create code, they define the rules that the system uses to produce its outcomes. Without any rules to decide what happens when users enter an input, the system will not work. This limitation is why you can do math in a calculator app on your phone, but can't text message with that app. The calculator app doesn't have the rules programmed to handle texting.

Blockchain systems are no different. For the ecosystem to work, rules have to be created by developers on the blockchain. As the developers create these rules by making code for the blockchain, they set the features and functions of the blockchain. The changes you see between different blockchains represent how those developers plan to solve or improve on other systems that came before them.

However, there's one key feature of a blockchain that other computer systems don't have to worry about: decentralization.

Users of blockchain systems expect there to be some aspect of decentralization, where the users of the system also help determine the fate of the system without being overruled by the creators of the system. So, these users expect there to be some way for them to participate in figuring out what direction the ecosystem will go.

### Ternoa's Governance: On-chain

On-chain governance refers to blockchain governance that takes place on the blockchain. This type of governance involves the voting on and implementation of changes to the blockchain protocol. How this exactly works with Ternoa can be found below.

#### Mechanism

To make any changes to the network, the idea is to compose active token(CAPS) holders and the council together to administrate a network upgrade decision. No matter whether the proposal is proposed by the public (token holders) or the council, it finally will have to go through a referendum to let all holders, weighted by stake, make the decision.

#### Council

To represent passive stakeholders, Ternoa follows the idea of a "council" by Polkadot. The council is an on-chain entity comprising several actors, each represented as an on-chain account. On Ternoa, the council currently consists of 8 members.

Along with controlling the treasury, the council is called upon primarily for three tasks of governance: proposing sensible referenda, canceling uncontroversially dangerous or malicious referenda, and electing the technical committee.

For a referendum to be proposed by the council, a strict majority of members must be in favor, with no member exercising a veto. Vetoes may be exercised only once by a member for any single proposal; if, after a cool-down period, the proposal is resubmitted, they may not veto it a second time.

Council motions that pass with a 3/5 (60%) super-majority - but without reaching unanimous support - will move to a public referendum under a neutral, majority-carries voting scheme. In the case that all members of the council vote in favor of a motion, the vote is considered unanimous and becomes a referendum with negative adaptive quorum biasing.

### Referenda

Referenda are simple, inclusive, stake-based voting schemes. Each referendum has a specific proposal associated with it that takes the form of a privileged function call in the runtime (that includes the most powerful call: set\_code, which can switch out the entire code of the runtime, achieving what would otherwise require a "hard fork").

Referenda are discrete events, have a fixed period where voting happens, and then are tallied and the function call is made if the vote is approved. Referenda are always binary; your only options in voting are "aye", "nay", or abstaining entirely.

Referenda can be started in one of several ways:

* Publicly submitted proposals;
* Proposals submitted by the council, either through a majority or unanimously;
* Proposals submitted as part of the enactment of a prior referendum;
* Emergency proposals are submitted by the Technical Committee and approved by the Council. All referenda have an enactment delay associated with them. This is the period between the referendum ending and, assuming the proposal was approved, the changes being enacted.

Referenda is considered baked if it is closed and tallied. Again, assuming the proposal was approved, it would be scheduled for enactment. Referenda are considered unbaked if it is pending an outcome, i.e. being voted on.

For the first two ways that a referendum is launched, this is a fixed time of 28 days. For the third type, it can be set as desired. Emergency proposals deal with major problems with the network that need to be "fast-tracked". These will have a shorter enactment time.

### Proposing a Referendum

#### Public Referenda

Anyone can propose a referendum by depositing the minimum amount of tokens for a certain period (number of blocks). If someone agrees with the proposal, they may deposit the same amount of tokens to support it - this action is called endorsing. The proposal with the highest amount of bonded support will be selected to be a referendum in the next voting cycle.

Note that this may be different from the absolute number of endorsements; for instance, three accounts bonding 20 CAPS each would "outweigh" ten accounts bonding a single CAPS each

The bonded tokens will be released once the proposal is tabled (that is, brought to a vote).

There can be a maximum of 100 public proposals in the proposal queue.

#### Council Referenda

\*\* Unanimous Council \*\* - When all members of the council agree on a proposal, it can be moved to a referendum. This referendum will have a negative turnout bias (that is, the smaller the amount of stake voting, the smaller the amount necessary for it to pass).

\*\* Majority Council \*\*- When agreement from only a simple majority of council members occurs, the referendum can also be voted upon, but it will be majority-carries (51% wins).

* There can only be one active referendum at any given time, except when there is also an emergency referendum in progress.

### Voting Timetable

Every 28 days, a new referendum will come up for a vote, assuming there is at least one proposal in one of the queues. There is a queue for Council-approved proposals and a queue for publicly submitted proposals. The referendum to be voted upon alternates between the top proposal in the two queues.

The "top" proposal is determined by the amount of stake bonded behind it. If the given queue whose turn it is to create a referendum that has no proposals (is empty), and proposals are waiting in the other queue, the top proposal in the other queue will become a referendum.

Multiple referenda cannot be voted upon in the same period, excluding emergency referenda. An emergency referendum occurring at the same time as a regular referendum (either public- or council-proposed) is the only time that multiple referenda will be able to be voted on at once.

### Voting on a Referendum

To vote, a voter generally must lock their tokens up for at least the enactment delay period beyond the end of the referendum. This is to ensure that some minimal economic buy-in to the result is needed and to dissuade vote selling.

It is possible to vote without locking at all, but your vote is worth a small fraction of a normal vote, given your stake. At the same time, holding only a small amount of tokens does not mean that the holder cannot influence the referendum result, thanks to time-locking.

Example:

* Peter: Votes No with 10 CAPS for a 128-week lock period => 10 x 6 = 60 Votes
* Logan: Votes Yes with 20 CAPS for a 4-week lock period => 20 x 1 = 20 Votes
* Kevin: Votes Yes with 15 CAPS for an 8-week lock period => 15 x 2 = 30 Votes

Even though both Logan and Kevin vote with more CAPS than Peter, the lock period for both of them is less than Peter's, leading to their voting power counting as less.


# Consensus & NPOS

### What is Consensus in Blockchain?

Blockchain is a secure and decentralized network that relies on a consensus protocol to ensure the accuracy and reliability of its transactions. This protocol enables all nodes in the network to agree on the current state of the ledger, thereby establishing trust between unknown peers in a distributed computing environment. The consensus algorithm helps achieve reliability, collaboration, co-operation, equal rights for every node, and mandatory participation from all nodes in the consensus process. This creates a single version of the truth that is agreed upon by all nodes in the network, making it a win for everyone involved.

### Why do we need Consensus?

Consensus is a crucial method for achieving agreement and synchronization among nodes in a decentralized blockchain network. It ensures that all nodes agree on the shared state and allows for the building and progression of the blockchain. Consensus aims to provide an objective view of the state by reconciling the subjective views of the participants. This process enables the nodes to communicate, reach agreement, and build new blocks.

### Widely known consensus

#### Proof of Work

This consensus algorithm used by Bitcoin to select a miner for the next block generation. The algorithm involves solving a complex mathematical puzzle that requires significant computational power. The node that solves the puzzle first is rewarded with the opportunity to mine the next block.

#### Proof of Stake

This is the most common alternative to PoW. Ethereum has shifted from PoW to PoS consensus. In this type of consensus algorithm, instead of investing in expensive hardware to solve a complex puzzle, validators invest in the coins of the system by locking up some of their coins as stake. After that, all the validators will start validating the blocks. Validators will validate blocks by placing a bet on it if they discover a block which they think can be added to the chain. Based on the actual blocks added in the Blockchain, all the validators get a reward proportionate to their bets and their stake increase accordingly. In the end, a validator is chosen to generate a new block based on their economic stake in the network. Thus, PoS encourages validators through an incentive mechanism to reach to an agreement.

### Ternoa's Consensus

#### Nominated Proof of Stake

In traditional PoS systems, block production participation is dependent on token holdings as opposed to computational power. While PoS developers usually have a proponent for equitable participation in a decentralized manner, most projects end up proposing some level of centralized operation, where the number of validators with full participation rights is limited. These validators are often seen to be the most wealthy, and, as a result, influence the PoS network as they are the most staked. Usually, the number of candidates to maintain the network with the necessary knowledge (and equipment) is limited; this can directly increase operational costs as well. Systems with a large number of validators tend to form pools to decrease the variance of their revenue and profit from economies of scale. These pools are often off-chain.

A way to alleviate this is to implement pool formation on-chain and allow token holders to vote \[with their stake] for validators to represent them.

Ternoa uses NPoS (Nominated Proof-of-Stake) as its mechanism for selecting the validator set. It is designed with the roles of **validators** and **nominators**, to maximize chain security. Actors who are interested in maintaining the network can run a validator node.

Validators assume the role of producing new blocks in BABE, validating blocks, and guaranteeing finality. Nominators can choose to back validators with their stake. Nominators can approve candidates that they trust and back them with their tokens.

### Probabilistic vs. Provable Finality

A pure Nakamoto consensus blockchain that runs PoW is only able to achieve the notion of *probabilistic finality* and reach *eventual consensus*. Probabilistic finality means that under some assumptions about the network and participants if we see a few blocks building on a given block, we can estimate the probability that it is final. Eventual consensus means that at some point in the future, all nodes will agree on the truthfulness of one set of data. This eventual consensus may take a long time and will not be able to determine how long it will take ahead of time. However, finality gadgets such as GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) or Ethereum's Casper FFG (the Friendly Finality Gadget) are designed to give stronger and quicker guarantees on the finality of blocks - specifically, that they can never be reverted after some process of Byzantine agreements has taken place. The notion of irreversible consensus is known as *provable finality.*

In the [GRANDPA paper](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf), it is phrased in this way:

{% hint style="success" %}
We say an oracle A in a protocol is *eventually consistent* if it returns the same value to all participants after some unspecified time.
{% endhint %}

### Hybrid Consensus

There are two protocols we use when we talk about the consensus protocol of Ternoa, GRANDPA and BABE (Blind Assignment for Blockchain Extension). We talk about both of these because Ternoa uses what is known as *hybrid consensus*. Hybrid consensus splits up the finality gadget from the block production mechanism.

This is a way of getting the benefits of probabilistic finality (the ability to always produce new blocks) and provable finality (having a universal agreement on the canonical chain with no chance for reversion) in Ternoa. It also avoids the corresponding drawbacks of each mechanism (the chance of unknowingly following the wrong fork in probabilistic finality, and a chance for "stalling" - not being able to produce new blocks - in provable finality). By combining these two mechanisms, Ternoa allows for blocks to be rapidly produced, and the slower finality mechanism to run in a separate process to finalize blocks without risking slower transaction processing or stalling.

Hybrid consensus has been proposed in the past. Notably, it was proposed (now defunct) as a step in Ethereum's transition to proof of stake in [EIP 1011](http://eips.ethereum.org/EIPS/eip-1011), which specified Casper FFG.

### Block Production

BABE (Blind Assignment for Blockchain Extension) is the block production mechanism that runs between the validator nodes and determines the authors of new blocks. BABE is comparable as an algorithm to [Ouroboros Praos](https://eprint.iacr.org/2017/573.pdf), with some key differences in chain selection rule and slot time adjustments. BABE assigns block production slots to validators according to stake and using the Ternoa randomness cycle. The chain's runtime is required to provide the BABE authority list and randomness to the host via a consensus message in the header of the first block of each epoch.

BABE execution happens in sequential non-overlapping phases known as epochs. Each epoch is divided into a predefined number of slots. All slots in each epoch are sequentially indexed starting from 0 (slot number). At the beginning of each epoch, the BABE node needs to run the [Block-Production-Lottery algorithm](https://spec.polkadot.network/#algo-block-production-lottery) to find out in which slots it should produce a block and gossip to the other block producers.

Validators participate in a lottery for every slot, which will inform whether or not they are the block producer candidate for that slot. Slots are discrete units of time of approximately 6 seconds in length. Because the mechanism of allocating slots to validators is based on a randomized design, multiple validators could be candidates for the same slot. Other times, a slot could be empty, resulting in inconsistent block time.

#### Multiple Validators per Slot

When multiple validators are block producer candidates in a given slot, all will produce a block and broadcast it to the network. At that point, it's a race. The validator whose block reaches most of the network first wins. Depending on network topology and latency, both chains will continue to build in some capacity, until finalization kicks in and amputates a fork.

#### No Validators in Slot

When no validators have rolled low enough in the randomness lottery to qualify for block production, a slot can remain seemingly blockless. We avoid this by running a secondary, round-robin style validator selection algorithm in the background. The validators selected to produce blocks through this algorithm always produce blocks, but these *secondary* blocks are ignored if the same slot also produces a primary block from a VRF-selected validator. Thus, a slot can have either a *primary* or a *secondary* block, and no slots are ever skipped.

### Finality Gadget

GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget that is implemented for the Ternoa Chain.

The Ternoa uses the GRANDPA Finality protocol to finalize blocks. Finality is obtained by consecutive rounds of voting by the validator nodes. Validators execute the GRANDPA finality process in parallel to Block Production as an independent service.

It works in a partially synchronous network model as long as 2/3 of nodes are honest and can cope with 1/5 Byzantine nodes in an asynchronous setting.

A notable distinction is that GRANDPA reaches agreements on chains rather than blocks, greatly speeding up the finalization process, even after long-term network partitioning or other networking failures.

In other words, as soon as more than 2/3 of validators attest to a chain containing a certain block, all blocks leading up to that one are finalized at once.

### Resources

* [BABE paper](https://research.web3.foundation/Polkadot/protocols/block-production/Babe) - The academic description of the BABE protocol.
* [GRANDPA paper](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf) - The academic description of the GRANDPA finality gadget. Contains formal proofs of the algorithm.
* [Rust implementation](https://github.com/paritytech/finality-grandpa) - The reference implementation and the accompanying [Substrate pallet](https://github.com/paritytech/substrate/blob/master/frame/grandpa/src/lib.rs).


# Primitives features

NFTs, or non-fungible tokens, are unique digital assets that signify ownership of distinctive items or content, which can range from artwork to items in video games or even credentials.&#x20;

Ternoa's fundamental components, also called primitives, are essential for the creation and management of NFTs. These primitives generally include the technical specifications and standards that define how NFTs are minted, transferred, and stored on the blockchain. They are vital in providing groundwork for diverse NFT applications and platforms, enabling developers to innovate and create new uses for NFTs. \
\
Ternoa provides an extensive range of primitives, spanning from fundamental NFT and Collection features to the more unique and distinctive Protocols or Private NFTs.

**Mint Basic NFTs**

* Create NFTs on Ternoa, up to 1000 NFTs per block for batch.

**NFT Collections**

* Group NFTs with similar attributes or functions into on-chain collections with defined supply.

**NFT Marketplaces**

* Create fully decentralized marketplaces, defining on-chain rules such as listing costs and commission fees.

**NFT Royalties**

* Set up on-chain royalties management rules for your NFTs. Fully decentralized royalties are not controlled by the Marketplace owner.

**NFT Auctions**

* Sell NFTs with on-chain English auctions rules. NFT owners can auction their NFTs and users can bid on them in a fully trustless manner.

**NFT Delegation**

* Share your NFT and its utilities with a beneficiary without giving up ownership. It’s a perfect solution for Guilds’ assets management.

**NFT Renting**

* Lend your NFT and its utilities to a borrower without transferring ownership. NFT owners can rent power-ups, add-ons, tools, products, or even subscriptions.

**Soulbound NFT**

* Create NFTs transferrable only once by the issuer. These NFTs can be used to represent commitments, credentials, or affiliations.

**Secret NFT**

* Associate private content to an NFT that only the owner can access. Including images, videos, audio, or documents. Secret NFTs can be transferred peer-to-peer or traded in marketplaces.

**Capsule NFT**

* Associate and update private content to an NFT that only the owner can access. Users can store an unlimited amount of digital assets and media in a Capsule. The capsules work with transfer protocols triggered based on an event or time.

**Transfer Protocols**

* Rules and standards that govern how NFTs are transferred to beneficiaries over the Ternoa network.

**Gtoken**

* Unit count token, not mintable nor tradable, designed for the gaming industry to streamline in-game purchases and enhance security for players. No need to pay gas fees, it’s managed by the contact.


# Basic NFT

Basic NFTs are digital assets on the blockchain that represent ownership of a digital or physical asset, with associated metadata stored on-chain and off-chain. They can be minted, transferred, listed, sold, auctioned, burned, and can have royalties associated with them. Basic NFTs involve storing the media file on a decentralized storage network and storing off-chain metadata in IPFS.

Use cases for Basic NFTs include digital artwork, music, video clips, memes, avatars, video games, trading cards, metaverse land, virtual fashion, text-based NFTs, ticket & membership NFTs, and real-world assets.

Ternoa Network supports the creation and trading of Basic NFTs. If a Basic NFT includes royalties, Ternoa facilitates the automatic payment of royalties on each sale by embedding it in the minting process, ensuring that creators receive payment for each sale of their NFT.


# Secret NFT

Secret NFTs give creators the ability to add private data in their NFTs, including images, videos, audio, or documents. Secret NFTs can be transferred peer-to-peer or traded in marketplaces. There are infinite ways in which secret NFTs can be utilized and transform how we store our private data. Now let's go into more technical detail on how we ensure privacy with Secret NFTs. Secret NFTs are an addition to the Basic NFTs; the secret data is stored in a decentralized manner using IPFS protocol. The secret consists of a media that is encrypted using generated PGP keys. After encrypting the media, the PGP private key is split into shares using Shamir's Secret Sharing algorithm. Each share is securely stored in an enclave using the TEE technology, where individuals or centralized entities other than the current owner of the Secret NFT cannot access them.

To view a secret, the NFT owner will request the shares for each enclave. The request consists of the NFT ID and a signed message. Once the NFT ownership is verified, the TEE enclaves will return the shares. The PGP Private Key can be reconstructed with the shares, and the secret media is decrypted.

Secret NFTs can revolutionize several industries by providing an extra layer of privacy to creators and collectors. They can be used to store and transfer exclusive content, such as music tracks, backstage photos, and gaming items, and ensure that the content is only accessible to verified fans or collectors. Secret NFTs also enable creators to hide their NFT content, protecting their work from unauthorized duplication or hacking. Ternoa has developed Secret NFTs to address the need for additional privacy on data and creations, and this innovation will give control back to NFT owners and creators.


# Capsule NFT

In an era where digital data is highly susceptible to hacking and breaches, preserving and protecting private data and memories have become paramount. Addressing this need is Ternoa's innovative solution, Capsules. These are a novel form of NFTs that offer unlimited storage capacity and automated transfer services, aiming to redefine how we store and transmit data. Unlike conventional storage methods, Capsules use decentralized technology, which allows for secure data storage and transmission by dispersing it across multiple locations, thus mitigating the risk of hacking or data tampering. Capsules facilitate data sharing at predetermined times or events, providing a streamlined and secure means of data transfer.

To assure privacy with Capsules, data is stored in a decentralized manner using IPFS protocol. Capsules can hold multiple media files and allow for off-chain data to be altered or updated even after they have been minted, which provides users with the flexibility to modify, remove, or add new files as needed. The media is encrypted using PGP keys, and the private key is divided into shares using Shamir's Secret Sharing algorithm. Each share is securely stored in an enclave using TEE technology, accessible only to the current owner. Capsules use advanced security measures to safeguard the data they store, such as partitioning the encryption key and securely storing it in enclaves.

Capsules offer a revolutionary approach to data storage and transfer, providing a secure and verifiable solution to protect information across multiple industries, from medical records and supply chain management to education and real estate. They ensure transparency and accountability in the transfer of essential data. In the art world, they help safeguard the authenticity of artworks, and in real estate, they streamline the storage and transfer of property titles and deeds. Significantly, Capsules serve as a unique medium for preserving personal legacies and memories for future generations. By securely storing personal data, photos, and videos, they ensure these memories can be passed down and cherished in the years to come. Capsules allow families to create digital time capsules of memories, triggered for sharing at significant milestones, offering a way to control personal data, protect privacy, and preserve memories across generations.


# Collection

Creating a collection for NFTs involves grouping together non-fungible tokens that share a common theme or attribute and organizing them. This allows for easy tracking, management, and trading of NFTs with unique properties and value. Collections are represented by smart contracts in EVM/Smart Contract based systems, but Ternoa allows users to create and own collections with consistent rules, making it easier to group NFTs with similar attributes and improve the user experience.

For example you could create a collection of NFTs that represent your favorite artists, or a collection of NFTs that all have a certain aesthetic. By organizing NFTs in this way, it's easier to keep track of them and showcase them to others. Collections with a common theme or attribute can create a sense of exclusivity and rarity, which can make them more desirable to collectors.


# Delegated NFT

Ternoa's NFT delegation feature empowers NFT owners to share the utilities of their unique digital assets without giving up ownership. This innovative solution enables users to share the benefits of their NFTs without exchanging any money, maintaining complete ownership rights, and retaining the NFT in their wallet. With Ternoa's NFT delegation, you can confidently share your NFT's capabilities while ensuring that you retain full control over your valuable digital assets.

For example, imagine an artist who has created an NFT, but wants to share that artwork with a museum to display their work. The artist could delegate some of the utilities of the NFT to a gallery, allowing them to display the artwork as part of an exhibition. The artist would still retain full ownership of the NFT, and would be able to revoke the delegation at any time, ensuring that they maintain control over work. This type of NFT delegation could be particularly useful in the art world, where physical exhibitions and events are often used to showcase and promote artists' work. By enabling NFT delegation, artists can extend the reach of their work beyond the digital realm, while still maintaining complete ownership and control over their NFTs.


# Soulbound NFT

SoulBound Tokens (SBTs), which are a particular type of NFT, but they differ in one major way: they are designed to be transferred only once.

SBTs represent credentials that are permanently tied to a user’s wallet address. For example, a person might have SBTs representing educational credentials, employment history, proof of achievement, or hashes of their writings or works of art.

SoulBounds are set to disrupt the NFT economy by reducing online manipulation and allowing users to build their reputation with their certified credentials. SoulBounds could come to represent individuals and reflect their unique traits and solidarities as they acquire SBTs that reflect their affiliations, memberships, and credentials.

With SoulBound Tokens, users can confidently showcase their achievements and skills, creating a verifiable digital identity that represents their unique qualities. This innovative feature has the potential to transform the way we view NFTs and open up new possibilities for users to establish their reputations and access new opportunities in the digital world. SoulBound Tokens are a game-changer for the NFT industry, providing a secure and reliable way for users to represent themselves and their accomplishments in the digital world.


# Rental NFT

NFT Renting allows individuals to rent NFTs they would like to borrow for a limited amount of time. A borrower can rent an NFT and gain access to exclusive content or experiences. At the same time, an NFT owner can rent their NFT to share its utility and earn passive income seamlessly. We believe Rental NFTs have endless possibilities from leveraging gaming assets, renting prime digital land, gaining access to exclusive music, and so on.

An NFT rental involves an owner of an NFT and a person who wants to borrow the NFT for a limited or infinite amount of time. The NFT owner/renter develops a contract with the guidelines on price, time period, and cancellation policy. At Ternoa, we support 2 main rental agreements with countless flexible combinations:

* Fixed: Borrower requests NFT and the rental contract is for a fixed amount of time and set price.
* Subscription: Borrower will pay the NFT owner a recurring payment to rent the NFT for a longer period of time


# Marketplace

Marketplaces are online platforms that facilitate the listing and sales of NFTs while giving artists a platform to display their work and collectors the ability to discover new art. Ternoa allows anyone to create their own marketplace, reducing friction in the buying process. Marketplaces can be used to exchange various kinds of NFTs, from artwork to gaming items. An artist can create their own marketplace to sell NFTs directly from their website, while a gaming company can create a marketplace for players to trade in-game items as NFTs, creating a secure and transparent exchange and incentivizing players to continue playing and collecting rare items.


# Auctions

Auctions can be an exciting way to sell an NFT and have it reach the highest selling potential. An auction is a type of sale where the NFT seller sets a minimum price and a time period. Buyers can place bids on the amount they are willing to pay for the NFT as long as they are above the minimum price. At the end of the time period, the NFT is sold to the highest bidder. Auctions can be conducted on-chain, making them transparent and secure, and supporting various features such as creating, canceling, and ending auctions, bidding, removing bids, and buying at a fixed price.

Auctions are valuable for several industries including gaming and entertainment industries to sell digital assets like in-game items and exclusive merchandise. In games, players can bid on unique items, creating excitement and competition. In entertainment, auctions can sell exclusive items related to movies, music, and sports events. Auctioning digital assets like NFTs creates additional revenue and engagement opportunities for companies and fans.


# Transmission protocols

Transmission Protocols are a set of rules used by the Ternoa network for secure transmission of NFTs and data between accounts. They offer users the ability to control who can access their data and when. This is achieved through encryption, authentication, and security measures that prevent third-party interference. Users can mint various types of NFTs, choose a Transmission Protocol, and set specific conditions for transferring the NFT. When these conditions are met, the protocol triggers the automatic transfer of the NFT to the designated recipient.

* Big Day Protocol - This protocol allows users to set a specific date for the automatic transfer of their NFTs. With the Big Day Protocol, there are two preset conditions to select from: you can program a specific date for automatic transmission or include a reset option that allows the date to change before transmission. This gives users the flexibility to make changes if needed while ensuring that their NFTs are protected until the designated release time. The Big Day Protocol can be used to coordinate product launches or company announcements by programming the specific transmission date. It can be used for personal surprises to transmit an NFT gift to arrive on a birthday, anniversary, or holiday.
* Consent Protocol - This protocol allows users to specify trusted individuals who can access their NFT under emergency or unforeseen circumstances. To set up the Consent Protocol, users choose specific recipient addresses and set a threshold on number of recipients that need to request access before the protocol is triggered. There is also a Consent at Date Protocol, which works similarly to the Consent Protocol, but with an additional requirement that a specified date must have passed for the protocol to be triggered and the transmission to happen. The Consent Protocol is a powerful tool for distributing assets to beneficiaries, such as a will or trust fund. By requiring a certain number of recipients to trigger the protocol, the Consent Protocol provides a secure and reliable way to ensure that your assets are passed on to the right people at the right time.


# G-tokens

G-tokens are non-fungible utility tokens used within the Ternoa network, not mineable or tradable with other fungible tokens. Ternoa has developed G-Tokens to improve gameplay and security in the video gaming industry, allowing players to perform in-game transactions without stopping gameplay, simplifying in-game purchases for game developers, and enhancing security by eliminating the need for players to expose their private keys.


# ink! Smart contracts

With ink! you can write smart contracts in Rust for blockchains built on the Substrate framework.

## Why Rust is an ideal smart-contract language?

It is type-safe, memory-safe, and free of undefined behaviors. It generates small binaries because it doesn’t include extra bloat, like a garbage collector, and advanced optimizations and tree shaking remove dead code. Through compiler flags, Rust can automatically protect against integer overflow.

* **Rust ecosystem:** You gain from all of the support available to the Rust ecosystem for free. As the language develops, new features and functionality will improve how you can write smart contracts in the future.
* **Tooling:** Tools like rustfmt, clippy and rust-analyzer already work out of the box. The same goes for code formatting and syntax highlighting in most modern text editors. Also, Rust has an integrated test and benchmark runner,
* **No overhead:** Minimal runtime.
* **Safe & Efficient:** Zero-cost & safe abstractions.
* **Productive:** Cargo + crates.io Ecosystem.
* **1st class Wasm:** Rust provides the first class support for the WebAssembly.
* **Small Size:** In the space-constrained blockchain world size is important. The Rust compiler is a great help for that since it reorders struct fields to make each type as small as possible. Thus Rust data structures are very compact, in many cases even more compact than in C.


# Ternoa Fortress

In this section, discover core concepts and features underlying Ternoa Fortress, our TEE network and decentralized key management use case

Ternoa Fortress is the first-of-a-kind flexible decentralized infrastructure that can host any confidential computing application. [Ternoa Fortress](https://medium.com/ternoa/ternoas-fortress-1dafe026f938) infrastructure co-evolved with the Ternoa [Secret-NFT](https://medium.com/ternoa/the-launch-of-ternoa-phase-4-part-i-secret-nft-c2c09a07eaa7) solution.

Fortress is an off-chain and chain-agnostic decentralized protocol based on the Trusted Execution Environment (TEE) technology while Secret-NFT is a radical approach for adding confidentiality to regular NFTs respecting transferability and transparent flexible ownership.&#x20;

Secret-NFT technology at its core is a Decentralized Key Management System ([DKMS](https://docs.ternoa.network/learn/ternoa-fortress/key-management)) where in Ternoa it is backed by tens of cryptographic layers called Fortress. In this article, we explain the design decisions and implementation details of these two products.

<figure><img src="/files/WTMDC23lNygQPKlT0vJ7" alt=""><figcaption><p>Figure 1: Core components of Ternoa Blockchain</p></figcaption></figure>

For a Decentralized Key Management System, Fortress in addition to expected security, the confidentiality of storage/retrieval of keys without any central authority or master key, provides a set of unique management features like Asynchronous Noninteractive Key Transfer, Interoperability between applications, and Resilience.


# TEE coprocessor


# Trusted Execution Environments

## General Considerations

Secure-hardware cryptography has always been the ultimate level of security, especially for financial and military-grade applications, because modern cryptography is based on mathematical algorithms that will eventually be executed in hardware, either conventional electronic CPU, GPU, FPGA, ASIC, or unconventional Quantum, Optical, Neuromorphic and biological computers. They all follow the same concept of computation known as the Turing machine. Computation inside the Turing machine hardware, in the hands of experts, can be manipulated, so we need verifiable computation at the micro level (proof system), and a fault-tolerant system at the macro level (state replication, error correction). Moreover, there are methods to eavesdrop on the running computation in hardware, in that case, we need to secure the processing and storage inside the hardware. Normally it has been done in expensive special-purpose microchips and secure modules like SRAM-based PUF, HSM, and TPM.

Recently main CPU manufacturers started a new line of powerful general-purpose processors as Trusted Execution Environment (TEE) which are both computationally impenetrable and verifiable. TEEs promise *integrity* (the program being run is exactly the one specified by the user) and *confidentiality* (the data processed by the program is not leaked outside of the enclave) against an actively malicious adversary with control over the operating system.

## TEEs use in Ternoa

Trusted Execution Environments (TEEs) are used in blockchain technology to provide a secure environment for code. A TEE is a secure hardware environment that isolates code execution from the main operating system, ensuring that code is executed securely and without interference.

The architecture proposed involves storage and retrieval of keys in a trusted execution environment (TEE) which is an off-chain component associated with the secret NFT solution. TEE programs running on processors such as SGX provide strong trust guarantees in terms of data privacy and verification of the programs running within them. This can be achieved through techniques such as remote attestation that gives assurance that the program running inside the enclave is running on genuine TEE hardware (such as SGX), and the programs have not been modified by the TEE node operators. Data storage on TEEs is also secured by sealing them with the secure keys associated with the TEE hardware and/or author of the TEE programs.

As an off-chain extension of Key Management, Secure Computation, and Confidential Storage for blockchains, there are at least five responsibilities of TEE :

* Using the Remote Attestation mechanism to prove the genuinity of hardware and the codes running on it to be approved by blockchain validators and registered on the blockchain
* Validation of the off-chain requests from the application, comparing to on-chain data (i.e NFT ownership)
* Processing the application request in a secure environment (i.e sealing the secrets)
* Providing the blockchain with verified off-chain data gathered from the application (i.e availability of encryption key for secure NFT)
* Secure distributed backup and secure migration of secrets to other TEE machines


# TEE Network

While traditional blockchain networks rely heavily on slow and expensive mechanisms like state replication and consensus due to the untrusted nature of validators, a network of fully attested enclaves using Intel SGX can potentially reduce or eliminate the need for constant verification of communication and computation without the risk of collusion by leveraging hardware-based trust and remote attestation.

This opens the space-time for performing confidential general-purpose computation over a trusted network instead of fixed useless tasks. In comparison to a centralized cloud, anybody can contribute to the TEE network and take the profit of sharing their verifiable processing power. This argument shows how TEE is secure, fast, and cheap compared to pure algorithms like ZKP and MPC.

Intel Software Guard Extensions (SGX) is a set of security-related instruction codes that are built into modern Intel CPUs. It allows an application to create private regions of memory called enclaves, which are designed to be protected from processes running at higher privilege levels, such as the operating system, BIOS, SMM, and even other enclaves.

One of the key features of SGX is the ability to remotely attest the enclave’s state to a remote party. This is done through a mechanism called “Remote Attestation.” The process involves generating a quote, which is a cryptographic report that contains essential information about the enclave, including:

1\. Measurement/MRENCLAVE: A cryptographic hash of the enclave’s initial memory state, which includes the code and data loaded into the enclave. Any tiny change to the source code or the official binary will cause a different Measurement (Tamper Evidence).

2\. UserData: An optional field that can be used to include arbitrary data in the quote, such as a public key or other security-related information.

## Report Data <a href="#a43c" id="a43c"></a>

The UserData field in the quote can be used to include the public key of the enclave, which can be used to verify the integrity and authenticity of the enclave’s code and data:

1\. Enclave Creation: When the enclave is created, the source code generates a confidential key pair (public and private keys) for the enclave, it is inaccessible to the outside world and is considered as the identity of the enclave, it can be sealed and stored on the disk to have a more persistent identity.

2\. Code Signing: We can sign the open-source code using the private key of the enclave.

3\. Enclave Initialization: During the enclave initialization process, the public key of the enclave is stored, in the UserData field of the quote. This is an extremely critical step, so we also concatenate the MRENCLAVE and some temporary values including the current block number to the public key and store the hash or signed value in the UserData field. This will help to detect anomalies earlier as well as differentiate between depth and stage of modifications.

4\. Remote Attestation: When a remote party wants to verify the integrity and authenticity of the enclave, they request a quote from the enclave.

5\. Code Verification: The remote party can then use the public key from the UserData field to verify the signature on the open-source code, ensuring that the code running inside the enclave is the same as the code signed by the developer.

6\. Quote Verification: The remote party receives the quote, which includes the measurement (hash of the enclave’s code and data) and the UserData field containing the enclave’s public key. The quote is signed by TEE confidential hardware key. Thus in addition to checking the available fields in the quote, the signature should be verified beforehand.

The quote is a cryptographic report generated by the SGX hardware that contains the measurement (hash) of the enclave’s initial state, including the code and data loaded into the enclave, as well as the UserData field.

## Quote Verification <a href="#id-1b9e" id="id-1b9e"></a>

To verify the quote, the remote party needs to perform the following steps:

a. Verify the signature of the quote using Intel’s public key to ensure the quote was generated by genuine SGX hardware.

b. Compare the measurement in the quote with the expected measurement of the enclave’s code and data. This expected measurement is provided by Ternoa for each new release.

c. Verify the UserData field contains the correct public key for the enclave.

If the quote verification succeeds, the remote party can be confident that the enclave is running the expected code and data, and that the public key in the UserData field belongs to that enclave.

## Intel Attestation Service (IAS) <a href="#eb36" id="eb36"></a>

* IAS is a cloud service provided by Intel that simplifies the remote attestation process by acting as an intermediary between the enclave and the remote party.
* Instead of verifying the quote directly, the enclave sends the quote to IAS, which verifies the quote’s signature and ensures it was generated by genuine SGX hardware.
* If the quote is valid, IAS generates a report containing the quote and additional metadata, such as the security version and platform information.
* The remote party can then verify the report from IAS using Intel’s public key, rather than verifying the quote directly.
* IAS simplifies the attestation process and offloads some of the cryptographic operations to Intel’s infrastructure.

If the quote verification fails, it could indicate several issues, such as:

a. The quote was not generated by genuine SGX hardware (e.g., spoofed or simulated quote).

b. The enclave’s code or data has been tampered with, resulting in a different measurement than expected.

c. The UserData field does not contain the expected public key for the enclave.

In such cases, the remote party should refuse to establish a trusted channel with the enclave, as its integrity and authenticity cannot be verified.

Additionally, if the report from IAS fails verification, it could indicate that the IAS service itself has been compromised or that the report has been tampered with during transmission.

By including the public key of the enclave in the UserData field of the quote, SGX provides a mechanism for remote parties to cryptographically verify that the code running inside the enclave is the same as the open-source code signed by the developer. This process, combined with the hardware-based protections offered by SGX enclaves, can help ensure the confidentiality and integrity of the enclave’s code and data, even in the presence of a compromised operating system or other privileged software.

It’s important to note that the effectiveness of this approach relies on the integrity of the SGX hardware and firmware, as well as the proper implementation of the remote attestation process by the developer and the remote party.

Due to the complexity, variations of SGX versions, or supporting the AMD SEV enclaves, Ternoa has a (centralized) remote attestation as a service to simplify Quote and Report verification.

We also provide a docker version of each newly released version to help enclave reproducibility. The issue comes from the dependencies of enclave source code to some OS libraries. We have identified and fixed all the dependencies for Ternoa enclaves. We also use the latest update on Ubuntu to create the docker enclave, though there are suggestions to use nixOS which has a reputation for reproducibility.

The security of SGX-based systems relies on the integrity of the SGX hardware and firmware, as well as the proper implementation of remote attestation protocols. Any vulnerabilities or flaws in these components could compromise the overall security of the system. That’s why in Ternoa we have the p2p synchronization of TEE clusters to increase the resilience and fault tolerance of the TEE network.


# Blockchain Registered TEE Clusters

Ternoa architecture organises enclaves in clusters to support the secret-sharing threshold scheme. Each cluster is made of 5 different enclaves (at this time). Enclaves of a cluster can either belong to a single private owner (for permission use) or be publicly distributed in different geographical locations or cloud providers.

Requests or Proposals to register or remove a cluster require approval from the technical committee of the Ternoa network, which is accessible from the Polkadot.js app for anybody who has an enclave a.k.a node operators.

Each TEE can contain multiple enclaves, while each enclave has an independent operator account. The operator can [request to register](https://github.com/capsule-corp-ternoa/ternoa-proposals/blob/main/TIPs/tip-510-TEE-Pallet.md#specification) the enclave to cluster or remove it from the network regarding the [staking rules](https://docs.ternoa.network/learn/caps-token/staking-and-nominating).

Enclaves which are members of a cluster should not share any data, while separate public clusters can peer-to-peer synchronize their corresponding “slots” to help the network reliability.

There are two types of general clusters:

* Public clusters
* Enterprise clusters

Public clusters serve to Ternoa secret network unconditionally while enterprise clusters have constraints. The key difference is the Enclave Operator. Whenever the operators are controlled or assigned by a company or are limited by legal terms, their enclaves and clusters are considered enterprises. Famous examples are the medical, financial, or military documents that can not be stored on servers outside of a country. This case is a geographical limitation on the enclave server location.


# Inter-Enclave Synchronization

To create a decentralized fault-tolerant network of TEE enclaves, they should asynchronously communicate and replicate their confidential state. Whenever an enclave receives, stores, and seals a secret share, it will send a confirmation transaction to the blockchain. When the blockchain receives 5 different confirmations for the same NFT-ID from a cluster, the blockchain will generate an ‘NFT-synced’ event in the current block. Since all enclaves in the network are listening to the blockchain events, as soon as they notice the ‘NFT-synced’ event, they send a request to the original cluster and corresponding slot number for the new secret share (s).

<figure><img src="https://miro.medium.com/v2/resize:fit:2000/0*lfap2mC3f5SMtvZI" alt=""><figcaption><p>P2P Synchronization: Inter-Cluster Replication</p></figcaption></figure>

## Mutual Remote Attestation <a href="#id-2a1e" id="id-2a1e"></a>

Expirable tokens, confidential signatures, and TLS standards secure the Communication channel of enclaves. However, the enclaves have to prove their genuineness in each secret exchange. That means they should prove that: they are running in verifiable updated (CPU microcodes) hardware, they are running under a secured mechanism of TEE in terms of memory, processing, and storage and finally they are running an updated official code of open-source Ternoa enclave.

These are only possible through a hardware-generated quote in TEE and then verifying it with Intel as the manufacturer. To make the process bulletproof, we inject a signature of some confidential data into the quote before being signed by the hardware key. These injected data will provide critical identity information to the other party that helps establish the trust. Above all at the final stage, the data will be encrypted another time with a temporary public key which is generated securely inside the enclave.

<figure><img src="https://miro.medium.com/v2/resize:fit:2000/0*p8wWZN4N0gQaOagp" alt=""><figcaption><p>Mutual Remote Attestation</p></figcaption></figure>

## New Enclave Synchronization <a href="#e965" id="e965"></a>

When a new enclave gets registered on the network, it starts discovering the existing clusters and especially the corresponding slots in each cluster to its slot number.

Then it chooses a proper enclave to fetch all of its current stored secret-shares. If the process fails, it goes to another cluster until all the secret shares of available NFT IDs are stored on the new enclave.

Then enclave will be ready to receive new data or synchronize its data to other enclaves.

## Resuming Enclave Synchronization <a href="#b632" id="b632"></a>

Enclave should persistently keep track of its latest synchronization state, to be able to recover after downtimes, either because of network connection problems or hardware maintenance, etc.

Down-time may happen to enclaves, either because of planned maintenance or network issues. Back to the online state, enclaves get the current block number from the blockchain, then start crawling the chain looking for minted secret-nft or capsules. The result of the crawling is a list of NFT-IDs whose secret shares should be fetched using the synchronization process we’ve described above.


# Decentralized KMS

A decentralized key management system (DKMS) leverages cryptographic primitives and distributed ledger technology (DLT) to establish a trustless environment for managing cryptographic keys. Unlike centralized systems with a single point of control (below Image from Google Cloud), DKMS employs a distributed network of nodes to perform key/randomness generation, protection, storage, exchange, replacement, and use through decentralized cryptographic mechanisms. This paradigm offers enhanced security by eliminating a central point of vulnerability. It ensures resilience through Byzantine Fault Tolerance (BFT) protocols, allowing the system to function even in the presence of malicious actors. Furthermore, DKMS fosters transparency through immutable audit trails recorded on the DLT, providing users with a verifiable and tamper-proof record of all key management operations.

![](/files/cFNK4u4o6eUMaPLFJxh7)

In Ternoa DKMS there is no root master key (Figure 2), whereas each TEE hardware is the key because nobody has access to it. Whenever data is encrypted by a data encryption key (DEK), it gets encrypted with the Key encryption key (KEK). The master key normally is used to encrypt a set of KEKs. In Ternoa for more security and forward secrecy, every key is temporary and partially accessible. To have a better vision, Ternoa KMS works like a very secure hardware wallet, but instead of putting it in a safe box, it is partitioned into smaller hardware wallets every one of which contains part of the data, moreover, these partial hardware wallets are replicable, if one of them lost we can still recover from other replicas. Additionally, key rotation happens in all of them regularly, which means even if this partial data is stolen, it will be useless after a short time, and if it is disconnected/isolated/outdated for a long time, it will be slashed off the system.

<br>


# Secret NFT

NFTs (Non-Fungible Tokens) have gained popularity as a way to represent ownership of unique digital assets. They are often associated with blockchain technology where ownership records are transparent and cannot be duplicated or forged. In the context of a network society, shared economy, and decentralized identities, NFTs play a role in redefining ownership and enabling partial, temporary, and delegated shared ownership of digital assets. This means that ownership of an NFT can be transferred or shared among multiple parties, and it can also include time-limited access rights.

As the world becomes more connected with autonomous AI-powered IoT devices, managing assets, including keys, becomes crucial. This implies that in addition to managing the ownership of digital assets through NFTs, effective key management methods should be considered to maintain security and control over these assets.

While NFTs use decentralized technology, DKMS refers to the secure storage and management of cryptographic keys in a decentralized manner. NFTs and DKMS are used together to enable secure and transparent ownership and transfer of digital assets. However, it’s important to note NFTs themselves are not a direct application of DKMS. Instead, DKMS can be utilized to enhance the security and privacy aspects of NFT ownership. DKMS can be used to add confidentiality to NFTs by enabling secure and private ownership of the NFT media content:

1\. Generation of Keys: Each user generates a pair of cryptographic keys — a public key and a private key. The private key is kept secret and is used to sign transactions, while the public key is shared publicly.

2\. Ownership Verification: When an NFT is created, its ownership is associated with the owner’s public key. This linkage is stored on the blockchain or decentralized ledger, making it publicly verifiable.

3\. Confidential Transactions: The private key allows the owner to prove ownership and transfer the NFT without revealing their identity or sensitive information. The transfer can be cryptographically signed with the private key and broadcast to the network.

4\. Decentralized Storage: The NFT’s metadata and ownership details can be stored decentrally, ensuring resilience and availability without relying on a single point of failure.

5\. Extensibility: Each confidential NFT can contain another private key, source code, or NFT for more complex applications.

<figure><img src="/files/LUFxnGZAtv14KODQcqGj" alt=""><figcaption><p>On-chain and off-chain components of Ternoa Secret NFT protocol</p></figcaption></figure>


# Secret Sharing

\
Secret Sharing among a set of hardware TEE has been the fundamental design element in Ternoa Fortress from the first day. Secret sharing allows a secret (private key) to be distributed among a group of participants (TEE nodes, i.e. Intel SGX server) such that only a qualified subset (threshold) can reconstruct the original secret key. Respecting the ownership of the plain data, in Ternoa the secret sharing process has to be done on the client side by the user, or users for multi-party applications.

## Verifiable Redistributable Secret Sharing <a href="#c8bf" id="c8bf"></a>

Secret Sharing among a set of hardware TEE has been the fundamental design element in Ternoa Fortress from the first day. Secret sharing allows a secret (private key) to be distributed among a group of participants (TEE nodes, i.e. Intel SGX server) such that only a qualified subset (threshold) can reconstruct the original secret key. Respecting the ownership of the plain data, in Ternoa the secret sharing process has to be done on the client side by the user, or users for multi-party applications.

## Secret Sharing Schemes (SSS) <a href="#id-661d" id="id-661d"></a>

* Shamir’s Secret Sharing: This popular scheme uses polynomial sharing. The secret is the constant term of a polynomial of degree (t-1), where t is the threshold. Each participant receives a share, which is a point on the polynomial. To reconstruct the secret, any participants can combine their shares using Lagrange interpolation. Ternoa Node.JS SDK natively supports this scheme.
* Pedersen’s Secret Sharing (Verifiable): [Pedersen’s scheme](https://link.springer.com/chapter/10.1007/3-540-46766-1_9) introduces verifiability. Shares are commitments (cryptographic objects hiding a value) to polynomials. Participants can verify the validity of their shares and those of others without revealing the secret. Rust Implementation WASM of this scheme has been provided in the development branch of Ternoa Node.JS SDK. In this version encryption of secret-NFT media is symmetric to increase the performance and security. The mutable nature of the Capsules requires public key encryption. To have a future-proof encrypted media, we are adopting the post-quantum [CRYSTALS-Kyber](https://pq-crystals.org/kyber/index.shtml) algorithm as an alternative option to have a future-proof encrypted media.

## Key Rotation: Towards Redistributable and Verifiable Secret Sharing (RVSS) <a href="#id-6759" id="id-6759"></a>

While the above schemes offer basic secret-sharing functionality, they lack proactive security for all participants. RVSS builds upon these concepts:

* Proactive security: Shares are updated periodically using a special technique without reconstructing the secret or requiring communication with the dealer (user wallet). This ensures security even if some participants are compromised over time.
* Universal verifiability: All participants can verify the correctness of their shares and those shared by others. This strengthens trust and helps detect inconsistencies or malicious tampering.

Of course, the user can re-encrypt the data with a new private key and then replace the previous key with a new one, but this is time-consuming for multiple data with large sizes and needs the user’s active presence. Cryptography aims to be less restrictive and more transparent for user experience. So key redistribution will happen regularly behind the scenes, between the TEE nodes.

There are few efficient and academically approved methods combining Redistributability and Verifiability, The Ternoa research team is investigating a post-quantum version of the RVSS/PVSS algorithm for the next stable release.

Currently, users can use any arbitrary secret sharing scheme on their private keys with two constraints (If they don’t want to use Ternoa SDK):

1. Ternoa blockchain (tee-pallet) supports the (3,5) threshold scheme, which means the private key must be partitioned into 5 secret shares, and then it can be reconstructed with 3 or more secret shares. We will support flexible and larger schemes in future releases. Higher shares and thresholds increase the security, require more TEE machines, and impose higher fees on the user.
2. Any encoding is acceptable while the size of each key share is kept at less than 3KB, which is sufficiently large for today’s cryptography. This limitation on size will either be replaced soon by a verification algorithm inside TEE or with a stronger limit of 128B for efficiency.

<figure><img src="https://miro.medium.com/v2/resize:fit:2000/1*cpc39yUdF6Of9RKV-Cg93Q.png" alt="" height="217" width="1000"><figcaption><p>Proactive Verifiable Secret Sharing</p></figcaption></figure>

When the secret shares are generated on the user’s device, they should be transferred securely to TEE nodes, and their ownership should be registered on the blockchain as well.


# Key Management

Security design to prevent unauthorized access to data starts with identifying the attack vectors. Here is the list of threats identified for design:

1. **Single point of attack/vulnerability:** Ternoa uses Shamir secret algorithm with (K, N) threshold decryption scheme, wherein the secret is split into N parts out of which K parts are needed to decrypt the secret. The split secrets called secret shares are stored across N secure enclaves running in Trusted Execution Environments, which are specialized hardware with built-in cryptographic identity and encryption capabilities.
2. **Compromised credentials:** To eliminate the impact of any unauthorized access to the TEE-powered secret nodes through compromised credentials, the secret shares are sealed to persistent disk storage, using the built-in cryptographic keys from within the enclave. Even if unauthorized access is obtained to the encoded secret shares stored on the disk of the compromised hardware, it is pretty much useless as it cannot be decrypted without access to the private key of the TEE, which is embedded into the hardware.
3. **Secret Node operator shuts down service:** To address the scenario of the secret node operators shutting down the servers unilaterally, the Ternoa architecture is designed from the very beginning for decentralization of the secret nodes. Any operator can register on-chain to express interest in running the secret node. The on-chain technical council governance would vote to onboard operators after verification. Operators are required to bond a certain number of native chain tokens as the security deposit, and the operator will be penalized in case of malicious behavior of the operator or poor operational performance of the secret nodes. This ensures that the secret shares are not under the control of any single entity or operator. Even if a particular operator shuts down their service, other operators can take their place and will be rewarded on-chain for their efforts.
4. **Secret Node operator with sudo access inspects VM memory to steal secrets:** TEEs execute programs in a protected area of memory that is not accessible even to administrators with root access.

<figure><img src="/files/Yflc7eKQDnHIC3X6jPNJ" alt=""><figcaption></figcaption></figure>

5. **Man-in-the-Middle (MITM) Attacks:** The communication between the DApps and the enclaves can be eavesdropped or intercepted. To prevent this, data exchange with enclaves is secured by TLS with a few additional layers of security. The TLS certification generation and termination itself occurs inside the enclave, so the operator does not have access to the private keys of the TLS certificates. All requests to store or retrieve secret shares are signed with the private keys of the wallet of the owner of encrypted NFTs.

<figure><img src="/files/b1QQwShTaaXsLCWhMOPR" alt=""><figcaption></figcaption></figure>

6. **Replay attacks:** An extension of the MITM attacks is for an interceptor to capture and replay the request to the enclaves. To prevent this, an authentication token is sent that contains the block-number at which the signature was captured and also the validity interval. This prevents replay attack scenarios.
7. **Denial of service attacks or censorship by node operators:** Denial of service attacks on specific nodes or node operators refusing to serve requests for secret shares are addressed by having real-time multi-cluster replication of secret shares using P2P sync across enclaves. The following diagram shows the security and authentication mechanisms in place during P2P sync of key shares across registered enclaves. The authentication process includes remote attestation of the requester and binary integrity checks enclave before secrets are shared.

<figure><img src="/files/fl4TgmVku0k8gmF0jkSM" alt=""><figcaption></figcaption></figure>

8. **Malicious operator modifying the enclave code:** A secret node operator may choose to not deploy the original enclave binary from the releases repository, and decide to alter the code (Ternoa’s enclave cluster code is open source) to steal secrets. But the operator will be unsuccessful in this case as the measurement of the binary (MRENCLAVE) will not match the publicly available MRENCLAVE on the GitHub releases repository, and other enclaves will refuse to share secret shares with the maliciously installed binary. Further in such cases, the metrics server will flag this operator while submitting data on-chain, which will result in penalizing the operator and slashing the rewards and/or original token staked amount, based on the severity of the issue.
9. **Provable secure open-source deployment:** The deployments of the Ternoa enclaves are publicly verifiable by anyone, anywhere globally. Any user can request an attestation quote from any enclave, which can be sent to an attestation server to verify if the enclave binaries are indeed running on trusted hardware from the Vendor. Likewise, the authorized enclave binary measurements (MRENCLAVE) are publicly available to inspect.
10. **A malicious operator can fake the identity of an enclave:** To prevent this, the enclave identity is established by generating a key-pair inside the secure enclaves such that even the operator of the enclave will not have access to the signing key of the enclave.


# User Workflow

The user workflow is as follows:

* Users encrypt their sensitive digital assets and store them on IPFS.
* The encryption key is split and stored on a cluster of separate secure hardware (TEE) distributed around the world. There may be enterprise owners who provide their own TEE clusters.
* Only the true owner from the blockchain can retrieve the split keys and reconstruct the original key to decrypt the content of the secret NFT.
* The owner can also schedule a transfer, rent, or delegate the ownership of the NFT to another user.

<figure><img src="/files/lw9P8OcZ72U4WvGQDacX" alt=""><figcaption></figcaption></figure>


# Ternoa zkEVM+

Ternoa zkEVM+ is an Ethereum Layer 2 validium designed for making "Secure Privacy" the new standard for builders and users in Web3.

Secure Privacy means that native privacy primitives made available on our network don't imply heavy trust assumptions for builders and users.

zkEVM+ will combine ZK validity proofs, external Data Availability, and trustless services execution to provide unmatched levels of security, while remaining affordable for builders and users.

##

## Validity proofs&#x20;

Built with Polygon CDK, Ternoa zkEVM+ uses Zero Knowledge validity proofs to confirm state transitions with fast finality.

*Available on Testnet* ✅

## Modular DA

Ternoa zkEVM+ posts rollup data on Avail DA for optimized costs, without compromising on security and data availability.

*Work in progress* 🚧

## TEE proofs

zkEVM+ services are deployed in trust-minimized setups, backed with economic security to alleviate implicit trust assumptions made by builders and users.

*Work in progress* 🚧


# \[Validity Proofs]

COMING SOON 👀


# \[Modular DA]

COMING SOON 👀


# Integrity Proofs

## TL;DR

L2 neworks such as rollups, validiums and optimiums primarily use execution proofs (ZK proofs or fraud proofs) to prove (or disprove) transaction and state transition validity to the base layer (Ethereum). While proofs of execution are important, they do not detect many categories of faults and frauds that can happen in the various components that comprise the overall layer-2 infrastructure. Such faults/frauds are difficult to prove and impossible to attribute and penalise on-chain.

This post introduces integrity proofs, which complements zk proofs and fraud proofs for rollup security. Integrity proof is a mechanism to attest to the integrity of services running in a particular instance of rollup, providing assurance to the end users that no malicious or other unauthorized code changes have been performed in the production environment. Integrity proofs use TEEs to deploy and monitor rollup services and report any breach of service integrity on a new layer-2 network (let’s call it Integrity verification chain) that provides decentralised security services to rollups.

Layering integrity proofs over existing execution proofs greatly improves the censorship resistance of the rollup, detects unauthorised MEV extraction and offers protection from other types of malicious activities in the rollup infrastructure from privileged or unauthorized users. This design also reduces the trust assumptions , compared to the current architecture of centralised rollup deployments that rely disproportionately on execution proofs to demonstrate offchain execution validity.

## **Introduction**

Layer-2 networks settling on Ethereum (aka base layer) predominantly use either fraud proofs (proofs of invalidity) or ZK-proofs (proofs of validity) to prove transaction validity and updated state commitments to the base layer. Both these are execution proofs that cryptographically attest to those activities that are objectively recorded and verifiable on-chain (aka running in the EVM or equivalent VM).

However, such execution proofs alone are inadequate to verify the security of the overall layer-2 network. This is because there are many centralised components in L2s where faults and malicious activities can occur, which cannot be proven on-chain (non-attributable faults). There are many solutions being worked on to address centralisation risk in rollups, but they come with their own tradeoffs including loss of sovereignty/control, reducing utility of own token, cost increase or increased complexity of architecture.

This post proposes a solution to detect *unattributable faults* while running rollup services (of the kind that cannot be detected by ZK proofs alone) , without any loss of sovereignty or loss of control for the project deploying the layer-2 network. (Note: The terms layer-2 network and rollup are used interchangeably in this post as a broad term to encompass rollups, validiums and optimums.)

Integrity proofs are proposed as a mechanism to certify to the presence (or absence) of unattributable faults in the operation of a rollup service, by having an observer running in a Trusted Execution Environment (TEE) provide cryptographic attestation of its own execution environment and signing the attestation with its own in-enclave generated cryptographic identity (signing key) that cannot be tampered with even by the operator of the attestation service.

## **Problem space**

Layer-2 networks (both optimistic and Zk stack chains) have many components such as rpc nodes, sequencers, pool & state databases, executors, provers, L1 transaction managers etc that are basically deployed either as platform-native binaries or docker images. Examples of non-attributable faults/frauds include censoring transactions based on addresses or geo-fencing access in json-rpc node, changing the ordering algorithm of sequencer, making unauthorised/undetected changes to the state or pool database, and withholding transaction batch data posted to external DA layer. Currently, users make heavy trust assumptions while using L2 chains that such malicious or unauthorised actions don’t take place in the centralised services operated by their provider. More specifically, users make the following trust assumptions:

a) they trust the rollup project foundations (eg Polygon, ZK, Optimism, Arbitrum) to not introduce any malicious code on the published rollup service images.

b) trust that the right security controls are in place such that employees/contractors that belong to the rollup project or RaaS operators have restricted privileged access (or that those who do , do not abuse privileged access)

In short, users rely on the security offered by the reputational credibility (social & commercial ) of these trusted third parties. Integrity of the rollup services operated by these parties is not verifiable, and any faults are not attributable or provable on-chain. This goes against the basic premise of blockchain networks aka verifiability.

## **Solution proposed**

[![Integrity Verified Services](https://ethresear.ch/uploads/default/optimized/3X/e/d/edb7cc61ad8bf9c863c1a9d1deeef28720e7a109_2_671x500.jpeg)](https://ethresear.ch/uploads/default/original/3X/e/d/edb7cc61ad8bf9c863c1a9d1deeef28720e7a109.jpeg)

Figure shows the overview of the proposed solution, which has a new layer-2 network acting as the integrity verification chain (let’s call it IVC in short), and three types of actors participating in it - rollup framework providers, rollup projects and TEE operators. Let’s understand this better using the example of a single rollup service- the sequencer (which needs no introduction).

1. Rollup framework providers (eg polygon cdk, Zkstack, OP stack , Arbitrum etc) register the service image of their latest release of sequencer with IVC.
2. A new rollup project comes along and wants to deploy the sequencer from one of these frameworks. The request is sent to a *Host program* (creatively named) that runs in a TEE. The host program retrieves the service image registered by the provider, and deploys it on a VM that’s specified by the rollup provider. (The only requirement is for the host program to be given SSH access to deploy the service in the VM). For simplicity, let’s assume this service image is a docker image. The host program downloads the docker image and instantiates a new container using this image. The container Id is captured by the host program and recorded on IVC smart contract designated for the purpose.
3. Periodically (based on frequency specified by the rollup project owner) the host program verifies if the container id of the running sequencer matches that recorded on the IVC layer-2 smart contract. If there is any discrepancy, it flags it as a violation of integrity on the integrity verification chain (IVC).
4. The host program can generate an integrity proof on demand (or it can be generated unconditionally in the protocol workflow) attesting to the integrity of a particular service that is deployed and monitored by it. The integrity proof would contain the details of the rollup service that’s being monitored, proof of the execution environment in which the host program runs including the quote/remote attestation parameters and its own binary fingerprint (MRENCLAVE), Further, the integrity proof generated by the host program can be signed by a keypair that’s generated within the enclave so that the operator of the host program VM cannot make a false attestation. The signing key would not be accessible even to the operator.

Here, the sequencer component that was used as the example, becomes the Integrity-verified service (IVS). Technically, the sequencer itself can be run inside a TEE, but that would be another solution not discussed here.

## **How does integrity verified service offer a better security model for rollups?**

In this example, let’s assume that after the rollup service is deployed , someone with privileged or unauthorised access modifies the sequencer code to add censoring logic or ordering algorithm, and restarts the docker container. This will result in a change to the container finggerprint, and this will immediately be detected by the host program (as the running container id will not match the registered container id that was started by the host program). The integrity proof from the host program can certify to the presence or absence of such non-attributable faults.

When integrity proofs are combined with prevailing proof mechanisms such as zk validity proofs or fraud proofs, it strictly improves the status quo in terms of rollup security.

## **Benefits of this solution**

*For end-user:* The end user of the rollup/L2 chain is now assured that in addition to their on-chain transactions being secure (due to natively built-in zk proofs or fraud proofs), additionally any non-attributable faults that can occur in sequencer such as censoring or ordering algorithm changes will immediately be detected and flagged for attention. The user can verify integrity proofs in a permission-less manner.

*For rollup project owner:* They don’t just have to trust their own devops teams or that of the RaaS operator that they outsource to, but they can verify the integrity of the rollup services deployed permissionlessly, on an ongoing basis. They get a higher security layer-2 chain (trust-minimised) compared to what they would get by deploying a standard rollup stack out of the box.

*For RaaS operators*: They have lower operational risk by ensuring that the right service images are deployed everytime. This also results in lower risk of reputational/business loss due to unauthorised access or security attacks on their infra.

*For rollup framework providers* : By publishing their service images and actively participating in the integrity verification activity, they attract better quality of builders and projects on their ecosystem.

**Further security enhancements**

The integrity proofs described solve two attack vectors on rollup services:

1. Any unauthorised changes to the deployed rollup service is detected and flagged.
2. The correct secure version of each rollup service is deployed in the production environment

This is a clear improvement from having just execution proofs. But there can be other types of attacks that need to be designed for. One example is that someone with privileged access can still log into the running docker container and change environment variables. To address this, the host program can be enhanced to periodically log into the running containers and compare the environment parameters on the current running version of container vs the original deployed version.

There can be other types of attacks that are more difficult to detect. for example a sophisticated actor can log into the docker container and manipulate memory . Memory encryption techniques can be evaluated to protect against such attacks. Other solutions could involve running multiple instances of a rollup service (eg sequencer or prover) governed by a consensus algorithm, but it increases costs of operating the rollup infrastructure, and it will be the decision of the rollup project to evaluate the level of risk they are willing to accept and the cost they are willing to pay.

## **Summary**

The premise of this solution is that a combination of existing *execution proof techniques* (zk or fraud proofs) for objectively-verifiable faults in combination with Tee-based *integrity proofs* for non-attributable faults offers a superior trust-minimised security model for rollups, compared to the status quo.


# CAPS Token


# Utility

CAPSULE COIN (CAPS) is the native coin of Ternoa.

Transactions made on the Ternoa blockchain are carried out in CAPS.

They include the following:

* Minting new NFTs
* Adding (collateralizing) data to a NFT
* Encrypt data attached to a NFT
* Transfer a NFT

Demand for NFTs and secured and decentralized storage are the two main appreciation factors of CAPSULE COINS on secondary markets.


# Staking & Nominating

Staking is the voluntary wagering of “chips” to receive a reward or exchange.

The Ternoa chain relies upon NPoS consensus. Hence, holders can stake their Capsule Coins to become, or nominate validators on the network.

Validators and nominators are rewarded with:

* CAPS paid by network users to create transactions on the blockchain as described in the [Utility](/learn/caps-token/utility) section
* CAPS from the treasury pallet, distributed proportionally amongst the active set of validators

### How to stake CAPS  on the Ternoa chain?

#### **Step 1 - Nominate validators on Polkadot-JS UI following these steps**

1. Go on the [Polkadot interface.](https://polkadot.js.org/apps/#/explorer)
2. Switch to **Ternoa Network** :
   * **Open the network** list by clicking on the down arrow in the top menu
   * Click **"Live Networks"** and select "Ternoa"
   * To validate, click on the **"Switch" button** at the top of the sidebar

***

**Step 2 - You are now connected to the Ternoa network and can start staking CAPS by following the next step.**

1. [Create a Polkadot account](https://wiki.polkadot.network/docs/learn-account-generation) if you don’t already own one.

{% hint style="info" %}
It's advisable to **set up two separate accounts:** a controller account for regular use and a stash account for additional security. You can find more information about this [**here**](https://wiki.polkadot.network/docs/learn-staking), as well as in the accompanying video tutorial below.
{% endhint %}

{% hint style="danger" %}
**Ensure that your stash account has a minimum amount of transferable CAPS, and your controller account contains over 1 CAPS.** This is necessary to maintain sufficient liquid funds to cover transaction fees during the bonding and unbonding of funds.
{% endhint %}

2. Go to the [**Polkadot-JS UI main page**](https://polkadot.js.org/apps/#/explorer)
3. Under the Network tab at the top click the **Staking** option
4. Select **“Account”** tab (on top). It may take a while to load
5. Select the **“+ Nominator”** button (top right)
6. Choose your **Stash** and **Controller** accounts
7. Select the amount you want to bond and the rewards destination and click **"Next"**
8. In the next screen select your validators

{% hint style="info" %}
Please make sure you've read the article on [how to select validators.](https://support.polkadot.network/support/solutions/articles/65000150130)
{% endhint %}

9. Once you're done, click **“Bond and Nominate”**
10. Enter the password for your account and click **"Sign & submit"**

***

{% embed url="<https://www.youtube.com/embed/7g4RaUyeTBQ>" %}


# Governance & Proposals

CAPS plays a role in Ternoa blockchain governance.

The **Democracy module** manages the administration of the general stakeholders' vote. Ternoa allows CAPS holders to be custodians of the network and to have decision-making power regarding blockchain governance. Blockchain governance includes developments, partners, protocols, etc.

There are two different queues to which a proposal can be added before it becomes a referendum:

1. **The proposal queue,** which comprises all public proposals
2. **The external queue** is comprised of a single proposal that comes from one of the external origins (such as a collective group).

At each launch period, a referendum is created from a proposal taken in turn from the proposal queue or from the external queue. Any CAPS holder in the system can vote on referendums. The voting system uses a fixed-time vote by allowing the token holder to fix his or her conviction behind the vote. The conviction dictates how long the tokens are locked for, as well as the multiplier that scales the power of the vote.


# Supply

* Total Supply: 2,500,000,000 CAPS (2.5 billion)
* Symbol: **CAPS**

<figure><img src="/files/kZvAc4eYJkry3DxB2N8P" alt=""><figcaption></figcaption></figure>


# Burn program #1

As part of this first burn program, starting Oct. 1st 2023, a total of c. $400 000 worth of CAPS will be burned going forward.

The amount of CAPS burned every month is going to be based on the volume of NFT transaction fees paid on the network.

With this mechanism, we intend to leverage $CAPS burns to help foster network growth and transactions on the chain.

This program will be followed by subsequent burn programs, whose timing will depend upon factors such as blockchain transaction growth, hardware cost evolution, network decentralization pace, etc.

**Terms & Conditions**

For each calendar month, the following amount of $CAPS shall be burned, based on the previous month's chain activity:

* 100% of NFT transaction fees paid on-chain
* Minimum 1 000 000 $CAPS
* Maximum 5 000 000 $CAPS

Burns will occur in the first days of the following month, and they will be announced on our social media accounts. As such, the first burn will happen in early October, for the month of September 2023.

This program will be in place up until 25 m$ CAPS have been burned, or a new burn program is implemented.

A token burn on a non-inflationary coin supply is not a common feat and may be a worldwide first. This is a bold decision we are making to show to our community of holders and signal to markets that the team is firmly committed to ensuring Ternoa’s tokenomics are healthy, and competitive in the crowded space of blockchain infrastructures.

Make sure you follow our social media accounts to keep in touch with updates on our $CAPS burn programs and strategy.


# Bridge

The Ternoa Token bridge is the safest and fastest way to swap between **ERC20 CAPS <-> Native CAPS & ERC20 CAPS <-> BEP20 CAPS.**

<figure><img src="/files/tQKUmKqtKWWrXWowsu7a" alt=""><figcaption></figcaption></figure>

A blockchain bridge provides a connection that allows for the transfer of tokens between two different blockchain ecosystems. A bridge is required for Ternoa because as of the ICO date, CAPS were ERC-20 tokens. However, native CAPS are necessary to stake, earn rewards and pay transaction fees on Ternoa chain.

This bridge enables CAPS ERC-20 holders to transfer them onto the Ternoa blockchain, on a one-on-one basis.\
\
Follow this link to discover the [Ternoa Bridge](https://bridge.ternoa.network/).

Unlike many other bridges, the **Ternoa Bridge** will lock your ERC20 CAPS and mint the equivalent in native CAPS on the Ternoa network. In this manner, if you decide to sell your native CAPS, you will need to transfer them back to the Ethereum network by using the Ternoa Bridge again.

{% hint style="info" %}
ERC20 contracts are built using [**ChainBridge**](https://github.com/ChainSafe/ChainBridge/), a modular Multi-Directional Blockchain Bridge to interact with Ethereum and Substrate, based chains networks.
{% endhint %}


# Mainnet network

### **How to connect your Ternoa account on Polkadot{.js}**

To interact with your Ternoa Wallet from your browser to any dApp, you need to get your Ternoa account imported in the Polkadot{.js} [**browser extension**](https://polkadot.js.org/extension/).

#### Get your Ternoa account on Polkadot{.js}

Download the [Polkadot{.js} extension](< https://polkadot.js.org/extension/>).

{% hint style="info" %}
The Polkadot{.js} extension is not compatible with mobile browsers. To connect your wallet to the extension, you will need to use a desktop browser.
{% endhint %}

#### A video tutorial is available below:

{% embed url="<https://youtu.be/sDut4eICNBk>" %}

If you already have Polkadot{.js} installed, you can either import account from pre-existing seed from your Ternoa Wallet or connect your Substrate address from a hardware wallet.

You can import your Ternoa Wallet directly on the extension by clicking the '+'. **It will be necessary to have your wallet connected to validate transactions.**

***

<figure><img src="/files/h7iQZSHYdezQyJQk6f30" alt="" width="375"><figcaption></figcaption></figure>

<div align="center"><figure><img src="/files/D9hphO4BJASQjk12DC52" alt="" width="375"><figcaption></figcaption></figure></div>

#### Need CAPS?

You have plenty of options to buy CAPS from centralized or decentralized platforms. You can find the list [here](https://www.ternoa.network/token).

{% hint style="info" %}
If you need to try it first on the Ternoa alphanet network, you can use the [Alphanet Bridge here.](https://alphanet.bridge.ternoa.network/)
{% endhint %}


# How to use the Bridge

The [**Token Bridge**](https://bridge.ternoa.network/) is extremely easy to use and intuitive, so all the magic happens on the backstage. But let's go through the basic steps to start bridging your CAPS.

<figure><img src="/files/1QtnUR27iTys2bxM7gaw" alt=""><figcaption></figcaption></figure>

#### **The way the Bridge works is very simple:**

1. Connect your wallet to **Polkadot{JS}** and/or **MetaMask**
2. Select the **'From'** and **'To'** network
3. Enter the amount of CAPS to bridge

> The minimum is 200 CAPS and the maximum is 200,000 CAPS

4. Approve the contract (only once)
5. Approve the transaction&#x20;
6. Wait a few minutes and your CAPS will arrive at the selected destination.

{% hint style="danger" %}
The Bridge has quantum limitations to reduce network congestion. Therefore, we offer OTC Bridge services for all transfers between Ethereum and Ternoa chains over 1M CAPS. To place a request for an OTC transfer, please contact our support team: <otcbridge@ternoa.network>&#x20;
{% endhint %}


# Native CAPS

How to bridge ETH (Ethereum) CAPS & Ternoa CAPS ?

### Bridge ERC20 CAPS <- to -> Native CAPS

1. On the [Token Bridge](https://bridge.ternoa.network/), click on the drop-down menu under "From"

<div align="left"><figure><img src="/files/pOWqXep3phSNgJPvZhIg" alt="" width="375"><figcaption></figcaption></figure></div>

2. Click the Ethereum Network button

<div align="left"><figure><img src="/files/XWJOcxtYaSBm6yMY0vaa" alt="" width="375"><figcaption></figcaption></figure></div>

3. To connect your wallet, click the "Connect Wallet" button

<div align="left"><figure><img src="/files/DyJLc2m9Fl1AAo1WopOj" alt="" width="375"><figcaption></figcaption></figure></div>

### With Wallet Connect

1. Click **Wallet Connect**
2. Either scan the QR code with a WalletConnect-compatible wallet or click **Desktop**
3. Choose your preferred wallet from the selection. Now you are connected!
4. Click on the dropdown under the **'To'** button and choose **'Ternoa Chain'**
5. Select **'Connect Wallet'** and connect Polkadot using the Polkadot{.js} [**browser extension**](https://polkadot.js.org/extension/)
6. Select your desired wallet
7. Enter the amount of ERC20 CAPS in the **Amount** section

> Note: the minimum is 200 CAPS and the maximum is 200,000 CAPS

8. Click **Continue**
9. On the Confirmation pop up, read and agree to the terms
10. Click **Continue**
11. Your Transfer is in progress and will take between 2 to 5 minutes.
12. Once completed, you will see a transaction successful notification
13. To view the transaction, click **View transaction** at the bottom of the notification


# BEP20 CAPS

How to bridge BNB (Binance Smart Chain) & ETH (Ethereum)

### Bridge ERC20 CAPS <- to -> BEP20 CAPS

<div align="left"><figure><img src="/files/b96XycggFjfCArhAf4pU" alt="" width="563"><figcaption></figcaption></figure></div>

{% hint style="danger" %}
Currently, the Bridge between BNB (Binance Smart Chain) and Ternoa is not possible. You have to use the Bridge between BNB and ETH (Ethereum), then bridge ETH to Ternoa
{% endhint %}

***

1. Go to the **Ternoa Bridge**: <https://bridge.ternoa.network>.
2. Under **From** select 'Binance Smart Chain' under **To** select 'Ethereum'
3. Click 'Connect Wallet' for each, and choose your preferred wallet from the selection
4. Enter the amount of **BEP20 CAPS** in the Amount section&#x20;

> Note: the minimum is 200 CAPS and the maximum is 200,000 CAPS

1. Click **Continue**
2. On the Confirmation pop-up, read and agree to the terms
3. Click **Continue**
4. Your transfer is in progress and could take up to 45 minutes to be completed.
5. Once completed, you will see a transaction successful notification
6. To view the transaction, click **View transaction** at the bottom of the notification

{% hint style="info" %}
The transaction fees will be associated with the 'From' network selected.
{% endhint %}


# Alphanet network

### **How to bridge test CAPS on Ternoa & Ethereum**

Before using the [**Token Bridge**](https://alphanet.bridge.ternoa.network/) on Alphanet, you will need to first get your Ternoa account imported in Polkadot{.js}. Once it's added to the Polkadot extension, you can claim Ternoa test CAPS and ETH test tokens.

#### Get your Ternoa account on Polkadot{.js}

To interact with your Ternoa Wallet from your browser to any dApp, you need to get your Ternoa account imported into the Polkadot{.js} [**browser extension.**](https://polkadot.js.org/extension/)

Download the [Polkadot{.js} extension](< https://polkadot.js.org/extension/>).

{% hint style="info" %}
The Polkadot{.js} extension is not compatible with mobile browsers. To connect your wallet to the extension, you will need to use a desktop browser.
{% endhint %}

Once installed, you can either import an account from pre-existing seed from your Ternoa Wallet or connect your Substrate address from a hardware wallet.

If you have a Ternoa Wallet account, you can import your wallet directly on the extension. **It will be necessary to have your wallet connected to validate transactions.**

{% embed url="<https://youtu.be/sDut4eICNBk>" %}

***

### Claim ETH test tokens & Ternoa test CAPS

To claim ETH test tokens, you will need to go to the [**Sepolia Faucet**.](https://sepoliafaucet.com/) Sepolia is an Ethereum test network that allows for blockchain development testing before deployment on Mainnet. We use Sepolia to drive our tests for the Ethereum network.

### Secure ETH test tokens on Sepolia:

1. Go to the Sepolia **Faucet:** [**Sepolia Faucet**](https://sepoliafaucet.com/)
2. Create a free Alchemy account and select **'Signup for free'**
3. Click **'Get started for free'**
4. Enter your first name, last name, email and password
5. Sign in to your email to verify your account. You will be directed to select an ecosystem
6. Click **'Ethereum'** to get started
7. Enter a team name and app name, choose the Sepolia network in the dropdown
8. Choose **'Free forever'** plan
9. You can **'Skip for now'** the payment info and referral
10. Continue past scaling policy and you will be directed to the Sepolia **Faucet** homepage
11. Enter your wallet address, and hit **'Send Me ETH'**
12. Check your wallet, you should have an additional 0.25 ETH

**To claim Ternoa test CAPS on the Alphanet Faucet, follow these steps** [**here**](https://www.ternoa.network/alphanet)**.**

### Bridge your tokens:

{% hint style="info" %}
You can follow the same steps as the [mainnet guide](/learn/caps-token/bridge/mainnet-network/native-caps) to bridge your tokens on the [alphanet bridge.](https://alphanet.bridge.ternoa.network/)
{% endhint %}


# Buy with Banxa

Ternoa has integrated with Banxa, one of the world's fastest-growing fiat-to-crypto gateways to purchase CAPS accessible directly through [**Banxa**](https://banxa.com/).

> Before starting your order, make sure you have your credit card on hand and your passport, then you are all set to start the process of purchasing CAPS.

### How to create your order

1. Go to Banxa.com: [**https://banxa.com/**](https://banxa.com/)
2. Select the currency you would like to use to purchase your CAPS using the dropdown arrow, then select CAPS to receive, and click **Create Order**.

<figure><img src="/files/EvIXxfIiU3PF6DJKCDYa" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="info" %}
Please note there is a minimum amount required to purchase CAPS, which is subject to change.
{% endhint %}

3. Input your Wallet Address

<figure><img src="/files/K3mvuvBZ9I7faQKUTnAA" alt="" width="563"><figcaption></figcaption></figure>

4. Select Payment method click **Create Order**

<figure><img src="/files/6oi6Yj5D34ptGkLRuDxC" alt="" width="563"><figcaption></figcaption></figure>

5. Begin creating your account by verifying your details

<figure><img src="/files/qpWBCtmksy3hM4DgbOdQ" alt="" width="563"><figcaption></figcaption></figure>

6. Add your billing details

<figure><img src="/files/rsxrRAVsW8me1ZRp4deE" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="info" %}
There are some countries where Banxa services are not currently available. Please review [**this list**](https://support.banxa.com/en/support/solutions/articles/44002216505-what-countries-are-supported-by-banxa-) for countries where services are not available.
{% endhint %}

7. Confirm your identity by uploading a photo of your passport

<figure><img src="/files/OOzB3kYLAlDp9pSn62R0" alt="" width="563"><figcaption></figcaption></figure>

8. Click **I'm Ready** and take a selfie

<figure><img src="/files/NbHx3VuEmBzNGQQ2v5U1" alt="" width="563"><figcaption></figcaption></figure>

9. Select the purpose of your purchase

<figure><img src="/files/pl0ZZ1tBVLD1sgDD9bls" alt="" width="563"><figcaption></figcaption></figure>

10. Select your bank and proceed to pay, you will be directed to your chosen payment option

<figure><img src="/files/rmRkmF6I2WwaDqs25kqP" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="info" %}
The time to process your order can vary due to several factors. Review [**this list**](https://support.banxa.com/en/support/solutions/articles/44002216503-how-long-will-my-order-take-) for process times.
{% endhint %}

11. Get ready to receive your **CAPS in your Wallet**!

***

You will receive a confirmation email from Banxa confirming your payment. Please be sure to read their emails in detail regarding the next steps, as you may be required to further verify your credit card by taking a photo of it, or resubmit your passport via email. If you have any questions regarding your order reach out to: [**https://support.banxa.com/en/support/tickets/new**](https://support.banxa.com/en/support/tickets/new)


# Glossary

Discover key Ternoa concepts, functionalities, and fundamental principles.

### Alphanet

Test network on the Ternoa blockchain. The goal of the Alphanet network is to test features before the final version is released on the Mainnet blockchain. The tokens on Alphanet have no real world value, so developers can deploy, test, and execute their projects on a functioning blockchain freely.

### Auction

A method of selling in which NFT owners list their digital assets for potential buyers to place bids. The NFT goes to the highest bidder at the end of a predefined time period. This competitive process often starts with a minimum price set by the seller and can generate excitement around the NFT's value.

### Blockchain

A blockchain is a digital concept to store data. This data can be anything from transactions, account balances, and network states–stored on a ledger that every network member is free to access. This data comes in blocks, so imagine blocks of digital data. These blocks are chained together using cryptographic algorithms, making their data impossible to change.

### Bridge

A blockchain bridge provides a connection that allows for the transfer of tokens between two different blockchain ecosystems.

### CAPS

CAPS is the native token of the Ternoa blockchain. All transactions on the network are carried out in CAPS.

### Capsules

With this enhanced NFT users can store all their digital assets without worrying about storage limitations. The capsules also have transmission protocols triggered based on an event or time. Capsule NFTs are similar to Secret NFTs, but they can store unlimited encrypted data and be transferred over time. Capsules are an enhanced form of NFTs that can take any number of files in encrypted media. Users can convert an existing basic NFT into a Capsule NFT, create an on-chain Secret NFT, remove the capsule part of an NFT, and set the capsule's off-chain data. Capsules are mutable unlike secret NFTs, and can be minted for a fee that can be changed through governance. Capsules use decentralized solutions to provide real data privacy, allowing users to take ownership of their data.

### Collection

Creating a collection for NFTs involves grouping together non-fungible tokens that share a common theme or attribute and organizing them. This allows for easy tracking, management, and trading of NFTs with unique properties and value. Collections are represented by smart contracts in EVM/Smart Contract based systems, but Ternoa allows users to create and own collections with consistent rules, making it easier to group NFTs with similar attributes and improve the user experience.

### Consensus

Consensus is a crucial part of any blockchain network, as it is the process by which all nodes in the network come to an agreement about the current state of the distributed ledger. It ensures that every new block added to the blockchain is the only version of the truth that is agreed upon by all nodes in the network, providing reliability and trust between unknown peers in a decentralized computing environment. Without consensus, there would be no way to ensure that the state of the blockchain is shared accurately by all nodes, making it impossible for the network to continue building and moving forward. (read more section)

### dApp

A decentralized app (also known dApp) operates on a blockchain or peer-to-peer network of computers.

### Delegation

Ternoa’s NFT delegation allows NFT owners to share the utilities of their NFTs without giving up ownership - there will be no exchange of money, you do not give up your NFT ownership rights, and the NFT stays in your wallet.

### Enclave

Inside a TEE are isolated compartments known as enclaves, which are protected environments where sensitive data can be securely processed. An enclave is a program running in an isolated, encrypted memory environment within a TEE. It ensures that even if the system is compromised, the data within the enclave remains protected.

### Explorer

A software that allows users to access details regarding blocks, addresses, and current and past transactions.

### GToken

Gtoken is a non-fungible utility token used within the Ternoa network, not mineable or tradable with other fungible tokens. Ternoa has developed GToken to improve gameplay and security in the video gaming industry.

### Governance

Governance in blockchain refers to the management and rules users must follow when participating in the system. On-chain governance is the process of blockchain governance that takes place on the blockchain. Ternoa's on-chain governance involves token holders and a council of 8 members who propose referenda for all holders to vote on. Referenda are proposals associated with a privileged function call in the runtime and have a fixed period for voting. Anyone can propose a referendum by depositing the minimum amount of tokens for a certain period, and the proposal with the highest amount of bonded support will be selected for the next voting cycle. (read more section)

### Indexer

The Ternoa Indexer is a tool used in the Ternoa blockchain network to index and store data related to the network's activities. It collects and stores data from various sources in the Ternoa network, such as transactions, smart contracts, and tokens, and makes this data available to other applications and services within the network.

### Layer-0

Layer-0 blockchain is the underlying infrastructure that provides the architecture for projects to build.

### Layer-1

Ternoa is a layer-1 blockchain A layer-1 blockchain is the foundation of the blockchain architecture, which validates and executes transactions without support from another network.

### Mainnet

The primary Ternoa network, where actual-value transactions occur with native CAPS to pay transaction fees and for staking. Mainnet is the final production network for blockchain projects and accessible to users, validators, and stakers.

### Marketplace

NFTs serve as proof of ownership on the blockchain, and marketplaces are used to sell and buy NFTs. Users can create their own marketplaces, defining rules such as listing cost and commission fees. Marketplaces provide a medium for exchanging NFTs and allow users to define prices for their digital assets, such as art, gaming items, tickets, and more.

### Minting

Minting on Ternoa is the process of creating a unique digital asset with specific attributes and properties, which are stored on the Ternoa blockchain. This allows creators to establish ownership of their digital creations and sell them as unique items on the Ternoa platform. NFTs can be traded or transferred to other users on the Ternoa network.

### NFT

NFTs (non-fungible tokens) are unique cryptographic tokens that exist on a blockchain.

### Nominated Proof of Stake (NPoS)

A method used to validate transactions and keep the database secure. With proof of stake, a validator is nominated and chosen to validate a transaction.

### Nominators

Nominators are CAPS holders who contribute to the security of the network by nominating validators to participate in the consensus of the protocol.

### Open Source Clusters

Open source clusters are groups of enclaves that work together to provide a more robust, resilient and decentralized network. Clusters enable direct, secure communication between enclaves for real-time data sync, enabling data to be synced up securely across clusters without human/operator intervention.

### Pallets

A Substrate module that provides all functionalities of a feature such as creating NFT, or governance votes. All pallets are modular and can be stacked to create more complex logic.

### Renting

NFT Renting allows individuals to rent NFTs they would like to borrow. A borrower can rent an NFT and gain access to exclusive content or experiences. At the same time, an NFT owner can rent their NFT to share its utility and earn passive income.

### Royalties

NFT royalties, which give the original NFT creator an option to receive an automatic percentage of the sale price each time their NFT creation is resold, are uniquely implemented on Ternoa. As users mint an NFT on Ternoa, they can specify their desired royalties, ensuring that every subsequent resale remits the stipulated percentage back to them.

### SDK

Software developer kit (SDK) is a set of tools Ternoa provides developers to build on the Ternoa chain.

### Secret NFT

Secret NFTs are a type of NFT that ensures privacy. The secret data is stored using the IPFS protocol and encrypted using PGP keys. The PGP key is split into shares using an algorithm and stored in a secure enclave where only the owner can access them. To view the secret, the NFT owner requests the shares from each enclave, and once the ownership is verified, the PGP key is reconstructed to decrypt the secret media.

### Secret Nodes

Secret nodes are specialized parts of the Ternoa ecosystem that function inside a secure, isolated environment known as Trusted Execution Environment (TEE). Think of these nodes as highly secured rooms designed to withstand malicious attacks. Even if the rest of the system is compromised, the data within these nodes remains untouched and secure. They operate on SGX (Intel Software Guard Extensions) machines, specialized hardware providing an extra layer of protection.

### Seed Phrase

A seed phrase is a group of random words generated by the Ternoa wallet, which can be used if a user forgets their password.

### Shamir Secret Sharing

Shamir's Secret Sharing is a cryptographic method that divides a secret into multiple parts, such that a specified number of those parts are required to reconstruct the original secret. On Ternoa, it is used to enhance the security of secret NFT owners' encryption keys by splitting them and distributing across various SGX machines

### SoulBound Token

SoulBound Tokens (SBTs), which are a particular type of NFT, but they differ in one major way: they are designed to be transferred only once. SBTs could represent credentials and are linked to ‘souls’, a type of address that establishes a source.

### Staking

Staking on Ternoa is a validation tool that involves committing your CAPS to maintain the network and confirm transactions.

### Substrate

Substrate is a Rust-based blockchain development framework created by Parity Technologies, the company behind Polkadot. The Substrate framework was designed to help developers launch a blockchain project in a streamlined and customizable way.

### TEE

Trusted Execution Environment (TEE) is a secure hardware environment that isolates code execution from the main operating system, ensuring that code is executed securely and without interference.

### Ternoa Protocol

Ternoa Protocol utilizes Trusted Execution Environments (TEEs) to store secret keys on both the Ternoa and Computing protocols, ensuring that only the enclave can claim ownership of the keys at any given point in time. This guarantees that no individual or entity, including a central one, can access the NFT Encryption Key apart from the current owner.

### Transmission Protocols

Transmission Protocols are rules and standards that govern how data is transmitted over the Ternoa network. These protocols define the format of the data, how it is packaged, and how it is transmitted from one user to another. These protocols allow users to customize their data permissions and how it is sent to other users.

### Validators

Validators provide the infrastructure and maintenance for the Ternoa network. A validator is a virtual entity that lives on the Ternoa Chain and participates in the consensus of the protocol. Learn how to become a validator here.

### Wallet

The Ternoa Wallet allows you to view your CAPS balance in real time, receive or send CAPS to another Ternoa wallet, create and send NFTs, and view dApps. You can download here.

### Wallet Address

String of characters that is generated when a Ternoa wallet is created. This address is used to receive assets in your wallet.


# Javascript  SDK

Welcome to the Javascript builder section 👨‍💻

Ternoa provides a collection of tools to make web3 project development easier and faster:

* [Ternoa-JS](https://www.npmjs.com/package/ternoa-js) - An isomorphic javascript library integrating the custom Ternoa FRAMEs to interact with the chain in a seamless experience.&#x20;
* [Ternoa Indexer](https://indexer-mainnet.ternoa.dev/) - A GraphQL queryable database to get on-chain data.
* [Ternoa FRAMEs](https://github.com/capsule-corp-ternoa/ternoa-pallets) - Custom substrate FRAMEs to create and manage utility NFTs.

The Ternoa chain has two networks based on Substrate: Mainnet and Alphanet.\
Find all the environment-related endpoints [here](/getting-started/networks).<br>

{% hint style="info" %}
If you're new to the Ternoa JavaScript builder ecosystem, we strongly suggest starting with the [Getting Started](/) introduction track. It will not only give you the necessary prerequisites but also aid in comprehending some vital architectural concepts for efficient building. Provide a specific focus to the following sections: Ternoa-js [architecture](/getting-started/javascript-sdk/ternoa-js-library/architecture), [events](/getting-started/javascript-sdk/ternoa-js-library/blockchain-events), and [workflow](/getting-started/javascript-sdk/ternoa-js-library/workflow).
{% endhint %}

If you are looking for a way to kickstart your builder journey, you should start interacting with the Ternoa-js SDK and Indexer with our [NODE-JS quickstart guide ](/getting-started/javascript-sdk/quickstart-node-js)🏁[.](/getting-started/javascript-sdk/quickstart-node-js)


# Handling wallets & accounts


# Ternoa wallet & Wallet connect

### **Introduction**

**Ternoa Wallet** is a non-custodial crypto wallet created and maintained by **Ternoa**. Powered by React-Native and Polkadot.js, it is built on top of the Ternoa ecosystem to allow users to manage their CAPS and NFTs on the Mainnet and Alphanet networks.

{% hint style="info" %}

#### Download Ternoa Wallet:

[On the PlayStore](https://play.google.com/store/apps/details?id=com.ternoa.wallet.prod###)\
[On the App Store](https://apps.apple.com/us/app/ternoa-wallet/id1562180877#?platform=iphone/)
{% endhint %}

> To learn more about creating a Ternoa Wallet, look at [this section](/getting-started/wallets/ternoa-wallet) first.

### Prerequisites

Before getting started, please ensure that you have the following prerequisites in place:

1. [Create a Ternoa account](/getting-started/wallets/ternoa-wallet) with [Alphanet CAPS](broken://pages/ej9gceaLIhCN2PgUBh42) from the [faucet.](https://faucet.ternoa.network/)
2. Install and configure your preferred code editor (for this tutorial, we will be using Visual Studio Code \[VSC]).
3. Install [NodeJS v.14+](https://nodejs.org/en/download/), along with NPM.

{% hint style="info" %}
We assume you have already created a new wallet for development purposes with no CAPS on Ternoa Mainnet. You must use a development wallet with *NO REAL MONEY* in it when learning, practicing, and testing.
{% endhint %}

This documentation is aimed at helping developers who create dApps leveraging the Ternoa ecosystem to integrate Ternoa Wallet and Wallet Connect.

### Getting Started

The simplest way to quickstart jumping into Ternoa Wallet and Wallet Connect to build on the blockchain is to look at the starter repository [here](https://github.com/capsule-corp-ternoa/ternoa-wallet?tab=readme-ov-file), and start our tutorial:

On that [repository](https://github.com/capsule-corp-ternoa/ternoa-wallet?tab=readme-ov-file), you will find the following useful resources that will help you with the integration:

* [Tutorial](https://github.com/capsule-corp-ternoa/ternoa-wallet/blob/main/wallet-connect-integration/TUTORIAL.md): A step-by-step guide
* [dApp-example](https://github.com/capsule-corp-ternoa/ternoa-wallet/blob/main/wallet-connect-integration/dapp-example) ([JS](https://github.com/capsule-corp-ternoa/ternoa-wallet/blob/main/wallet-connect-integration/dapp-example) / [TS](https://github.com/capsule-corp-ternoa/ternoa-wallet/blob/main/wallet-connect-integration/dapp-example-ts)): A boilerplate app
* [QR Scan, Deeplink, and Webview](https://github.com/capsule-corp-ternoa/ternoa-wallet/blob/main/wallet-connect-integration/CONNECTION.md): The 3 different ways to connect
* [Transaction request object](https://github.com/capsule-corp-ternoa/ternoa-wallet/blob/main/wallet-connect-integration/REQUEST.md): How to send transactions or sign a message

### Issues

If you are experiencing an issue with Ternoa Wallet, please visit the [issues section](https://github.com/capsule-corp-ternoa/ternoa-wallet/issues). If the issue you are experiencing has not yet been reported, create a new issue.

### Support

If you face any trouble, feel free to reach out to our community engineers in our [Discord](https://discord.gg/fUmBkPpnRu).


# Access your account through a seed & a keyring

### Prerequisites

Before getting started, please ensure that you have the following prerequisites in place:

1. [Create a Ternoa account](/getting-started/wallets/ternoa-wallet) with [Alphanet CAPS](broken://pages/ej9gceaLIhCN2PgUBh42) from the [faucet.](https://faucet.ternoa.network/)
2. Install and configure your preferred code editor (for this tutorial, we will be using Visual Studio Code \[VSC]).
3. Install [NodeJS v.14+](https://nodejs.org/en/download/), along with NPM.

{% hint style="success" %}
If you are not familiar with the process of creating a transaction on the Ternoa chain, we highly suggest first reading the Getting Started section of the documentation with a focus on the [Ternoa-js workflow](/getting-started/javascript-sdk/ternoa-js-library/workflow) and the two transaction [approaches](/getting-started/javascript-sdk/ternoa-js-library/workflow#to-build-applications-within-the-ternoa-sdk-we-provide-two-approaches-for-each-primitive-extrinsic).&#x20;
{% endhint %}

Most of our examples in this documentation use the **automated approach** and involve creating the Keyring to sign and submit a transaction.&#x20;

{% hint style="info" %}
&#x20;Polkadot ***Keyring's*** definition: *The Keyring allows you to manage a set of keys in a consistent environment, allows you to perform operations on these keys (such as sign/verify), and never exposes the secretKey to the outside world.*\
\
Learn more on keyring in the[ Polkadot's documentation.](https://polkadot.js.org/docs/keyring)&#x20;
{% endhint %}

### Generating a keyring

{% hint style="warning" %}
We assume you have already created a new wallet for development purposes with no CAPS on Ternoa Mainnet. You must use a development wallet with *NO REAL MONEY* in it when learning, practicing, and testing.\
\
**The 12 worlds' seeds must be stored in a .env.variable file. Be sure to NEVER make your seed publicly accessible or visible in a browser.**
{% endhint %}

```typescript
import { initializeApi, getKeyringFromSeed } from "ternoa-js";

const main = async () => { 
	try { 
		await initializeApi();	
		const ACCOUNT_SEED = "REPLACE_WITH_YOUR_SEED"; // 12 worlds seed
		const keyring = await getKeyringFromSeed(ACCOUNT_SEED);
		console.log(`The keyring address is ${keyring.address}`);
		process.exit(0)
	} catch (e) {
		console.error(e);
		process.exit(1)
	} finally {
		process.exit(0)
	}
};
main();
```

You can now provide your keyring as function parameters to create some transactions like we do to [mint an NFT.](/build-1/javascript/nft-features-and-pallets/basics-nft-and-collections/nft/mint-a-basic-nft) \
\
See more examples in the [NFT features & Pallets section. ](/build-1/javascript/nft-features-and-pallets)


# Connect with Polkadot extension

### Prerequisites

Before getting started, please ensure that you have the following prerequisites in place:

1. [Import your Ternoa account](https://docs.ternoa.network/build-1/javascript/wallets/pages/74OQM5fJ55PU0jJHPDl4#how-to-connect-your-ternoa-account-on-polkadot-.js) in the Polkadot{.js} extension, or [create an account in the extension ](/getting-started/wallets/polkadot-extension)directly.&#x20;
2. Install and configure your preferred code editor (for this tutorial, we will be using Visual Studio Code \[VSC]).
3. Install [NodeJS v.14+](https://nodejs.org/en/download/), along with NPM.

#### Utilizing Polkadot extension, Next.js, and TypeScript:

In the code snippet below, we cover how to connect to the @polkadot/extension-dapp and fetch your accounts registered in your Polkadot browser extension (it will also fetch all substrate accounts registered in the other browser extensions).

Please, note that this solution is not the only one. **Feel free to use any provider that would suit best your dApp.**

*This code snipped is designed to work in a **Next-js environment**. According to Next-js server-side components rules, the import of the @polkadot/extension-dapp extension library might need to be slightly adapted to work in your javascript environment.*

```typescript
export const getAccounts = async () => {
  const { web3Accounts, web3Enable } = await import("@polkadot/extension-dapp");
  const extensions = await web3Enable("Name your dApp powered by Ternoa");
  if (extensions.length === 0)
    throw new Error(
      'polkadot{.js} extension might not be installed. Make sure you allowed the dApp in the "Manage Website Access" settings of your wallet.'
    );
  return await web3Accounts();
};

```

{% hint style="info" %}
You can implement this **atomic function** in your repository.&#x20;
{% endhint %}

Now you can access the accounts, you can fetch them when needed, and store the index of the account you want to set as the connected account in your storage solution (context, redux, or any solution you use).

### Next

The next step will be to [sign a transaction in a browser environment](/build-1/javascript/ternoa-js-library-utilities/sign-a-transaction-with-polkadot-.js-extension-in-a-browser-environment). You can also look at how to [mint an NFT](/build-1/javascript/ternoa-js-library-utilities/sign-a-transaction-with-polkadot-.js-extension-in-a-browser-environment) or a [secret NFT](/build-1/javascript/privacy-protocols/tee-privacy-and-encryption/encryption-in-browser-with-wallet-and-extension) with your extension.&#x20;




---

[Next Page](/llms-full.txt/1)

