> This is part 1 of 3 of the full documentation (pages 1–100 of 203).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.zetrix.com/en/llms-full.txt/1
> Page index: https://docs.zetrix.com/en/llms.txt

> Agents can also search and read this documentation through its [MCP server](https://docs.zetrix.com/en/~gitbook/mcp).

# Overview of Zetrix

## What is Zetrix

Zetrix is a next-generation layer-1 public blockchain engineered to power enterprise and government-grade decentralised applications (dApps). Designed with scalability, interoperability, and regulatory compliance at its core, Zetrix aspires to serve as a foundational platform for cross-border digital services and digital asset ecosystems.

As a public blockchain infrastructure, Zetrix facilitates the secure and efficient transfer of value, analogous to how the internet enables the free flow of information. It is specifically tailored to address real-world enterprise challenges such as:

* Interoperability between different blockchain networks
* Digital identity and verifiable credentials
* Cross-chain data exchange

Additionally, Zetrix is aligned with emerging global digital trade frameworks, making it a strategic enabler for next-generation digital commerce.

## Consensus Mechanism

Technically, Zetrix leverages a hybrid consensus mechanism that combines Delegated Proof of Stake (DPoS) and Zetrix Byzantine Fault Tolerance (zBFT). This approach delivers rapid block finality, scalability, and robust security. With a current throughput of 2,000 transactions per second (TPS) and theoretical scalability to 10,000 TPS through sharding and subchains, Zetrix is designed for high-performance applications.

Smart contracts on Zetrix are written in JavaScript and supported by an integrated web-based IDE, enabling developers to build, test, and deploy seamlessly.

A key differentiator of Zetrix is its cross-chain and cross-border focus. It is interoperable with other blockchain ecosystems like Ethereum, Hyperledger, and Astron through inter-chain protocols. Additionally, it is integrated with Xinghuo BIF, China’s national blockchain infrastructure, via MYEG’s international supernodes. This positions Zetrix as a digital bridge between Southeast Asia and China, particularly under the Regional Comprehensive Economic Partnership (RCEP) initiative, making it a vital infrastructure for regional digital trade and digital ID applications.

Based on the DPoS mechanism, ordinary nodes stake ZETRIX tokens to join the validating node-set. From this set, 21 validating nodes are randomly selected in a cyclical rotation to generate blocks using the zBFT algorithm. Validators are elected via a validator contract, enabling the chain to maintain high transaction speeds while ensuring decentralisation and security.

## Architecture

![Zetrix Architecture](https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FblPnXGUy6DWuRUyP5uT9%2Fimage.png?alt=media\&token=0e6678ff-9f7a-44b6-b351-14b6f5843c8b)

## Zetrix Currency Unit

The currency unit of Zetrix is called Zetrix, represented as "ZETRIX". For example, both "1 Zetrix" and "1 ZETRIX" are valid expressions.

Zetrix is subdivided into smaller units, with the smallest possible unit named Zeta.\
The conversion rate is:

> **1 ZETRIX = 1,000,000 Zeta**

This micro-denomination allows for high-precision transactions and fine-grained asset management within the Zetrix ecosystem.

|  ZETRIX  |    Zeta   |
| :------: | :-------: |
|     1    | 1,000,000 |
| 0.000001 |     1     |


# Why Build on Zetrix

## Safe and Efficient Consensus Algorithm

Zetrix’s consensus mechanism is a hybrid model that integrates Delegated Proof of Stake (DPoS) with an advanced form of Byzantine Fault Tolerance called zBFT. This architecture is carefully designed to deliver both safety and efficiency, addressing the need for fast transaction processing, robust fault tolerance, and environmental sustainability. By combining these two layers, Zetrix provides an optimal consensus model suitable for high-throughput and compliance-sensitive applications across both the enterprise and public sectors.

At the foundation of this model is DPoS, a voting-based mechanism where Zetrix token holders delegate their tokens to elect a limited set of validator nodes. These elected validators are responsible for producing blocks in a fixed, cyclical order. This significantly reduces the computational overhead seen in traditional Proof-of-Work systems, allowing Zetrix to operate at high transaction speeds with minimal energy consumption. The dynamic nature of validator selection also enhances decentralisation and introduces a layer of governance, as voters can replace non-performing or malicious validators through staking smart contracts.

Layered on top of DPoS is the Zetrix Byzantine Fault Tolerance (zBFT) protocol. This component ensures strong consistency and resilience within the validator node set. For every block, a random selection of 21 validators is made, and these validators reach consensus through a secure message-passing process. Unlike traditional BFT protocols that struggle with communication overhead, zBFT optimises this process by reducing the message complexity from quadratic to linear scale.

![](https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Ft2YPpdJPah6voKSQJM8e%2Fimage.png?alt=media\&token=3c698a90-cdd2-4c1f-89d3-177ec3865844)

## Parallel and Diverse Multi-Chain Sharding

Traditional blockchain systems often rely on a single-chain architecture, where all transactions and data are handled through a centralised, unified ledger. This design creates performance bottlenecks, as the entire network's efficiency depends on the processing capacity of individual nodes. As transaction volumes grow, such systems encounter scalability and throughput limitations.

Additionally, most of these systems store data directly on-chain, which significantly increases storage and computational overhead. This further constrains performance and makes it challenging to support high-demand enterprise applications, especially those requiring real-time processing, large data throughput, or complex logic execution.

Zetrix addresses these challenges through a multi-chain sharding architecture, enabling the blockchain to scale horizontally. This approach segments data and transaction processing across multiple independent sub-chains, each tailored to specific business functions or application domains. These sub-chains operate in parallel, significantly increasing the system’s overall throughput and responsiveness.

The underlying framework is described as a “two-layer capacity expansion model.” The main chain manages governance, validation, and security coordination, while the sub-chains handle specialised computation and data storage tasks. Each sub-chain inherits the security and trust guarantees of the main chain but operates independently, ensuring that congestion or data growth on one chain does not impact others. This results in true resource isolation and flexible, scalable deployment across diverse industry use cases.

![](https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FKUequV3U6m2479cCf0NK%2Fimage.png?alt=media\&token=08c22dd0-1cd3-4d47-840f-21f7d907a094)

## Reliable Privacy Protection and Permission Control

The Zetrix blockchain integrates advanced cryptographic technologies, including homomorphic hiding and zero-knowledge proofs, to enable non-interactive privacy protection. This ensures that transaction amounts, addresses, and metadata remain confidential. Additionally, Zetrix employs a proxy re-encryption algorithm to support authorized access to on-chain data, allowing designated parties to securely decrypt and interact with private information without exposing it to the public.

Non-interactive privacy protection in Zetrix is achieved by generating a blinding factor using the Elliptic Curve Diffie-Hellman (ECDH) algorithm. This blinding factor is calculated such that the receiver can recover it by performing an algebraic operation using their private key and the sender’s public key. However, a third party without access to either of the private keys cannot reconstruct the blinding factor. This cryptographic approach ensures that transaction details remain hidden from unauthorized observers, effectively enabling confidential transactions without direct interaction between sender and receiver.

Transaction amount hiding in Zetrix is accomplished using Pedersen commitments, which provide homomorphic encryption of transaction amounts. This means that the sum or difference of encrypted values corresponds to the encrypted result of the sum or difference of the original values. As a result, blockchain nodes can perform mathematical operations directly on encrypted data such as verifying that total inputs equal total outputs without ever revealing the actual transaction amounts. This ensures both privacy and verifiability in confidential transactions.

Transaction address hiding in Zetrix is achieved by transferring ownership through a transformed version of the recipient’s public key. For each transaction output, a unique one-time public key is generated based on the recipient’s original key using a defined transformation rule. This ensures that each output uses a different address, making it impossible for external observers to link multiple transactions to the same recipient. As a result, ownership changes occur securely while preserving address confidentiality and preventing traceability.

![](https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FwrwO9g1vFymu0IptAZP8%2Fimage.png?alt=media\&token=7a41fffb-8c7c-41a7-bf44-466969f46df9)

## Application Development - Friendly Smart Contract

The Zetrix blockchain features a smart contract engine built on the Chrome V8 virtual machine, offering an integrated development environment (IDE) along with multiple contract templates tailored for various application scenarios. To enhance contract security, Zetrix employs a restricted subset of JavaScript as its primary programming language, enabling developers to safely and efficiently build smart contract applications.

![](https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FYcPPfHFpShyFW9xKjd9k%2Fimage.png?alt=media\&token=6023e5f4-3e0a-449a-b69a-dd62eed46acd)

## Scalable Homogeneous / Heterogeneous Cross Chain Interoperability

The Zetrix blockchain utilizes an interconnected chain architecture to enable advanced cross-chain capabilities, supporting multiple interoperability models such as multi-notary consensus and trusted hardware mechanisms. Developers can build a Relay Chain using SPV (Simplified Payment Verification) to connect with external business chains and create parallel chains as needed, which are then linked to the Relay Chain via a defined cross-chain protocol. This modular structure reduces architectural complexity and offers greater flexibility, making it ideal for practical enterprise use cases. Zetrix supports both isomorphic and heterogeneous cross-chain operations, facilitating not only the transfer of digital assets but also enabling cross-chain execution of smart contracts and decentralized applications.

![](https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Fgit-blob-e853667b1e30a64584601bab66d6c1954e2b70db%2Frelay_chain.png?alt=media)

## Legal Effect and Compliance

The Zetrix Blockchain integrates digital certificates into its network for identity authentication, supporting both software and hardware modes. Software certificates enhance operational convenience, while hardware certificates bolster security for sensitive enterprise use cases. Only users with CA-issued digital certificates can operate on the blockchain, and institutional nodes must authenticate using these certificates. By leveraging the existing PKI infrastructure, Zetrix binds all authentication data to blockchain accounts, enabling secure on-chain verification.

Zetrix supports national commercial cryptographic standards such as SM2 / SM3 / SM4, meeting the security requirements of domestic institutions, while also supporting international standards like SHA256, making it globally interoperable. Furthermore, Zetrix nodes integrate with platforms such as judicial risk control systems, Internet courts, and CFCA, enabling services like judicial deposits, electronic contracts, and real-name authentication. The ecosystem is open to developers, who can contribute their own services and participate in building a distributed business application ecosystem on the Zetrix blockchain.

## Ease of Use

Zetrix adaptors abstract API interfaces tailored for diverse business scenarios such as digital assets, traceability, and certificate storage, allowing businesses to integrate these capabilities directly. For new use cases, Zetrix can rapidly customize interfaces within its existing framework to fulfill specific business functionality requirements. To support developer adoption, Zetrix offers packaged SDKs compatible with multiple mainstream programming languages including Java, C++, Node.js, and PHP.

Currently, blockchain services follow two main models: one builds the underlying infrastructure and exposes standardized APIs for developers to integrate; the other embeds the distributed ledger into existing applications to address industry-specific challenges. As an emerging technology, blockchain must evolve by continuously adapting to real-world business needs. Zetrix accelerates this by encapsulating the distributed ledger layer, lowering the integration barrier for upper-layer applications. Through continuous usage, integration, and feedback, Zetrix optimizes its consensus algorithms and core infrastructure, making the platform increasingly aligned with commercial demands.

## Visual Operation and Maintenance

Zetrix provides comprehensive visual tools to support operation and maintenance management across its blockchain infrastructure. Through the deployment of System Monitoring Services (MonitorAgent) on each blockchain node, Zetrix enables real-time monitoring across multiple dimensions:

* Business-level metrics: Blocks, transactions, smart contracts, consensus activity
* Network-level metrics: Network connectivity, latency, throughput
* System-level metrics: CPU usage, memory consumption, disk space utilization

In addition to data visualization, the platform includes a robust logging, alarm, and notification mechanism, ensuring timely alerts and simplified troubleshooting. This integrated monitoring framework is designed to enhance the stability, reliability, and maintainability of commercial systems running on the Zetrix blockchain.

## Fund Account System

In business applications, blockchain networks typically lack real-world "money" directly on-chain. To address this, the Zetrix blockchain introduces a set of components that enable integration between blockchain accounts and traditional bank accounts. This allows for seamless settlement between digital and fiat systems. By leveraging smart contracts, the fund clearing process becomes fully automated, relying solely on on-chain digital signatures rather than a centralized system administrator. This design enhances transparency, efficiency, and trust in hybrid digital-financial ecosystems.


# Roadmap

Zetrix is developed by a well-established IT group (MYEG) which is a successful late-stage innovator with a proven track record of product development, tech experience curve, and multinational presence.

Our initial target market will be to the strategic priority sectors in Phase 1 and 2 (see below). These are at the industry level that require cross-functional participation and upfront investment, and are expected to take a relatively longer gestation period due to its nature and complexity. Nevertheless the competitive advantages acquired will be entrenched and with long term benefits for us.

We are uniquely positioned, due to our technical expertise and strategic investments, to deploy the product roadmap for these priority sectors between Malaysia and China. It bears repeating that Zetrix’s products have been showcased during the MOU signing with CAICT (under China’s Ministry of Industry & Information Technology) which was inaugurated by the Ministry of Science, Technology and Innovation (MOSTI) of Malaysia in 2021, as well as at the Malaysia Pavilion in Expo 2020 Dubai.

For the broader small-to-medium enterprise (SME) segment, which make up the vast majority of ASEAN’s GDP growth engine, our objective is to introduce these blockchain tech products in the form of Traceability-as-a-Service (TaaS) software, which will be monthly subscription-based, modularised, and delivered online with easy plug-and-play usage. This enables much easier market penetration and scalability, akin to a cloud-based data storage service.

The international supply chain is growing in complexity at the same time as nation states seek to improve their border compliance for imports and facilitate access to export markets for their domestic producers.

Zetrix has developed Ztrade as the next-generation trade connectivity platform that utilizes blockchain technology and document digitization to save time, minimizes human error, making Malaysia a leader in technology innovation within the Regional Comprehensive Economic Partnership (RCEP).

Zetrix has also introduced ZTradeFi, an innovative blockchain powered trade financing solution that elevates cross-border trading to new heights. Our cutting-edge platform simplifies complex cross-border trading processes and creates new opportunities for local businesses to seamlessly and securely connect with Chinese counterparties, enabling cross-border financial and trade connectivity.

Blockchain technology can help solve issued faced by the traditional way of international trading namely:

* Cost of trade
* Allowing SMEs to participate instead of big corporations only
* Eliminate/reducing fake goods transactions
* Environmental issues like carbon emissions
* Managing border risks based on data integrity
* Importance of digitization
* Traceability through supply chain
* Automated compliance and risk

The above issues have been highlighted in the eDATA Verifiable Credentials for Cross Border Trade whitepaper in September 2022. The importance of blockchain technology highlights the need to further improve trading facilities whilst keeping in abreast with the ever-growing technology of today.


# Quick Start Guide

Welcome to the Zetrix Blockchain! This guide is designed to help you quickly get started with using Zetrix, setting up wallets, and diving into development.

### 1. Quick Start <a href="#id-1.-quick-start" id="id-1.-quick-start"></a>

This section provides a brief overview of how to quickly get up and running with Zetrix.

**1.1 Creating a Wallet**

* Visit the official Zetrix wallet website <https://www.zetrix.com/zetrix-wallet/> or download the mobile app (iOS/Android).
* Create a new wallet by following the on-screen instructions.
* Securely store your secret recovery phrase for recovery. This is critical for accessing your wallet in case you lose access to the app.
* Set up a password or PIN for added security.

**1.2 Funding Your Wallet**

* Acquire Zetrix tokens (ZETRIX) through an exchange or directly via Zetrix's supported platforms.
* Here list of platforms where you can get your ZETRIX:
  * Coinstore <https://www.coinstore.com/>
  * MEXC <https://www.mexc.com/>
* Transfer the tokens to your Zetrix wallet by copying the wallet’s public address and initiating the transaction.

**1.3 Performing a Transaction**

* Navigate to the "Send" section in your wallet.
* Enter the recipient’s wallet address, the amount of ZETRIX to send, and confirm the transaction.
* Monitor the transaction status using the Zetrix blockchain explorer.

**2. Introduction to Development**

Zetrix provides an easy-to-use Integrated Development Environment (IDE) at [ide.zetrix.com](https://ide.zetrix.com/), allowing developers to quickly start building and deploying smart contracts on the Zetrix blockchain. This section will guide you through setting up your development environment, writing smart contracts, and interacting with the Zetrix blockchain using the IDE.

**2.1 Setting Up Development Environment**

The Zetrix IDE is a web-based platform, so there's no need for extensive local setup. To get started, follow these simple steps:

**Steps:**

1. **Visit** [**ide.zetrix.com**](https://ide.zetrix.com/): Open your web browser and navigate to the IDE.
2. **Create an Account or Sign In**: If you are a new user, create an account by registering with your email. If you already have an account, log in.
3. **Connect to Zetrix Testnet**: The IDE automatically connects to the Zetrix testnet for development and testing purposes. You can switch to the mainnet when you're ready to deploy live contracts.
4. **Access Developer Tools**: The IDE provides a fully integrated suite of tools, including javascript contract editor and a interface development environment for deploying contracts to the Zetrix blockchain.


# Key Concept

* **Flexible Account Structure**\
  Supports accounts with multiple assets and multiple operators, making complex setups easy to manage.
* **Dual-Layer Consensus called "Firework"**\
  Uses a two-step system (DPoS + BFT) to process transactions quickly and securely.
* **Multi-Chain System called "Orbits"**\
  Allows many sub-chains to run under a main chain, boosting performance and scalability.
* **Cross-Chain Network called "Canal"**\
  Enables smooth transfer of data and assets between different blockchains.
* **Powerful Smart Contracts**\
  Supports full programming capabilities using JavaScript for building dApps.
* **Multiple Signature Options**\
  Includes strong cryptographic support like ED25519 and SM2 for secure digital signatures.
* **Multi-Signature Accounts**\
  Allows accounts to require approvals from multiple users for extra security.
* **High-Speed Transactions**\
  Can handle thousands of transactions per second, making it suitable for large-scale use.
* **Runs on All Major Platforms**\
  Compatible with Linux, Windows, macOS, and Android for flexible deployment.
* **Built-in Privacy Protection**\
  Uses advanced cryptography like zero-knowledge proofs to keep user data and transactions private.


# Blockchain Layer

Zetrix is a public blockchain network that functions as a Layer-1 solution designed to support cross-border and cross-chain transactions. It focuses on creating a seamless ecosystem for decentralized applications (dApps), smart contracts, and digital assets. Zetrix aims to bridge private and public blockchains, facilitating secure and scalable cross-chain interoperability.

Here are key aspects of Zetrix:

1. **Cross-border Compatibility**: Zetrix is designed to enable cross-border transactions, making it suitable for applications like international trade, payments, and logistics. This makes it well-suited for global business and financial transactions.
2. **Layer-1 Blockchain**: Zetrix operates as a Layer-1 blockchain, meaning it is a foundational blockchain that provides its own security, consensus, and transaction processing, without depending on other networks like Ethereum or Bitcoin for these services.
3. **Interoperability**: Zetrix supports cross-chain transactions, which means it can connect with other blockchain networks (currently ETH, Hyperledger and Astron), allowing for the transfer of assets or data between different chains.
4. **Smart Contracts**: It supports smart contracts, allowing developers to build decentralized applications (dApps) on the network. These smart contracts can be used for a variety of applications, from DeFi (Decentralized Finance) to supply chain management.
5. **Security and Scalability**: Zetrix emphasizes both security and scalability, using mechanisms like zero-knowledge proofs and cryptographic algorithms to ensure the integrity and privacy of transactions while maintaining a scalable network architecture.
6. **Partnerships and Ecosystem**: Zetrix has been working with various international partners, including collaborations with government and business entities, to promote the use of blockchain in cross-border solutions.

In summary, Zetrix is designed to be a global, interoperable, and scalable blockchain network that supports decentralized applications and secure cross-border transactions.


# Consensus Mechanism

The consensus mechanism is the fundamental process by which transactions are validated and committed to the blockchain. The Zetrix blockchain employs an advanced hybrid consensus algorithm combining Delegated Proof of Stake (DPoS) and Zetrix Byzantine Fault Tolerance (zBFT). This architecture supports large-scale node participation and enables high-speed transaction processing, making Zetrix well-suited for a wide range of commercial applications.

In this model, ordinary nodes must pledge ZETRIX tokens to become part of the validating node set. From this pool, the system randomly selects 21 validators in each consensus round to generate blocks in a cyclical rotation, governed by the zBFT algorithm. Validators are elected via a validator smart contract, ensuring that only trusted and high-performing nodes participate. This setup allows Zetrix to maintain high throughput, strong consistency, and robust decentralisation, aligning with the security and performance needs of enterprise-grade blockchain solutions.


# DPos

Delegated Proof of Stake (DPoS) is a consensus algorithm designed to enhance blockchain security through a technology-driven democratic process. It relies on voting and election mechanisms to maintain decentralisation and defend against malicious activity.

\
In Zetrix, DPoS is optimised for high performance, requiring validating nodes to operate on high-specification servers within stable environments. To ensure robust network security, Zetrix implements a unique validation protocol.

* **Validator Selection**: Ordinary nodes may become validator candidates by pledging a specific amount of ZETRIX tokens. These candidates are reviewed and approved by a consensus committee.
* **Validation Pool Governance**: Approved validators enter a rotating pool. If a validator fails to produce blocks over an extended period or is found to propagate malicious consensus messages, their pledged tokens are subject to confiscation, and their validator status may be revoked.
* **On-Chain Voting Mechanism**: Validator governance is managed via smart contracts that enable a dynamic and transparent voting process. This allows the network to adjust validator participation based on the evolving needs and security parameters of the chain.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Fvz9fkcocBvU8Pbnhdd0v%2Fimage.png?alt=media&amp;token=53824bd4-afb7-42ae-b08a-6c0bdf760d62" alt=""><figcaption></figcaption></figure>

The Zetrix Delegated Proof of Stake (DPoS) mechanism is executed via smart contracts, allowing for automated governance and scalable adaptability as the network expands. It incorporates a dynamic upgrade system that adjusts validator participation requirements in line with network growth, thereby maintaining decentralization and performance. Unlike traditional consensus models, DPoS is highly resource-efficient, requiring minimal computational power while supporting high transaction throughput. This low-energy architecture aligns with Environmental, Social, and Governance (ESG) principles, positioning Zetrix as a sustainable and future-ready blockchain infrastructure.


# DPOS Lifecycle Flow

This chapter explains how Zetrix Delegated Proof of Stake (DPOS) operates from an application and contract-integration perspective.

* how validator rotation is triggered,
* how freeze and unfreeze decisions are made,
* how heartbeat statistics are accumulated and stored,
* how reward eligibility is derived, and
* how daily reward extraction and transfer are executed.

### System Overview

Zetrix uses Delegated Proof of Stake (DPOS). Validators are elected to produce blocks in rotation. Around that core block-production model, the platform runs a continuous operational loop that:

* monitors validator health,
* freezes lagging validators,
* restores recovered validators,
* records hourly online-validator status, and
* distributes rewards once per day.

The model operates on three time scales:

* every 10 seconds for rotation and forecast-based protection,
* every 1 minute for local sequence reconciliation,
* every 1 hour for heartbeat aggregation, and
* daily at 18:00 for reward settlement.

## End-to-End DPOS Lifecycle

The following diagram shows the full lifecycle from startup through continuous monitoring, hourly statistics, and daily reward extraction.

````mermaid
flowchart TD
    START([System Startup]) --> INIT_NODE

    subgraph SG_INIT["Initialisation"]
        INIT_NODE["Load keystores<br/>Load contracts<br/>Load admin validator list"]
    end

    SG_INIT --> SG_CYCLE

    subgraph SG_CYCLE["Continuous Monitoring Cycle"]

        subgraph T30["Every 10 seconds — ValidatorsRotateJob"]
            R1["Get DPOS config on-chain<br/>validator slice count + rotate interval"]
            R2["Get current max block sequence"]
            R3{"currentSeq ><br/>sliceCount + rotate?"}
            R4["Identify freeze candidates<br/>freezeToActive list"]
            R5["Call updateValidator()<br/>on DPOS Contract"]
            R6["Log rotation event"]
            R1 --> R2 --> R3
            R3 -->|No| R_SKIP["Skip rotation"]
            R3 -->|Yes| R4 --> R5 --> R6
        end

        subgraph T1A["Every 10 seconds — ValidatorsForecastCheckJob"]
            FA1["Get current max seq<br/>from blockchain"]
            FA2["Get active validators list<br/>from ledger"]
            FA3["Calculate next 3 forecasted<br/>producers via viewNum mod count"]
            FA4{"Forecasted validator<br/>local seq lagging<br/>> 2 blocks?"}
            FA5["Mark as ABNORMAL<br/>Add to freeze list"]
            FA6["Trigger freeze<br/>ABNORMAL status"]
            FA7["Call setFreeze(true)<br/>on DPOS Contract<br/>skip admin addresses"]
            FA8["Log freeze event"]
            FA1 --> FA2 --> FA3 --> FA4
            FA4 -->|No| FA_OK["Validator healthy<br/>no action"]
            FA4 -->|Yes| FA5 --> FA6 --> FA7 --> FA8
        end

        subgraph T1B["Every 1 min — ValidatorsLocalSeqCheckJob"]
            LS1["Query all validators<br/>local seq from DB"]
            LS2["Query on-chain seq<br/>from blockchain"]
            LS3{"Frozen validator<br/>seq now current?"}
            LS4["Mark NORMAL<br/>trigger unfreeze"]
            LS5{"Active validator<br/>seq lag > 2 blocks?"}
            LS6["Mark ABNORMAL<br/>trigger freeze"]
            LS7["Call setFreeze(freeze)<br/>on DPOS Contract"]
            LS8["Log state change"]
            LS1 --> LS2 --> LS3
            LS3 -->|Yes| LS4 --> LS7
            LS3 -->|No| LS5
            LS5 -->|Yes| LS6 --> LS7
            LS5 -->|No| LS_OK["No change"]
            LS7 --> LS8
        end
    end

    SG_CYCLE --> SG_HOURLY

    subgraph SG_HOURLY["Every 1 Hour — ValidatorsHeartStatisticJob"]
        H1["Query all configured<br/>validator addresses"]
        H2["Read heartbeat counts<br/>from cache"]
        H3{"Count >= threshold<br/>47 beats?"}
        H4["Add to onlineValidatorList"]
        H5["Call pushStatus(onlineList, onlineTimestamp)<br/>on Heartbeat Contract<br/>via operator key"]
        H6["Insert heartbeat statistic record"]
        H7["Reset heartbeat counters<br/>for next hour"]
        H1 --> H2 --> H3
        H3 -->|Yes| H4 --> H5
        H3 -->|No| H3_SKIP["Validator excluded<br/>from online list"]
        H5 --> H6 --> H7
    end

    SG_HOURLY --> SG_DAILY

    subgraph SG_DAILY["Daily 18:00 — ValidatorExtractJob"]
        D1["Reset heartbeat stats<br/>in cache"]
        D2["Call extract()<br/>via admin key"]
        D3["Submit extract tx to DPOS contract<br/>On-chain reward calculation triggered"]
        D4["Call extractTransfer()<br/>via admin key"]
        D5["Fetch all validator<br/>fund addresses from chain"]
        D6["Partition into batches of 10"]
        D7["Submit extractTransfer tx<br/>per batch"]
        D8["Wait between batches<br/>for nonce management"]
        D9["Rewards transferred<br/>to validator accounts"]
        D10["Log all tx hashes"]
        D1 --> D2 --> D3 --> D4 --> D5 --> D6 --> D7 --> D8
        D8 -->|next batch| D7
        D7 -->|All batches done| D9 --> D10
    end

    D10 -.->|"Next day — loop continues"| SG_CYCLE
```
````

#### Lifecycle explanation

The DPOS lifecycle is split into continuous safety checks, hourly evidence collection, and daily reward settlement. Sequence lag drives operational freeze decisions, while heartbeat inclusion drives reward eligibility.

Operational Jobs

#### `ValidatorsRotateJob`

Frequency: every 10 seconds

Purpose: rotate validator participation when the configured block slice and rotation interval require it.

Behavior summary:

* read DPOS configuration from chain,
* read the latest block sequence,
* decide whether the rotation threshold has been reached,
* identify candidates that can move from freeze-related state back to active participation,
* call updateValidator(), and
* log the rotation event.

#### `ValidatorsForecastCheckJob`

Frequency: every 10 seconds

Purpose: forecast upcoming producers and freeze validators that are already lagging.

Behavior summary:

* read current chain sequence,
* read the active validator list,
* calculate the next three expected producers,
* compare projected validators against local sequence progress,
* mark lagging validators as abnormal,
* skip protected admin validators, and
* call setFreeze(true) for the affected validators.

#### `ValidatorsLocalSeqCheckJob`

Frequency: every 1 minute

Purpose: reconcile validator state using current local and on-chain sequence numbers.

Behavior summary:

* read local validator sequence values,
* compare them with the latest on-chain values,
* restore frozen validators that have caught up,
* freeze active validators that exceed the lag threshold, and
* log any resulting state changes.

#### `ValidatorsHeartStatisticJob`

Frequency: every 1 hour

Purpose: convert raw heartbeat counts into an hourly online-validator snapshot.

Behavior summary:

* read configured validator addresses,
* read heartbeat counts from cache,
* check whether each validator reaches the hourly threshold,
* build the online validator list,
* push that list with the timestamp to the Heartbeat contract,
* persist the heartbeat statistic record, and
* reset counters for the next hour.

#### `ValidatorExtractJob`

Frequency: daily at 18:00

Purpose: finalize the daily reward cycle.

Behavior summary:

* reset heartbeat statistics in cache,
* call extract(),
* trigger on-chain reward calculation,
* read validator fund addresses,
* batch them in groups of 10,
* call extractTransfer() for each batch, and
* log the resulting transaction hashes.


# Validator State Machine

The lifecycle is split into three operational time scales:

* short interval monitoring for validator safety and rotation,
* hourly aggregation for online-presence recording, and
* daily extraction for reward settlement.

This separation matters because not every operational decision is made from the same signal. Sequence lag drives freeze decisions, while accumulated heartbeat presence drives reward eligibility.

### Validator State Model

The validator state machine below captures the functional states used by the system.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FnsCuiCr67vG4FhQCpCiE%2FWallet%20%26%20Holdings%20%E2%80%94%20Sequence%20Diagram-2026-05-13-081208.png?alt=media&amp;token=c91b9a1d-b74e-4036-9fb1-4cac18f45a15" alt=""><figcaption></figcaption></figure>

#### State semantics

**ACTIVE**

The validator is considered healthy and able to participate in block production. It may also accumulate heartbeat presence that contributes to reward qualification.

**FROZEN**

The validator has been marked abnormal, typically because it is lagging behind the expected chain sequence or failed a forecast-based health check. Frozen validators are excluded from normal participation until recovery conditions are met.

**REWARDED**

This is not a long-lived operational state in the same sense as ACTIVE or FROZEN. It represents the reward-settlement phase in which accumulated eligibility is materialized into token transfers.


# Reward Extraction Flow

The following sequence diagram shows the two-phase daily reward process.(Daily 18:00)

```mermaid
sequenceDiagram
    participant JOB as ValidatorExtractJob
    participant CACHE as Cache
    participant SVC as On-Chain Service
    participant BC as Blockchain Service
    participant CHAIN as DPOS Contract
    participant HB as Heartbeat Contract
    participant DB as Database

    JOB->>CACHE: Reset heartbeat statistics
    CACHE-->>JOB: Cache cleared

    Note over JOB,CHAIN: Phase 1 — Trigger On-Chain Reward Calculation

    participant API as Backend API
    participant NODE as Zetrix Node

    JOB->>SVC: doExtract()
    SVC->>BC: Generate extract() transaction blob
    BC->>API: Build extract() blob
    API-->>BC: blob
    BC-->>SVC: blob
    SVC->>SVC: Sign blob with admin key
    SVC->>BC: Submit signed transaction
    BC->>API: Submit TransactionEnv{extract()}
    API->>NODE: POST /submitTransaction
    NODE-->>API: tx hash
    API->>NODE: Poll getTransactionByHash() until COMPLETE
    NODE-->>API: tx confirmed
    API-->>BC: tx_hash + COMPLETE
    BC-->>SVC: tx_hash + COMPLETE
    Note over CHAIN,HB: extract() runs on-chain — getOnlineNodeList()
    CHAIN->>HB: contractQuery getNodeList(rate)
    Note right of HB: Count per-validator appearances across all stored timestamps.<br/>Include if appearances/total * 100 >= rate (e.g. 80%)
    HB-->>CHAIN: online validator address list
    CHAIN->>HB: clearRecord() — wipe all timestamp records
    Note right of CHAIN: calculate() distributes reward only to online validators,<br/>cross-referenced against validator candidates list
    SVC->>DB: Log tx hash + timestamp

    Note over JOB,CHAIN: Phase 2 — Distribute Rewards to Validator Accounts

    JOB->>SVC: doExtractTransfer()
    SVC->>NODE: GET validator fund addresses (DPOS contract metadata)
    NODE-->>SVC: validator fund address list

    loop For each batch of 10 validators
        SVC->>SVC: Wait for nonce increment
        SVC->>BC: Generate extractTransfer(batch) blob
        BC->>API: Build extractTransfer(list) blob
        API-->>BC: blob
        BC-->>SVC: blob
        SVC->>SVC: Sign blob with admin key
        SVC->>BC: Submit signed transaction
        BC->>API: Submit TransactionEnv{extractTransfer(list)}
        API->>NODE: POST /submitTransaction
        NODE-->>API: tx confirmed
        API-->>BC: tx_hash + COMPLETE
        BC-->>SVC: tx_hash + COMPLETE
        SVC->>DB: Log batch tx hash
        Note right of CHAIN: Contract transfers reward tokens<br/>directly to each validator fund address
    end

    SVC-->>JOB: All rewards distributed
    Note over JOB: Cycle complete. Next extraction at 18:00 tomorrow
```

The reward flow has two distinct phases.

**Phase 1: calculate eligibility and reward amounts**

The `extract()` call causes the DPOS contract to query the Heartbeat contract for the validators that met the configured online-rate threshold across the stored hourly snapshots.

After the eligible list is returned:

* reward calculation is performed on-chain
* only validators satisfying the heartbeat-based policy are considered eligible
* heartbeat records are cleared to prepare for the next cycle

**Phase 2: transfer rewards to fund addresses**

The `extractTransfer(list[])` calls distribute the already calculated rewards to validator fund addresses. Batching is used to control transaction size and nonce handling.

The two-minute delay between batches is operationally significant because it reduces nonce-collision risk when multiple transactions are submitted in sequence.


# Heartbeat Accumulation → Reward Eligibility Flow

The following diagram shows how heartbeat signals become reward eligibility input.

```mermaid
flowchart LR
    subgraph SG_NODE["Zetrix Node (Monitor Connection)"]
        PING["Node sends WebSocket PING every ~15s"]
        SYS["Node responds with system status<br/>(cpu · memory · disk)"]
    end

    subgraph SG_DC["BaaS Data Center"]
        PONG["Receive PING<br/>Every 3 PINGs (~45s)<br/>Request system status"]
        RCV["Parse system status response"]
        HBCNT["Increment heartbeat counter in cache<br/>key = validator address"]
    end

    subgraph SG_HR["Every 1 Hour"]
        STAT["ValidatorsHeartStatisticJob"]
        FILTER{"Count >= 47?"}
        ONLINE["Add to onlineList"]
        SKIP["Exclude from onlineList"]
        PUSH["Call pushStatus(onlineList, onlineTimestamp)<br/>on Heartbeat Contract<br/>via operator key"]
        DBINS["Insert heartbeat statistic record"]
        RESET["Reset cache counters"]
    end

    subgraph SG_HB["Heartbeat Contract"]
        HB_STORE["Stores per-timestamp validator sets<br/>Each hourly push appended to contract storage"]
    end

    subgraph SG_DAY["Daily 18:00"]
        EXTRACT["DPOS extract()<br/>getNodeList(rate = 80%)<br/>Keep validators in >= 80% of hourly slots<br/>clearRecord() wipes all records<br/>calculate() distributes reward"]
        TRANSFER["DPOS extractTransfer()<br/>Transfer rewards to fund addresses"]
    end

    PING --> PONG --> SYS --> RCV --> HBCNT
    HBCNT --> STAT
    STAT --> FILTER
    FILTER -->|Yes| ONLINE --> PUSH
    FILTER -->|No| SKIP
    PUSH --> HB_STORE
    PUSH --> DBINS --> RESET
    HB_STORE -.->|"daily contractQuery"| EXTRACT
    EXTRACT --> TRANSFER
```

#### Eligibility model explained

Eligibility is determined in two stages.

**Stage 1: hourly inclusion**

A validator must accumulate at least 47 heartbeat hits within the hour to appear in that hour's online list.

**Stage 2: cross-hour qualification**

During extract(), the Heartbeat contract checks how often each validator appeared across the stored hourly snapshots. A validator must appear in at least 80% of those slots to qualify for daily reward.


# Contract Methods Reference

The table below summarizes the contract methods and their operational role.

<table><thead><tr><th>Contract</th><th width="189.9090576171875">Method</th><th>Key Role</th><th>Trigger</th><th>Purpose</th></tr></thead><tbody><tr><td>DPOS Contract</td><td><code>setFreeze(freeze, validators[])</code></td><td>Admin key</td><td>Every 10s (freeze) + Every 1min (freeze or unfreeze)</td><td>Freeze or unfreeze validators</td></tr><tr><td>DPOS Contract</td><td><code>updateValidator()</code></td><td>Admin key</td><td>Every 10s</td><td>Rotate validator set</td></tr><tr><td>Heartbeat Contract</td><td><code>pushStatus({onlineList[], onlineTimestamp})</code></td><td>Operator key</td><td>Every 1 hour</td><td>Append online node set for that timestamp slot into contract storage</td></tr><tr><td>Heartbeat Contract</td><td><code>getNodeList({rate})</code></td><td>DPOS Contract (internal)</td><td>Daily 18:00, inside <code>extract()</code></td><td>Return validators that appeared in ≥rate% of stored hourly slots</td></tr><tr><td>Heartbeat Contract</td><td><code>clearRecord()</code></td><td>DPOS Contract (internal)</td><td>Daily 18:00, after <code>getNodeList()</code></td><td>Delete all timestamp records</td></tr><tr><td>DPOS Contract</td><td><code>extract()</code></td><td>Admin key</td><td>Daily 18:00</td><td>Query Heartbeat Contract, calculate reward distribution, wipe records</td></tr><tr><td>DPOS Contract</td><td><code>extractTransfer(list[])</code></td><td>Admin key</td><td>Daily 18:00</td><td>Distribute rewards to fund addresses</td></tr></tbody></table>

#### Contract interaction pattern

The DPOS contract is the decision and settlement contract. The Heartbeat contract is the historical evidence store used to derive online participation.

This separation is useful because it keeps monitoring evidence and reward execution loosely coupled while preserving on-chain verification of eligibility.


# Cron Schedule Summary

The following timeline summarizes the recurring jobs.

```mermaid
gantt
    title DPOS Job Schedule (24-hour view)
    dateFormat HH:mm
    axisFormat %H:%M

    section Every 10s
    ValidatorsRotateJob      :crit, rot1, 00:00, 24h
    ForecastCheckJob         :active, fc1, 00:00, 24h

    section Every 1 min
    LocalSeqCheckJob         :active, lsc1, 00:00, 24h

    section Every 1 hour
    HeartStat 00-01          :done, hs00, 00:00, 1h
    HeartStat 01-02          :done, hs01, 01:00, 1h
    HeartStat 02-03          :done, hs02, 02:00, 1h
    HeartStat 03-04          :done, hs03, 03:00, 1h
    HeartStat 04-05          :done, hs04, 04:00, 1h
    HeartStat 05-06          :done, hs05, 05:00, 1h
    HeartStat 06-07          :done, hs06, 06:00, 1h
    HeartStat 07-08          :done, hs07, 07:00, 1h
    HeartStat 08-09          :done, hs08, 08:00, 1h
    HeartStat 09-10          :done, hs09, 09:00, 1h
    HeartStat 10-11          :done, hs10, 10:00, 1h
    HeartStat 11-12          :done, hs11, 11:00, 1h
    HeartStat 12-13          :done, hs12, 12:00, 1h
    HeartStat 13-14          :done, hs13, 13:00, 1h
    HeartStat 14-15          :done, hs14, 14:00, 1h
    HeartStat 15-16          :done, hs15, 15:00, 1h
    HeartStat 16-17          :done, hs16, 16:00, 1h
    HeartStat 17-18          :done, hs17, 17:00, 1h
    HeartStat 18-19          :done, hs18, 18:00, 1h
    HeartStat 19-20          :done, hs19, 19:00, 1h
    HeartStat 20-21          :done, hs20, 20:00, 1h
    HeartStat 21-22          :done, hs21, 21:00, 1h
    HeartStat 22-23          :done, hs22, 22:00, 1h
    HeartStat 23-00          :done, hs23, 23:00, 1h

    section Daily
    ValidatorExtractJob      :milestone, ext1, 18:00, 0h
```

The schedule reflects a design choice:

* very fast jobs protect chain continuity,
* hourly jobs build durable monitoring evidence, and
* daily jobs settle reward consequences.

That separation keeps the monitoring path lightweight while limiting on-chain settlement to a predictable daily window.


# Key Configuration

| Parameter             | Value                  | Purpose                                                                                                                                                                                  |
| --------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Block lag threshold   | 2 blocks               | Maximum block sequence lag before a validator is frozen                                                                                                                                  |
| Heartbeat threshold   | 47 hits/hour           | Minimum cache heartbeat increments per hour to qualify as online. Math: PING every 15s, incremented every 3 PINGs (\~45s) → \~80 max/hr. 47/80 ≈ 58.75% uptime required within the hour. |
| Online rate threshold | 80%                    | Minimum percentage of hourly push slots a validator must appear in to qualify for daily reward                                                                                           |
| Forecast depth        | 3 blocks               | Number of blocks forecasted ahead for early freeze detection                                                                                                                             |
| Admin validator list  | (configured addresses) | Protected validators that are never frozen                                                                                                                                               |
| Freeze master switch  | configurable           | Enables or disables all freeze operations system-wide                                                                                                                                    |

### Operational Notes

#### Freeze policy

Freeze decisions are not based on a single signal source. The system can freeze validators due to forecast-based risk or due to actual sequence lag seen during the reconciliation job.

#### Protected validators

The admin exclusion list prevents certain validators from being frozen automatically. This is an explicit policy exception and should be reviewed carefully because it changes the behavior of automated health enforcement.

#### Reward qualification is not equivalent to active status

A validator may move between ACTIVE and FROZEN during the cycle yet still qualify for reward if its hourly online participation satisfies the contract threshold for the relevant period.

#### Record clearing is part of settlement

The heartbeat contract clears its stored timestamp records after extract() consumes them. That means the monitoring dataset is intentionally cyclical and aligned to the reward interval.

#### Batching and nonce handling

The extractTransfer(list\[]) phase uses batches of 10 validators and waits two minutes between batches. This indicates that operational safety around transaction sequencing is a deliberate part of the design.

### Summary

Zetrix DPOS operations are built around a layered control model:

* fast validator health monitoring,
* periodic online-state recording,
* contract-based reward qualification, and
* batched daily reward transfer.

The design separates monitoring evidence, validator state enforcement, and reward settlement while still connecting them through well-defined contract calls and scheduled jobs.


# BFT

Byzantine Fault Tolerance (BFT) is a consensus mechanism that enables a distributed network to agree on a single data value even when some nodes are malicious or unresponsive. Its core objective is to uphold system reliability and data integrity by accommodating both honest and faulty nodes in the decision-making process. This ensures that the network maintains operational consistency and security, even under adverse conditions.

In Zetrix, nodes elected through the DPoS mechanism enter a validating set and generate blocks using a Byzantine Fault Tolerant algorithm. Unlike traditional BFT models which are constrained by communication overhead and limited validator scalability Zetrix introduces zBFT, a custom-optimized adaptation of BFT that supports a larger number of validators while preserving high performance, strong consistency, and robust security.

The zBFT algorithm includes several innovations:

* Segmented time slices for upcoming blocks, with each slice using a randomized selection of 21 validators.
* A random validator rotation mechanism that enhances network resilience and decentralization.
* An optimized quorum structure that improves liveness and responsiveness.
* A refined ViewChange protocol that reduces communication complexity from O(n²) to O(n), dramatically boosting efficiency in large-scale networks.

Together, these enhancements make zBFT a cornerstone of Zetrix’s capability to deliver enterprise-grade performance while sustaining trustless decentralization.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FicD7Wxq4N9Rz2MejRhES%2Fimage.png?alt=media&amp;token=e821d16d-f85d-4259-8d45-e67a0e4961b7" alt=""><figcaption></figcaption></figure>

The zBFT algorithm in Zetrix empowers the network to achieve consensus and finality even when some validators are faulty or unresponsive. By tolerating a bounded number of node failures without undermining consensus on the blockchain state, zBFT guarantees continuous network availability and mitigates the risk of service disruptions. This level of fault resilience is vital for preserving the reliability and operational integrity of Zetrix particularly in enterprise and cross-border environments, where uptime, data consistency, and network trustworthiness are mission-critical.


# Node Type

The Zetrix blockchain operates as a public smart contract platform targeting international markets outside of China. In partnership with the Institute of Industrial Internet and Internet of Things under the China Academy of Information and Communications Technology (CAICT), MYEG is deploying Zetrix as the international extension of the Xinghuo Blockchain Infrastructure Framework (BIF). Zetrix supernodes are interconnected with Xinghuo BIF through MYEG’s overseas hosted Xinghuo supernode, facilitating inter-chain communication. This setup enables seamless interoperability between Zetrix, Xinghuo BIF, and other connected participants, supporting cross-border blockchain applications and digital infrastructure integration.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FyxG0qA9tyjd3ETBJ8HAH%2Fimage.png?alt=media&amp;token=0298df01-774b-4f82-a071-c4e1b2197221" alt=""><figcaption></figcaption></figure>

This structure allows local assets and value to be created and transacted across multiple chains, easing the flow of economic activity and improving liquidity for the assets transacted.

## Enterprise Ready

Zetrix is engineered as an enterprise-grade blockchain from inception, offering a robust suite of features tailored for business and institutional adoption. These include seamless cross-chain and subchain compatibility, comprehensive development tools, support for smart contracts, multi-asset wallet functionality, and advanced cryptographic security. This integrated ecosystem ensures that enterprises can rapidly deploy scalable, secure, and interoperable blockchain solutions without the need to build foundational infrastructure from scratch.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F7pHgR90Px7L7Tn8rF1c0%2Fimage.png?alt=media&amp;token=bf9f7f49-54b9-4948-b0ac-e81772241bfa" alt=""><figcaption></figcaption></figure>

With Zetrix’s ready-to-use enterprise-grade infrastructure, businesses can immediately begin development without the overhead of building or configuring foundational systems. This allows organizations to allocate resources more efficiently, focusing their teams on innovating, developing, and deploying next-generation blockchain applications, rather than managing technical setup or integration complexities.


# Security

Zetrix leverages both **Delegated Proof of Stake (DPoS)** and **Byzantine Fault Tolerance (BFT)** as its core consensus mechanisms, each contributing to network security through distinct methodologies. DPoS emphasises governance and efficiency, allowing token holders to vote for validators who produce blocks, ensuring representation and accountability. In contrast, BFT focuses on fault tolerance, enabling the network to reach consensus even if some nodes act maliciously or fail. Together, these mechanisms provide a balanced framework that combines high performance, decentralisation, and resilience against faults or attacks.

#### DPoS: A Delegated Approach

**Consensus Mechanism:** In Zetrix’s Delegated Proof of Stake (DPoS) consensus mechanism, token holders assign their voting rights to a limited set of trusted representatives known as delegates. These delegates are tasked with validating transactions and proposing new blocks to the blockchain. This delegation model enhances efficiency and scalability by reducing the number of nodes directly involved in block production, while still maintaining a level of decentralisation through community-driven elections.

**Security:**

* **Accountability:** Delegating accountability is fundamental to the security of Zetrix's DPoS mechanism. Since delegates are elected by token holders, their position depends on maintaining trust and performance. Failure to fulfil responsibilities such as validating blocks reliably or acting in the network’s best interest can result in loss of voter support and removal from the validator set. This built-in incentive structure promotes honest behaviour and operational integrity among delegates, reinforcing the overall stability and trustworthiness of the network.
* **Efficiency:** By restricting consensus participation to a selected group of delegates, Zetrix’s DPoS mechanism significantly enhances network efficiency compared to traditional models like Proof of Work (PoW) or Proof of Stake (PoS). This streamlined validator structure enables faster transaction finality, lowers network fees due to reduced computational overhead, and minimises energy consumption making Zetrix both performance optimised and environmentally sustainable.
* **Vulnerability:** Despite its efficiency and scalability benefits, DPoS carries inherent centralisation risks. If a majority of elected delegates collude, they could gain disproportionate control over the network, enabling potential manipulation of the blockchain. This could result in serious vulnerabilities such as transaction censorship, double-spending, or malicious protocol changes. As such, maintaining a transparent, well-governed voting process and active community oversight is critical to mitigating these risks and preserving the integrity of the Zetrix network.

#### Mitigating DPoS Vulnerabilities

To mitigate the risk of delegate collusion, DPoS systems typically implement several countermeasures, including:

* **Voting Thresholds:** Implementing a high voting threshold ensures that delegates must receive substantial backing from the community to be elected. This reduces the likelihood of a small group gaining control over the network and strengthens decentralisation.
* **Delegate Rotation:** Regular delegate rotation helps distribute authority more evenly over time, preventing power from becoming concentrated and lowering the risk of collusion among validators.
* **Community Oversight:** A proactive and informed community is essential for monitoring delegate actions and quickly identifying any signs of misconduct or abuse of power within the network.

Even with these safeguards in place, DPoS remains more centralized than consensus models like Proof of Work (PoW) or Proof of Stake (PoS). This inherent centralization can increase vulnerability to coordinated attacks, particularly in networks that lack robust governance structures or an active, engaged community to provide oversight and accountability.

#### BFT: A Fault-Tolerant Approach

**Consensus Mechanism:** Byzantine Fault Tolerance (BFT) algorithms are structured to enable a distributed network to reach consensus on a single system state, even when some nodes act maliciously or fail. By relying on majority agreement, BFT mechanisms preserve the integrity and consistency of the blockchain, making the system highly resilient to faults and external attacks.

**Security:**

* **Resilience:** BFT is highly resistant to attacks due to its fault-tolerant nature. It can tolerate a certain number of faulty nodes without compromising the system's security. This means that even if some nodes are malicious, the system can still reach consensus and maintain its integrity.
* **Complexity:** BFT algorithms can be complex to implement. They often involve intricate protocols and cryptographic techniques to achieve fault tolerance. This complexity can make it challenging to design and deploy BFT systems.
* **Performance:** BFT algorithms can have performance limitations. The frequent communication required between nodes can increase network overhead and reduce transaction throughput. This can be a concern for applications that require high performance, such as financial systems or decentralized exchanges.


# Smart Contract Development Tool

## Zetrix Development Tool

The following guide explains how to use our [Zetrix development tool](https://github.com/Zetrix-Chain/zetrix-development-tool), built for professionals. It facilitates performing frequent tasks, such as smart contract deployment and testing.

### Getting Started

For the purpose of this guide, clone the [repository](https://github.com/Zetrix-Chain/zetrix-development-tool) to your local machine. It will be used a base project for your own smart contract development on Zetrix.

After cloning the repository, we install the NPM packages for this project by running the following command:

```shell
npm install
```

Then create a `.env` file in the root of your project and insert your key/value pairs in the following format of `KEY=VALUE`:

If you're using the Zetrix testnet:

```sh
NODE_URL=test-node.zetrix.com
```

If you're using the Zetrix mainnet:

```shell
NODE_URL=node.zetrix.com
```

Insert the Zetrix address you are going to use to deploy the smart contract from

```sh
ZTX_ADDRESS=<YOUR ZETRIX ADDRESS>
```

Insert the private key of the Zetrix address you are going to use to deploy the smart contract from

```sh
PRIVATE_KEY=<THE PRIVATE KEY TO YOUR ZETRIX ADDRESS>
```

#### Contract development

The smart contract components can be found in the **contracts** directory. If you change the filename(s), please modify the contract name in **scripts** directory as well.

**Manual for running script:**

```sh
npm run help
```

**Contract deployment:**

```sh
npm run deploy:<NAMING_REFER_TO_PACKAGE_JSON>
```

**Contract upgrade:**

```sh
npm run upgrade:<NAMING_REFER_TO_PACKAGE_JSON>
```

**Run test with coverage:**

```sh
npm run test-coverage tests/unit/<TEST_CASE>.js
```

**Run integration test:**

```sh
npm test tests/integration/<TEST_CASE>.js
```

#### Development Guide

The development of Zetrix smart contract is using Javascript ES5 which has less support on OOP concepts such as `class`. Hence, we imitate the OOP implementation by using functionalities available in ES5.

**Class**

OOP implementation

```java
class Example {
    
    Example(String param) {
        // constructor
    }
}

Example exampleInst = new Example(param);
```

ES5 Javascript implementation

```javascript
const Example = function () {
    
    const self = this; // keep the context
    
    self.init = function (param) {
        // constructor
    };
};

const exampleInst = new Example();
exampleInst.init(param);
```

**Managing private, protected and public method**

OOP implementation

```java
class Example {
    
    private void privateMethod() {
        // private method
    }
    
    public void publicMethod() {
        // public method
    }

    protected void protectedMethod() {
        // protected method
    }
}
```

ES5 Javascript implementation

```javascript
const Example = function () {
    
    const self = this; // keep the context

    self.p = {/*protected function*/};
    
    const _privateMethod = function () {
        // private method
    };
    
    self.publicMethod = function () {
        // public method
    };
    
    self.p.protectedMethod = function () {
        // protected method : this method is similar to the public method, but we just defined in `p` nameclass to differentiate  
    };
};
```

**Inheritance and override**

OOP implementation

```java
class ExampleParent {
    
    public void parentMethod1() {
        
    }

    public void parentMethod2() {

    }
    
    public void parentMethod3(int a, int b) {
        
    }
}

class ExampleChild extends ExampleParent {
    
    @Override
    public void parentMethod1() {
        // Override parent method
        // Do something else and continue with original parentMethod
        super.parentMethod1();
    }

    @Override
    public void parentMethod2() {
        // Override parent method
    }
    
    private void childMethod(int a, int b) {
        // Use parent function in child wrapper
        return super.parentMethod3(a, b);
    } 
}
```

ES5 Javascript implementation

```javascript
const ExampleParent = function () {

    const self = this; // keep the context

    self.p = {/*protected function*/};
    
    self.p.parentMethod1 = function () {

    };
    
    self.p.parentMethod2 = function() {
        
    };
    
    self.parentMethod3 = function(a, b) {
        
    };
};

const ExampleChild = function () {

    const self = this;

    ExampleParent.call(self); // Inherit
    
    const _parentMethod1 = self.p.parentMethod1
    self.p.parentMethod1 = function(){
        // Override parent method
        // Do something else and continue with original parentMethod
        _parentMethod1.call(self);
    };
    
    self.p.parentMethod2 = function() {
        // Override parent method
    };

    const _childMethod = function() {
        // Use parent function in child wrapper
        return self.parentMethod3(a, b);
    };

};
```

This is the end of the tutorial. Happy buidling!


# Smart Contract

## Introduction to Zetrix Smart Contract

### Overview

Zetrix smart contracts are written in standard JavaScript (ECMAScript as defined in ECMA-262) and follow a structured format. Each contract includes an `init` function for initialization, a `main` function as the primary execution entry point, and a `query` function for retrieving data. These functions accept parameters as stringified input when invoked, enabling controlled and predictable contract behavior within the Zetrix execution environment.

The following is a simple example:

```javascript
"use strict";
function init(input)
{
  /*init whatever you want*/
  return;
}

function main(input)
{
  let para = JSON.parse(input);
  if (para.do_foo)
  {
    let x = {
      'hello' : 'world'
    };
  }
}

function query(input)
{ 
  return input;
}
```

### Objects in the Interfaces

In Zetrix smart contracts, the global objects `Chain` and `Utils` are provided to facilitate blockchain interaction. These objects offer a range of methods and variables that allow contracts to access blockchain state data and initiate transactions. While they support operations such as querying balances, issuing assets, and logging transactions, they do not handle account-level configurations like setting thresholds or weights.

> **Note:** Custom variables in Zetrix smart contracts must not use the same names as built-in objects (e.g., `Chain`, `Utils`). Doing so can lead to unpredictable behavior and data conflicts, potentially resulting in execution errors or corrupted contract logic. Always use unique and clearly defined variable names to maintain contract integrity.

#### Method Usage

Object. method (variable)

* Obtain the account balance

  ```javascript
  Chain.getBalance('ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE');
  ```
* Print logs

  ```javascript
  Utils.log('hello');
  ```
* The current block number

  ```javascript
  Chain.block.number;
  ```

#### Read and Write Privileges

1. Each function within the `Chain` and `Utils` objects in Zetrix smart contracts is assigned a fixed permission level—either **read-only** or **write**:
   * **Read-Only Functions**: These do not modify blockchain state. Examples include `Chain.getBalance`, which retrieves an account’s balance.
   * **Write Functions**: These modify blockchain data. For instance, `Chain.payCoin` performs token transfers and writes to the ledger.
2. When developing smart contracts, it's important to observe function call permissions based on the contract entry point:
   * The `init` and `main` functions can invoke both read-only and write operations.
   * The `query` function is restricted to read-only calls. Attempting to execute a write operation within `query` will result in an "undefined" error during execution or debugging.

#### Return Value

When invoking an internal function in a Zetrix smart contract, the function should return `false` upon failure or throw an exception to terminate execution. Successful execution continues normally for other objects. If a parameter error occurs, the error message will specify the index of the faulty parameter starting from 0. For example, if the message indicates “parameter 1,” it means the second parameter in the function call is incorrect. This helps developers quickly identify and correct input issues during contract development or debugging.

The following is an example:

```javascript
Chain.issueAsset("CNY", 10000);
/*
    Error description:
    Contract execute error,issueAsset parameter 1 should be a string

    It means that the second parameter should be a string
*/
```

The next section will explain in detail the APIs available when writing smart contract on Zetrix.


# API References

### Methods of the Chain Object

This section describes some methods of the Chain object, including:

Chain.load, Chain.store, Chain.del, Chain.getBlockHash, Chain.tlog, Chain.getAccountMetadata, Chain.getBalance, Chain.getAccountAsset, Chain.getContractProperty, Chain.payCoin, Chain.issueAsset, Chain.payAsset, Chain.delegateCall, Chain.delegateQuery, Chain.contractCall, Chain.contractQuery, and Chain.contractCreate.

#### Chain.load

* Description

  Get the metadata information of the contract account.
* Function call

```javascript
Chain.load(metadata_key);
```

* Parameter description
  * Metadata\_key: The keyword for metadata.
* Example

  ```javascript
  let value = Chain.load('abc');
  /*
    
    Permission: Read-only.
    Return value: Return a string if it succeeds, such as 'values'; return false if it fails.
  */
  ```

#### Chain.store

* Description

  Store the metadata information of the contract account.
* Function call

  ```javascript
  Chain.store(metadata_key, metadata_value);
  ```
* Parameter description
  * metadata\_key: The keyword for metadata.
  * metadata\_key: The content of metadata.
* Example

  ```javascript
  Chain.store('abc', 'values');
  /*
    Permission: Write
    Return value: Return true if it succeeds, or throw an exception if it fails
  */
  ```

#### Chain.del

* Description

  Delete the metadata information of the contract account.
* Function call

  ```javascript
  Chain.del(metadata_key);
  ```
* Parameter description
  * metadata\_key: The keyword for metadata.
  * metadata\_key: The metadata content.
* Example

  ```javascript
  Chain.del('abc');
  /*
    Permission: Write
    Return: Return true if it succeeds, or throw an exception if it fails
  */
  ```

#### Chain.getBlockHash

* Description

  Get block information.
* Function call

  ```javascript
  Chain.getBlockHash(offset_seq);
  ```
* Parameter description
  * offset\_seq: The offset from the last block ranges: \[0,1024).
* Example

  ```javascript
  let ledger = Chain.getBlockHash(4);
  /*
    Permission: Read-only
    Return value: Return a string if it succeeds, such as'c2f6892eb934d56076a49f8b01aeb3f635df3d51aaed04ca521da3494451afb3', or return false if it fails
  */
  ```

#### Chain.tlog

* Description

  Output transaction logs.
* Function call

  ```javascript
  Chain.tlog(topic,args...);
  ```
* Parameter description
  * tlog will generate a transaction written on the block.
  * topic: The log subject, which must be a string type with a parameter length of (0,128].
  * args...: It can contain up to 5 parameters, which can be string, numeric or Boolean type, with each parameter length (0,1024].
* Example

  ```javascript
  Chain.tlog('transfer',sender +' transfer 1000',true);
  /*
    Permission: Write
    Return value: Return true if it succeeds, or throw an exception if it fails
  */
  ```

#### Chain.getAccountMetadata

* Description

  Get the metadata of the specified account.
* Function call

  ```javascript
  Chain.getAccountMetadata(account_address, metadata_key);
  ```
* Parameter description
  * account\_address: The account address.
  * metadata\_key: The keyword for metadata.
* Example

  ```javascript
  let value = Chain.getAccountMetadata('ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE', 'abc');

  /*
    Permission: Read-only
    Return value: Return a string if it succeeds, such as 'values', or return false if it fails.
  */
  ```

#### Chain.getBalance

* Description

  Get the coin amount of the account.
* Function call

  ```javascript
  Chain.getBalance(address);
  ```
* Parameter description
  * address: The account address
* Example

  ```javascript
  let balance = Chain.getBalance('ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE');
  /*
    Permission: Read-only
    Return value: Number in string format '9999111100000'
  */
  ```

#### Chain.getAccountAsset

* Description

  Get asset information for an account
* Function call

  ```javascript
  Chain.getAccountAsset(account_address, asset_key);
  ```
* Parameter description
  * account\_address: The account address.
  * asset\_key: The asset attributes.
* Example

  ```javascript
  let asset_key =
  {
    'issuer' : 'ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE',
    'code' : 'CNY'
  };
  let bar = Chain.getAccountAsset('ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE', asset_key);

  /*
    Permission: Read-only
    Return value: Return the asset value such as '10000' if it succeeds, or return false if it fails
  */
  ```

#### Chain.getAccountPrivilege

* Description

  Get privilege info for an account.
* Function call

  ```javascript
  Chain.getAccountPrivilege(account_address);
  ```
* Parameter description
  * account\_address: The account address。
* Example

  ```javascript
  let bar = Chain.getAccountPrivilege('ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE');

  /*
    Permission: Read-only
    Return value: If it succeeds, the permission JSON string is returned, such as' {"master" weight ": 1," thresholds ": '{" TX "threshold": 1}}'. If it fails, the false is returned.
  */
  ```

#### Chain.getContractProperty

* Description

  Get the attributes of the contract account.
* Function call

  ```javascript
  Chain.getContractProperty(contract_address);
  ```
* Parameter description
  * contract\_address: The contract address.
* Example

  ```javascript
  let value = Chain.getContractProperty('ztxSgCwYLWoCZnP6s2WXtQCwhxuFxhvsr375z');

  /*
    Permission: Read-only
    Return value: Return a JSON object such as {"type":0, "length" : 416} if it succeeds, where the type refers to the contract type and the length refers to the code length of the contract, and if the account is not a contract, then the length is 0; return false if it fails.
    
  */
  ```

#### Chain.payCoin

* Description

  Transfer gas.
* Function call

  ```javascript
  Chain.payCoin(address, amount[, input]);
  ```
* Parameter description
  * address: The target address.
  * amount: The amount of Gas.
  * input: Optional, the contract parameter. By default, it is an empty string if it is not filled in.
* Example

  ```javascript
  Chain.payCoin("ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE", "10000", "{}");
  /*
    Permission: Write
    Return value: Return true if it succeeds, or throw an exception if it fails  
  */
  ```

#### Chain.issueAsset

* Description

  Issue assets.
* Function call

  ```javascript
  Chain.issueAsset(code, amount);
  ```
* Parameter description
  * code: The asset code.
  * amount: The amount of the asset to be issued.
* Example

  ```javascript
  Chain.issueAsset("CNY", "10000");
  /*
    Permission: Write
    Return value: Return true if it succeeds, or throw an exception if it fails  
  */
  ```

#### Chain.payAsset

* Description

  Transfer assets
* Function call

  ```javascript
  Chain.payAsset(address, issuer, code, amount[, input]);
  ```
* Parameter description
  * address: The target address.
  * issuer: The asset issuer.
  * code: The asset code.
  * amount: The amount to be transferred.
  * input: Optional, the contract parameter. By default, it is an empty string if it is not filled in.
* Example

  ```javascript
  Chain.payAsset("ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE", "ztxSj9kGyXR2YpyxwZVMrnGcLWoG3Hf9qXne8", "CNY", "10000", "{}");
  /*
    Permission: Write
    Return value: Return true if it succeeds, or throw an exception if it fails    
  */
  ```

#### Chain.delegateCall

* Description

  Delegate call.
* Function call

  ```javascript
  Chain.delegateCall(contractAddress, input);
  ```
* Parameter description

  * contractAddress: The address of the contract to be called.
  * input：Input parameter.

  The `Chain.delegateCall` function will trigger the `main` function of the contract to be called, and the Chain.delegateCall function will assign the execution environment of the current contract to the contract to be called.
* Example

  ```javascript
  let ret = Chain.delegateCall('ztxSgGkHuPv6FQUu6C5uWnaqyKJ22bSNrJUCJ'，'{}');
  /*
    Permission: Write
    Return value: Return a result if it succeeds, or throw an exception if it fails.
  */
  ```

#### Chain.delegateQuery

* Description

  Delegate query.
* Function call

  ```javascript
  Chain.delegateQuery(contractAddress, input);
  ```
* Parameter description

  * contractAddress: The address of the contract to be called.
  * input：Input parameter.

  The `Chain.delegateQuery` function will trigger the `query` function of the contract to be called, and the Chain.delegateQuery function will assign the execution environment of the current contract to the contract to be called.
* Example

  ```javascript
  let ret = Chain.delegateQuery('ztxSgGkHuPv6FQUu6C5uWnaqyKJ22bSNrJUCJ'，"");
  /*
    Permission: Read-only
    Return value: If the target account is a normal account, it returns true. If the target account is a contract, and the call succeeds, the string {"result":"4"} is returned, where the value of the result field is the specific result of the query, and if the call fails return {"error ":true} string.
  */
  ```

#### Chain.contractCall

* Description

  Call contracts.
* Function call

  ```javascript
  Chain.contractCall(contractAddress, asset, amount, input);
  ```
* Parameter description

  * contractAddress: The address of the contract to be called
  * asset: The asset class, true for Gas, object {"issue": adxxx, "code" : USDT} for assets.
  * amount: The amount of the asset.
  * input：Input parameter.

  The `Chain.contractCall` function triggers the `main` function entry of the contract to be called.
* Example

  ```javascript
  let ret = Chain.contractCall('ztxSgGkHuPv6FQUu6C5uWnaqyKJ22bSNrJUCJ'，true, toBaseUnit("10"), "");
  /*
    Permission: Write
    Return value: Return true if the target account is a normal account. If the target account is a contract, the return value of the main function is returned if the call succeeds, and an exception is thrown if the call fails.
  */
  ```

#### Chain.contractQuery

* Description

  Query contracts.
* Function call

  ```javascript
  Chain.contractQuery(contractAddress, input);
  ```
* Parameter description

  * contractAddress: The address of the contract to be called
  * input：Input parameter.

  The `Chain.contractQuery` function will call the `query` interface of the contract.
* Example

  ```javascript
  let ret = Chain.contractQuery('ztxSgGkHuPv6FQUu6C5uWnaqyKJ22bSNrJUCJ'，"");
  /*
    Permission: Read-only
    Return value: If the call succeeds, the string {"result":"xxx"} is returned, where the value of the result field is the specific result of the query, and if the call fails, return a string of {"error":true}.
  */
  ```

#### Chain.contractCreate

* Description

  Create Contracts.
* Function call

  ```javascript
  Chain.contractCreate(balance, type, code, input);
  ```
* Parameter description

  * balance: The asset that is transferred to the contract created, in string.
  * type :0 indicates javascript, in integer.
  * code: The contract code, in string.
  * input：The initiation parameter of the init function.

  The `Chain.contractCreate` function create contracts.
* Example

  ```javascript
  let ret = Chain.contractCreate(toBaseUnit("10"), 0, "'use strict';function init(input){return input;} function main(input){return input;} function query(input){return input;} ", "");
  /*
    Permission: Write
    Return value: Return the contract address if it is created successfully, or throw an exception if it fails.
  */
  ```

### Variables of the Chain Object

This section outlines key variables provided by the `Chain` object in Zetrix smart contracts, which offer access to contextual blockchain, transaction, and message-level data:

#### Chain.block

* The `Chain.block` object enables smart contracts to make decisions based on the current blockchain state, ensuring time-sensitive and sequence-sensitive logic executes reliably.

**Chain.block.timestamp**

* Variable description

  The timestamp of the block when the current transaction is executed.

**Chain.block.number**

* Variable description

  The height of the block where the current transaction is executed.

Chain.tx

* Variable description

  The transaction information signed by the user at the time of the transaction.

**Chain.tx.initiator**

* Variable description

  The original originator of the transaction, that is the fee payer of the transaction.

**Chain.tx.sender**

* Variable description

  The most primitive trigger of the transaction, that is the account in the transaction that triggers the execution of the contract. For example, an account initiates a transaction, and an operation in the transaction is to call the contract Y (the source\_address of the operation is x), then the value of the sender is the address of the account x during the execution of the contract Y.
* Example

  ```javascript
  let bar = Chain.tx.sender;
  /*  
   Then the value of bar is the account address of x.
  */
  ```

**Chain.tx.gasPrice**

* Variable description

  The price of the gas in the transaction signature.

**Chain.tx.hash**

* Variable description

  The hash value of the transaction.

**Chain.tx.feeLimit**

* Variable description

  The limit fee for the transaction.

#### Chain.msg

A **message** in Zetrix smart contracts refers to the contextual data that initiates contract execution within a transaction. While the **transaction data remains immutable** during execution, the **message object (`Chain.msg`) can be updated** as the contract interacts with other contracts. For instance, when using functions like `Chain.contractCall` or `Chain.contractQuery`, the message context switches to reflect the called contract’s perspective. This allows the contract to correctly process the execution flow and maintain state awareness across inter-contract interactions.

**Chain.msg.initiator**

* Variable description

  The original originator account for this message.

**Chain.msg.sender**

* Variable description

  The account number for triggering this message.
* Example

  For example, an account initiates a transaction, and an operation in the transaction is to call the contract Y (the source\_address of the operation is x), then the value of the sender is the address of the account x during the execution of the contract Y.

  ```javascript
  let bar = Chain.msg.sender;
  /*
  Then the value of bar is the account address of x.
  */
  ```

**Chain.msg.coinAmount**

* Variable description

  The Gas for this payment operation

**Chain.msg.asset**

* Variable description

  The assets for this payment operation
* Example

  ```json
  {
      "amount": 1000, 
      "key" : {
          "issuer": "ztxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE", 
          "code":"CNY"
      }
  }
  ```

**Chain.msg.nonce**

* Variable description

  The nonce value of the initiator in this transaction, ie the nonce value of the Chain.msg.initiator account.

**Chain.msg.operationIndex**

* Variable description

  The sequence number for triggering this contract calling operation.
* Example

  For example, an account A initiates a transaction tx0, and tx0 has a 0th (counting from 0) operation which is to transfer assets to a contract account (contract call), then the value of `Chain.msg.operationIndex` is 0.

  ```javascript
  let bar = Chain.msg.operationIndex;
  /* bar is a non-negative integer*/
  ```

#### Chain.thisAddress

* Variable description

  The address of the current contract account.
* Example

  For example, the account x initiates a transaction to call contract Y. During this execution, the value is the address of the contract account Y.

  ```js
  let bar = Chain.thisAddress;
  /*
   The value of bar is the account address of the contract Y.
  */
  ```

### Methods of the Utils Object

The `Utils` object in Zetrix smart contracts provides a comprehensive set of utility functions that assist in logging, mathematical operations, cryptographic verification, and data validation. These methods are essential for ensuring accurate, secure, and efficient smart contract execution. The `Utils` object includes the following methods:

Utils.log, Utils.stoI64Check, Utils.int64Add, Utils.int64Sub , Utils.int64Mul, Utils.int64Mod, Utils.int64Div, Utils.int64Compare, Utils.assert, Utils.sha256, Utils.ecVerify, Utils.toBaseUnit, Utils.addressCheck and Utils.toAddress.

#### Utils.log

* Description
  * `Utils.log(message)`: Outputs logs for debugging purposes during contract execution.
* Function call

  ```javascript
  Utils.log(info);
  ```
* Parameter description
  * info: The log content.
* Example

  ```javascript
  let ret = Utils.log('hello');
  /*
    Permission: Read-only
    Return value: If it succeeds, no value will be returned, and a snippet of Trace log will be output in the process of executing the contract, such as V8contract log[adxSnBFboATCEgbiDRYS7gfbe1XRsTPWJhCFE:hello], or return false if it fails.
  */
  ```

#### Utils.stoI64Check

* Description

  Legal check for string numerics.
* Function call

  ```javascript
  Utils.stoI64Check(strNumber);
  ```
* Parameter description
  * strNumber: String numeric parameter
* Example

  ```javascript
  let ret = Utils.stoI64Check('12345678912345');
  /*
    Permission: Read-only
    Return value: Return true if it succeeds, or return false if it fails.
  */
  ```

#### Utils.int64Add

* Description

  256-bit addition.
* Function call

  ```javascript
  Utils.int64Add(left_value, right_value);
  ```
* Parameter description
  * left\_value: Left value.
  * right\_value: Right value.
* Example

  ```javascript
  let ret = Utils.int64Add('12345678912345', 1);
  /*
    Permission: Read-only
    Return value: Return a string if it succeeds, such as '12345678912346', or throw an exception if it fails.
  */
  ```

#### Utils.int64Sub

* Description

  256-bit subtraction.
* Function call

  ```javascript
  Utils.int64Sub(left_value, right_value);
  ```
* Parameter description
  * left\_value: Left value.
  * right\_value：Right value.
* Example

  ```javascript
  let ret = Utils.int64Sub('12345678912345', 1);
  /*
    Permission: Read-only
    Return value: Return a string such as '12345678912344' if it succeeds, or throw an exception if it fails.
  */
  ```

#### Utils.int64Mul

* Description

  256-bit multiplication.
* Function call

  ```javascript
  Utils.int64Mul(left_value, right_value);
  ```
* Parameter description
  * left\_value: Left value.
  * right\_value：Right value.
* Example

  ```javascript
  let ret = Utils.int64Mul('12345678912345', 2);
  /*
    Permission: Read-only
    Return value: Return a string such as '24691357824690' if it succeeds, or throw an exception if it fails.
  */
  ```

#### Utils.int64Mod

* Description

  256-bit modulo.
* Function call

  ```javascript
  Utils.int64Mod(left_value, right_value);
  ```
* Parameter description
  * left\_value: Left value.
  * right\_value: Right value.
* Example

  ```javascript
  let ret = Utils.int64Mod('12345678912345', 2);
  /*
    Permission: Read-only
    Return value: Return a string such as '1' if it succeeds, or throw an exception if it fails.
  */
  ```

#### Utils.int64Div

* Description

  256-bit division.
* Function call

  ```javascript
  Utils.int64Div(left_value, right_value);
  ```
* Parameter description
  * left\_value: Left value.
  * right\_value: Right value.
* Example

  ```javascript
  let ret = Utils.int64Div('12345678912345', 2);
  /*
    Permission: Read-only
    Return value: Return '6172839456172' if it succeeds, or throw an exception if it fails.
  */
  ```

#### Utils.int64Compare

* Description

  256-bit comparison.
* Function call

  ```javascript
  Utils.int64Compare(left_value, right_value);
  ```
* Parameter description
  * left\_value: Left value.
  * right\_value: Right value.
* Example

  ```javascript
  let ret = Utils.int64Compare('12345678912345', 2);
  /*
    Permission: Read-only
    Return value: Return 1 if it succeeds (the left value is greater than the right value), or throw an exception if it fails.
  */
  ```
* Return value

  1: left value is greater than right value, 0: left value equals to right value, -1: left value less than right value.

#### Utils.assert

* Description

  256 assertion.
* Function call

  ```javascript
  Utils.assert(condition[, message]);
  ```
* Parameter description
  * condition: Assertive variable
  * message: Optional, an exception message is thrown when it fails
* Example

  ```javascript
  Utils.assert(1===1, "Not valid");
  /*
    Permission: Read-only
    Return value: Return true if it succeeds, or throw an exception if it fails  
  */
  ```

#### Utils.sha256

* Description

  sha256 computation.
* Function call

  ```javascript
  Utils.sha256(data[, dataType]);
  ```
* Parameter description
  * data: The raw data of the hash to be calculated. According to the dataType, fill in the data in different formats.
  * dataType: The data type, integer, optional field, by default is 0. 0: base16 encoded string, such as "61626364"; 1: ordinary original string, such as "abcd"; 2: base64 encoded string, such as "YWJjZA==". If you are calculating binary data, it is recommended to use base16 or base64 encoding.
* Return value

  Return a base16 encoded string if it succeeds, or return false if it fails.
* Example

  ```javascript
  let ret = Utils.sha256('61626364');
  /*
    Permission: Read-only
    Function: Right
    Return value: Return a 64-byte base16 string if it succeeds, such as '88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589', or return false it fails.
  */
  ```

#### Utils.ecVerify

* Description

  Check if the signature is legal.
* Function call

  ```javascript
  Utils.ecVerify(signedData, publicKey,blobData [, blobDataType]);
  ```
* Parameter description
  * signedData: The signature data, a string encoded by base16.
  * publicKey: The public key, a string encoded by base16.
  * blobData: The raw data, fill in different formats of data per blobDataType.
  * blobDataType: The blobData type, integer, optional field, the default is 0. 0: base16 encoded string, such as "61626364"; 1: ordinary original string, such as "abcd"; 2: base64 encoded string, such as "YWJjZA==". If you are verifying binary data, it is recommended to use base16 or base64 encoding.
* Return value

  Return true if it succeeds, or return false if it fails.
* Example

  ```javascript
  let ret = Utils.ecVerify('3471aceac411975bb83a22d7a0f0499b4bfcb504e937d29bb11ea263b5f657badb40714850a1209a0940d1ccbcfc095c4b2d38a7160a824a6f9ba11f743ad80a', 'b0014e28b305b56ae3062b2cee32ea5b9f3eccd6d738262c656b56af14a3823b76c2a4adda3c', 'abcd', 1);
  /*
    Permission: Read-only
    Return value: Return true if it succeeds, or return false if it fails
  */
  ```

#### Utils.toBaseUnit

* Description

Transform the unit.

* Function call

  ```javascript
  Utils.toBaseUnit(value);
  ```
* Parameter description
  * value: The converted number, only string is allowed to pass in, and it can contain a decimal point, which allows up to 6 digits after the decimal point.
* Return value

  Return a string multiplied by 10^6 if it succeeds or return false if it fails.
* Example

  ```javascript
  let ret = Utils.toBaseUnit('12345678912');
  /*
    Permission: Read-only
    Return value: Return a string '1234567891200000000' if it succeeds, or throw an exception if it fails.
  */
  ```

#### Utils.addressCheck

* Description

  Address legality check.
* Function call

  ```javascript
  Utils.addressCheck(address);
  ```
* Parameter description
  * address The address parameter in string.
* Return value

  Return true if it succeeds, or return false if it fails.
* Example

  ```javascript
  let ret = Utils.addressCheck('ztxSj9kGyXR2YpyxwZVMrnGcLWoG3Hf9qXne8');
  /*
    Permission: Read-only
    Return value: Return true if it succeeds, or return false if it fails.
  */
  ```

#### Utils.toAddress

* Description

  Transform a public key to an address.
* Function call

  ```javascript
  Utils.toAddress(public_key);
  ```
* Parameter description
  * public\_key The public key, a base16 encoded string
* Return value

  Return the account address if it succeeds, or return false if it fails.
* Example

  ```javascript
  let ret = Utils.toAddress('b0016ebe6191f2eb73a4f62880b2874cae1191183f50e1b18b23fcf40b75b7cd5745d671d1c8');
  /*
    Permission: Read-only
    Return value: Return "adxSkMvC2RcvXLpDgXBJCSb4m9mPe8gpNDKAG" if it succeeds, or return false if it fails.
  */
  ```

#### Utils.bcRangeProofVerify

* Description

  Verifying the certificate for scope (for privacy protection).
* Function call

  ```javascript
  Utils.bcRangeProofVerify(commit, proof);
  ```
* Parameter description
  * commit, 66 bit Pedersen commitment string
  * proof, Range proof string, variable length
* Return value

  Return true if it succeeds, or return false if it fails.
* Example

  ```javascript
  let ret = Utils.bpRangeProofVerify('097ff10254037114cae985f044189a3faa044ac32c26ffadc0f08dc4b81a536638', '410905f651c9448e8a4e6db10c0bc23b2b09cf37ee2b6909b0e9178cf89b371584ea8533ed9648a942feb6b797bbdd8e9cd49ab8a86e6bf89f7e3b2c35c01818ad9006329e8dc4c9e335d60021b13c33c8aa8bd471908be4ce74a4cdfe968006abc3819e9e7d0aba261b947ed9bd8706d439707e783e34323c7c24b7c3dd722b66546f5c0d7c66d6c5a7390cc4cd1ed4ef53a0b1db3778a56b0ff418bfcababd966ae82cf0f44c29ba27f9eaa0a9ca1b4c913ddb7e42453666ccfbaad55f981b8cbede5023705cfeb08a26b323ea05b06ba3853cbfe02315c335f742c6a4ca290ca3d31a619534a38fc0754a6b52b9b66e69088a6265a0e68914b1a230bbd6d742875aac47259be01d60fff5c301c552a66b81152b2b2d7dca9064cde271690e30a7cae5fee6b89e0bd7a5c571d561f65a7d34cb4f5aba49fbeef91132e229fdf38ca61c2c737d3055ea143d0e5732b43ade6d7cf66269c7b3333f1ee9a295fc7f5d3cf47770d9a15651d176fa2792e39ad4bdacb14eb13657faf5eed43f3620a09441a5032c4919744692844a214455204662e9f7f80c88a569ab1a1986186f35a0eefd53d7be56d1150ed6a0cb030a10de35d0cb25738d66234646998b70dc6210ec8985c9bda183dd0a0d985c1bf1255afc326fd86029bc88e2db0433061a0bf6be107d6ddebb2516843b9c6a56f9e03a420e4665bc013f7e6a497412015d4fed2cf9895c756857d5434799e20fbf8feef4473c778bd06fc997ea9772bec1d0cc30870580575017239cef0f693922c12a1ab850628302f970d07caaa54196c5ed59eefaaad981dfeeef4efe06d5ab3634b8e9882416cde960dee25f22701faf63086771d2987e3b300659278cc9e8543ee81c9f70ebbe2897f1020c609b3fe1667358b5998dbf089720cecc401810acbb48864262065c7742c5cd2b83b76aafc6ff2428e51a66e89ca1b1cf552bb8f8a261fb2e91e49ea68fc2db1c00a079bf2b0b39c9f43be25d31136399666ff05dcbbbc98d47358a5052c0d3cd113f9f0a3fe6838babd160411f22d6a187f73b69e45f042149e7e1e879a8b75c6ac4dfa4bbb473f22f89738f163f2a64efb20a0bb67e16acd06791080cc5246d48887a158f8b');
  /*
    Permission: Read-only
    Return value: Return true if it succeeds, or return false if it fails.
  */
  ```

#### Utils.pedersenTallyVerify

* Description

  Verifying the equal for Output and input (for privacy protection).
* Function call

  ```javascript
  Utils.pedersenTallyVerify(input_commits, output_commits, excess_msg, excess_sig);
  ```
* Parameter description
  * input\_commits, Enter Pedersen commitment list, JSON array
  * output\_commits, Output Pedersen commitment list, JSON array
  * excess\_msg, Message to be signed, 32-bit string, no encoding requirements
  * excess\_sig, Signature result string of transaction core (input minus output remainder)
* Return value

  Return true if it succeeds, or return false if it fails.
* Example

  ```javascript
  let ret = Utils.pedersenTallyVerify(['08aab3b3c403129887d1f5932565c0fd9ef7b8d562de6eb0b6eb64c1b7396d268a'], ['08a64f2ed7be3940dfb5b76b450418524df48837595c98698dbe191708cb911c40', '09c28bb504d0c4e4ea4f19e3041a90b608aada114fab1786175ffaefd5fe6c0d3b'], 'b649bd965a5126984cc785cbeb1ef053', '304402202345c4e1f4efd8bfdb77681e7d638f9a8f29f473e47a698c56eeab3fe3bc278502206bbdf0db0e04bafa4a88c0382b9b600e72976fceeaa9129cb257a82a89ee52fb');
  /*
    Permission: Read-only
    Return value: Return true if it succeeds, or return false if it fails.
  */
  ```

### **Exception Handling in Zetrix Smart Contracts**

Zetrix smart contracts use JavaScript-style exception handling. When an exception occurs and is not caught during execution, it triggers specific failure behavior defined by the blockchain environment.

**JavaScript Exceptions**

* If an **uncaught exception** occurs during contract execution:
  * The **entire contract execution fails**.
  * **All state changes and transactions** initiated by the contract are **reverted**—nothing takes effect.
  * The transaction that triggered the contract is marked as **failed**, and an error code **151** is returned to indicate the failure.

**Transactional Integrity**

* A contract may initiate **multiple internal transactions** (e.g., transfers, state updates).
* If **any single transaction** within the contract fails, it throws an exception.
* This causes the **entire contract execution to abort**, and all previous operations in that call are **rolled back**, ensuring atomicity.

**Implication**

* Developers must use `try-catch` logic and proper assertions (`Utils.assert`) to validate conditions and handle potential failures gracefully.
* Failing to do so will result in complete transaction failure, impacting contract reliability and user experience.

This strict exception handling ensures **consistency, security, and predictability** in the Zetrix smart contract environment.


# ZTP Standard


# ZTP-20

## Simple Summary

A standard interface for tokens.

## Abstract

The following standard allows for the implementation of a standard API for tokens within smart contracts. This standard provides basic functionality to transfer tokens, as well as allow tokens to be approved so they can be spent by another on-chain third party.

## Motivation

A standard interface allows any tokens on Zetrix to be re-used by other applications: from wallets to decentralized exchanges.

## Specification Token Methods

## Metadata

### name

Returns the name of the token - e.g. `"MyToken"`

OPTIONAL - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present.

```javascript
self.name = function(paramObj) {
    let name = ...;
    return name;
};
```

**Query Example**

To get the token name, use the following request and expect the response below:

**Request:**

```json
{
    "method": "name"
}
```

**Response:**

```json
{
    "name": "MyToken"
}
```

**Sample** `query` **Function:**

```javascript
function query(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "name") {
                ret = { "name": self.name(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### symbol

Returns the symbol of the token. E.g. `“MYTKN”`

OPTIONAL - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present.

```javascript
self.symbol = function(paramObj) {
    let symbol = ...;
    return symbol;
};
```

**Query Example**

To get the token symbol, use the following request and expect the response below:

**Request:**

```json
{
    "method": "symbol"
}
```

**Response:**

```json
{
    "symbol": "MYTKN"
}
```

**Sample** `query` **Function:**

```javascript
function query(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "symbol") {
                ret = { "symbol": self.symbol(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### decimals

Returns the number of decimals the token uses - e.g. `6`, means to divide the token amount by `1000000` to get its user representation.

```javascript
self.decimals = function(paramObj) {
    let decimals = ...;
    return decimals;
};
```

**Query Example**

To get the token decimals, use the following request and expect the response below:

**Request:**

```json
{
    "method": "decimals"
}
```

**Response:**

```json
{
    "decimals": "6"
}
```

**Sample** `query` **Function:**

```javascript
function query(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "decimals") {
                ret = { "decimals": self.decimals(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

## Core

### totalSupply

Returns the total token supply.

```javascript
self.totalSupply = function(paramObj) {
    let totalSupply = ...;
    return totalSupply;
};
```

**Query Example**

To get the total token supply, use the following request and expect the response below:

**Request:**

```json
{
    "method": "totalSupply"
}
```

**Response:**

```json
{
    "totalSupply": "1000"
}
```

**Sample** `query` **Function:**

```javascript
function query(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "totalSupply") {
                ret = { "totalSupply": self.totalSupply(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### balanceOf

Returns the account balance of another account with address `account`.

```javascript
self.balanceOf = function(paramObj) {
    let balance = ...;
    return balance;
};
```

**Query Example**

To get the balance of an account, use the following request and expect the response below:

**Request:**

```json
{
    "method": "balanceOf",
    "params": { "address": "ZTX3abc123..." }
}
```

**Response:**

```json
{
    "balance": "500"
}
```

**Sample** `query` **function:**

```javascript
function query(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "balanceOf") {
                ret = { "balance": self.balanceOf(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### transfer

Transfers `value` amount of tokens to address `to`. The function SHOULD throw an exception if the message caller’s account balance does not have enough tokens to spend.

```javascript
self.transfer = function(paramObj) {
    let transfer = ...;
    return transfer;
};
```

**Submit** `transfer` **Example**

To transfer tokens, use the following request and expect the response below:

**Request:**

```json
{
    "method": "transfer",
    "params": { "to": "ZTX3to...", "value": "100" }
}
```

**Response:**

```json
{
   "results" : [
      {
         "error_code" : 0,
         "error_desc" : "",
         "hash" : "caa80.......395f9"
      }
   ],
   "success_count" : 1
}
```

**Sample** `main` **Function:**

```javascript
function main(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "transfer") {
                ret = { "transfer": self.transfer(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### transferFrom

Transfers `value` amount of tokens from address `from` to address `to`.

The `transferFrom` method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. The function SHOULD throw an exception unless the `from` account has deliberately authorized the sender of the message.

```javascript
self.transferFrom = function(paramObj) {
    let transferFrom = ...;
    return transferFrom;
};
```

**Submit** `transferFrom` **Example**

To transfer tokens from another account, use the following request and expect the response below:

**Request:**

```json
{
    "method": "transferFrom",
    "params": { "from": "ZTX3from...", "to": "ZTX3to...", "value": "100" }
}
```

**Response:**

```json
{
   "results" : [
      {
         "error_code" : 0,
         "error_desc" : "",
         "hash" : "caa80.......395f9"
      }
   ],
   "success_count" : 1
}
```

**Sample** `main` **Function:**

```javascript
function main(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "transferFrom") {
                ret = { "transferFrom": self.transferFrom(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### approve

Allows `spender` to withdraw from your account multiple times, up to the `value` amount. If this function is called again it overwrites the current allowance with `value`.

```javascript
self.approve = function(paramObj) {
    let approve = ...;
    return approve ;
};
```

**Submit** `approve` **Example**

To approve a spender, use the following request and expect the response below:

**Request:**

```json
{
    "method": "approve",
    "params": { "spender": "ZTX3spender...", "value": "100" }
}
```

**Response:**

```json
{
   "results" : [
      {
         "error_code" : 0,
         "error_desc" : "",
         "hash" : "caa80.......395f9"
      }
   ],
   "success_count" : 1
}
```

**Sample** `main` **Function:**

```javascript
function main(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "approve") {
                ret = { "approve": self.approve(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

### allowance

Returns the amount which `spender` is still allowed to withdraw from `owner`.

```javascript
self.allowance = function(paramObj) {
    let allowance = ...;
    return allowance;
};
```

**Query** `allowance` **Example**

To check the allowance for a spender, use the following request and expect the response below:

**Request:**

```json
{
    "method": "allowance",
    "params": { "owner": "ZTX3owner...", "spender": "ZTX3spender..." }
}
```

**Response:**

```json
{
    "allowance": "200"
}
```

**Sample** `main` **Function:**

```javascript
function main(input_str) {
        let inputObj = JSON.parse(input_str);
        let ret = {};
        if (inputObj.method === "allowance") {
                ret = { "allowance": self.allowance(inputObj.params) };
        }
        return JSON.stringify(ret);
}
```

## Extension

### Permit

The `permit` function enables **gasless approvals** for ZTP20 tokens by allowing an owner to approve a spender via an **off-chain signature**, instead of an on-chain `approve` transaction. This design is inspired by **EIP-2612**, adapted for the Zetrix / ZTP20 execution environment and cryptographic primitives.

The `permit` mechanism allows a token holder to approve an allowance via an off-chain signature, which may subsequently be submitted on-chain by any relayer that pays the associated transaction fee.

### Function Signature

```javascript
const PERMIT_TYPEHASH = Utils.sha256("Permit(owner,spender,value,nonce,deadline)", 1);

function permit(owner, spender, value, deadline, p, s) {
  // 1. Basic input validation
  Utils.assert(Utils.addressCheck(owner) === true, "Arg-owner is not a valid address.");
  Utils.assert(Utils.addressCheck(spender) === true, "Arg-spender is not a valid address.");
  Utils.assert(Utils.stoI64Check(value) === true, "Arg-value must be alphanumeric.");
  Utils.assert(Utils.int64Compare(value, "0") >= 0, "Arg-value must be >= 0.");
  Utils.assert(Utils.stoI64Check(deadline) === true, "Arg-deadline must be alphanumeric.");
  Utils.assert(typeof p === "string" && p.length > 0, "Public key is required.");
  Utils.assert(typeof s === "string" && s.length > 0, "Signature is required.");
  Utils.assert(Utils.int64Compare(deadline, Chain.block.timestamp) >= 0, "Permit signature has expired.");

  // 2. Consume the owner's nonce (replay protection)
  let nonce = useNonce(owner);

  // 3. Domain separator — binds the signature to this contract on this chain
  //    chainId should be stored at init time (or via a one-time setChainId()) —
  //    see "Domain separator" note below.
  let domainSeparator = Utils.sha256(chainId + "|" + Chain.thisAddress, 1);

  // 4. Struct hash — the data being authorised, "|" delimited to remove all ambiguity
  let structHash = Utils.sha256(
    PERMIT_TYPEHASH + "|" +
    owner           + "|" +
    spender         + "|" +
    value           + "|" +
    nonce           + "|" +
    deadline,
    1
  );

  // 5. Final digest — domain applied at the outer layer, mirrors EIP-712
  let hash = Utils.sha256(domainSeparator + "|" + structHash, 1);

  // 6. Verify signature and signer identity
  let validateSign = Utils.ecVerify(s, p, hash);
  let validatePubKey = Utils.toAddress(p) === owner;
  Utils.assert(validateSign && validatePubKey, "Invalid permit signature.");

  // 7. Apply the approval
  let allowKey = makeAllowanceKey(owner, spender);
  Chain.store(allowKey, value);
  Chain.tlog("Approval", owner, spender, value);
  Chain.tlog("Permit", owner, spender, value, deadline);
  return true;
}
```

### Parameters

| Parameter  | Type             | Description                         |
| ---------- | ---------------- | ----------------------------------- |
| `owner`    | `address`        | Token holder granting the allowance |
| `spender`  | `address`        | Address receiving spending rights   |
| `value`    | `int64 (string)` | Allowance amount to approve         |
| `deadline` | `int64 (string)` | Expiration timestamp for the permit |
| `p`        | `bytes`          | Public key of the signer            |
| `s`        | `bytes`          | Signature generated by the owner    |

**Hash construction (what the owner actually signs off-chain)**

```js
PERMIT_TYPEHASH  = sha256("Permit(owner,spender,value,nonce,deadline)")
domainSeparator  = sha256(chainId + "|" + contractAddress)
structHash       = sha256(PERMIT_TYPEHASH + "|" + owner + "|" + spender + "|" + value + "|" + nonce + "|" + deadline)
hash        
```

**Domain separator — chain ID storage**

`chainId` must be available in contract storage before `permit()` can compute a domain separator. Recommended pattern:

```javascript
// init() — required for new deployments
Utils.assert(paramObj.chainId === "5687162" || paramObj.chainId === "1635227727", "Invalid chain ID.");
// ... store paramObj.chainId as part of contract_info

// setChainId() — one-time, for contracts deployed before this change adopt it
function setChainId(chainId) {
  validateOwner();
  Utils.assert(chainId === "5687162" || chainId === "1635227727", "Invalid chain ID.");
  let contractInfo = JSON.parse(Chain.load(CONTRACT_PRE));
  Utils.assert(contractInfo.chainId === undefined, "Chain ID already set.");
  contractInfo.chainId = chainId;
  Chain.store(CONTRACT_PRE, JSON.stringify(contractInfo));
  Chain.tlog("ChainIdSet", chainId);
  return true;
}
```

| Network | Chain ID     |
| ------- | ------------ |
| Mainnet | `5687162`    |
| Testnet | `1635227727` |

**Invoke Example**

The `permit` function is a main contract function (transaction/invoke), not a query. It is used to submit a transaction that enables gasless approval for a spender using an off-chain signature.

**Sample** `main` **function call:**

```javascript
if (input.method === 'permit') {
  permit(
    input.params.owner,
    input.params.spender,
    input.params.value,
    input.params.deadline,
    input.params.p,
    input.params.s
  );
}
```

**Sample request:**

```json
{
    "method": "permit",
    "params": {
        "owner": "ZTX3WeinXtt28YMyr4vUZ14ddTgEMGeuc1e6b",
        "spender": "ZTX3MVqzyhcYZJBnLa9do5ZqzHEUtT8KdhCsT",
        "value": "1000",
        "deadline": "1680000000",
        "p": "04bfc...e2a1",
        "s": "3045...0221"
    }
}
```

**`nonces(owner)` — query current nonce**

```javascript
function nonces(owner) {
  Utils.assert(Utils.addressCheck(owner) === true, "Arg-owner is not a valid address.");
  let nonceKey = makeNonceKey(owner);
  let nonce = Chain.load(nonceKey);
  return nonce === false ? "0" : nonce;
}
```

Callers must query this **before** constructing the off-chain hash, since `nonce` is part of `structHash` but is not a `permit()` parameter.

**Security Notes**

* **Front-running is expected, not a bug.** Anyone holding a valid `(p, s)` pair can submit it, this is inherent to EIP-2612-style meta-transactions. The outcome is always the value the owner signed; a front-runner cannot steal funds, only grief a combined `permit + transferFrom` flow by consuming the signature first. Integrators should check `allowance(owner, spender)` before calling `permit()` and skip it if already sufficient.
* **Signatures are single-use** because `nonce` is consumed on every successful `permit()` call, whether or not the caller supplied it, the contract reads it internally.
* **`deadline` must be validated against `Chain.block.timestamp`** before consuming the nonce or verifying the signature, so expired signatures fail fast.
* **Changing `chainId` invalidates all outstanding signatures** signed under the old value — treat it as a one-time, owner-only operation, not something toggled routinely.

***

## [Zetrix Ecosystem Proposals](https://github.com/Zetrix-Chain/zetrix-protocol)

***


# ZTP-165

## Introduction

### What is the Protocol ZTP-165

`ZTP165` provides a protocol standard similar to `ZEP165` and `ERC165` for detecting smart contract interfaces on the `ZTP` blockchain. It specifies how smart contracts can declare and validate their supported interfaces, ensuring compatibility and ease of integration between different smart contracts.

The `ZTP165` standard introduces a way for contracts on the ZTP blockchain to explicitly declare the interfaces they support. This allows other contracts to interact seamlessly with them, by querying supported interfaces and adjusting their functionality accordingly.

### **Protocol Overview**

#### **Interface Function**

Contracts implementing `ZTP165` must include the following function:

```javascript
const IZEP165 = {
  supportsInterface: function() {
    return this;
  }
};
```

#### **Support Interface Function**

```javascript
this.supportsInterface = function(interfaceId) {
    let iface1 = Utils.sha256(JSON.stringify(IZEP165), 1);
    let iface2 = Utils.sha256(JSON.stringify(IOptimismMintableZTP20), 1);
    return interfaceId === iface1 || interfaceId === iface2;
};
```

#### **Support Interface Validation in Init Function**

```javascript
function init(input_str) {
  let input = JSON.parse(input_str);

  Utils.assert(implementsInterface(OptimismMintableZTP20, IOptimismMintableZTP20), 'OptimismMintableZTP20 does not implement IOptimismMintableZTP20');
  Utils.assert(implementsInterface(OptimismMintableZTP20, IZEP165), 'OptimismMintableZTP20 does not implement IZEP165');

  return true;
}
```

#### **Usage**

```javascript
this.isOptimismMintableZTP20 = function (token) {
    let interfaceId = Utils.sha256(JSON.stringify(interfaceId), 1);
    let queryInput = {
        'method': 'supportsInterface',
        'params': {
            'interfaceId' : interfaceId
        }
    };

    let ret = Chain.contractQuery(token, JSON.stringify(queryInput));
    Utils.assert(ret !== false, 'Contract does not exist');

    if (ret.err === null && ret.error) {
        return false;
    }

    return JSON.parse(ret.result).data;
    
```

### Full ZTP-165 contract example:

```javascript
'use strict';

const IOptimismMintableZTP20 = {
  remoteToken: function() {
    return this;
  },
  bridge: function() {
    return this;
  },
  mint: function() {
    return this;
  },
  burn: function() {
    return this;
  }
};

const IZEP165 = {
  supportsInterface: function() {
    return this;
  }
};

function implementsInterface(obj, interfaceObj) {
  let keys = Object.keys(interfaceObj);
  let i;
  for (i = 0; i < keys.length; i += 1) {
    if (!obj.hasOwnProperty(keys[i]) || typeof obj[keys[i]] !== "function") {
      return false;
    }
  }
  return true;
}

const OptimismMintableZTP20Class = function() {
  this.remoteToken = function() {
    Chain.tlog('remoteToken1');
  };

  this.bridge = function() {
    Chain.tlog('bridge1');
  };

  this.mint = function() {
    Chain.tlog('mint1');
  };

  this.burn = function() {
    Chain.tlog('burn1');
  };

  this.supportsInterface = function(interfaceId) {
    let iface1 = Utils.sha256(JSON.stringify(IZEP165), 1);
    let iface2 = Utils.sha256(JSON.stringify(IOptimismMintableZTP20), 1);
    return interfaceId === iface1 || interfaceId === iface2;
  };
};

const OptimismMintableZTP20 = new OptimismMintableZTP20Class();

function init(input_str) {
  let input = JSON.parse(input_str);

  Utils.assert(implementsInterface(OptimismMintableZTP20, IOptimismMintableZTP20), 'OptimismMintableZTP20 does not implement IOptimismMintableZTP20');
  Utils.assert(implementsInterface(OptimismMintableZTP20, IZEP165), 'OptimismMintableZTP20 does not implement IZIP165');

  return true;
}

function main(input_str) {
  let input = JSON.parse(input_str);
  let params = input.params;

  let result = {};
  if (input.method === 'mint') {
    OptimismMintableZTP20Class.mint();
  } else {
    throw 'Unknown operating: ' + input.method + '.';
  }
  return JSON.stringify(result);

}

function query(input_str) {
  let input = JSON.parse(input_str);
  let params = input.params;

  let result = {};
  if (input.method === 'supportsInterface') {
    result.data = OptimismMintableZTP20.supportsInterface(params.interfaceId);
  } else {
    throw 'Unknown operating: ' + input.method + '.';
  }

  return JSON.stringify(result);
}
```


# ZTP-173

**ZTP-173** is the Zetrix Contract Ownership Standard, inspired by Ethereum's [ERC-173](https://eips.ethereum.org/EIPS/eip-173). It provides a standard interface for querying and transferring ownership of a smart contract on the Zetrix blockchain.

### Overview

| Property     | Detail             |
| ------------ | ------------------ |
| **Standard** | ZTP-173            |
| **Category** | Contract Ownership |
| **Network**  | Zetrix Blockchain  |

### Abstract

ZTP-173 defines a standard interface for **contract ownership** on the Zetrix blockchain. It specifies how a smart contract declares, queries, transfers, and renounces a single owner address enabling block explorers, tooling, and other contracts to interact with ownership in a predictable and interoperable way.

The ownership model follows a **two-step transfer** pattern: the current owner initiates a transfer, and the new owner must explicitly accept it. This prevents accidental or malicious transfers to inaccessible addresses.

### Motivation

Many smart contracts deployed on Zetrix require an administrative owner — an account that can adjust parameters, mint tokens, pause functionality, or manage funds. Without a common interface:

* Block explorers cannot uniformly display or verify contract ownership.
* Tooling cannot generically transfer or renounce ownership across contracts.
* Other contracts cannot safely query the owner of an on-chain resource.
* Security audits cannot follow a predictable, auditable ownership lifecycle.

ZTP-173 solves this by standardising five entry points so every conforming contract exposes the same ownership API, consistent with existing Zetrix contract conventions (`Chain.load`, `Chain.store`, `Chain.tlog`, `contractInfo.issuer`).

### Specification

#### Interface

A ZTP-173-compliant contract **MUST** implement the following functions:

| Function                      | Access     | Description                             |
| ----------------------------- | ---------- | --------------------------------------- |
| `owner()`                     | Public     | Returns the current owner address       |
| `transferOwnership(newOwner)` | Owner only | Initiates a two-step ownership transfer |

#### Functions

**owner**

```javascript
function owner()
```

Returns the address of the current contract owner. Reads from `contractInfo.issuer` stored under the `CONTRACT_PRE` key.

| Items       | Description                                                   |
| ----------- | ------------------------------------------------------------- |
| **Access**  | Public (query)                                                |
| **Returns** | `String` — current owner Zetrix address, or `''` if renounced |
| **Throws**  | Never                                                         |

**transferOwnership**

```javascript
function transferOwnership(newOwner)
```

Initiates a two-step ownership transfer. The proposed new owner must call `acceptOwnership()` to finalise the transfer. This function does **not** immediately change `contractInfo.issuer`.

| Items          | Description                                                                                                |
| -------------- | ---------------------------------------------------------------------------------------------------------- |
| **Access**     | Owner only                                                                                                 |
| **Parameters** | `newOwner` — target Zetrix address                                                                         |
| **Emits**      | `OwnershipTransferStarted(newOwner)`                                                                       |
| **Throws if**  | Caller is not owner; address is invalid or empty; address is same as current owner; address is blacklisted |

#### Invoking the Contract

#### Query — owner

```json
{ "method": "owner" }
```

**Response**

```json
{ "result": "ZTXabc123..." }
```

#### transferOwnership

json

```json
{
  "method": "transferOwnership",
  "params": { "newOwner": "ZTXxyz789..." }
}
```

### Sample Code

```javascript
'use strict';

// ============================================================================
// CONSTANTS
// ============================================================================

const CONTRACT_PRE = 'contract_info';

// ============================================================================
// INTERNAL HELPERS
// ============================================================================

function getOwner() {
  let contractInfo = JSON.parse(Chain.load(CONTRACT_PRE));
  return contractInfo.issuer;
}

function validateOwner() {
  Utils.assert(Chain.msg.sender === getOwner(), 'Only the contract owner can perform this action.');
}

function validateNotBlacklisted(address) {
  // Plug in your blacklist logic here if needed.
  // Example: Utils.assert(!isBlacklisted(address), 'Address is blacklisted.');
}

// ============================================================================
// OWNERSHIP MANAGEMENT (ZTP-173)
// ============================================================================

function owner() {                           
  return getOwner();
}

function transferOwnership(newOwner) {
  validateOwner();
  Utils.assert(                              
    newOwner !== undefined && newOwner.length > 0,
    'New owner address is required.'
  );
  Utils.assert(                              
    Utils.addressCheck(newOwner),
    'New owner address is invalid.'
  );
  validateNotBlacklisted(newOwner);

  let contractInfo  = JSON.parse(Chain.load(CONTRACT_PRE));
  let previousOwner = contractInfo.issuer;
  Utils.assert(previousOwner !== newOwner, 'New owner must be different from current owner.');

  contractInfo.issuer = newOwner;
  Chain.store(CONTRACT_PRE, JSON.stringify(contractInfo));
  Chain.tlog('OwnershipTransferred', previousOwner, newOwner);
  return true;
}

// ============================================================================
// CONTRACT LIFECYCLE
// ============================================================================

function init(input_str) {
  let params = JSON.parse(input_str).params || {};

  Utils.assert(params.name   !== undefined, 'Contract name is required.');
  Utils.assert(params.symbol !== undefined, 'Contract symbol is required.');

  let initialOwner = params.owner || Chain.msg.sender;
  Utils.assert(Utils.addressCheck(initialOwner), 'Invalid initial owner address.');

  let contractInfo = {
    name       : params.name,
    symbol     : params.symbol,
    issuer     : initialOwner,
    createTime : Chain.block.timestamp
  };

  Chain.store(CONTRACT_PRE, JSON.stringify(contractInfo));
  Chain.tlog('OwnershipTransferred', '', initialOwner);
  return true;
}

function main(input_str) {
  let input  = JSON.parse(input_str);
  let method = input.method;
  let params = input.params || {};

  Utils.assert(method !== undefined && method.length > 0, 'Method is required.');

  if (method === 'transferOwnership') {
    return transferOwnership(params.newOwner);
  }

  Utils.assert(false, 'Unknown method: ' + method);
}

function query(input_str) {
  let input  = JSON.parse(input_str);
  let method = input.method;

  Utils.assert(method !== undefined && method.length > 0, 'Query method is required.');

  if (method === 'owner') {
    return JSON.stringify({ result: owner() });   // ✅ owner() now defined
  }

  Utils.assert(false, 'Unknown query method: ' + method);
}

```


# ZTP-721

| Method   | Description                                          |
| -------- | ---------------------------------------------------- |
| name     | Token Name. Example: “Global Coin”                   |
| symbol   | Token Symbol. Example: GCN                           |
| describe | Token description: “Global coin token issued by XYZ” |
| version  | Token version                                        |

## Simple Summary

A standard interface for non-fungible tokens, also known as deeds.

## Abstract

The following standard allows for the implementation of a standard API for NFTs (non-fungible tokens) within smart contracts. This standard provides basic functionality to track and transfer NFTs.

We considered use cases of NFTs being owned and transacted by individuals as well as consignment to third party brokers/wallets/auctioneers (“operators”). NFTs can represent ownership over digital or physical assets. We considered a diverse universe of assets, and we know you will dream up many more:

* Physical property — houses, unique artwork
* Virtual collectibles — unique pictures of kittens, collectible cards
* “Negative value” assets — loans, burdens and other responsibilities

In general, all houses are distinct and no two kittens are alike. NFTs are *distinguishable* and you must track the ownership of each one separately.

## Motivation

A standard interface allows wallet/broker/auction applications to work with any NFT on Zetrix. Additional applications are discussed below.

## Specification Token Methods

#### balanceOf

Count all NFTs assigned to an `owner` , and returns the number of NFTs owned by `owner` , possibly zero.

```javascript
self.balanceOf = function (paramObj) {
    Utils.assert(Utils.addressCheck(paramObj.owner), "ZTP721: Invalid owner address: " + paramObj.owner);
    let balance = BasicOperationUtil.loadObj(BasicOperationUtil.getKey(BALANCES_PRE, paramObj.owner));
    if (balance === false) {
        return '0';
    }
    return balance;
};
```

#### ownerOf

Find the owner of an NFT, and returns the address of the owner of the NFT.

```javascript
self.ownerOf = function (paramObj) {
    return _requiredOwned(paramObj.tokenId);
};
```

#### safeTransferFrom

Transfers the ownership of an NFT from one address to another address. This function SHOULD also enforce the `onZTP721Received` check to ensure that if the receiver is a contract address, it is able to receive NFTs.

```javascript
self.safeTransferFrom = function (paramObj) {
    self.transferFrom(paramObj);
    /*
     if(paramObj.data !== "") {
         // Implement checkOnZTP721Received
     }
    */
};
```

#### transferFrom

Transfers the ownership of an NFT from one address to another address.

Note: THE CALLER IS RESPONSIBLE TO CONFIRM THAT THE RECEIVER IS CAPABLE OF RECEIVING NFTS OR ELSE THEY MAY BE PERMANENTLY LOST.

```javascript
self.transferFrom = function (paramObj) {
    Utils.assert(Utils.addressCheck(paramObj.to), "ZTP721: Invalid receiver address.");
    let previousOwner = self.p.update(paramObj.to, paramObj.tokenId, Chain.msg.sender);
    Utils.assert(previousOwner === paramObj.from, "ZTP721: Incorrect owner");
};
```

#### approve

Change or reaffirm the approved address for an NFT.

```javascript
self.approve = function (paramObj) {
    return self.p.approve(paramObj.to, paramObj.tokenId, Chain.msg.sender);
};
```

#### setApprovalForAll

Enable or disable approval for a third party ("operator") to manage all of `Chain.msg.sender`'s assets.

```javascript
self.setApprovalForAll = function (paramObj) {
    return self.p.setApprovalForAll(Chain.msg.sender, paramObj.operator, paramObj.approved);
};
```

#### getApproved

Get the approved address for a single NFT, and returns the approved address for this NFT.

```javascript
self.getApproved = function (paramObj) {
    _requiredOwned(paramObj.tokenId);
    return self.p.getApproved(paramObj.tokenId);
};
```

#### isApprovedForAll

Query if an address is an authorized operator for another address, and returns true if `operator` is an approved operator for `owner`, false otherwise.

```javascript
self.isApprovedForAll = function (paramObj) {
    return BasicOperationUtil.loadObj(BasicOperationUtil.getKey(OPERATOR_APPROVAL_PRE, paramObj.owner, paramObj.operator));
};
```

#### Note: A wallet/broker/auction application MUST implement the **wallet interface** (ZTP721Receiver interface with the onZTP721Received function) if it will accept safe transfers.

## [Zetrix Ecosystem Proposals](https://github.com/Zetrix-Chain/zetrix-protocol)

Sample ZTP721 contract can be found [here](https://github.com/Zetrix-Chain/zetrix-protocol/blob/main/ZTP/ZTP-721.js).


# ZTP-1155

| Method   | Description                                          |
| -------- | ---------------------------------------------------- |
| name     | Token Name. Example: “Global Coin”                   |
| symbol   | Token Symbol. Example: GCN                           |
| describe | Token description: “Global coin token issued by XYZ” |
| version  | Token version                                        |

## Simple Summary

A standard interface for contracts that manage multiple token types. A single deployed contract may include any combination of fungible tokens, non-fungible tokens or other configurations (e.g. semi-fungible tokens).

## Abstract

This standard outlines a smart contract interface that can represent any number of fungible and non-fungible token types. Existing standards such as ZTP-20 require deployment of separate contracts per token type. The ZTP-721 standard’s token ID is a single non-fungible index and the group of these non-fungibles is deployed as a single contract with settings for the entire collection. In contrast, the ZTP-1155 Multi Token Standard allows for each token ID to represent a new configurable token type, which may have its own metadata, supply and other attributes.

The `id` argument contained in each function’s argument set indicates a specific token or token type in a transaction.

## Motivation

Tokens standards like ZTP-20 and ZTP-721 require a separate contract to be deployed for each token type or collection. This places a lot of redundant bytecode on the Zetrix blockchain and limits certain functionality by the nature of separating each token contract into its own permissioned address. With the rise of blockchain games, game developers may be creating thousands of token types, and a new type of token standard is needed to support them. However, ZTP-1155 is not specific to games and many other applications can benefit from this flexibility.

New functionality is possible with this design such as transferring multiple token types at once, saving on transaction costs. Trading (escrow / atomic swaps) of multiple tokens can be built on top of this standard and it removes the need to “approve” individual token contracts separately. It is also easy to describe and mix multiple fungible or non-fungible token types in a single contract.

## Specification Token Methods

#### safeTransferFrom

Transfers `value` amount of an `id` from the `from` address to the `to` address specified (with safety call).

`data` is an additional field with no specified format, MUST be sent unaltered in call to `onZTP1155Received` on `to` .

```javascript
self.safeTransferFrom = function (paramObj) {
    let sender = Chain.msg.sender;
    Utils.assert(paramObj.from === sender || self.isApprovedForAll({
        account: paramObj.from,
        operator: sender
    }), "ZTP1155: Missing approval for all");
    _safeTransferFrom(paramObj.from, paramObj.to, paramObj.id, paramObj.value, paramObj.data);
};
```

#### safeBatchTransferFrom

Transfers `values` amount(s) of `ids` from the `from` address to the `to` address specified (with safety call).

`data` is an additional data with no specified format, MUST be sent unaltered in call to the `ZTP1155TokenReceiver` hook(s) on `to` .

```javascript
self.safeBatchTransferFrom = function (paramObj) {
    let sender = Chain.msg.sender;
    Utils.assert(paramObj.from === sender || self.isApprovedForAll({
        account: paramObj.from,
        operator: sender
    }), "ZTP1155: Missing approval for all");
    _safeBatchTransferFrom(paramObj.from, paramObj.to, paramObj.ids, paramObj.values, paramObj.data);
};
```

#### balanceOf

Get the balance of an account's tokens for the token type requested.

```javascript
self.balanceOf = function (paramObj) {
    let balance = BasicOperationUtil.loadObj(BasicOperationUtil.getKey(BALANCES_PRE, paramObj.id, paramObj.account));
    if (balance === false) {
        return "0";
    }
    return balance;
};
```

#### balanceOfBatch

The owner's balance of the token types requested (i.e. balance for each (owner, id) pair).

```javascript
self.balanceOfBatch = function (paramObj) {
    Utils.assert(paramObj.accounts.length === paramObj.ids.length, 'Invalid array length');

    let batchBalances = [];
    let i;
    for (i = 0; i < paramObj.accounts.length; i += 1) {
        batchBalances.push(self.balanceOf({id: paramObj.ids[i], account: paramObj.accounts[i]}));
    }
    return batchBalances;
};
```

#### setApprovalForAll

Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. Returns true if the operator is approved, false to revoke approval.

```javascript
self.setApprovalForAll = function (paramObj) {
    self.p.setApprovalForAll(Chain.msg.sender, paramObj.operator, paramObj.approved);
};
```

#### isApprovedForAll

Queries the approval status of an operator for a given owner.

```javascript
self.isApprovedForAll = function (paramObj) {
    return BasicOperationUtil.loadObj(BasicOperationUtil.getKey(OPERATOR_APPROVAL_PRE, paramObj.owner, paramObj.operator));
};
```

## [Zetrix Ecosystem Proposals](https://github.com/Zetrix-Chain/zetrix-protocol)

Sample ZTP1155 contract can be found [here](https://github.com/Zetrix-Chain/zetrix-protocol/blob/main/ZTP/ZTP-1155.js).


# ZTP-3525

## Introduction

### What is the Semi Fungible Token

This standard introduces semi-fungible tokens (SFTs), which allow for dynamic partitioning of tokens into slots, creating a hybrid model that bridges fungible and non-fungible assets. The proposed contract will enhance flexibility, efficiency, and scalability for managing tokenized assets across various use cases, including financial instruments, gaming, and digital ownership.

### What is ZTP-3525

ZTP-3525 introduces slot-based token management, where tokens are grouped based on shared characteristics but retain unique balances. This allows for more complex token designs and dynamic allocation of value within a single smart contract.

* Semi-Fungibility: Tokens within the same slot act as fungible, while tokens across different slots are non-fungible.
* Slot Metadata: Each slot can hold custom metadata, enabling innovative use cases such as dynamic financial instruments or evolving assets.
* Batch Operations: The standard supports efficient batch operations, reducing gas costs and improving scalability.

ZTP3525 combines features of fungible and non-fungible tokens, enabling innovative use cases like tokenized subscriptions, multi-asset collateralized loans, dynamic NFTs, shared asset ownership, and loyalty programs. This standard allows tokens to carry both a unique identity and a fungible balance, making it ideal for applications requiring personalized attributes alongside transferable or divisible values. ZTP3525 could power advanced blockchain solutions, such as tradable subscription tokens, customizable financial instruments, interactive game assets, fractionalized ownership, and interoperable reward systems, all while enhancing flexibility and utility in tokenized ecosystems.

## Methods

The list below outlines the required methods to be implemented in the contract:

Token definition:

Notes: Token definitions are defined during the *init* procedure.

### init

| Method   |                                                   |
| -------- | ------------------------------------------------- |
| name     | Token Name. Example: “Contract Token”             |
| symbol   | Token Symbol. Example: CTK                        |
| describe | Token description: “Contract token issued by XYZ” |
| version  | Token version                                     |

Example:

```javascript
function init(input_str) {
    let paramObj = JSON.parse(input_str).params;
    Utils.assert(paramObj.name !== undefined && paramObj.name.length > 0, 'Param obj has no name.');
    Utils.assert(paramObj.symbol !== undefined && paramObj.symbol.length > 0, 'Param obj has no symbol.');
    Utils.assert(paramObj.describe !== undefined && paramObj.describe.length > 0, 'Param obj has no describe.');
    Utils.assert(paramObj.version !== undefined && paramObj.version.length > 0, 'Param obj has no version.');

    
    let totalSupplyObject = {};
    totalSupplyObject.tokens = [];
    Chain.store(TOTAL_SUPPLY, JSON.stringify(totalSupplyObject));

    paramObj.protocol = ZTP_PROTOCOL;
    Chain.store(CONTRACT_PRE, JSON.stringify(paramObj));
    return;
}
```

Function implementation:

### safeTransferFromToken <a href="#transfer" id="transfer"></a>

| Method                                             | Description                                                                                                                                                                                                                                                                                                                          |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function safeTransferFromToken(tokenId, toAddress) | The `safeTransferFromToken(tokenId, toAddress)` function facilitates the secure transfer of a specific token, identified by its `tokenId`, from the current owner to a designated `toAddress`. This function ensures that the transfer complies with the token's rules and validates that the recipient can safely handle the token. |

```javascript
function safeTransferFromToken(tokenId, toAddress) {
    let key = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(key);
    Utils.assert(tokenData !== false, 'Failed to get storage data, key: ' + key);
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    Utils.assert(Utils.addressCheck(toAddress) === true, 'Recipient address is invalid.');

    // remove the balance of existing owner
    let ownerKey = getKey(BALANCE_PRE, tokenData.owner);
    let ownerData = Chain.load(ownerKey);
    Utils.assert(ownerData !== false, 'Failed to get storage data, key: ' + ownerKey);
    ownerData = JSON.parse(ownerData);
    ownerData.tokens = ownerData.tokens.filter(function(tokenKey) {
        return tokenKey !== key;
    });
    Chain.store(ownerKey, JSON.stringify(ownerData));

    // add the balance to new owner
    let recipientKey = getKey(BALANCE_PRE, toAddress);
    let recipientData = Chain.load(recipientKey);
    // Utils.assert(recipientData !== false, 'Failed to get storage data, key: ' + recipientKey);
    if (recipientData === false) {
        recipientData = {};
        recipientData.tokens = [];
    } else {
        recipientData = JSON.parse(recipientData);
    }
    recipientData.tokens.push(key);
    Chain.store(recipientKey, JSON.stringify(recipientData));

    // update the token owner
    tokenData.owner = toAddress;
    Chain.store(key, JSON.stringify(tokenData));
}
```

### transferFromToken <a href="#transfer" id="transfer"></a>

| Method                                         | Description                                                                                                                                                                      |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function transferFromToken(tokenId, toAddress) | The `transferFromToken(tokenId, toAddress)` function executes the transfer of a semi-fungible token identified by `tokenId` from its current owner to the specified `toAddress`. |

Example:

```javascript
function transferFromToken(tokenId, toAddress) {
    let key = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(key);
    Utils.assert(tokenData !== false, 'Failed to get storage data, key: ' + key);
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    Utils.assert(Utils.addressCheck(toAddress) === true, 'Recipient address is invalid.');

    // remove the balance of existing owner
    let ownerKey = getKey(BALANCE_PRE, tokenData.owner);
    let ownerData = Chain.load(ownerKey);
    Utils.assert(ownerData !== false, 'Failed to get storage data, key: ' + ownerKey);
    ownerData = JSON.parse(ownerData);
    ownerData.tokens = ownerData.tokens.filter(function(tokenKey) {
        return tokenKey !== key;
    });
    Chain.store(ownerKey, JSON.stringify(ownerData));

    // add the balance to new owner
    let recipientKey = getKey(BALANCE_PRE, toAddress);
    let recipientData = Chain.load(recipientKey);
    // Utils.assert(recipientData !== false, 'Failed to get storage data, key: ' + recipientKey);
    if (recipientData === false) {
        recipientData = {};
        recipientData.tokens = [];
    } else {
        recipientData = JSON.parse(recipientData);
    }
    recipientData.tokens.push(key);
    Chain.store(recipientKey, JSON.stringify(recipientData));

    // update the token owner
    tokenData.owner = toAddress;
    Chain.store(key, JSON.stringify(tokenData));
}
```

### safeTransferFromBalance

| Method                                                           | Description                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function safeTransferFromBalance(fromTokenId, toTokenId, amount) | The `safeTransferFromBalance(fromTokenId, toTokenId, amount)` function securely transfers a specified `amount` of balance from one semi-fungible token (`fromTokenId`) to another (`toTokenId`). Unlike transferring an entire token, this function focuses on the fungible value associated with the tokens, ensuring that the balance is accurately moved while preserving the unique identity of both the source and destination tokens. |

Example:

```javascript
function safeTransferFromBalance(fromTokenId, toTokenId, amount) {
    let senderTokenKey = getKey(TOKEN_PRE, fromTokenId);
    let senderTokenData = Chain.load(senderTokenKey);
    Utils.assert(senderTokenData !== false, 'Failed to get storage data, key: ' + senderTokenKey);
    senderTokenData = JSON.parse(senderTokenData);
    Utils.assert(Chain.msg.sender === senderTokenData.owner || senderTokenData.operators.includes(Chain.msg.sender), 'Only owner or operator of the token can call this function.');
    Utils.assert(Utils.int256Compare(senderTokenData.balance, amount) > 0, 'Insufficient balance to transfer amount.');

    let recipientTokenKey = getKey(TOKEN_PRE, toTokenId);
    let recipientTokenData = JSON.parse(Chain.load(recipientTokenKey));
    Utils.assert(recipientTokenData !== false, 'Failed to get storage data, key: ' + recipientTokenKey);
    recipientTokenData = JSON.parse(recipientTokenData);

    // subtract sender balance
    senderTokenData.balance = Utils.int256Sub(senderTokenData.balance, amount);
    Chain.store(senderTokenKey, JSON.stringify(senderTokenData));

    // add recipient balance
    recipientTokenData.balance = Utils.int256Add(recipientTokenData.balance, amount);
    Chain.store(recipientTokenKey, JSON.stringify(recipientTokenData));
}
```

### transferFromBalance

| Method                                                       | Description                                                                                                                                                                                                                                                                                                                                                                 |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function transferFromBalance(fromTokenId, toTokenId, amount) | The `transferFromBalance(fromTokenId, toTokenId, amount)` function transfers a specified `amount` of balance from one semi-fungible token (`fromTokenId`) to another (`toTokenId`). Unlike the safer version, `safeTransferFromBalance`, this function does not include additional checks for the recipient's ability to handle the balance or compatibility of the tokens. |

Example:

```javascript
function transferFromBalance(fromTokenId, toTokenId, amount) {
    let senderTokenKey = getKey(TOKEN_PRE, fromTokenId);
    let senderTokenData = Chain.load(senderTokenKey);
    Utils.assert(senderTokenData !== false, 'Failed to get storage data, key: ' + senderTokenKey);
    senderTokenData = JSON.parse(senderTokenData);
    Utils.assert(Chain.msg.sender === senderTokenData.owner || senderTokenData.operators.includes(Chain.msg.sender), 'Only owner or operator of the token can call this function.');
    Utils.assert(Utils.int256Compare(senderTokenData.balance, amount) > 0, 'Insufficient balance to transfer amount.');

    let recipientTokenKey = getKey(TOKEN_PRE, toTokenId);
    let recipientTokenData = JSON.parse(Chain.load(recipientTokenKey));
    Utils.assert(recipientTokenData !== false, 'Failed to get storage data, key: ' + recipientTokenKey);
    recipientTokenData = JSON.parse(recipientTokenData);

    // subtract sender balance
    senderTokenData.balance = Utils.int256Sub(senderTokenData.balance, amount);
    Chain.store(senderTokenKey, JSON.stringify(senderTokenData));

    // add recipient balance
    recipientTokenData.balance = Utils.int256Add(recipientTokenData.balance, amount);
    Chain.store(recipientTokenKey, JSON.stringify(recipientTokenData));
}

```

### approve

| Method                              | Description                                                                                                                                                                                                                                                                                                                                                  |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function approve(operator, tokenId) | The `approve(operator, tokenId)` function allows the token owner to grant approval for an `operator` to manage or transfer a specific token identified by `tokenId` on their behalf. This approval is specific to the given token, meaning the operator is authorized to perform actions like transferring the token, but only for that particular token ID. |

Example:

```javascript
function approve(operator, tokenId) {
    Utils.assert(Utils.addressCheck(operator) === true, 'Operator address is invalid.');
    let tokenData = Chain.load(getKey(TOKEN_PRE, tokenId));
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner, 'Only owner of the token is allowed to call this function.');
    tokenData.operators.push(operator);
    Chain.store(getKey(TOKEN_PRE, tokenId), JSON.stringify(tokenData));
}

```

### approveForSlot

| Method                                    | Description                                                                                                                                                                                                                                                                                                                          |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function approveForSlot(operator, slotId) | The `approveForSlot(operator, slotId)` function allows the token owner to grant permission to an `operator` to manage all tokens associated with a specific `slotId`. A slot in the ZTP-3525 standard often represents a grouping or categorization of tokens sharing common attributes, such as a shared purpose or financial terms |

Example:

```javascript
function approveForSlot(operator, slotId) {
    Utils.assert(Utils.addressCheck(operator) === true, 'Operator address is invalid.');
    let slotKey = getKey(SLOT_PRE, slotId);
    let slotData = Chain.load(slotKey);
    Utils.assert(slotData !== false, 'Slot key does not exist: ' + slotKey);
    slotData = JSON.parse(slotData);
    Utils.assert(Chain.msg.sender === slotData.owner, 'Only owner of the slot is allowed to call this function.');
    slotData.operators.push(operator);
    Chain.store(slotKey, JSON.stringify(slotData));
}
```

### approveForAll

| Method                                  | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function approveForAll(owner, operator) | The `approveForAll(owner, operator)` function allows the `owner` of tokens to grant an `operator` permission to manage all of their tokens without needing individual approvals for each one. This function is often used in scenarios where the owner wants to delegate broad control to an operator, enabling the operator to perform actions like transferring, staking, or interacting with tokens on behalf of the owner.(to), and MUST fire the Transfer event. |

Example:

```javascript
function approveForAll(owner, operator) {
    Utils.assert(Utils.addressCheck(owner) === true, 'Owner address is invalid.');
    Utils.assert(Utils.addressCheck(operator) === true, 'Operator address is invalid.');
    let balanceData = Chain.load(getKey(BALANCE_PRE, owner));
    Utils.assert(balanceData !== false, `Balance data for address "${owner}" does not exist.`);
    Utils.assert(Chain.msg.sender === owner, 'Only the owner is allowed to call this function.');
    balanceData = JSON.parse(balanceData);
    balanceData.tokens.forEach(function(tokenKey) {
        let tokenData = JSON.parse(Chain.load(tokenKey));
        Utils.assert(tokenData.owner === owner, `Token ID ${tokenKey} is not owned by ${owner}.`);
        tokenData.operators.push(operator);
        Chain.store(tokenKey, JSON.stringify(tokenData));    
    });
}
```

### setSlotMetadata

| Method                                                     | Description                                                                                                                                                                                                                                                                                                                                                    |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function setSlotMetadata(slotId, tokens, operators, owner) | The `setSlotMetadata(slotId, tokens, operators, owner)` function allows for the configuration or update of metadata for a specific `slotId` in a token contract. It enables the assignment of tokens to a slot, designates authorized operators to manage or interact with the tokens, and specifies the owner or controlling address responsible for the slot |

Example:

```javascript
function setSlotMetadata(slotId, tokens, operators, owner) {
    Utils.assert(Utils.addressCheck(owner) === true, 'Owner address is invalid.');
    operators.forEach(function(operator) {
        Utils.assert(Utils.addressCheck(operator) === true, `Operator address "${operator}" is invalid.`);
    });

    let slotData = Chain.load(getKey(SLOT_PRE, slotId));
    // slot does not exist yet
    if (slotData === false) {
        let slotObject = {};
        slotObject.id = slotId;
        slotObject.tokens = tokens;
        slotObject.operators = operators;
        slotObject.owner = owner;

        Chain.store(getKey(SLOT_PRE, slotId), JSON.stringify(slotObject));
    } else {
        slotData = JSON.parse(slotData);
        slotData.tokens = tokens;
        slotData.operators = operators;
        slotData.owner = owner;

        Chain.store(getKey(SLOT_PRE, slotId), JSON.stringify(slotData));
    }
}
```

### mintToken

| Method                                                  | Description                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function mintToken(toAddress, slotId, tokenId, balance) | The `mintToken(toAddress, slotId, tokenId, balance)` function is used to mint a new semi-fungible token in a blockchain contract. It assigns a specific `tokenId` to the newly created token, associates it with a particular `slotId` (which groups the token with others that share common attributes), and sets the initial `balance` of the token. |

Example:

```javascript
function mintToken(toAddress, slotId, tokenId, balance) {
    Utils.assert(Utils.addressCheck(toAddress) === true, 'Recipient address is invalid.');
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData === false, 'Token ID already exists.');
    let slotKey = getKey(SLOT_PRE, slotId);
    let slotData = Chain.load(slotKey);
    // slot does not exist
    if (slotData === false) {
        // create slot
        slotData = {};
        slotData.id = slotId;
        slotData.tokens = [];
        slotData.operators = [];
        slotData.owner = toAddress;
    } else {
        slotData = JSON.parse(slotData);
    }

    // create object
    let tokenObject = {};
    tokenObject.id = tokenId;
    tokenObject.slotId = slotData.id;
    tokenObject.balance = balance;
    tokenObject.owner = toAddress;
    tokenObject.operators = [];

    // store token object
    Chain.store(tokenKey, JSON.stringify(tokenObject));

    // store token key in slot
    slotData.tokens.push(tokenKey);
    Chain.store(slotKey, JSON.stringify(slotData));

    // update balance for recipient
    let recipientKey = getKey(BALANCE_PRE, toAddress);
    let recipientData = Chain.load(recipientKey);

    if (recipientData === false) {
        recipientData = {};
        recipientData.tokens = [];
    } 
    else {
        recipientData = JSON.parse(recipientData);
    }
    recipientData.tokens.push(tokenKey);
    Chain.store(recipientKey, JSON.stringify(recipientData));

    // update total supply
    let currentSupply = totalSupply();
    currentSupply.tokens.push(tokenKey);
    Chain.store(TOTAL_SUPPLY, JSON.stringify(currentSupply));
}
```

### mintBalance

| Method                                | Description                                                                                                                                                                                                                                                                 |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function mintBalance(tokenId, amount) | The `mintBalance(tokenId, amount)` function is used to mint additional balance to an existing semi-fungible token identified by its `tokenId`. This function increases the token's balance by the specified `amount`, without changing the token's unique identity or slot. |

Example:

```javascript
function mintBalance(tokenId, amount) {
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    tokenData.balance = Utils.int256Add(tokenData.balance, amount);
    Chain.store(tokenKey, JSON.stringify(tokenData));
}
```

### burnToken

| Method                      | Description                                                                                                                                                                                                                                                                                              |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function burnToken(tokenId) | The `burnToken(tokenId)` function is used to permanently destroy or "burn" a specific semi-fungible token identified by its `tokenId`. This function reduces the total supply of tokens by removing the specified token from circulation, effectively making it inaccessible for future use or transfer. |

Example:

```javascript
function burnToken(tokenId) {
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');

    // remove token key from slot
    let slotKey = getKey(SLOT_PRE, tokenData.slotId);
    let slotData = Chain.load(slotKey);
    Utils.assert(slotData !== false, 'Slot does not exist.');
    slotData = JSON.parse(slotData);
    slotData.tokens = slotData.tokens.filter(function(token) {
        return token !== tokenKey;
    });
    Chain.store(slotKey, JSON.stringify(slotData));

    // remove token key from owner
    let ownerKey = getKey(BALANCE_PRE, tokenData.owner);
    let ownerData = Chain.load(ownerKey);
    Utils.assert(ownerData !== false, 'Owner data does not exist.');
    ownerData = JSON.parse(ownerData);
    ownerData.tokens = ownerData.tokens.filter(function(token) {
        return token !== tokenKey;
    });
    Chain.store(ownerKey, JSON.stringify(ownerData));

    // update total supply
    let currentSupply = totalSupply();
    currentSupply.tokens = currentSupply.tokens.filter(function(token) {
        return token !== tokenKey;
    });

    Chain.store(TOTAL_SUPPLY, JSON.stringify(currentSupply));

    // remove token from Chain.store
    Chain.del(tokenKey);
}

```

### burnBalance

| Method                                | Description                                                                                                                                                                                                                                                                                                                                                                                  |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function burnBalance(tokenId, amount) | The `burnBalance(tokenId, amount)` function is used to destroy or "burn" a specified amount of balance from an existing semi-fungible token identified by its `tokenId`. Unlike burning the entire token, this function reduces the token's balance by the given `amount`, effectively decreasing the fungible value associated with the token while retaining its unique identity and slot. |

Example:

```javascript
function burnBalance(tokenId, amount) {
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    tokenData.balance = Utils.int256Sub(tokenData.balance, amount);
    Chain.store(tokenKey, JSON.stringify(tokenData));
}
```

### balanceOf

| Method                      | Description                                                                                                                                                                                                                                   |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function balanceOf(address) | The `balanceOf(address)` function returns the total balance of tokens held by a specific address. In the context of token standards like ZTP-20 or ZTP-3525, it provides the amount of tokens (or the fungible balance) that an address owns. |

Example:

```javascript
function balanceOf(address) {
    let key = getKey(BALANCE_PRE, address);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? 0 : JSON.parse(data).tokens.length;
}
```

### ownerOf

| Method                    | Description                                                                                                                                                                                                                                                          |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function ownerOf(tokenId) | The `ownerOf(tokenId)` function returns the address of the owner of a specific token identified by its `tokenId`. This function is commonly used in ZTP-721 (NFT) and ZTP-3525 (semi-fungible) token contracts to determine the current owner of a particular token. |

Example:

```javascript
function ownerOf(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find owner." : JSON.parse(data).owner;
}

```

### getApproved

| Method                        | Description                                                                                                                                                                                             |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function getApproved(tokenId) | The `getApproved(tokenId)`function returns the address of the approved operator for a specific token identified by its `tokenId`. This address is allowed to transfer the token on behalf of the owner. |

Example:

```javascript
function getApproved(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find token." : JSON.parse(data).operators;
}
```

### isApprovedForAll

| Method                                     | Description                                                                                                                                                                                                                                                                    |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| functionis ApprovedForAll(owner, operator) | The `isApprovedForAll(owner, operator)` function checks whether an `operator` is approved to manage all tokens owned by the `owner`. This approval is global, meaning the operator can manage any token held by the owner without needing individual approvals for each token. |

Example:

```javascript
function isApprovedForAll(owner, operator) {
    let key = getKey(BALANCE_PRE, owner);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    data = JSON.parse(data);
    if (data.tokens.length !== 0) {
        let result = data.tokens.every(function(token) {
            let tokenData = Chain.load(getKey(TOKEN_PRE, token.id));
            if (tokenData !== false) {
                tokenData = JSON.parse(tokenData);
                if (tokenData.operator !== operator) {
                    return false; // Stop checking if operator does not match
                }
            }
            return true; // Continue checking
        });
        return result;
    } else {
        return false;
    }
}
```

### isApprovedForSlot

| Method                                                | Description                                                                                                                                                                                                                                                                                                                                                                                                             |
| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function isApprovedForSlot(slotId, operator) , value) | The `isApprovedForSlot(slotId, operator)` function checks whether an `operator` is authorized to manage or interact with all tokens associated with a specific `slotId`. In token standards like ZTP-3525, where tokens are grouped into slots with shared attributes, this function verifies if the operator has permission to perform actions on all tokens within that slot, such as transfers or other interactions |

Example:

```javascript
function isApprovedForSlot(slotId, operator) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    data = JSON.parse(data);
    let result = data.operators.includes(operator);
    return result;
}
```

### slotOf

| Method                   | Description                                                                                                                                                                                                                              |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function slotOf(tokenId) | The `slotOf(tokenId)` function retrieves the specific slot associated with a given `tokenId` in the ZTP-3525 token standard. A slot represents a category or grouping of tokens with shared attributes, such as value, purpose, or type. |

Example:

```javascript
function slotOf(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find token." : JSON.parse(data).slotId;
}
```

### contractInfo

| Method                  | Description                                                                                                                                                                                                                                                          |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function contractInfo() | The `contractInfo()` function typically returns metadata or key details about the smart contract that governs the token. This can include information such as the contract's name, symbol, total supply, version, or other relevant details defined by the contract. |

Example:

```javascript
function contractInfo() {
    let data = Chain.load(CONTRACT_PRE);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + CONTRACT_PRE);
    if (data === false) {
        return false;
    }
    return JSON.parse(data);
}
```

### tokenURI

| Method                     | Description                                                                                                                                                                                                                                       |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function tokenURI(tokenId) | The `tokenURI(tokenId)` function retrieves the Uniform Resource Identifier (URI) associated with a specific `tokenId` in a token contract. The URI typically points to a location where metadata about the token is stored, often in JSON format. |

Example:

```javascript
function tokenURI(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find token." : JSON.parse(data);
}

```

### slotURI

| Method                   | Description                                                                                                                                                                     |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function slotURI(slotId) | The `slotURI(slotId)` function retrieves the Uniform Resource Identifier (URI) associated with a specific `slotId` in a token contract, typically within the ZTP-3525 standard. |

Example:

```javascript
function slotURI(slotId) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    if (data === false) {
        return false;
    }
    return JSON.parse(data);
}
```

### totalSupply

| Method                 | Description                                                                                                                                                                    |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function totalSupply() | The `totalSupply()` function returns the total number of tokens that exist within a specific contract or token standard, often used to represent the total circulating supply. |

Example:

```javascript
function totalSupply() {
    let data = Chain.load(TOTAL_SUPPLY);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + TOTAL_SUPPLY);
    return data === false ? [] : JSON.parse(data);
}
```

### tokensOfOwner

| Method                          | Description                                                                                                                                                                                                                                            |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function tokensOfOwner(address) | The `tokensOfOwner(address)` function returns a list of token IDs owned by a specific address. In the context of token standards like ZTP-3525, ZTP-721, or ZTP-20, it allows users to query which tokens are owned by a particular wallet or address. |

Example:

```javascript
function tokensOfOwner(address) {
    let key = getKey(BALANCE_PRE, address);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find address." : JSON.parse(data).tokens;
}
```

### tokensInSlot

| Method                        | Description                                                                                                                                                                                                                                                                 |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function tokensInSlot(slotId) | The `tokensInSlot(slotId)` function returns a list of all token IDs associated with a specific `slotId`. In token standards like ZTP-3525, a slot represents a grouping or categorisation of tokens that share common attributes, such as purpose, value, or functionality. |

Example:

```javascript
function tokensInSlot(slotId) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    if (data === false) {
        return false;
    }
    return JSON.parse(data).tokens;
}

```

### getSlotMetadata

| Method                           | Description                                                                                                                                                                                                                                                                                                        |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| function getSlotMetadata(slotId) | The `getSlotMetadata(slotId)` function retrieves the metadata associated with a specific `slotId` in a token contract. This metadata can include details about the attributes, rights, or characteristics that are common to all tokens within that slot, such as its purpose, associated values, or restrictions. |

Example:

```javascript
function getSlotMetadata(slotId) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    if (data === false) {
        return false;
    }
    return JSON.parse(data);
}
```

### query

| Method                     | Description                                                                                                                                                                                                                                                                                                 |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function query(input\_str) | The `query(input_str)`function is typically used to search or retrieve information based on a given input string (`input_str`). The function is designed to process the input, which can be a request or a query, and return relevant results or data from a database, smart contract, or external service. |

Example:

```javascript
function query(input_str) {
    let result = {};
    let input = JSON.parse(input_str);
    if (input.method === "balanceOf") {
        result.balance = balanceOf(input.params.address);
    } else if (input.method === "ownerOf") {
        result.owner = ownerOf(input.params.tokenId);
    } else if (input.method === "getApproved") {
        result.operators = getApproved(input.params.tokenId);
    } else if (input.method === "isApprovedForAll") {
        result.approvedForAll = isApprovedForAll(input.params.owner, input.params.operator);
    } else if (input.method === "isApprovedForSlot") {
        result.isApprovedForSlot = isApprovedForSlot(input.params.slotId, input.params.operator);
    } else if (input.method === "slotOf") {
        result.slot = slotOf(input.params.tokenId);
    } else if (input.method === "contractInfo") {
        result.contractInfo = contractInfo();
    } else if (input.method === "tokenURI") {
        result.tokenURI = tokenURI(input.params.tokenId);
    } else if (input.method === "slotURI") {
        result.slotURI = slotURI(input.params.slotId);
    } else if (input.method === "totalSupply") {
        result.totalSupply = totalSupply();
    } else if (input.method === "tokensOfOwner") {
        result.tokens = tokensOfOwner(input.params.address);
    } else if (input.method === "tokensInSlot") {
        result.tokens = tokensInSlot(input.params.slotId);
    } else if (input.method === "getSlotMetadata") {
        result.slotMetadata = getSlotMetadata(input.params.slotId);
    } else {
        throw `Error matching strings. Input: ${input}. Method: ${input.method}. Parameters: ${input.params}`;
    }

    return JSON.stringify(result);
}
```

### main

| Method                    | Description                                                                                                                                                                                                                                                             |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| function main(input\_str) | The `main(input_str)` function serves as the entry point for executing a process that takes an input string (`input_str`). This function processes the input, which could be a query, command, or data, and then executes a defined set of actions based on that input. |

Example:

```javascript
function main(input_str) {
    let input = JSON.parse(input_str);
    if (input.method === "safeTransferFromToken") {
        safeTransferFromToken(input.params.tokenId, input.params.toAddress);
    } else if (input.method === "transferFromToken") {
        transferFromToken(input.params.tokenId, input.params.toAddress);
    } else if (input.method === "safeTransferFromBalance") {
        safeTransferFromBalance(input.params.fromTokenId, input.params.toTokenId, input.params.amount);
    } else if (input.method === "transferFromBalance") {
        transferFromBalance(input.params.fromTokenId, input.params.toTokenId, input.params.amount);
    } else if (input.method === "approve") {
        approve(input.params.operator, input.params.tokenId);
    } else if (input.method === "approveForSlot") {
        approveForSlot(input.params.operator, input.params.slotId);
    } else if (input.method === "approveForAll") {
        approveForAll(input.params.owner, input.params.operator);
    } else if (input.method === "setSlotMetadata") {
        setSlotMetadata(input.params.slotId, input.params.tokens, input.params.operators, input.params.owner);
    } else if (input.method === "mintToken") {
        mintToken(input.params.toAddress, input.params.slotId, input.params.tokenId, input.params.balance);
    } else if (input.method === "mintBalance") {
        mintBalance(input.params.tokenId, input.params.amount);
    } else if (input.method === "burnToken") {
        burnToken(input.params.tokenId);
    } else if (input.method === "burnBalance") {
        burnBalance(input.params.tokenId, input.params.amount);
    } else {
        throw `Error matching strings. Input: ${input}. Method: ${input.method}. Parameters: ${input.params}`;
    }
}
```

## Full ZTP-3525 contract example:

```javascript
'use strict';

const SLOT_PRE = 'slot';
const TOKEN_PRE = 'token';
const BALANCE_PRE = 'balance';
const CONTRACT_PRE = 'contract_info';
const TOTAL_SUPPLY = 'total_supply';
const ZTP_PROTOCOL = 'ztp3525';

// key generating function
function getKey(first, second, third = '') {
    return (third === '') ? (first + '_' + second) : (first + '_' + second + '_' + third);
}

// get a list of all the tokens belonging to this contract
function totalSupply() {
    let data = Chain.load(TOTAL_SUPPLY);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + TOTAL_SUPPLY);
    return data === false ? [] : JSON.parse(data);
}

// returns the number of tokens for a given address
function balanceOf(address) {
    let key = getKey(BALANCE_PRE, address);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? 0 : JSON.parse(data).tokens.length;
}

// returns list of tokens owned by the given address
function tokensOfOwner(address) {
    let key = getKey(BALANCE_PRE, address);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find address." : JSON.parse(data).tokens;
}

// get the owner of a given token id
function ownerOf(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find owner." : JSON.parse(data).owner;
}

// returns the slot ID of a given token
function slotOf(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find token." : JSON.parse(data).slotId;
}

// returns contract information
function contractInfo() {
    let data = Chain.load(CONTRACT_PRE);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + CONTRACT_PRE);
    if (data === false) {
        return false;
    }
    return JSON.parse(data);
}

// return token metadata
function tokenURI(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find token." : JSON.parse(data);
}


// get the approved operator addresses with the given token id
function getApproved(tokenId) {
    let key = getKey(TOKEN_PRE, tokenId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    return data === false ? "Could not find token." : JSON.parse(data).operators;
}

// function to check whether an operator is approved to manage all tokens owned by the owner
function isApprovedForAll(owner, operator) {
    let key = getKey(BALANCE_PRE, owner);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    data = JSON.parse(data);
    if (data.tokens.length !== 0) {
        let result = data.tokens.every(function(token) {
            let tokenData = Chain.load(getKey(TOKEN_PRE, token.id));
            if (tokenData !== false) {
                tokenData = JSON.parse(tokenData);
                if (tokenData.operator !== operator) {
                    return false; // Stop checking if operator does not match
                }
            }
            return true; // Continue checking
        });
        return result;
    } else {
        return false;
    }
}

// function to check whether an operator is approved to manage the slot owned by the owner
function isApprovedForSlot(slotId, operator) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    data = JSON.parse(data);
    let result = data.operators.includes(operator);
    return result;
}

// approves an operator to a single token 
function approve(operator, tokenId) {
    Utils.assert(Utils.addressCheck(operator) === true, 'Operator address is invalid.');
    let tokenData = Chain.load(getKey(TOKEN_PRE, tokenId));
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner, 'Only owner of the token is allowed to call this function.');
    tokenData.operators.push(operator);
    Chain.store(getKey(TOKEN_PRE, tokenId), JSON.stringify(tokenData));
}

// approves an operator to a slot
function approveForSlot(operator, slotId) {
    Utils.assert(Utils.addressCheck(operator) === true, 'Operator address is invalid.');
    let slotKey = getKey(SLOT_PRE, slotId);
    let slotData = Chain.load(slotKey);
    Utils.assert(slotData !== false, 'Slot key does not exist: ' + slotKey);
    slotData = JSON.parse(slotData);
    Utils.assert(Chain.msg.sender === slotData.owner, 'Only owner of the slot is allowed to call this function.');
    slotData.operators.push(operator);
    Chain.store(slotKey, JSON.stringify(slotData));
}

// approves an operator to all the tokens owned by the given owner
function approveForAll(owner, operator) {
    Utils.assert(Utils.addressCheck(owner) === true, 'Owner address is invalid.');
    Utils.assert(Utils.addressCheck(operator) === true, 'Operator address is invalid.');
    let balanceData = Chain.load(getKey(BALANCE_PRE, owner));
    Utils.assert(balanceData !== false, `Balance data for address "${owner}" does not exist.`);
    Utils.assert(Chain.msg.sender === owner, 'Only the owner is allowed to call this function.');
    balanceData = JSON.parse(balanceData);
    balanceData.tokens.forEach(function(tokenKey) {
        let tokenData = JSON.parse(Chain.load(tokenKey));
        Utils.assert(tokenData.owner === owner, `Token ID ${tokenKey} is not owned by ${owner}.`);
        tokenData.operators.push(operator);
        Chain.store(tokenKey, JSON.stringify(tokenData));    
    });
}

// return slot metadata
function slotURI(slotId) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    if (data === false) {
        return false;
    }
    return JSON.parse(data);
}

// return slot metadata
function getSlotMetadata(slotId) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    if (data === false) {
        return false;
    }
    return JSON.parse(data);
}

// returns list of tokens in the slot
function tokensInSlot(slotId) {
    let key = getKey(SLOT_PRE, slotId);
    let data = Chain.load(key);
    Utils.assert(data !== false, 'Failed to get storage data, key: ' + key);
    if (data === false) {
        return false;
    }
    return JSON.parse(data).tokens;
}

// set slot metadata
function setSlotMetadata(slotId, tokens, operators, owner) {
    Utils.assert(Utils.addressCheck(owner) === true, 'Owner address is invalid.');
    operators.forEach(function(operator) {
        Utils.assert(Utils.addressCheck(operator) === true, `Operator address "${operator}" is invalid.`);
    });

    let slotData = Chain.load(getKey(SLOT_PRE, slotId));
    // slot does not exist yet
    if (slotData === false) {
        let slotObject = {};
        slotObject.id = slotId;
        slotObject.tokens = tokens;
        slotObject.operators = operators;
        slotObject.owner = owner;

        Chain.store(getKey(SLOT_PRE, slotId), JSON.stringify(slotObject));
    } else {
        slotData = JSON.parse(slotData);
        slotData.tokens = tokens;
        slotData.operators = operators;
        slotData.owner = owner;

        Chain.store(getKey(SLOT_PRE, slotId), JSON.stringify(slotData));
    }
}

// creates a new token under a slot
function mintToken(toAddress, slotId, tokenId, balance) {
    Utils.assert(Utils.addressCheck(toAddress) === true, 'Recipient address is invalid.');
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData === false, 'Token ID already exists.');
    let slotKey = getKey(SLOT_PRE, slotId);
    let slotData = Chain.load(slotKey);
    // slot does not exist
    if (slotData === false) {
        // create slot
        slotData = {};
        slotData.id = slotId;
        slotData.tokens = [];
        slotData.operators = [];
        slotData.owner = toAddress;
    } else {
        slotData = JSON.parse(slotData);
    }

    // create object
    let tokenObject = {};
    tokenObject.id = tokenId;
    tokenObject.slotId = slotData.id;
    tokenObject.balance = balance;
    tokenObject.owner = toAddress;
    tokenObject.operators = [];

    // store token object
    Chain.store(tokenKey, JSON.stringify(tokenObject));

    // store token key in slot
    slotData.tokens.push(tokenKey);
    Chain.store(slotKey, JSON.stringify(slotData));

    // update balance for recipient
    let recipientKey = getKey(BALANCE_PRE, toAddress);
    let recipientData = Chain.load(recipientKey);

    if (recipientData === false) {
        recipientData = {};
        recipientData.tokens = [];
    } 
    else {
        recipientData = JSON.parse(recipientData);
    }
    recipientData.tokens.push(tokenKey);
    Chain.store(recipientKey, JSON.stringify(recipientData));

    // update total supply
    let currentSupply = totalSupply();
    currentSupply.tokens.push(tokenKey);
    Chain.store(TOTAL_SUPPLY, JSON.stringify(currentSupply));
}

// increase balance of token by "amount"
function mintBalance(tokenId, amount) {
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    tokenData.balance = Utils.int256Add(tokenData.balance, amount);
    Chain.store(tokenKey, JSON.stringify(tokenData));
}

// burn an entire token
function burnToken(tokenId) {
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');

    // remove token key from slot
    let slotKey = getKey(SLOT_PRE, tokenData.slotId);
    let slotData = Chain.load(slotKey);
    Utils.assert(slotData !== false, 'Slot does not exist.');
    slotData = JSON.parse(slotData);
    slotData.tokens = slotData.tokens.filter(function(token) {
        return token !== tokenKey;
    });
    Chain.store(slotKey, JSON.stringify(slotData));

    // remove token key from owner
    let ownerKey = getKey(BALANCE_PRE, tokenData.owner);
    let ownerData = Chain.load(ownerKey);
    Utils.assert(ownerData !== false, 'Owner data does not exist.');
    ownerData = JSON.parse(ownerData);
    ownerData.tokens = ownerData.tokens.filter(function(token) {
        return token !== tokenKey;
    });
    Chain.store(ownerKey, JSON.stringify(ownerData));

    // update total supply
    let currentSupply = totalSupply();
    currentSupply.tokens = currentSupply.tokens.filter(function(token) {
        return token !== tokenKey;
    });

    Chain.store(TOTAL_SUPPLY, JSON.stringify(currentSupply));

    // remove token from Chain.store
    Chain.del(tokenKey);
}

// decrease a portion (specified by "amount") of the token's balance
function burnBalance(tokenId, amount) {
    let tokenKey = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(tokenKey);
    Utils.assert(tokenData !== false, 'Token does not exist.');
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    tokenData.balance = Utils.int256Sub(tokenData.balance, amount);
    Chain.store(tokenKey, JSON.stringify(tokenData));
}

// same as transferFrom
function safeTransferFromBalance(fromTokenId, toTokenId, amount) {
    let senderTokenKey = getKey(TOKEN_PRE, fromTokenId);
    let senderTokenData = Chain.load(senderTokenKey);
    Utils.assert(senderTokenData !== false, 'Failed to get storage data, key: ' + senderTokenKey);
    senderTokenData = JSON.parse(senderTokenData);
    Utils.assert(Chain.msg.sender === senderTokenData.owner || senderTokenData.operators.includes(Chain.msg.sender), 'Only owner or operator of the token can call this function.');
    Utils.assert(Utils.int256Compare(senderTokenData.balance, amount) > 0, 'Insufficient balance to transfer amount.');

    let recipientTokenKey = getKey(TOKEN_PRE, toTokenId);
    let recipientTokenData = JSON.parse(Chain.load(recipientTokenKey));
    Utils.assert(recipientTokenData !== false, 'Failed to get storage data, key: ' + recipientTokenKey);
    recipientTokenData = JSON.parse(recipientTokenData);

    // subtract sender balance
    senderTokenData.balance = Utils.int256Sub(senderTokenData.balance, amount);
    Chain.store(senderTokenKey, JSON.stringify(senderTokenData));

    // add recipient balance
    recipientTokenData.balance = Utils.int256Add(recipientTokenData.balance, amount);
    Chain.store(recipientTokenKey, JSON.stringify(recipientTokenData));
}

// transfer balance to another token of the same slot
function transferFromBalance(fromTokenId, toTokenId, amount) {
    let senderTokenKey = getKey(TOKEN_PRE, fromTokenId);
    let senderTokenData = Chain.load(senderTokenKey);
    Utils.assert(senderTokenData !== false, 'Failed to get storage data, key: ' + senderTokenKey);
    senderTokenData = JSON.parse(senderTokenData);
    Utils.assert(Chain.msg.sender === senderTokenData.owner || senderTokenData.operators.includes(Chain.msg.sender), 'Only owner or operator of the token can call this function.');
    Utils.assert(Utils.int256Compare(senderTokenData.balance, amount) > 0, 'Insufficient balance to transfer amount.');

    let recipientTokenKey = getKey(TOKEN_PRE, toTokenId);
    let recipientTokenData = JSON.parse(Chain.load(recipientTokenKey));
    Utils.assert(recipientTokenData !== false, 'Failed to get storage data, key: ' + recipientTokenKey);
    recipientTokenData = JSON.parse(recipientTokenData);

    // subtract sender balance
    senderTokenData.balance = Utils.int256Sub(senderTokenData.balance, amount);
    Chain.store(senderTokenKey, JSON.stringify(senderTokenData));

    // add recipient balance
    recipientTokenData.balance = Utils.int256Add(recipientTokenData.balance, amount);
    Chain.store(recipientTokenKey, JSON.stringify(recipientTokenData));
}

// same as transferFrom
function safeTransferFromToken(tokenId, toAddress) {
    let key = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(key);
    Utils.assert(tokenData !== false, 'Failed to get storage data, key: ' + key);
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    Utils.assert(Utils.addressCheck(toAddress) === true, 'Recipient address is invalid.');

    // remove the balance of existing owner
    let ownerKey = getKey(BALANCE_PRE, tokenData.owner);
    let ownerData = Chain.load(ownerKey);
    Utils.assert(ownerData !== false, 'Failed to get storage data, key: ' + ownerKey);
    ownerData = JSON.parse(ownerData);
    ownerData.tokens = ownerData.tokens.filter(function(tokenKey) {
        return tokenKey !== key;
    });
    Chain.store(ownerKey, JSON.stringify(ownerData));

    // add the balance to new owner
    let recipientKey = getKey(BALANCE_PRE, toAddress);
    let recipientData = Chain.load(recipientKey);
    // Utils.assert(recipientData !== false, 'Failed to get storage data, key: ' + recipientKey);
    if (recipientData === false) {
        recipientData = {};
        recipientData.tokens = [];
    } else {
        recipientData = JSON.parse(recipientData);
    }
    recipientData.tokens.push(key);
    Chain.store(recipientKey, JSON.stringify(recipientData));

    // update the token owner
    tokenData.owner = toAddress;
    Chain.store(key, JSON.stringify(tokenData));
}

// transfer ownership of token
function transferFromToken(tokenId, toAddress) {
    let key = getKey(TOKEN_PRE, tokenId);
    let tokenData = Chain.load(key);
    Utils.assert(tokenData !== false, 'Failed to get storage data, key: ' + key);
    tokenData = JSON.parse(tokenData);
    Utils.assert(Chain.msg.sender === tokenData.owner || tokenData.operators.includes(Chain.msg.sender), 'Only owner of the token can call this function.');
    Utils.assert(Utils.addressCheck(toAddress) === true, 'Recipient address is invalid.');

    // remove the balance of existing owner
    let ownerKey = getKey(BALANCE_PRE, tokenData.owner);
    let ownerData = Chain.load(ownerKey);
    Utils.assert(ownerData !== false, 'Failed to get storage data, key: ' + ownerKey);
    ownerData = JSON.parse(ownerData);
    ownerData.tokens = ownerData.tokens.filter(function(tokenKey) {
        return tokenKey !== key;
    });
    Chain.store(ownerKey, JSON.stringify(ownerData));

    // add the balance to new owner
    let recipientKey = getKey(BALANCE_PRE, toAddress);
    let recipientData = Chain.load(recipientKey);
    // Utils.assert(recipientData !== false, 'Failed to get storage data, key: ' + recipientKey);
    if (recipientData === false) {
        recipientData = {};
        recipientData.tokens = [];
    } else {
        recipientData = JSON.parse(recipientData);
    }
    recipientData.tokens.push(key);
    Chain.store(recipientKey, JSON.stringify(recipientData));

    // update the token owner
    tokenData.owner = toAddress;
    Chain.store(key, JSON.stringify(tokenData));
}

function init(input_str) {
    let paramObj = JSON.parse(input_str).params;
    Utils.assert(paramObj.name !== undefined && paramObj.name.length > 0, 'Param obj has no name.');
    Utils.assert(paramObj.symbol !== undefined && paramObj.symbol.length > 0, 'Param obj has no symbol.');
    Utils.assert(paramObj.describe !== undefined && paramObj.describe.length > 0, 'Param obj has no describe.');
    Utils.assert(paramObj.version !== undefined && paramObj.version.length > 0, 'Param obj has no version.');

    
    let totalSupplyObject = {};
    totalSupplyObject.tokens = [];
    Chain.store(TOTAL_SUPPLY, JSON.stringify(totalSupplyObject));

    paramObj.protocol = ZTP_PROTOCOL;
    Chain.store(CONTRACT_PRE, JSON.stringify(paramObj));
    return;
}
  
function main(input_str) {
    let input = JSON.parse(input_str);
    if (input.method === "safeTransferFromToken") {
        safeTransferFromToken(input.params.tokenId, input.params.toAddress);
    } else if (input.method === "transferFromToken") {
        transferFromToken(input.params.tokenId, input.params.toAddress);
    } else if (input.method === "safeTransferFromBalance") {
        safeTransferFromBalance(input.params.fromTokenId, input.params.toTokenId, input.params.amount);
    } else if (input.method === "transferFromBalance") {
        transferFromBalance(input.params.fromTokenId, input.params.toTokenId, input.params.amount);
    } else if (input.method === "approve") {
        approve(input.params.operator, input.params.tokenId);
    } else if (input.method === "approveForSlot") {
        approveForSlot(input.params.operator, input.params.slotId);
    } else if (input.method === "approveForAll") {
        approveForAll(input.params.owner, input.params.operator);
    } else if (input.method === "setSlotMetadata") {
        setSlotMetadata(input.params.slotId, input.params.tokens, input.params.operators, input.params.owner);
    } else if (input.method === "mintToken") {
        mintToken(input.params.toAddress, input.params.slotId, input.params.tokenId, input.params.balance);
    } else if (input.method === "mintBalance") {
        mintBalance(input.params.tokenId, input.params.amount);
    } else if (input.method === "burnToken") {
        burnToken(input.params.tokenId);
    } else if (input.method === "burnBalance") {
        burnBalance(input.params.tokenId, input.params.amount);
    } else {
        throw `Error matching strings. Input: ${input}. Method: ${input.method}. Parameters: ${input.params}`;
    }
}
  
function query(input_str) {
    let result = {};
    let input = JSON.parse(input_str);
    if (input.method === "balanceOf") {
        result.balance = balanceOf(input.params.address);
    } else if (input.method === "ownerOf") {
        result.owner = ownerOf(input.params.tokenId);
    } else if (input.method === "getApproved") {
        result.operators = getApproved(input.params.tokenId);
    } else if (input.method === "isApprovedForAll") {
        result.approvedForAll = isApprovedForAll(input.params.owner, input.params.operator);
    } else if (input.method === "isApprovedForSlot") {
        result.isApprovedForSlot = isApprovedForSlot(input.params.slotId, input.params.operator);
    } else if (input.method === "slotOf") {
        result.slot = slotOf(input.params.tokenId);
    } else if (input.method === "contractInfo") {
        result.contractInfo = contractInfo();
    } else if (input.method === "tokenURI") {
        result.tokenURI = tokenURI(input.params.tokenId);
    } else if (input.method === "slotURI") {
        result.slotURI = slotURI(input.params.slotId);
    } else if (input.method === "totalSupply") {
        result.totalSupply = totalSupply();
    } else if (input.method === "tokensOfOwner") {
        result.tokens = tokensOfOwner(input.params.address);
    } else if (input.method === "tokensInSlot") {
        result.tokens = tokensInSlot(input.params.slotId);
    } else if (input.method === "getSlotMetadata") {
        result.slotMetadata = getSlotMetadata(input.params.slotId);
    } else {
        throw `Error matching strings. Input: ${input}. Method: ${input.method}. Parameters: ${input.params}`;
    }

    return JSON.stringify(result);
}
```

## Use Case

A use case for the **ZTP-3525** standard, which is designed for semi-fungible tokens (SFTs) on the Zetrix blockchain, involves creating a tokenized subscription service. Here's how it works:

#### **Tokenized Subscription Service with ZTP-3525**

In this scenario, **ZTP-3525** tokens are used to represent subscription plans with both unique and fungible properties. Each subscription plan is represented by a token (`tokenId`) that holds a balance (fungible) to represent usage, duration, or remaining service credits.

**Steps for Implementation:**

1. **Minting Subscription Tokens**:\
   The service provider mints **ZTP-3525** tokens for a user, assigning them a `tokenId` linked to a specific subscription plan (e.g., "Premium Plan" or "Basic Plan"). This token is linked to a `slotId`, representing the type or category of the subscription (e.g., "Premium", "Basic").
2. **Tracking Balance**:\
   The `balance` associated with the `tokenId` keeps track of the subscription's usage, such as how many hours of service or credits remain. For example, a "Premium Plan" token might have a balance of 30, representing 30 days of service left.
3. **Transferring or Selling**:\
   If the user decides to transfer their remaining subscription balance to someone else (for example, selling part of the remaining credits), they can use `safeTransferFromBalance` or `transferFromBalance` to move a portion of their subscription balance to another user's token, allowing partial transfers of service.
4. **Slot Management**:\
   The service can define different slots for various types of subscriptions (e.g., “Basic”, “Premium”). This allows the operator to manage all tokens within a particular category or plan using the `approveForSlot` function, where an authorized operator can transfer, manage, or adjust all tokens in the “Premium” slot, for example.
5. **Burning Subscription Tokens**:\
   When the subscription expires or the service is fully used, the token can be "burned" using the `burnToken` or `burnBalance` function, removing the subscription token from circulation, reflecting that the user has used or forfeited their subscription.

**Benefits of Using ZTP-3525 for Subscription Services:**

* **Flexibility**: A token can represent both the unique identity of a subscription and the fungible balance of remaining service, allowing seamless management of credits or time-based services.
* **Partial Transfers**: Users can transfer portions of their subscription or balance to others, allowing flexible use of services.
* **Efficient Slot Management**: Subscription plans can be grouped into slots, simplifying management and control for operators (e.g., managing the entire Premium plan in one action).
* **Transparency**: Smart contracts ensure the automatic and transparent management of tokens, including subscription duration and usage.

This use case demonstrates how **ZTP-3525**’s combination of non-fungible and fungible elements can be leveraged to manage services that require both unique attributes and divisible, transferable balances on the Zetrix blockchain.


# Syntax

## Syntax in Zetrix smart contract

### Overview

Zetrix smart contracts are developed using **JavaScript**, and to promote secure and standardized coding practices, **JSLint** is integrated for syntax validation. This ensures contracts conform to a consistent code style and helps detect common programming errors before deployment.

#### **Syntax Validation with JSLint**

* **Purpose**: JSLint enforces a strict subset of JavaScript to improve contract safety, readability, and maintainability.
* **Standard Reference**: Zetrix adapts the core JSLint rules and augments them with custom modifications tailored for smart contract use.
* **Usage Documentation**: Detailed explanations of the standard JSLint syntax and Zetrix-specific extensions are provided through a local documentation site.

#### **Accessing the JSLint Manual**

You can access the complete JSLint guide, including examples and rule definitions, via:

```html
127.0.0.1:36002/jslint/help.html
```

This URL is accessible through **Zetrix node servers** or **wallet interfaces** that run the local environment.

> **Note**: Ensure the local node or wallet server is running to open this documentation.

This tool is essential for validating contract scripts prior to deployment on the Zetrix blockchain.

### Detection Tool

You can access the Zetrix JSLint interface via:

```html
127.0.0.1:36002/jslint/index.html
```

This page is available through **Zetrix node servers** or **local wallet interfaces**, and serves as the primary interface for contract syntax checking.

For error description, details will be given when you debug contract syntax in the web tool. When you input the following code:

```javascript
"use strict";
function init(bar)
{
    
}
```

Error is shown below:

```
Empty block.   2.0
{
```

Cause: Blank statement block at row 2 and column 0.

Correct code is shown below:

```javascript
"use strict";
function init(bar)
{
    return;    
}
```

If the code is correct, no warning or error messages will be shown the tool will simply remain silent, indicating successful validation..

### &#x20;<a href="#text-compression" id="text-compression"></a>

### Text Compression

After writing your smart contract, you can use the **JSMin** tool to compress the code. This reduces file size by removing unnecessary whitespace and comments. However, since compression is **irreversible** and may affect readability, it's important to **save the original version** of the contract before performing this operation.

### &#x20;<a href="#demo" id="demo"></a>

### Demo

```javascript
"use strict";
function init(bar)
{
    /*init whatever you want*/
    return;
}

function main(input) 
{
    Utils.log(input);

    //for statement
    let i;
    for (i = 0; i < 5; i += 1) 
    {
        Utils.log(i);
    }

    //while statement
    let b = 10;
    while (b !== 0) 
    {
        b -= 1;
        Utils.log(b);
    }

    //if statement
    let compare = 1;
    if(compare === 1)
    {
        Utils.log("it is one");
    }
    else if(compare === 2)
    {
        Utils.log("it is two");
    }
    else
    {
        Utils.log("it is other");
    }

    //if statement
    if(compare !== 2)
    {
        Utils.log("no, different");
    }

    //switch statement
    let sw_value = 1;
    switch(sw_value)
    {
    case 1:
        Utils.log("switch 1");
        break;
    default:
        Utils.log("default");
    }

    //Number
    let my_num = Number(111);
    Utils.log(my_num);

    //String
    let my_str = String(111);
    Utils.log(my_str);

    //Boolean
    let my_bool = Boolean(111);
    Utils.log(my_bool);

    //Array
    let str_array = ["red","black"]; 
    Utils.log(str_array);

    //Array
    let num_array = [1,2,3,4];
    Utils.log(num_array);

    throw "this is a exception";
}
```

### &#x20;<a href="#rules-list" id="rules-list"></a>

### Rules List

* **Strict Mode**
  * Every contract must begin with:

    ```javascript
    javascriptCopyEdit"use strict";
    ```
* **Variable Declarations**
  * Use `let` to declare variables within block scopes.
  * Avoid `var` for variable declarations.
* **Comparison Operators**
  * Use strict equality: `===` and `!==`
  * Avoid loose comparisons: `==` and `!=`
* **Statement Termination**
  * All statements must end with a **semicolon (`;`)**.
* **Statement Blocks**
  * Blocks must be enclosed in `{}`.
  * **Empty blocks are not allowed**.
* **For Loops**
  * Declare the loop variable **before** the condition block.
  * Update its value with **explicit assignment**, not using `++` or `--`.
* **Operators**
  * Use `+=` and `-=` instead of `++` and `--`.
* **Restricted Keywords**
  * **Prohibited**: `eval`, `void`, `try`, and `catch`
  * You **can** use `throw` to raise exceptions.
* **Object Creation**
  * Do not use `new` with primitives like `Number`, `String`, or `Boolean`.\
    Example (not allowed): `new Number(5)`
  * Instead, use direct value constructors:\
    Example (allowed): `Number("5")`
* **Array Creation**
  * Avoid creating arrays using the `Array` constructor.\
    Example (not allowed): `new Array(3)`
  * Instead, use array literals:\
    Example (allowed): `[1, 2, 3]`
* **Prohibit to use keywords** like `try` and `catch`, but you can use `throw` to throw exceptions

```javascript
"Array", "ArrayBuffer", "Float32Array", "Float64Array", 
"Int8Array", "Int16Array", "Int32Array", "Uint8Array", 
"Uint8ClampedArray", "Uint16Array", "Uint32Array"

let color = new Array(100); //Compiling error

//You can use the alternative new Array(100) statement;
let color = ["red","black"]; 
let arr = [1,2,3,4];
```

* Keywords prohibited to use

```javascript
"DataView", "decodeURI", "decodeURIComponent", "encodeURI", 
"encodeURIComponent", "Generator","GeneratorFunction", "Intl", 
"Promise", "Proxy", "Reflect", "System", "URIError", "WeakMap", 
"WeakSet", "Math", "Date"
```


# API


# Overview

### Overview of Zetrix API

Zetrix offers a comprehensive set of **API interfaces** including **HTTP** and **WebSocket** to simplify user interaction with the blockchain. These APIs allow developers to efficiently query data, submit transactions, and receive real-time updates, streamlining integration and application development on the Zetrix network.

#### HTTP Interface Overview

​The request data and response data in the HTTP interface are in JSON format.

The configuration items of the HTTP interface are configured under the `webserver` file in the `config` directory. The configuration contents are as follows:

```json
"webserver": {
  "listen_addresses": "0.0.0.0:36002" // Listen IP and PORT
}
```

#### Websocket Interface Overview

The WebSocket interface in Zetrix uses **Protocol Buffer 3 (proto3)** for both request and response data, a data serialization format developed by Google; users unfamiliar with it are encouraged to refer to the proto3 documentation for more details.

​The configuration items of the Websocket interface are configured under the `wsserver` file in the `config` directory. The configuration contents are as follows:

```json
"wsserver": {
    "listen_address": "0.0.0.0:36003" // Listen IP and PORT
}
```

### Transaction Process

1. **Assemble the Transaction Object**
   * Create the transaction according to your requirements.
   * Use JSON format for HTTP interfaces and Protobuf format for WebSocket interfaces.
2. **Serialize the Transaction**
   * Convert the transaction object into a byte stream (`transaction_blob`).
   * Use `getTransactionBlob` for HTTP or the Protobuf `serialize` method for WebSocket.
3. **Sign the Transaction**
   * Sign the `transaction_blob` with your private key (`skey`) to generate `sign_data`.
   * The corresponding public key (`pkey`) will also be used.
4. **Submit the Transaction**
   * Use the appropriate submit method: HTTP Submit Transaction or WebSocket Submit Transaction.
5. **Verify Transaction Execution**
   * For HTTP: use `getTransactionHistory`.
   * For WebSocket: check the response message from the submitted transaction.


# HTTP

### Give it a go!

If your blockchain has just been deployed, it will initially contain only the **genesis account**. You can verify this account using the HTTP interface. For example, on a local setup on port **36002**, use the following endpoint:

```http
http://127.0.0.1:36002/v1/account/getGenesisAccount
```

This will return details of the genesis account, including address, balance, and other initial parameters.

```http
HTTP GET https://{endpoint}/getGenesisAccount
or
curl get https://{endpoint}/getGenesisAccount
```

If you would like to use our testnet or mainnet as reference, the respective endpoints are below:

Testnet: <https://test-node.zetrix.com>

Mainnet: <https://node.zetrix.com>

The response content should be as follows:

```json
{
  "error_code" : 0,
  "result" : {
    "address" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",
    "assets" : null,
    "balance" : 100000000000000000,
    "metadatas" : null,
    "priv" : {
      "master_weight" : 1,
      "thresholds" : {
        "tx_threshold" : 1
      }
    }
  }
}
```

The value of `address` in the returned result is the genesis account address.

### HTTP Interfaces

#### Generating Public and Private Key pairs - Test

```http
HTTP GET /createKeyPair
```

* CURL command

  ```shell
  curl get https://{endpoint}/createKeyPair
  ```
* Function

  > **Note:** This interface is intended **only for testing purposes** and should **not be used in a production environment**. In production, use the SDK or command line tools. Calling this interface on an untrusted or malicious node server may expose your **private key**, as it only generates a key pair and does **not broadcast anything to the blockchain**. Use it with caution and only in isolated, secure testing environments.
* Return value

  ```json
  {
    "error_code" : 0,
    "result" : {
      "address" : "ztxSkMvC2RcvXLpDgXBJCSb4m9mPe8gpNDKAG",  //The account address
      "private_key" : "privbzMRMFKoT8xPSPLqXoJb3GxgoULcR2go9WVNPG2N9e9oX251AgAU",  //The private key of the account
      "private_key_aes" : "7594a97bc5e6432704cc5f58ff60727ee9bda10a6117915d025553afec7f81527cb857b882b7c775391fe1fe3f7f3ec198ea69ada138b19cbe169a1a3fa2dec8",  //The data after the private key of the account is encrypted with AES
      "public_key" : "b00101da11713eaad86ad8ededfc28e86b8cd619ca2d593a21d8b82da34320a7e63b09c279bc", //The public key of the account
      "public_key_raw" : "01da11713eaad86ad8ededfc28e86b8cd619ca2d593a21d8b82da34320a7e63b",  //The data of the public key excluding the prefix and suffix
      "sign_type" : "ed25519"  //The type of the account encryption
    }
  }
  ```

#### getAccount

```http
HTTP GET /getAccount?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV&key=hello&code=xxx&issuer=xxx
```

* CURL command

```shell
curl get https://{endpoint}/getGenesisAccount?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
```

* Function

  Return information about the specified account and all its assets and metadata.
* Parameters

  | Parameter                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
  | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | address (required)           | Zetrix account address.                                                                                                                                                                                                                                                                                                                                                                                                                               |
  | key (optional)               | Specifies the key to retrieve a specific metadata value associated with the account. If left blank, the response will return **all metadata** linked to the account.                                                                                                                                                                                                                                                                                  |
  | code, issuer (both optional) | <p><strong>Asset Code and Asset Issuer:</strong> These two fields must be either <strong>both be provided</strong> or <strong>both left blank</strong>.</p><ul><li>If <strong>left blank</strong>, the response will include <strong>all assets</strong> associated with the account.</li><li>If <strong>provided</strong>, the response will return details <strong>only for the specified asset</strong> (matching both code and issuer).</li></ul> |
* Return value

  The content returned is as follows:

  ```json
  {
  "error_code" : 0,//Error code, 0 means success
  "result" : {
    "address" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV", //The address of the account
    "balance" : 300000000000,//Gas balance, in UGas
    "nonce" : 1, //The number of transactions that the account has currently executed. If nonce is 0, this field is not displayed.
    "assets" : [//The asset list
      {
        "amount" : 1400,//The amount of the asset
        "key"　://Keyword of this asset
        {
          "code" : "CNY",//The asset code
          "issuer" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV"　//The account address of the asset issuer 
        }
      }, {
        "amount" : 1000,
        "key" :
        {
          "code" : "USD",
          "issuer" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV"
        }
      }
    ],
    "assets_hash" : "9696b03e4c3169380882e0217a986717adfc5877b495068152e6aa25370ecf4a",//The hash value generated by the asset list
    "contract" : null,//Contract. **Empty** means that the current contract is not a contract
    "metadatas" : [//Metadata list
      {
        "key" : "123",//Keyword of metadata
        "value" : "123_value",//Metadata content
        "version" : 1 // Metadata version
      }, {
        "key" : "456",
        "value" : "456_value",
        "version" : 1
      }, {
        "key" : "abcd",
        "value" : "abcd_value",
        "version" : 1
      }
    ],
    "metadatas_hash" : "82c8407cc7cd77897be3100c47ed9d43ec4097ee1c00e2c13447187e5b1ac66c",//The hash value generated by the metadata list
    "priv" : {//The privilege of the account
      "master_weight" : 1,//The weight for the account
      "thresholds" : {
        "tx_threshold" : 1//The weight required to initiate a transaction
      }
    }
  }
  }
  ```

  \
  If the account does not exist, the content returned is as follows:

  ```json
  {
  "error_code" : 4,//Error code, 4 means the account does not exist
  "result" : null
  }
  ```

#### getAccountBase

```http
HTTP GET /getAccountBase?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
```

* CURL command

  ```shell
  curl get https://{endpoint}//getAccountBase?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
  ```
* Function

  Return basic information about the specified account, excluding assets and metadata.
* Parameter

  | Parameter          | Description             |
  | ------------------ | ----------------------- |
  | address (required) | Zetrix account address. |
* Return value

  The content returned is as follows:

  ```json
  {
  "error_code" : 0,//Error code, 0 indicates success
  "result" : {
    "address" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV", //The address of the account
    "assets_hash" : "9696b03e4c3169380882e0217a986717adfc5877b495068152e6aa25370ecf4a",//The hash value generated by the asset list
    "balance" : 899671600,//Gas balance in UGas
    "contract" : null,//Contract. **Empty** indicates the current account is not a contract account
    "nonce" : 1, //The number of transactions that the account has currently executed. If nonce is 0, this field is not displayed.
    "priv" : {//Account privileges
      "master_weight" : 1,//The weight of the account
      "thresholds" : {
        "tx_threshold" : 1 //The weight required to initiate a transaction
      }
    },
    "metadatas_hash" : "82c8407cc7cd77897be3100c47ed9d43ec4097ee1c00e2c13447187e5b1ac66c"　// The hash value generated by the metadata list
  }
  }
  ```

  \
  If the account does not exist, the content returned is as follows:

  ```json
  {
  "error_code" : 4,//Error code, 4 indicates the account does not exist
  "result" : null
  }
  ```

#### getAccountAssets

```http
HTTP GET /getAccountAssets?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
```

* CURL command

  ```shell
  curl get https://{endpoint}/getAccountAssets?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
  ```
* Function

  Return the asset information of the specified account.
* Parameters

  | Parameter                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
  | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | address (required)           | Zetrix account address.                                                                                                                                                                                                                                                                                                                                                                                                                               |
  | code, issuer (both optional) | <p><strong>Asset Code and Asset Issuer:</strong> These two fields must be either <strong>both be provided</strong> or <strong>both left blank</strong>.</p><ul><li>If <strong>left blank</strong>, the response will include <strong>all assets</strong> associated with the account.</li><li>If <strong>provided</strong>, the response will return details <strong>only for the specified asset</strong> (matching both code and issuer).</li></ul> |
* Return value

  The content returned is as follows:

  ```json
  {
  "error_code" : 0,//Error code, 0 indicates the account does not exist
  "result": [//If the result is not null, it indicates the asset is existed
    {
      "amount" : 1400,//The amount of assets owned
      "key" ://Asset identification, including asset code and issuer
      {
        "code" : "EES",//Asset code
        "issuer" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV" //The account address of the issuer
      }
    },
    {
      "amount" : 1000,
      "key" :
      {
        "code" : "OES",
        "issuer" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV"
      }
    }
  ]
  }
  ```

  \
  If the account does not hold any assets, the returned content is typically:

  ```json
  {
  "error_code" : 0,//Error code, 0 indicates the account does not existed
  "result" : null　//Result is null, indicating that the asset does not exist
  }
  ```

#### getAccountMetaData

```http
HTTP GET /getAccountMetaData?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
```

* CURL command

  ```shell
  curl get https://{endpoint}/getAccountMetaData?address=ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV
  ```
* Function

  Return the metadata information of the specified account.
* Parameters

  | Parameter          | Description                           |
  | ------------------ | ------------------------------------- |
  | address (required) | Zetrix account address.               |
  | key (optional)     | Specify the key value in the metadata |
* Return value

  The content returned is as follows:

  ```json
  {
  "error_code" : 0,//Error code, 0 indicates the account does not exist
  "result": {//Result is not null, indicating that metadata exists
    "123": {
      "key" : "123",
      "value" : "123_value",
      "version" : 1
    },
    "456": {
      "key" : "456",
      "value" : "456_value",
      "version" : 1
    },
    "abcd": {
      "key" : "abcd",
      "value" : "abcd_value",
      "version" : 1
    }
  }
  }
  ```

  \
  If the account does not have metadata, return the content:

  ```json
  {
  "error_code" : 0,//Error code, 0 indicates the account does not exist
  "result" : null //Result is null, indicating that the metadata does not exist
  }
  ```

#### getTransactionHistory

```http
HTTP GET /getTransactionHistory?ledger_seq=6
```

* CURL command

  ```shell
  curl get https://{endpoint}/getTransactionHistory?ledger_seq=6
  ```
* Function

  Return the completed transaction history.
* Parameters

  | Parameter   | Description                                                       |
  | ----------- | ----------------------------------------------------------------- |
  | hash        | Query using the transaction hash, which is its unique identifier. |
  | ledger\_seq | Query all transactions in the specified block                     |

  > **Note**: The constraint between the two parameters operates as a **logical AND**. If both are specified, the system will query the **specific transaction within the specified block**.
* Return value

  The content returned is as follows:

  > **Note**: Below are two transactions; the second one creates a contract account. Carefully review the `error_desc` field for any execution errors or issues during processing.

  ```json
  {
      "error_code": 0,//Error code, o indicates the transaction is exited
      "result": {
          "total_count": 2,//The number of transactions queried
          "transactions": [{//The transaction list
              "actual_fee": 313000,//The actual fee for the transaction
              "close_time": 1524031260097214,//When the transaction is completed
              "error_code": 0,// The error code of the transaction, 0 means the transaction is executed successfully, and non-zero means the transaction execution failed
              "error_desc": "",//Description for the error in the transaction
              "hash": "89a9d6e5d2c0e2b5c4fe58045ab2236d12e9449ef232342a48a2e2628e12014d",//The hash value of the transaction
              "ledger_seq": 6,//The block height of the transaction
              "signatures": [{//The signature list
                  "public_key": "b00180c2007082d1e2519a0f2d08fd65ba607fe3b8be646192a2f18a5fa0bee8f7a810d011ed",//Public key
                  "sign_data": "27866d70a58fc527b1ff1b4a693b8034b0078fc7ac7591fb05679abe5ca660db5c372922bfa8f26e76511e2c33386306ded7593874a6aec5baeeaddbd2012f06"//Data signed
              }],
              "transaction": {//Transaction content
                  "fee_limit": 10000000000,//The maximum fee provided for this transaction, in UGas
                  "gas_price": 1000,//The price of gas, in UGas
                  "nonce": 1,//The sequence number of the transaction in the account
                  "operations": [{//The operation list
                      "create_account": {//The operation to create an account
                          "dest_address": "ztxSrDYeqnCeyDFNJQDdMJok3PB1jAhmctaWY",//The address of the target account
                          "init_balance": 10000000,//The initial Gas of the target account, in UGas
                          "priv": {//The privilege of the target account
                              "master_weight": 1,//The weight of the target account
                              "thresholds": {
                                  "tx_threshold": 1 //The weight required to initiate a transaction for the target account
                              }
                          }
                      },
                      "type": 1 //The type of the operation, 1 means the operation is to create an account
                  },
                  {
                      "create_account": {
                          "dest_address": "ztxSVVQUx2GJSb1sfoWDMmHNpms4fuuA5s2WW",
                          "init_balance": 10000000,
                          "priv": {
                              "master_weight": 1,
                              "thresholds": {
                                  "tx_threshold": 1
                              }
                          }
                      },
                      "type": 1
                  }],
                  "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV" //The account address to initiate the transaction
              },
              "tx_size": 313 //The transaction byte
          },
          {
              "actual_fee": 1000402000,//The actual fee for the transaction
              "close_time": 1524031260097214,//When the transaction is completed
              "error_code": 0,// The error code of the transaction, 0 means the transaction is executed successfully, and non-zero means the transaction execution failed
              "error_desc": "[{\"contract_address\":\"ztxSpuMcbgPuNALPdRMJEQZhrMfA5u9ycUZCo\",\"operation_index\":0}]", //The result of contract creation, including contract address and operation index values
              "hash": "4cbf50e03645f1075d7e5c450ced93e26e3153cf7b88ea8003b2fda39e618e64",//The hash value of the transaction
              "ledger_seq": 6,//The block height of the transaction
              "signatures": [{//The signature list
                  "public_key": "b00180c2007082d1e2519a0f2d08fd65ba607fe3b8be646192a2f18a5fa0bee8f7a810d011ed",//Public key
                  "sign_data": "87fdcad0d706479e1a3f75fac2238763cd15fd93f81f1b8889fb798cefbe1752c192bbd3b5da6ebdb31ae47d8b62bb1166dcceca8d96020708f3ac5434838604" //Data signed
              }],
              "transaction": {//Transaction content
                  "fee_limit": 20004420000,//The maximum fee for this transaction
                  "gas_price": 1000,//The price of gas
                  "nonce": 30,//The sequence number of the transaction in the account
                  "operations": [{//The operation list
                      "create_account": {//The operation to create an account
                          "contract": {//Contract
                              "payload": "'use strict';\n\t\t\t\t\tfunction init(bar)\n\t\t\t\t\t{\n\t\t\t\t\t  return;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfunction main(input)\n\t\t\t\t\t{\n\t\t\t\t\t  return;\n\t\t\t\t\t}\n\t\t     function query()\n\t\t\t\t\t{\n\t\t\t\t\t  return;\n\t\t\t\t\t}\n\t\t      \n\t\t          "　//Contract code
                          },
                          "init_balance": 10000000,//The initial Gas of the contract account, in UGas
                          "priv": {//The privilege of the contract account
                              "thresholds": {
                                  "tx_threshold": 1 //The weight required to initiate a contract account transaction
                              }
                          }
                      },
                      "type": 1 // The operation type, 1 indicates the operation to create an account
                  }],
                  "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV" //The account address to initiate the transaction
              },
              "tx_size": 402 //The transaction byte
          }]
      }
  }
  ```

  \
  If no transaction is found, the response will be:

  ```json
  {
  "error_code": 4,//Error code, 4 indicates no transaction
  "result":
  {
    "total_count": 0,//The number of transactions queried
    "transactions": []
  }
  }
  ```

#### getTransactionCache

```http
HTTP GET /getTransactionCache?hash=ad545bfc26c440e324076fbbe1d8affbd8a2277858dc35927d425d0fe644e698&limit=100
```

* CURL command

  ```shell
  curl get https://{endpoint}/getTransactionCache?hash=ad545bfc26c440e324076fbbe1d8affbd8a2277858dc35927d425d0fe644e698&limit=100
  ```
* Function

  If a transaction has been submitted successfully but not yet executed, the response will include the transaction details with a status indicating it is **pending** or **not yet executed**, and `error_code` will typically be `0`, with execution fields left unset
* Parameters

  <table><thead><tr><th width="360">Parameter</th><th>Description</th></tr></thead><tbody><tr><td>hash</td><td>Use the transaction hash, which is its unique ID, to query specific transaction details.</td></tr><tr><td>limit</td><td>Query multiple (N) transactions currently in the transaction queue to view their pending processing status.</td></tr></tbody></table>

  > **Note**: The constraint between the two parameters functions as a **logical OR**. If both parameters are provided, the system will prioritize and perform a **hash-based query**.
* Return value

  The response will returned is as follows:

  ```json
  {
  "error_code": 0,//Error code, 0 indicates the query is successful
  "result": {
    "total_count": 1,//The total transactions
    "transactions": [//The transaction list
      {
        "hash": "a336c8f4b49c8b2c5a6c68543368ed3b450b6138a9f878892cf982ffb6fe234e",//The transaction hash
        "incoming_time": 1521013029435154,//When the transaction enters the cache queue
        "signatures": [//The signature list
          {
            "public_key": "b001882b9d1b5e7019f163d001c85194cface61e294483710f5e66ef40a4d387f5fcb0166f4f",//Public key
            "sign_data": "c5885144ffccb0b434b494271258e846c30a4551036e483822ee2b57400576e9e700e8960eb424764d033a2e73af6e6a2bfa5da390f71161732e13beee206107" //Data signed
          }
        ],
        "status": "processing",//The transaction status
        "transaction": {//Transaction content
          "fee_limit": 100000,//The maximum fee provided for this transaction, in UGas
          "gas_price": 1000,//The price of gas, in UGas
          "nonce": 2,//The sequence number of the transaction in the account
          "operations": [//The operation list
            {
              "create_account": {//The operation to create an account
                "dest_address": "ztxSnVDvg3gfW8as4BeodEJDDQAMXu9NobyvN",//The address of the target account
                "init_balance": 300000,//The initial Gas of the target account, in UGas
                "priv": {//The privilege of the target account
                  "master_weight": 1,//The weight of the target account
                  "thresholds": {
                    "tx_threshold": 2 //The weight required to initiate a transaction for the target account
                  }
                }
              },
              "type": 1　// The operation type, 1 indicates the operation to create an account
            }
          ],
          "source_address": "ztxSkScnQJ1ciM1C9rBVw6DbtogbAcWFuXRhC"// The account address to initiate the transaction
        }
      }
    ]
  }
  }
  ```

  \
  If no transaction is found, the response will be:

  ```json
  {
  "error_code": 4,//Error code, 4 indicates no transaction is queried
  "result":
  {
    "total_count": 0,//The number of transactions queried
    "transactions": []
  }
  }
  ```

#### getLedger

```http
HTTP GET /getLedger?seq=xxxx&with_validator=true&with_consvalue=true&with_fee=true
```

* CURL command

  ```shell
  curl get https://{endpoint}/getLedger?seq=6&with_validator=true&with_consvalue=true&with_fee=true
  ```
* Function

  Return information about block header.
* Parameters

  <table><thead><tr><th width="170">Parameter</th><th>Description</th></tr></thead><tbody><tr><td>seq</td><td>The ledger serial number specifies a particular block; if left blank, the latest (current) ledger is returned.</td></tr><tr><td>with_validator</td><td>By default, this is set to <strong>false</strong>, so the list of verification nodes will <strong>not</strong> be displayed.</td></tr><tr><td>with_consvalue</td><td>By default, this is set to <strong>false</strong>, and the consensus value is <strong>not</strong> displayed.</td></tr><tr><td>with_fee</td><td>By default, this is set to <strong>false</strong>, so the cost configuration is not shown.</td></tr></tbody></table>
* Return value

  Return response as follows:

  ```json
  {
  "error_code" : 0,//Error code, 0 indicates success
  "result" : {
    "block_reward" : 800000000,//Block reward, in UGas
    "consensus_value" : {//Consensus content
      "close_time" : 1524031260097214,//When the consensus is finished
      "ledger_seq" : 6,//The block height
      "previous_ledger_hash" : "ef329c7ed761e3065ab08f9e7672fd5f4e3ddd77b0be35598979aff8c21ada9b",//The hash of the previous block
      "previous_proof" : "0ac1010a2c080110022a26080310052220432dde2fd32a2a66da77647231821c87958f56c303bd08003633952d384eb0b61290010a4c623030316435363833363735303137666662633332366538666232303738653532316566383435373234363236353339356536383934633835323434656566643262666130386635393862661240deeb9b782410f0f86d897006cac8ad152e56e4f914e5d718706de84044ef98baef25512a337865772641d57090b5c77e9e2149dbd41910e8d6cd85c3387ea708",//The certificate of the previous block 
      "previous_proof_plain" : {//The content of the previous block certificate
        "commits" : [
          {
            "pbft" : {
              "commit" : {
                "sequence" : 5,//The serial number of the block
                "value_digest" : "432dde2fd32a2a66da77647231821c87958f56c303bd08003633952d384eb0b6",//Summary
                "view_number" : 3 //The serial number of the view
              },
              "round_number" : 1,
              "type" : 2 //Type
            },
            "signature" : {//The signature of the node
              "public_key" : "b001d5683675017ffbc326e8fb2078e521ef8457246265395e6894c85244eefd2bfa08f598bf",//Public key
              "sign_data" : "deeb9b782410f0f86d897006cac8ad152e56e4f914e5d718706de84044ef98baef25512a337865772641d57090b5c77e9e2149dbd41910e8d6cd85c3387ea708"　//Data signed
            }
          }
        ]
      },
      "txset" : {//Transaction set
        "txs" : [//The transaction list
          {
            "signatures" : [//The signature list
              {
                "public_key" : "b00180c2007082d1e2519a0f2d08fd65ba607fe3b8be646192a2f18a5fa0bee8f7a810d011ed",//Public key
                "sign_data" : "27866d70a58fc527b1ff1b4a693b8034b0078fc7ac7591fb05679abe5ca660db5c372922bfa8f26e76511e2c33386306ded7593874a6aec5baeeaddbd2012f06" //Data signed
              }
            ],
            "transaction" : {//Transaction content
              "fee_limit" : 10000000000,//The maximum fee provided for this transaction, in UGas
              "gas_price" : 1000,//The price of gas, in UGas
              "nonce" : 1,//The sequence number of the transaction in the account
              "operations" : [//The operation list
                {
                  "create_account" : {//The operation to create an account
                    "dest_address" : "ztxSrDYeqnCeyDFNJQDdMJok3PB1jAhmctaWY",//The target account
                    "init_balance" : 10000000,//The initial Gas of the target account, in UGas
                    "priv" : {//The privilege of the target account
                      "master_weight" : 1,//The weight owned by the target account
                      "thresholds" : {
                        "tx_threshold" : 1 //The weight required to initiate a transaction for the target account
                      }
                    }
                  },
                  "type" : 1 //The operation type, 1 indicates the operation is to create an account
                },
                {
                  "create_account" : {
                    "dest_address" : "ztxSVVQUx2GJSb1sfoWDMmHNpms4fuuA5s2WW",
                    "init_balance" : 10000000,
                    "priv" : {
                      "master_weight" : 1,
                      "thresholds" : {
                        "tx_threshold" : 1
                      }
                    }
                  },
                  "type" : 1
                }
              ],
              "source_address" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV"
            }
          },
          {
            "signatures" : [
              {
                "public_key" : "b00180c2007082d1e2519a0f2d08fd65ba607fe3b8be646192a2f18a5fa0bee8f7a810d011ed",
                "sign_data" : "fb7d9d87f4c9140b6e19a199091c6871e2380ad8e8a8fcada9b42a2911057111dc796d731f3f887e600aa89cc8692300f980723298a93b91db711155670d3e0d"
              }
            ],
            "transaction" : {
              "fee_limit" : 10000000000,
              "gas_price" : 1000,
              "nonce" : 2,
              "operations" : [
                {
                  "create_account" : {
                    "dest_address" : "ztxSrbWSdMvysHtKQqpJzKAduQmDFHa1VHhRN",
                    "init_balance" : 10000000,
                    "priv" : {
                      "master_weight" : 1,
                      "thresholds" : {
                        "tx_threshold" : 1
                      }
                    }
                  },
                  "type" : 1
                },
                {
                  "create_account" : {
                    "dest_address" : "ztxSWwQmECKbyTTyx8RGVbaTapPqpHSPeskJy",
                    "init_balance" : 10000000,
                    "priv" : {
                      "master_weight" : 1,
                      "thresholds" : {
                        "tx_threshold" : 1
                      }
                    }
                  },
                  "type" : 1
                }
              ],
              "source_address" : "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV"
            }
          }
        ]
      }
    },
    "fees" : {//The fee standard of blocks
      "base_reserve" : 10000000,//The minimum Gas in the account, in UGas
      "gas_price" : 1000 //The price of gas, in UGas
    },
    "header" : {//The block header
      "account_tree_hash" : "6aca37dfe83f213942b21d02618b989619cfd7c0e67a8a14b0f7599dd4010aad",//The hash value of the account tree
      "close_time" : 1524031260097214,//When the block is generated
      "consensus_value_hash" : "14a65d69f619395135da2ff98281d5707494801f12184a4318b9a76383e651a8",//The hash value of onsensus content
      "fees_hash" : "916daa78d264b3e2d9cff8aac84c943a834f49a62b7354d4fa228dab65515313",//The hash value of the fee standard
      "hash" : "2cf378b326ab0026625c8d036813aef89a0b383e75055b80cb7cc25a657a9c5d",//The hash value of the block
      "previous_hash" : "ef329c7ed761e3065ab08f9e7672fd5f4e3ddd77b0be35598979aff8c21ada9b",//The hash value of the previous block
      "seq" : 6,//The block height
      "tx_count" : 2,//The total transactions
      "validators_hash" : "d857aa40ecdb123415f893159321eb223e4dbc11863daef86f35565dd1633316",//The hash value of the validation node list
      "version" : 1000 //The block version
    },
    "validators" : [//The validation node list
        "ztxSVW6zpibJ3amyauqk6339jjAgaL5LU9yAt" //The address of the validation node
    ]
   }
  }
  ```

  \
  If no ledger is found, the following response is returned:

  ```json
  { "error_code": 4, "result": null }
  ```

#### multiQuery

```http
HTTP POST /multiQuery
```

* CURL Command

  ```shell
  curl localhost:26002/multiQuery -X POST -d "{\"items\":[{\"url\":\"getAccount?address=ztxSgJCoz19wLJ4KbFjb3KDFs96xeW966iYgD\",\"method\":\"GET\",\"jsonData\":\"\"},{\"url\":\"hello\",\"method\":\"GET\",\"jsonData\":\"\"}]}"
  ```
* Function

  Returns multiple results based on the provided query list.
* Here, the request body should contain the **query list**. For example:

  ```json
  {
    "items":
    [
        {
        "url":"https://{endpoint}/?address=ztxSgJCoz19wLJ4KbFjb3KDFs96xeW966iYgD", // Query Command
        "method": "GET", // GET or POST query
        "jsonData":"" // If post query, here is the content of body
        },
        {
        "url":"hello", // Query Command
        "method": "GET", // GET or POST query
        "jsonData":"" // If post query, here is the content of body
        }
    ]
  }
  ```
* Return

  ```json
  {
      "error_code": 0, // Query error code
      "results": [
          {
              "error_code": 0, // getAccount error code
              "result": { // getAccount result
                  "address": "ztxSgJCoz19wLJ4KbFjb3KDFs96xeW966iYgD",
                  "assets": null,
                  "assets_hash": "ad67d57ae19de8068dbcd47282146bd553fe9f684c57c8c114453863ee41abc3",
                  "balance": 99989879492755000,
                  "metadatas": null,
                  "metadatas_hash": "ad67d57ae19de8068dbcd47282146bd553fe9f684c57c8c114453863ee41abc3",
                  "nonce": 10,
                  "priv": {
                      "master_weight": 1,
                      "thresholds": {
                          "tx_threshold": 1
                      }
                  }
              }
          },
          { // hello result
              "zetrix_version": "4.0.0",
              "current_time": "2020-02-28 17:33:37.282237",
              "hash_type": 0,
              "ledger_version": "4000",
              "license_version": "1.0.0",
              "monitor_version": "4000",
              "network_id": 30000,
              "overlay_version": "2000",
              "websocket_address": 36003
          }
      ]
  }
  ```

#### getTransactionBlob

```http
HTTP POST /getTransactionBlob
```

* CURL command

  ```shell
  curl https://{endpoint}/getTransactionBlob -X POST -d "{\"source_address\":\"adxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV\",\"nonce\":1,\"fee_limit\":100000,\"gas_price\":1000,\"operations\":[{\"type\":1,\"create_account\":{\"dest_address\":\"ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo\",\"metadatas\":[{\"key\":\"hello\",\"value\":\metadata\"}],\"priv\":{\"thresholds\":{\"tx_threshold\":1}},\"contract\":{\"payload\":\"function main(inputStr){\n}\"}}}]}"
  ```
* Function

  Returns both the **transaction hash** and the **hexadecimal string** representing the serialized transaction.
* Here, the request body field **`transfer`** contains the transaction data. For the specific JSON structure and parameter definitions, refer to the **Transaction Structure** section.

  ```json
  {
    "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",
    "nonce": 1,
    "fee_limit": 100000,
    "gas_price": 1000,
    "operations": [{
      "type": 1,
      "create_account": {
        "dest_address": "ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo",
        "metadatas": [{
          "key": "hello",
          "value": "metadata"
        }],
        "priv": {
          "thresholds": {
            "tx_threshold": 1
          }
        },
        "contract": {
          "payload": "function main(inputStr){\n}"
        }
      }
    }]
  }
  ```
* Return value

  ```json
  {
    "error_code": 0,//The serialized transaction error code
    "error_desc": "",//Description for the error
    "result": {
      "hash": "7ea4b61b86c5e2248e1ec24a8c04568e6b17c7121fb86f648b42b73bd3bada5d",//The transaction hash
      "transaction_blob": "0a2462755173396e70614371396d4e465a473138717538385a636d5859716436627170545533100118a08d0620e8073aad01080122a8010a24627551747336446654354b6176745639344a675a79373548397069776d62374b6f555767123a123866756e6374696f6e206d61696e28696e707574537472297b0a202f2ae8bf99e698afe59088e7baa6e585a5e58fa3e587bde695b02a2f207d1a041a020801223e0a0568656c6c6f1235e8bf99e698afe5889be5bbbae8b4a6e58fb7e79a84e8bf87e7a88be4b8ade8aebee7bdaee79a84e4b880e4b8aa6d65746164617461" //The hexadecimal representation after serializing the transaction
    }
  }
  ```

#### &#x20;<a href="#submittransaction" id="submittransaction"></a>

#### submitTransaction

```http
HTTP POST /submitTransaction
```

* CURL command

  ```shell
  curl https://{endpoint}/submitTransaction -X POST -d "{\"items\":[{\"transaction_blob\":\"0a2e61303032643833343562383964633334613537353734656234393736333566663132356133373939666537376236100122b90108012ab4010a2e61303032663836366337663431356537313934613932363131386363353565346365393939656232396231363461123a123866756e6374696f6e206d61696e28696e707574537472297b0a202f2ae8bf99e698afe59088e7baa6e585a5e58fa3e587bde695b02a2f207d1a06080a1a020807223e0a0568656c6c6f1235e8bf99e698afe5889be5bbbae8b4a6e58fb7e79a84e8bf87e7a88be4b8ade8aebee7bdaee79a84e4b880e4b8aa6d65746164617461\",\"signatures\":[{\"sign_data\":\"2f6612eaefbdadbe792201bb5d1e178aff118dfa0a640edb2a8ee91933efb97c4fb7f97be75195e529609a4de9b890b743124970d6bd7072b7029cfe7683ba2d\",\"public_key\":\"b00204e1c7dddc36d3153adcaa451b0ab525d3def48a0a10fdb492dc3a7263cfb88e80ee974ca4da0e1f322aa84ff9d11340c764ea756ad148e979c121619e9fe52e9054\"},{\"sign_data\":\"90C1CD2CD371F581EB8GasCDA295C390D62C19FE7F080FB981584FB5F0BAB3E293B613C827CB1B2E063E5783FFD7425E1DEC0E70F17C1227FBA5997A72865A30A\",\"public_key\":\"b00168eceea7900ddcb8f694161755f98590ba7944de3bfe339610fe0cacc10a18372dcbf71b\"}]}]}"
  ```
* Function

  Send the **serialized transaction** along with the **signature list** to the blockchain for processing and execution.
* Request example:

  ```json
  {
    "items" : [{//The transaction package list
      "transaction_blob" : "0a2e61303032643833343562383964633334613537353734656234393736333566663132356133373939666537376236100122b90108012ab4010a2e61303032663836366337663431356537313934613932363131386363353565346365393939656232396231363461123a123866756e6374696f6e206d61696e28696e707574537472297b0a202f2ae8bf99e698afe59088e7baa6e585a5e58fa3e587bde695b02a2f207d1a06080a1a020807223e0a0568656c6c6f1235e8bf99e698afe5889be5bbbae8b4a6e58fb7e79a84e8bf87e7a88be4b8ade8aebee7bdaee79a84e4b880e4b8aa6d65746164617461",//The hexadecimal representation after serializing the transaction
      "signatures" : [{//The first signature
        "sign_data" : "2f6612eaefbdadbe792201bb5d1e178aff118dfa0a640edb2a8ee91933efb97c4fb7f97be75195e529609a4de9b890b743124970d6bd7072b7029cfe7683ba2d",//Data signed
        "public_key" : "b00204e1c7dddc36d3153adcaa451b0ab525d3def48a0a10fdb492dc3a7263cfb88e80ee974ca4da0e1f322aa84ff9d11340c764ea756ad148e979c121619e9fe52e9054"//Public key
      }, {//The second signature
        "sign_data" : "90C1CD2CD371F581EB8GasCDA295C390D62C19FE7F080FB981584FB5F0BAB3E293B613C827CB1B2E063E5783FFD7425E1DEC0E70F17C1227FBA5997A72865A30A",//Data signed
        "public_key" : "b00168eceea7900ddcb8f694161755f98590ba7944de3bfe339610fe0cacc10a18372dcbf71b"//Public key
      }
                     ]
    }
              ]
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="184">Parameter</th><th width="101.3333740234375">Type</th><th>Description</th></tr></thead><tbody><tr><td>transaction_blob</td><td>string</td><td>The serialized transaction is represented in a <strong>hexadecimal string format</strong>, which encodes the transaction's binary data for transmission and verification.</td></tr><tr><td>sign_data</td><td>string</td><td>The signed data should be in <strong>hexadecimal format</strong> and represents the signature generated from the <code>transaction_blob</code>.<br><strong>Note:</strong> Before signing, <strong>convert <code>transaction_blob</code> to a byte stream</strong>—do <strong>not</strong> sign the hexadecimal string directly.</td></tr><tr><td>public_key</td><td>string</td><td>The public key must be provided in <strong>hexadecimal format</strong>, corresponding to the private key used to sign the transaction.</td></tr></tbody></table>
* Return value

  > **Note**: The transaction is submitted and executed successfully.

  ```json
  {
  "error_code": 0,//The result of the submission
  "error_desc": "",//Description for the error
  "result": {
    "hash": "8e97ab885685d68b8fa8c7682f77ce17a85f1b4f6c8438eda8ec955890919405",//The transaction hash
  }
  }
  ```

#### &#x20;<a href="#callcontract" id="callcontract"></a>

#### callContract

```http
HTTP POST /callContract
```

* CURL command

  ```shell
  curl https://{endpoint}/callContract -X POST -d "{\"contract_address\":\"\",\"code\":\"\\\"use strict\\\";log(undefined);function query() { return 1; }\",\"input\":\"{}\",\"contract_balance\":\"100009000000\",\"fee_limit\":100000000000000000,\"gas_price\":1000,\"opt_type\":2,\"source_address\":\"\"}"
  ```
* Function

  In Zetrix's smart contract module, a **sandbox environment** is provided for safe debugging. During debugging, **neither the blockchain state nor the contract state is modified**. Zetrix offers the `callContract` interface specifically for this purpose it allows you to test smart contracts either by referencing a deployed contract on the public chain or by passing local contract code as parameters. Since this interface does **not submit actual transactions**, **no transaction fee is required**.
* Request example:

  ```json
  {
    "contract_address" : "",//Optional, the smart contract address
    "code" : "\"use strict\";log(undefined);function query() { return 1; }",//Optional, the smart contract code
    "input" : "{}",//Optional, pass parameters to the contract to be called
    "contract_balance" : "100009000000",//The initial Gas balance assigned to the contract
    "fee_limit" : 100000000000000000,//The transaction fee
    "gas_price": 1000,//Optional, the gas price
    "opt_type" : 2,//Optional, the operation type
    "source_address" : "" //Optional, the original address of the simulated contract call
  }
  ```
* Keywords in JSON

  | Keyword           | Type   | Description                                                                                                                                                                                                           |
  | ----------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | contract\_address | string | The smart contract address to be called must be provided; if it cannot be found in the database, an error will be returned. If left blank, the system will default to using the content provided in the `code` field. |
  | code              | string | The `code` field contains the contract code to be debugged. If `contract_address` is not provided, the system will use the `code` field. If both `contract_address` and `code` are empty, an error will be returned.  |
  | input             | string | Pass the parameters to the contract to be called                                                                                                                                                                      |
  | contract\_balance | string | The initial Gas balance assigned to the contract                                                                                                                                                                      |
  | fee\_limit        | int64  | The transaction fee                                                                                                                                                                                                   |
  | gas\_price        | int64  | The price of gas                                                                                                                                                                                                      |
  | opt\_type         | int    | 0: call the contract's read-write interface `init`, 1: call the contract's read-write interface `main`, 2: call the read-only interface `query`                                                                       |
  | source\_address   | string | Simulate the original address of the contract called                                                                                                                                                                  |
* Return value

  ```json
  {
    "error_code" : 0,//The result of the call, 0 means success
    "error_desc" : "",//Description of error code
    "result" : {
      "logs" : {
        "0-ztxSWaq8TmFVyyHKXsYwb9FTaGEx77EWW2hne" : null　//Not used any more
      },
      "query_rets" : [
        {
          "result" : {
            "type" : "bool", //　Return the name of the variable
            "value" : false  // The value of the variable is false
          }
        }
      ],
      "stat" : {
        "apply_time" : 6315,//Execution time
        "memory_usage" : 886176,//Memory usage
        "stack_usage": 2564,//Stack usage
        "step" : 3 //Frequency of execution
      },
      "txs" : null　//Transaction set
    }
  }
  ```

#### &#x20;<a href="#testtransaction" id="testtransaction"></a>

#### testTransaction

```http
HTTP POST /testTransaction
```

* CURL command

  ```shell
  curl localhost:36002/testTransaction -X POST -d "{\"contract_address\":\"\",\"code\":\"\\\"use strict\\\";log(undefined);function query() { return 1; }\",\"input\":\"{}\",\"contract_balance\":\"100009000000\",\"fee_limit\":100000000000000000,\"gas_price\":1000,\"opt_type\":2,\"source_address\":\"\"}"
  ```
* Function

  The evaluation fee is fixed and **does not depend on the account balance**. Both the **originating account** and the **target account** involved in a transaction must exist in the system. However, when creating a new account, the **target address** is not required to pre-exist in the system.
* Request example:

  ```json
  {
    "items": [
      {
        "transaction_json": {
          "fee_limit": 99999999700110000,
          "gas_price": 1,
          "nonce": 1,
          "operations": [
            {
              "pay_coin": {
                "amount": 299890000,
                "dest_address": "ztxSdCZ13uZUWKv7AdhRcED6a9g7RjxpfKC1D"
              },
              "type": 7
            }
          ],
          "source_address": "ztxSkScnQJ1ciM1C9rBVw6DbtogbAcWFuXRhC"
        },
        "signature_number":1
      }
    ]
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="191">Keyword</th><th width="107.3333740234375">Type</th><th>Description</th></tr></thead><tbody><tr><td>source_address</td><td>string</td><td>The original address of the simulated transaction refers to the <strong>sender's address</strong> that initiates the contract call during debugging.</td></tr><tr><td>nonce</td><td>int64</td><td>Unique transaction sequence number.</td></tr><tr><td>signature_number</td><td>int64</td><td>Signature count; defaults to 1 if unset.</td></tr><tr><td>metadata</td><td>string</td><td>Optional, the number of signatures</td></tr><tr><td>operations</td><td>array</td><td><strong>Operation List</strong>: The transaction's payload defining its intended actions. Refer to <strong>Operations Structure</strong> for details.</td></tr></tbody></table>
* Return value

  ```json
  {
    "error_code": 0,
    "error_desc": "",
    "result": {
      "hash": "7f0d9de23d6d8f2964a1efe4a458e02e43e47f60f3c22bb132b676c54a44ba04",
      "logs": null,
      "query_rets": null,
      "stat": null,
      "txs": [
        {
          "actual_fee": 264,
          "gas": 264,
          "transaction_env": {
            "transaction": {
              "fee_limit": 99999999700110000,
              "gas_price": 1,
              "nonce": 1,
              "operations": [
                {
                  "pay_coin": {
                    "amount": 299890000,
                    "dest_address": "ztxSdCZ13uZUWKv7AdhRcED6a9g7RjxpfKC1D"
                  },
                  "type": 7
                }
              ],
              "source_address": "ztxSkScnQJ1ciM1C9rBVw6DbtogbAcWFuXRhC"
            }
          }
        }
      ]
    }
  }
  ```

### Transaction Structure

* In JSON format

  ```json
  {
    "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
    "nonce":2, //The nonce value of the source account
    "fee_limit" : 1000000, //The transaction fee that you intend to pay
    "gas_price": 1000,//The gas price (not less than the minimum configured)
    "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
    "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
    "operations":[
      {
        //Fill in according to specific operations
      },
      {
        //Fill in according to specific operations
      }
      ......
    ]
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="189">Keyword</th><th width="108">Type</th><th>Description</th></tr></thead><tbody><tr><td>source_address</td><td>string</td><td>The original address of the simulated transaction refers to the <strong>sender's address</strong> that initiates the contract call during debugging.</td></tr><tr><td>nonce</td><td>int64</td><td>Unique transaction sequence number.</td></tr><tr><td>fee_limit</td><td>int64</td><td><p><strong>Fee Limit</strong>: The maximum fee allowed for the transaction.</p><ul><li>If successful, the actual fee is charged.</li><li>If failed, the full fee limit is charged.<br><strong>Unit</strong>: UGas (1 Gas = 10⁶ UGas).</li></ul></td></tr><tr><td>gas_price</td><td>int64</td><td><strong>Gas Price</strong>: Used to calculate the handling fee per operation and the transaction byte fee.<br><strong>Unit</strong>: UGas (1 Gas = 10⁶ UGas).</td></tr><tr><td>ceil_ledger_seq</td><td>int64</td><td><strong>Optional</strong>: Sets a block height limit for the transaction an advanced feature to control when the transaction can be included.</td></tr><tr><td>operations</td><td>array</td><td><strong>Operation List</strong>: Defines what the transaction is intended to perform. Refer to <strong>Operations Structure</strong> for detailed information.</td></tr><tr><td>metadata</td><td>string</td><td><strong>Optional</strong>: A user-defined field that can be left blank or used to include a note.</td></tr></tbody></table>

### &#x20;<a href="#operations-structure" id="operations-structure"></a>

### Operations Structure

The corresponding `operations` in the JSON structure of the transaction can contain one or more operations.

* In JSON format

  ```json
  {
    "type": 1,//The operation type
    "source_address": "adxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations 
    "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
    "create_account": {
      //The parameters of the account to be created
    },
    "issue_asset": {
      //The parameters of the asset to be issued
    },
    "pay_asset": {
      //The parameters of the asset to be transferred
    },
    "set_metadata": {
      //Set the relevant parameters of the account metadata
    },
    "pay_coin": {
      //The parameters of the native token(Gas) to be transferred
    },
    "set_privilege": {
      ///The parameters of setting the account privileges
    },
    "log": {
      //The parameters of the log
    }
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="182">Keyword</th><th width="111">Type</th><th>Description</th></tr></thead><tbody><tr><td>type</td><td>int</td><td><strong>Operation Code</strong>: Identifies the specific action to perform. Different codes correspond to different operations. See <strong>Operation Codes</strong> for more details.</td></tr><tr><td>source_address</td><td>string</td><td><strong>Optional</strong>: Specifies the source account for the operation. If left blank, it defaults to the transaction’s source account.</td></tr><tr><td>metadata</td><td>string</td><td><strong>Optional</strong>: A custom field that can remain empty or include a user-defined note.</td></tr><tr><td>create_account</td><td>JSON</td><td>Creating Accounts operation</td></tr><tr><td>issue_asset</td><td>JSON</td><td>Issuing Assets operation</td></tr><tr><td>pay_asset</td><td>JSON</td><td>Transferring Assets operation</td></tr><tr><td>set_metadata</td><td>JSON</td><td>Setting Metadata operation</td></tr><tr><td>pay_coin</td><td>JSON</td><td>Transferring Gas Assets operation</td></tr><tr><td>log</td><td>JSON</td><td>Recording Logs operation</td></tr><tr><td>set_privilege</td><td>JSON</td><td>Setting Privileges operation</td></tr></tbody></table>

#### &#x20;<a href="#operation-codes" id="operation-codes"></a>

#### Operation Codes

<table><thead><tr><th width="156.33333333333331">Operation Code</th><th width="187">Operation</th><th>Description</th></tr></thead><tbody><tr><td>1</td><td>create_account</td><td>Creating Accounts</td></tr><tr><td>2</td><td>issue_asset</td><td>Issuing Assets</td></tr><tr><td>3</td><td>pay_asset</td><td>Transferring Assets</td></tr><tr><td>4</td><td>set_metadata</td><td>Setting Metadata</td></tr><tr><td>7</td><td>pay_coin</td><td>Transferring Gas Assets</td></tr><tr><td>8</td><td>log</td><td>Recording Logs</td></tr><tr><td>9</td><td>set_privilege</td><td>Setting Privileges</td></tr></tbody></table>

#### &#x20;<a href="#creating-accounts" id="creating-accounts"></a>

#### Creating Accounts

The source account creates a new account on the blockchain. Creating Accounts are divided into Creating Normal Accounts and Creating Contract Accounts.

**Creating Normal Accounts**

> **Note**: Both `master_weight` and `tx_threshold` must be 1 in the current operation.

* In JSON format

  ```json
  {
    "dest_address": "ztxSfW5K2GkmzNgBG95qjyX2tgZezmUCHYMfp",//The target account address to be created
    "init_balance": 100000,//The initial balance of the target account
    "priv":  {
      "master_weight": 1,//The weight owned by the target account
      "thresholds": {
        "tx_threshold": 1//The threshold required to initiate a transaction
      }
    }
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="157">Keyword</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td>dest_address</td><td>string</td><td><strong>Target Account Address</strong>: Required when creating a normal account; this field cannot be left empty.</td></tr><tr><td>init_balance</td><td>int64</td><td>The initial Gas value of the target account, in UGas, 1 Gas = 10^6 UGas</td></tr><tr><td>master_weight</td><td>int64</td><td>The master weight of the target account, which ranges [0, MAX(UINT32)]</td></tr><tr><td>tx_threshold</td><td>int64</td><td>The threshold for initiating a transaction below which the transaction cannot be initiated, which ranges ​​[0, MAX(INT64)]</td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
    "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
    "nonce":2, //The nonce value of the source account
    "fee_limit" : 1000000, //The transaction fee that you intend to pay
    "gas_price": 1000,//The gas price (not less than the minimum configured)
    "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
    "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
    "operations":[
      {
        "type": 1,//The create_account operation type
        "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations
        "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
        "create_account": {
          "dest_address": "ztxSfW5K2GkmzNgBG95qjyX2tgZezmUCHYMfp",//The target account address to be created
          "init_balance": 100000,//The initial balance of the target account
          "priv":  {
            "master_weight": 1,//The weight owned by the target account
            "thresholds": {
              "tx_threshold": 1//The threshold required to initiate a transaction
            }
          }
        }
      }
    ]
  }
  ```
* Query

  The account information is queried through the getAccount interface.

**Creating Contract Accounts**

> **Note**: In the current operation, `master_weight` must be 0 and `tx_threshold` must be 1.

* In JSON format

  ```json
  {
      "contract": { //Contract
          "payload": "
              'use strict';
              function init(bar)
              {
                return;
              }

              function main(input)
              {
                return;
              }

              function query()
              {
                return;
              }
            "//Contract code
          },
          "init_balance": 100000,//The initial asset of the contract account 
          "init_input" : "{\"method\":\"toWen\",\"params\":{\"feeType\":0}}",//Optional, the entry of the init function
          "priv": {
              "master_weight": 0,//The weight of the contract account to be created
              "thresholds": {
              "tx_threshold": 1 //The weight required to initiate a transaction
          }
      }
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="159">Keyword</th><th width="114">Type</th><th>Description</th></tr></thead><tbody><tr><td>payload</td><td>string</td><td>Contract code</td></tr><tr><td>init_balance</td><td>int64</td><td>The initial Gas value of the target account, in UGas, 1 Gas = 10^6 UGas</td></tr><tr><td>init_input</td><td>string</td><td><strong>Optional</strong>: Specifies the input parameters for the <code>init</code> function in the contract code.</td></tr><tr><td>master_weight</td><td>int64</td><td><strong>Master Weight</strong>: Defines the main authority level of the target account.</td></tr><tr><td>tx_threshold</td><td>int64</td><td>The threshold for initiating a transaction below which it is not possible to initiate a transaction.</td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
    "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
    "nonce":2, //The nonce value of the source account
    "fee_limit" : 1000000, //The transaction fee that you intend to pay
    "gas_price": 1000,//The gas price (not less than the minimum configured)
    "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
    "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
    "operations":[
      {
        "type": 1,//The create_account operation type
        "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations
        "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
        "create_account": {
          "contract": { //Contract
            "payload": "
              'use strict';
              function init(bar)
              {
                return;
              }

              function main(input)
              {
                return;
              }

              function query()
              {
                return;
              }
            "//Contract code
          },
          "init_balance": 100000,//The initial asset of the contract account 
          "init_input" : "{\"method\":\"toWen\",\"params\":{\"feeType\":0}}",//Optional, the entry of the init function
          "priv": {
            "master_weight": 0,//The weight of the contract account to be created
            "thresholds": {
              "tx_threshold": 1 //The weight required to initiate a transaction
            }
          }
        }
      }
    ]
  }
  ```
* Query
  * The account information is queried through the getAccount interface.
  * Query with the getTransactionHistory interface, and the result is as follows:

    ```json
    [
      {
        "contract_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV", //The contract account
        "operation_index": 0                                        //The operation index value in the transaction array, 0 means the first transaction
      }
    ]
    ```

#### Issuing Assets

* Function

  The source account in this operation issues a digital asset, which will appear in its asset balance upon successful execution.
* In JSON format

  ```json
  {
    "code": "HYL", //The code of the asset to be issued
    "amount": 1000 //The amount of the asset to be issued
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="120">Keyword</th><th width="113">Type</th><th>Description</th></tr></thead><tbody><tr><td>code</td><td>string</td><td>The code of the asset to be issued, which ranges [1, 64]</td></tr><tr><td>amount</td><td>int64</td><td>The amount of the asset to be issued, which ranges (0, MAX(int64))</td></tr></tbody></table>
* Complete transaction structure

  ```json
    {
    "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
    "nonce":2, //The nonce value of the source account
    "fee_limit" : 1000000, //The transaction fee that you intend to pay
    "gas_price": 1000,//The gas price (not less than the minimum configured)
    "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
    "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
    "operations":[
      {
        "type": 2,//The issue_asset operation type
        "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations
        "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
        "issue_asset": {
          "code": "HYL", //The code of the asset to be issued
          "amount": 1000 //The amount of the asset to be issued
        }
      }
    ]
  }
  ```

#### Transferring Assets

> **Note**: If the target account is a contract account, the current operation triggers the contract execution of the target account.

* Function

  The source account of this operation transfers an asset to the target account.
* In JSON format

  ```json
  {
    "dest_address": "ztxSmcbrEqbnNKWxfeWCb8kHR8zGBxdviJ7Pd",//The target account to receive the asset
    "asset": {
      "key": {
        "issuer": "ztxShgsZCaSrAQY3fS4xnvSruA2a9yBeopUYy",//The account to issue the asset
        "code": "HYL" // The code of the asset to be transferred
      },
      "amount": 100 //The amount of the asset to be transferred
    },
    "input": "{\"bar\":\"foo\"}"　// Optional, the input parameters of the main code of the contract code in the target account
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="166">Keyword</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td>dest_address</td><td>string</td><td>Address of the target account</td></tr><tr><td>issuer</td><td>string</td><td>Address of the issuer</td></tr><tr><td>code</td><td>string</td><td>Asset code which ranges [1, 64]</td></tr><tr><td>amount</td><td>int64</td><td>Amount of the asset which ranges (0,MAX(int64))</td></tr><tr><td>input</td><td>string</td><td><strong>Optional</strong>: If the target account is a contract, the input is passed to the <code>main</code> function's argument. This setting is ignored for normal accounts.</td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
    "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
    "nonce":2, //The nonce value of the source account
    "fee_limit" : 1000000,//The transaction fee that you intend to pay
    "gas_price": 1000,//The gas price (not less than the minimum configured)
    "ceil_ledger_seq": 100,//Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
    "metadata":"0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
    "operations":[
      {
        "type": 3,//The pay_asset operation type
        "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations
        "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
        "pay_asset": {
          "dest_address": "ztxSmcbrEqbnNKWxfeWCb8kHR8zGBxdviJ7Pd",//The target account to receive the asset
          "asset": {
            "key": {
              "issuer": "ztxShgsZCaSrAQY3fS4xnvSruA2a9yBeopUYy",//The account to issue the asset
              "code": "HYL" // The code of the asset to be transferred
            },
            "amount": 100 //The amount of the asset to be transferred
          },
          "input": "{\"bar\":\"foo\"}" // Optional, the input parameters of the main code of the contract code in the target account
        }
      }
    ]
  }
  ```

#### Setting Metadata

* Function

  The source account of this operation modifies or adds metadata to the metadata table.
* In JSON format

  ```json
  {
    "key": "abc",//Metadata Keyword
    "value": "hello abc!",//Metadata content
    "version": 0 //Optional, the metadata version
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="143">Keyword</th><th width="131">Type</th><th>Description</th></tr></thead><tbody><tr><td>key</td><td>string</td><td>Keyword of metadata, which ranges (0, 1024].</td></tr><tr><td>value</td><td>string</td><td>Content of metadata, which ranges [0, 256K].</td></tr><tr><td>version</td><td>int64</td><td><p><strong>Optional</strong>: Metadata version number, default is <code>0</code>.</p><ul><li><code>0</code>: No version limit</li><li><code>>0</code>: Must match the specified version</li><li><code>&#x3C;0</code>: Invalid value</li></ul></td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
  "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
  "nonce":2, //The nonce value of the source account
  "fee_limit" : 1000000, //The transaction fee that you intend to pay
  "gas_price": 1000,//The gas price (not less than the minimum configured)
  "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
  "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
  "operations":[
    {
      "type": 4,//The set_metadata operation type
      "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations
      "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
      "set_metadata": {
        "key": "abc",//Metadata Keyword
        "value": "hello abc!",//Metadata content
        "version": 0 //Optional, the metadata version
      }
    }
  ]
  }
  ```

#### Setting Privileges

* Function

  Set the **signer weights** and the **thresholds** required for different operations. For more details, refer to **Assignment of Control Rights**.
* In JSON format

  ```json
  {
    "master_weight": "10",//Optional, the current account's weight
    "signers": //Optional, a list of signers that need to operate
    [
      {
        "address": "ztxSWriszctU64GQAKdVjCCgW7bSsTb8repJk",//The signer's address
        "weight": 8　//Optional, the signer's weight
      }
    ],
    "tx_threshold": "2",//Optional, the threshold required to initiate the transaction
    "type_thresholds": //Optional, the thresholds required for different operations
    [
      {
        "type": 1,//The type of account creation
        "threshold": 8 //Optional, the threshold required for this operation
      },
      {
        "type": 2,//The type of asset issuance
        "threshold": 9 //Optional, the threshold required for this operation
      }
    ]
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="164">Keyword</th><th width="108">Type</th><th>Description</th></tr></thead><tbody><tr><td>master_weight</td><td>string</td><td><p><strong>Optional</strong>: Defaults to <code>""</code>, which refers to the account’s master weight.</p><ul><li><code>""</code>: Do not modify the value</li><li><code>"0"</code>: Set master weight to 0</li><li><code>"1"</code> to <code>"MAX(UINT32)"</code>: Set weight to the specified value</li><li>Any other input: Invalid value</li></ul></td></tr><tr><td>signers</td><td>array</td><td><strong>Optional</strong>: A list of signers involved in the operation. Defaults to an empty object, which means no signers are set.</td></tr><tr><td>address</td><td>string</td><td><strong>Signer Address</strong>: The address of the signer to be set, which must comply with the address verification rules.</td></tr><tr><td>weight</td><td>int64</td><td><p><strong>Optional</strong>: Defaults to <code>0</code>.</p><ul><li><code>0</code>: Deletes the signer</li><li><code>(0, MAX(UINT32)]</code>: Sets the signer’s weight to the specified value</li><li>Other values: Invalid</li></ul></td></tr><tr><td>tx_threshold</td><td>string</td><td><p><strong>Optional</strong>: Defaults to <code>""</code>, indicating the account’s minimum privilege (<code>tx_threshold</code>).</p><ul><li><code>""</code>: Do not modify the value</li><li><code>"0"</code>: Set <code>tx_threshold</code> to 0</li><li><code>"1"</code> to <code>"MAX(INT64)"</code>: Set to specified weight</li><li>Other values: Invalid</li></ul></td></tr><tr><td>type_thresholds</td><td>array</td><td><strong>Optional</strong>: A list of thresholds required for different operations. Defaults to an empty object, which means no thresholds are set.</td></tr><tr><td>type</td><td>int</td><td>To indicate a certain operation type (0, 100]</td></tr><tr><td>threshold</td><td>int64</td><td><p><strong>Optional</strong>: Defaults to <code>0</code>.</p><ul><li><code>0</code>: Deletes the operation type</li><li><code>(0, MAX(INT64)]</code>: Sets the operation’s threshold to the specified value</li><li>Other values: Invalid</li></ul></td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
  "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
  "nonce":2, //The nonce value of the source account
  "fee_limit" : 1000000, //The transaction fee that you intend to pay
  "gas_price": 1000,//The gas price (not less than the minimum configured)
  "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
  "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
  "operations":[
    {
      "type": 9,//The set_privilege operation type
      "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations
      "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
      "set_privilege": {
        "master_weight": "10",//Optional, the current account's weight
        "signers"://Optional, a list of signers that need to operate
        [
          {
            "address": "ztxSWriszctU64GQAKdVjCCgW7bSsTb8repJk",//The signer's address
            "weight": 8 //Optional, the signer's weight
          }
        ],
        "tx_threshold": "2",//Optional, the threshold required to initiate the transaction
        "type_thresholds"://Optional, the thresholds required for different operations
        [
          {
            "type": 1,//The type of account creation
            "threshold": 8 //Optional, the threshold required for this operation
          },
          {
            "type": 2,//The type of asset issuance
            "threshold": 9 //Optional, the threshold required for this operation
          }
        ]
      }
    }
  ]
  }
  ```

#### Transferring Gas Assets

> **Note**: If the target account is a contract account, the current operation triggers the contract execution of the target account.

* Function

  Two functions:

  1. The source account of this operation transfers a Gas asset to the target account.
  2. The source account of this operation creates a new account on the blockchain.
* In JSON format

  ```json
  {
    "dest_address": "ztxSgGkHuPv6FQUu6C5uWnaqyKJ22bSNrJUCJ",//The target account to receive Gas assets
    "amount": 100,//The amount of Gas assets to be transferred
    "input": "{\"bar\":\"foo\"}" // Optional, the input parameters of the main code of the contract code in the target account
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="136">Keyword</th><th width="99">Type</th><th>Description</th></tr></thead><tbody><tr><td>dest_address</td><td>string</td><td>The target account</td></tr><tr><td>amount</td><td>array</td><td><strong>Optional</strong>: A list of signers to be configured. Defaults to an empty object, which means no signer settings will be applied.</td></tr><tr><td>input</td><td>string</td><td><strong>Optional</strong>: If the target is a contract account, the input is passed to the <code>main</code> function of the contract code. This setting is ignored for normal accounts.</td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
  "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
  "nonce":2, //The nonce value of the source account
  "fee_limit" : 1000000, //The transaction fee that you intend to pay
  "gas_price": 1000,//The gas price (not less than the minimum configured)
  "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
  "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
  "operations":[
    {
      "type": 7,//The pay_coin operation type
      "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations 
      "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
      "pay_coin": {
        "dest_address": "ztxSgGkHuPv6FQUu6C5uWnaqyKJ22bSNrJUCJ",//The target account to receive Gas assets
        "amount": 100,//The amount of Gas assets to be transferred
        "input": "{\"bar\":\"foo\"}" // Optional, the input parameters of the main code of the contract code in the target account
      }
    }
  ]
  }
  ```

#### Recording Logs

* Function

  The source account of this operation writes the log to the blockchain.
* In JSON format

  ```json
  {
    "topic": "hello",// The topic of the log
    "datas"://The content of the log
    [
      "hello, log 1",
      "hello, log 2"
    ]
  }
  ```
* Keywords in JSON

  <table><thead><tr><th width="117">Keyword</th><th width="112">Type</th><th>Description</th></tr></thead><tbody><tr><td>topic</td><td>string</td><td>Log topic and the parameter length is (0,128]</td></tr><tr><td>datas</td><td>array</td><td>Log content. The length of each element is (0,1024]</td></tr></tbody></table>
* Complete transaction structure

  ```json
  {
    "source_address":"ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//The source account, also called the originator of the transaction
    "nonce":2, //The nonce value of the source account
    "fee_limit" : 1000000, //The transaction fee that you intend to pay
    "gas_price": 1000,//The gas price (not less than the minimum configured)
    "ceil_ledger_seq": 100, //Optional, block height limit, if greater than 0, the transaction is only valid below (including the height) the block height
    "metadata":"0123456789abcdef", //Optional, a user-defined note for transactions, in hexadecimal format
    "operations":[
      {
        "type": 8,//The log operation type
        "source_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV",//Optional, the source account of the operations 
        "metadata": "0123456789abcdef",//Optional, a user-defined note for transactions, in hexadecimal format
        "log": {
          "topic": "hello",// The topic of the log
          "datas"://The content of the log
          [
            "hello, log 1",
            "hello, log 2"
          ]
        }
      }
    ]
  }
  ```

### Assignment of Control Rights

When creating an account, you can define its control rights using the `priv` field. This allows you to assign signer weights and operation thresholds.

```json
{
  "master_weight": "70",//The weight for the private key of this address is 70
  "signers": [//The weights assigned
    {
      "address": "ztxSigpdiWcW22hw54i9PEFk1s4WLEy5Rmh6K",
      "weight": 55    //The weight of the above address is 55
    },
    {
      "address": "ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo",
      "weight": 100    //The weight of the above address is 100
    }
  ],
  "tx_threshold": "8",//The weight required to initiate the transaction is 8
  "type_thresholds": [
    {
      "type": 1,//The weight required to create an account is 11
      "threshold": 11
    },
    {//The weight required to issue an asset is 21
      "type": 2,
      "threshold": 21
    },
    {//The weight required to transfer assets is 31
      "type": 3,
      "threshold": 31
    },
    {//The weight required to set metadata is 41
      "type": 4,
      "threshold": 41
    },
    {//The weight required to change controllers is 51
      "type": 5,
      "threshold": 51
    },
    {//The weight required to change operations is 61
      "type": 6,
      "threshold": 61
    }
  ]
}
```

### Example

In this example, the account **`ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E`** initiates a transaction containing a single operation:

* **Create a new account** with address **`ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo`**
* The account creation is completed by **transferring Gas** to the new account during the operation.

#### Assembling Transactions

Referring to the structure of Transaction Structure, the following three steps are required:

1. Obtaining the account nonce value
2. Assembling operations
3. Generating transaction objects

**Obtaining the Account Nonce Value**

In a transaction structure, it's essential to confirm the **serial number (`nonce`)** of the initiating account. To do this:

1. Use the **`getAccountBase`** interface to retrieve the current `nonce` value of the initiating account.
2. **Increment the `nonce` by 1** to set the correct value for the new transaction.

This ensures transaction ordering and prevents replay.

The interface call is as follows:

```http
HTTP GET https://{endpoint}/getAccountBase?address=ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E
or
curl get https://{endpoint}/getAccountBase?address=ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E
```

The following content is returned:

```json
{
  "error_code" : 0,
  "result" : {
    "address" : "ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E",
    "assets_hash" : "ad67d57ae19de8068dbcd47282146bd553fe9f684c57c8c114453863ee41abc3",
    "balance" : 96545066100,
    "metadatas_hash" : "ad67d57ae19de8068dbcd47282146bd553fe9f684c57c8c114453863ee41abc3",
    "nonce" : 20,
    "priv" : {
      "master_weight" : 1,
      "thresholds" : {
        "tx_threshold" : 1
      }
    }
  }
}
```

**Assembling Operations**

According to the structure of Operations Structure, Operation Codes, and Transferring Gas Assets structure, the JSON format of the generation operation is as follows:

```json
{
  "type": 7,
  "pay_coin": {
    "dest_address": "ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo",
    "amount": 10000000,
    "input": ""
  }
}
```

**Generating Transaction Objects**

In this example, after obtaining the account's nonce value of **20**, the **new transaction’s serial number** is set to **21**. Based on the assembled operation structure, the transaction JSON format will look like this:

```json
{
  "source_address": "ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E",
  "nonce": 21,
  "fee_limit":1000000,
  "gas_price":1000,
  "operations": [{
    "type": 7,
    "pay_coin": {
      "dest_address": "ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo",
      "amount": 10000000,
      "input": ""
    }
  }]
}
```

#### Serializing Transaction Data

This is done through the `getTransactionBlob` interface.

The interface call is as follows:

```http
HTTP POST https://{endpoint}/getTransactionBlob
or
curl https://{endpoint}/getTransactionBlob -X POST -d "{\"source_address\":\"ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E\",\"nonce\":21,\"fee_limit\":1000000,\"gas_price\":1000,\"operations\":[{\"type\":7,\"pay_coin\":{\"dest_address\":\"ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo\",\"amount\":10000000,\"input\":\"\"}}]}"
```

Return the following content:

```json
{
  "error_code": 0,
  "error_desc": "",
  "result": {
    "hash": "3f90865062d7737904ea929cbde7c45e831e4972cf582b69a0198781c452e9e1",
    "transaction_blob": "0a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a7356101518c0843d20e8073a2f0807522b0a24627551747336446654354b6176745639344a675a79373548397069776d62374b6f5557671080ade204"
  }
}
```

#### &#x20;<a href="#signing-signatures" id="signing-signatures"></a>

#### Signing Signatures

Signing signatures is to sign the value of `transaction_blob` in `getTransactionBlob` with the private key of `ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E` and generate a public key. For details, please refer to keypair. The resulting signature data is as follows:

```json
［{
  "sign_data": "ACF64A7D41244AFC4465DBC225D616E0499776140D46BA7A84B1B6B263DAF1422904137E0181301F480F7114EC7CC5BBE4763EDA981E565EF81EF7705596CB0B",
  "public_key": "b00168eceea7900ddcb8f694161755f98590ba7944de3bfe339610fe0cacc10a18372dcbf71b"
}］
```

#### Submitting Transaction Data

According to the signature data obtained by Signing Signatures and the `transaction_blob` obtained by Serializing Transaction Data, the JSON format of the body in the `submitTransaction` interface is generated as follows:

```json
{
  "items" : [{
    "transaction_blob" : "0a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a7356101518c0843d20e8073a2f0807522b0a24627551747336446654354b6176745639344a675a79373548397069776d62374b6f5557671080ade204",
    "signatures" : [{
      "sign_data" : "ACF64A7D41244AFC4465DBC225D616E0499776140D46BA7A84B1B6B263DAF1422904137E0181301F480F7114EC7CC5BBE4763EDA981E565EF81EF7705596CB0B",
      "public_key" : "b00168eceea7900ddcb8f694161755f98590ba7944de3bfe339610fe0cacc10a18372dcbf71b"
    }]
  }]
}
```

The interface call is as follows:

```http
HTTP POST https://{endpoint}/submitTransaction
or
curl https://{endpoint}/submitTransaction -X POST -d "{\"items\":[{\"transaction_blob\":\"0a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a7356101518c0843d20e8073a2f0807522b0a24627551747336446654354b6176745639344a675a79373548397069776d62374b6f5557671080ade204\",\"signatures\":[{\"sign_data\":\"ACF64A7D41244AFC4465DBC225D616E0499776140D46BA7A84B1B6B263DAF1422904137E0181301F480F7114EC7CC5BBE4763EDA981E565EF81EF7705596CB0B\",\"public_key\":\"b00168eceea7900ddcb8f694161755f98590ba7944de3bfe339610fe0cacc10a18372dcbf71b\"}]}]}"
```

Return the following content:

```json
{
  "results": [
    {
      "error_code": 0,
      "error_desc": "",
      "hash": "3f90865062d7737904ea929cbde7c45e831e4972cf582b69a0198781c452e9e1"
    }
  ],
  "success_count": 1
}
```

#### Querying the Transaction Result

According to the hash obtained by the `submitTransaction` interface, confirm whether the transaction is executed successfully by the `getTransactionHistory` interface (check whether `error_code` under `transactions` is equal to 0).

The interface call is as follows:

```http
HTTP GET https://{endpoint}/getTransactionHistory?hash=3f90865062d7737904ea929cbde7c45e831e4972cf582b69a0198781c452e9e1
or
curl get https://{endpoint}/getTransactionHistory?hash=3f90865062d7737904ea929cbde7c45e831e4972cf582b69a0198781c452e9e1
```

Return the following result:

```json
{
  "error_code": 0,//The transaction is queried
  "result": {
    "total_count": 1,
    "transactions": [
      {
        "actual_fee": 245000,
        "close_time": 1552125554325904,
        "error_code": 0,//The transaction is executed successfully
        "error_desc": "",
        "hash": "3f90865062d7737904ea929cbde7c45e831e4972cf582b69a0198781c452e9e1",
        "ledger_seq": 2688046,
        "signatures": [
          {
            "public_key": "b00168eceea7900ddcb8f694161755f98590ba7944de3bfe339610fe0cacc10a18372dcbf71b",
            "sign_data": "acf64a7d41244afc4465dbc225d616e0499776140d46ba7a84b1b6b263daf1422904137e0181301f480f7114ec7cc5bbe4763eda981e565ef81ef7705596cb0b"
          }
        ],
        "transaction": {
          "fee_limit": 1000000,
          "gas_price": 1000,
          "nonce": 21,
          "operations": [
            {
              "pay_coin": {
                "amount": 10000000,
                "dest_address": "ztxSX1SypC33doY4a5MYYr5zBZUvB33kKHdAo"
              },
              "type": 7
            }
          ],
          "source_address": "ztxSW512jUyDASna878ECgZ4QFyhh6AtEJP6E"
        },
        "tx_size": 245
      }
    ]
  }
}
```

### Error Codes

The error code is composed of two parts:

* error\_code : Error code, approximate error classification
* error\_desc : Error Description, which can accurately find the error specific information from the error description

The error list is as follows:

<table><thead><tr><th width="107.33333333333331">Error code</th><th width="433">Name</th><th>Description</th></tr></thead><tbody><tr><td>0</td><td>ERRCODE_SUCCESS</td><td>Successful operation</td></tr><tr><td>1</td><td>ERRCODE_INTERNAL_ERROR</td><td>Inner service defect</td></tr><tr><td>2</td><td>ERRCODE_INVALID_PARAMETER</td><td>Parameters error</td></tr><tr><td>3</td><td>ERRCODE_ALRGasDY_EXIST</td><td>Objects already exist, such as repeated transactions submitted</td></tr><tr><td>4</td><td>ERRCODE_NOT_EXIST</td><td>Objects do not exist, such as null account, transactions and blocks etc</td></tr><tr><td>5</td><td>ERRCODE_TX_TIMEOUT</td><td>Transactions expired. It means the transaction has been removed from the buffer, but it still has probability to be executed</td></tr><tr><td>7</td><td>ERRCODE_MATH_OVERFLOW</td><td>Math calculation is overflown</td></tr><tr><td>20</td><td>ERRCODE_EXPR_CONDITION_RESULT_FALSE</td><td>The expression returns false. It means the TX failed to be executed currently, but it still has probability to be executed in the following blocks</td></tr><tr><td>21</td><td>ERRCODE_EXPR_CONDITION_SYNTAX_ERROR</td><td>The syntax of the expression returns is false. It means that the TX must fail</td></tr><tr><td>90</td><td>ERRCODE_INVALID_PUBKEY</td><td>Invalid public key</td></tr><tr><td>91</td><td>ERRCODE_INVALID_PRIKEY</td><td>Invalid private key</td></tr><tr><td>92</td><td>ERRCODE_ASSET_INVALID</td><td>Invalid assets</td></tr><tr><td>93</td><td>ERRCODE_INVALID_SIGNATURE</td><td>The weight of the signature does not match the threshold of the operation</td></tr><tr><td>94</td><td>ERRCODE_INVALID_ADDRESS</td><td>Invalid address</td></tr><tr><td>97</td><td>ERRCODE_MISSING_OPERATIONS</td><td>Absent operation of TX</td></tr><tr><td>98</td><td>ERRCODE_TOO_MANY_OPERATIONS</td><td>Over 100 operations in a single transaction</td></tr><tr><td>99</td><td>ERRCODE_BAD_SEQUENCE</td><td>Invalid sequence or nonce of TX</td></tr><tr><td>100</td><td>ERRCODE_ACCOUNT_LOW_RESERVE</td><td>Low reserve in the account</td></tr><tr><td>101</td><td>ERRCODE_ACCOUNT_SOURCEDEST_EQUAL</td><td>Sender and receiver accounts are the same</td></tr><tr><td>102</td><td>ERRCODE_ACCOUNT_DEST_EXIST</td><td>The target account already exists</td></tr><tr><td>103</td><td>ERRCODE_ACCOUNT_NOT_EXIST</td><td>Accounts do not exist</td></tr><tr><td>104</td><td>ERRCODE_ACCOUNT_ASSET_LOW_RESERVE</td><td>Low reserve in the account</td></tr><tr><td>105</td><td>ERRCODE_ACCOUNT_ASSET_AMOUNT_TOO_LARGE</td><td>Amount of assets exceeds the limitation ( int64 )</td></tr><tr><td>106</td><td>ERRCODE_ACCOUNT_INIT_LOW_RESERVE</td><td>Insufficient initial reserve for account creation</td></tr><tr><td>111</td><td>ERRCODE_FEE_NOT_ENOUGH</td><td>Low transaction fee</td></tr><tr><td>114</td><td>ERRCODE_OUT_OF_TXCACHE</td><td>TX buffer is full</td></tr><tr><td>120</td><td>ERRCODE_WEIGHT_NOT_VALID</td><td>Invalid weight</td></tr><tr><td>121</td><td>ERRCODE_THRESHOLD_NOT_VALID</td><td>Invalid threshold</td></tr><tr><td>144</td><td>ERRCODE_INVALID_DATAVERSION</td><td>Invalid data version of metadata</td></tr><tr><td>146</td><td>ERRCODE_TX_SIZE_TOO_BIG</td><td>TX exceeds upper limitation</td></tr><tr><td>151</td><td>ERRCODE_CONTRACT_EXECUTE_FAIL</td><td>Failure in contract execution</td></tr><tr><td>152</td><td>ERRCODE_CONTRACT_SYNTAX_ERROR</td><td>Failure in syntax analysis</td></tr><tr><td>153</td><td>ERRCODE_CONTRACT_TOO_MANY_RECURSION</td><td>The depth of contract recursion exceeds upper limitation</td></tr><tr><td>154</td><td>ERRCODE_CONTRACT_TOO_MANY_TRANSACTIONS</td><td>the TX submitted from the contract exceeds upper limitation</td></tr><tr><td>155</td><td>ERRCODE_CONTRACT_EXECUTE_EXPIRED</td><td>Contract expired</td></tr><tr><td>160</td><td>ERRCODE_TX_INSERT_QUEUE_FAIL</td><td>Failed to insert the TX into buffer</td></tr></tbody></table>


# Websocket

### Websocket Interfaces

The WebSocket interface of Zetrix processes a variety of **predefined message types**, enabling real-time communication for tasks such as transaction submission, event subscription, and status updates. Each message type corresponds to a specific action or query within the Zetrix network protocol.

#### Message Type

```protobuf
enum ChainMessageType {
    CHAIN_TYPE_NONE = 0;
    CHAIN_HELLO = 10; // response with CHAIN_STATUS = 2;
    CHAIN_TX_STATUS = 11;
    CHAIN_PEER_ONLINE = 12;
    CHAIN_PEER_OFFLINE = 13;
    CHAIN_PEER_MESSAGE = 14;
    CHAIN_SUBMITTRANSACTION = 15;
    CHAIN_LEDGER_HGasDER = 16; //Zetrix notifies the client ledger(protocol::LedgerHeader) when closed
    CHAIN_SUBSCRIBE_TX = 17; //response with CHAIN_RESPONSE
    CHAIN_TX_ENV_STORE = 18;
}
```

#### Notification Message Registration

* Function

  The client uses this interface to **register message types** it wants to receive from the blockchain (note: this feature is currently unavailable). Additionally, this is the **only interface** through which the **blockchain version information** can be retrieved.
* Request Message Type

  `CHAIN_HELLO`
* Request Data Object

  ```protobuf
  message ChainHello {
    repeated ChainMessageType api_list = 1; //By default, enable all apis
    int64   timestamp = 2;
  }
  ```
* Request Parameter

  | Parameter | Type  | Description                                         |
  | --------- | ----- | --------------------------------------------------- |
  | api\_list | array | List of message types for applying for registration |
  | timestamp | int64 | Application time                                    |
* Reponse Message Type

  `CHAIN_HELLO`
* Reponse Data Object

  ```protobuf
  message ChainStatus {
    string self_addr        = 1;
    int64 ledger_version    = 2;
    int64 monitor_version   = 3;
    string buchain_version      = 4;
    int64   timestamp       = 5;
  }
  ```
* Reponse Result

  | Variable         | Type   | Description            |
  | ---------------- | ------ | ---------------------- |
  | self\_addr       | string | Connected node address |
  | ledger\_version  | int64  | Ledger version         |
  | monitor\_version | int64  | Monitor version        |
  | zetrix\_version  | string | Zetrix version         |
  | timestamp        | int64  | Timestamp              |

#### Submit Transaction

* Function

  The transaction to be executed is sent to the blockchain using a specific **WebSocket message type**. For full details on how to format the transaction, refer to the **Transaction Structure** documentation.
* Request Message Type

  `CHAIN_SUBMITTRANSACTION`
* Request Message Object

  ```protobuf
  //　Signature
  message Signature {
    string public_key = 1;
    bytes sign_data = 2;
  }

  //　Request object
  message TransactionEnv {
    Transaction transaction = 1;
    repeated Signature signatures   = 2;
    Trigger trigger = 3;
  }
  ```
* Request Parameter

  | Parameter   | Type        | Description                                           |
  | ----------- | ----------- | ----------------------------------------------------- |
  | transaction | Transaction | Details for transaction structure。                    |
  | public\_key | string      | The public key of transaction sender                  |
  | sign\_data  | bytes       | Signature data obtained by signing `transaction_blob` |
* Reponse Message Type
  * `CHAIN_TX_STATUS`：This returns the **result of the transaction submission** note that a successful submission **only confirms receipt** by the blockchain, not successful execution.
  * `CHAIN_TX_ENV_STORE`：Returns the result of the transaction execution.
* `CHAIN_TX_STATUS` Object

  ```protobuf
  message ChainTxStatus {
    enum TxStatus {
        UNDEFINED   = 0;
        CONFIRMED   = 1;    // web server will check tx parameters, signatures etc fist, noitfy CONFIRMED if pass
        PENDING     = 2;    // master will check futher before put it into pending queue
        COMPLETE    = 3;    // notify if Tx write ledger successfully
        FAILURE     = 4;    // notify once failed and set error_code
    };

    TxStatus    status = 1;
    string      tx_hash = 2;
    string      source_address = 3;
    int64       source_account_seq = 4;
    int64       ledger_seq = 5;         //on which block this tx records
    int64       new_account_seq = 6;        //new account sequence if COMPLETE
    ERRORCODE   error_code = 7;         //use it if FAIL
    string      error_desc = 8  ;           //error desc
    int64       timestamp = 9;          
  }
  ```
* `ChainTxStatus` Member

  | Variable             | Type      | Description                                                   |
  | -------------------- | --------- | ------------------------------------------------------------- |
  | status               | TxStatus  | Transaction status.                                           |
  | tx\_hash             | string    | Transaction hash.                                             |
  | source\_address      | string    | Source account address of transaction sender.                 |
  | source\_account\_seq | int64     | Transaction sequence of transaction sender.                   |
  | ledger\_seq          | int64     | Height of the block where this transaction record is located. |
  | new\_account\_seq    | int64     | Block height when the transaction is completed.               |
  | error\_code          | ERRORCODE | Error code                                                    |
  | error\_desc          | string    | Error description                                             |
  | timestamp            | int64     | Timestamp                                                     |
* `CHAIN_TX_ENV_STORE` Object

  ```protobuf
  message TransactionEnvStore{
    TransactionEnv transaction_env = 1;
    int32 error_code = 2;
    string error_desc = 3;
    int64 ledger_seq = 4;
    int64 close_time = 5;
    //for notify
    bytes hash = 6;
    int64 actual_fee = 7;
    repeated bytes contract_tx_hashes = 8;
  }
  ```
* `TransactionEnvStore` Member

  | Variable             | Type           | Description                                                   |
  | -------------------- | -------------- | ------------------------------------------------------------- |
  | transaction\_env     | TransactionEnv | Submitted transaction content.                                |
  | error\_code          | int32          | Error code.                                                   |
  | error\_desc          | string         | Error description.                                            |
  | ledger\_seq          | int64          | Height of the block where this transaction record is located. |
  | close\_time          | int64          | Transaction completion time.                                  |
  | hash                 | bytes          | Transaction hash.                                             |
  | actual\_fee          | int64          | Actual transaction fee, uint is UGas                          |
  | contract\_tx\_hashes | bytes          | contract transaction hashes                                   |

#### Message Subscription

* Function

  This interface implements transaction notifications that only specify the account address of the interface.
* Request Message Type

  `CHAIN_SUBSCRIBE_TX`
* Request Data Object

  ```protobuf
  message ChainSubscribeTx{
    repeated string address = 1;
  }
  ```
* Request Parameter

  | Parameter | Type        | Description                      |
  | --------- | ----------- | -------------------------------- |
  | address   | Transaction | Account address for subscription |
* Reponse Message Type

  `ChainResponse`
* Reponse Data Object

  ```protobuf
  message ChainResponse{
        int32 error_code = 1;
        string error_desc = 2;
  }
  ```
* Reponse Result

  | Variable    | Type   | Description       |
  | ----------- | ------ | ----------------- |
  | error\_code | int32  | Error code        |
  | error\_desc | string | Error description |

### Transaction structure

* In protobuf format

  ```protobuf
  message Transaction {
      enum Limit{
          UNKNOWN = 0;
          OPERATIONS = 1000;
      };
      string source_address = 1;
      int64 nonce = 2;
      int64  fee_limit = 3;
      int64  gas_price =4;
      int64 ceil_ledger_seq = 5;
      bytes metadata = 6;
      repeated Operation operations = 7;
      int64 chain_id = 8;
  }
  ```
* Keywords in protobuf

  | Keyword           | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                   |
  | ----------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | source\_address   | string | **Source Account**: The address of the transaction initiator. Upon successful transaction execution, the account's `nonce` will automatically increase by 1, representing the total number of transactions completed by that account.                                                                                                                                                         |
  | nonce             | int64  | <p>The <strong>nonce</strong> must equal the current nonce of the source account <strong>plus 1</strong>, ensuring each transaction is unique and preventing replay attacks.<br>To check an account's nonce, use the <strong><code>getAccount</code></strong> HTTP interface.<br>If the nonce is not shown in the response, the account’s current nonce is considered <strong>0</strong>.</p> |
  | fee\_limit        | int64  | <p><strong>Fee Limit</strong>: The maximum fee the transaction is allowed to consume.</p><ul><li>If the transaction <strong>succeeds</strong>, only the <strong>actual cost</strong> is charged.</li><li>If it <strong>fails</strong>, the full <strong>fee limit</strong> is deducted.<br><strong>Unit</strong>: UGas (1 Gas = 10⁸ UGas).</li></ul>                                          |
  | gas\_price        | int64  | <p><strong>Gas Price</strong>: Determines the handling fee per operation and contributes to the transaction's byte fee.<br><strong>Unit</strong>: UGas (1 Gas = 10⁸ UGas).</p>                                                                                                                                                                                                                |
  | ceil\_ledger\_seq | int64  | **Optional**: Sets a block height limit for when the transaction can be included. This is an advanced feature for controlling transaction validity.                                                                                                                                                                                                                                           |
  | operations        | array  | **Operation List**: Represents the core actions the transaction intends to perform. Refer to **Operations Structure** for detailed specifications.                                                                                                                                                                                                                                            |
  | metadata          | bytes  | **Optional**: A user-defined field that can be left empty or used to include a custom note.                                                                                                                                                                                                                                                                                                   |

### Operations structure

The corresponding `operations` in the protobuf structure of the transaction can contain one or more operations.

* In protobuf format

  ```protobuf
  message Operation {
      enum Type {
          UNKNOWN = 0;
          CREATE_ACCOUNT          = 1;
          ISSUE_ASSET             = 2;
          PAY_ASSET               = 3;
          SET_METADATA            = 4;
          SET_SIGNER_WEIGHT       = 5;
          SET_THRESHOLD           = 6;
          PAY_COIN                = 7;
          LOG                     = 8;
          SET_PRIVILEGE           = 9;
      };
      Type type = 1;
      string source_address = 2;
      bytes metadata  = 3;

      OperationCreateAccount      create_account     = 4;
      OperationIssueAsset         issue_asset        = 5;
      OperationPayAsset           pay_asset          = 6;
      OperationSetMetadata        set_metadata       = 7;
      OperationSetSignerWeight    set_signer_weight  = 8;
      OperationSetThreshold       set_threshold      = 9;
      OperationPayCoin            pay_coin           = 10;
      OperationLog                log                = 11;
      OperationSetPrivilege       set_privilege      = 12;
  }
  ```
* Keyword in protobuf

  | Keyword         | Type                   | Description                                                                                                                                                 |
  | --------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | type            | Type                   | **Operation Code**: Specifies the type of operation to be executed. Each code corresponds to a distinct function. See **Operation Codes** for more details. |
  | source\_address | string                 | **Optional**: Indicates the operation's source account (the operator). If not specified, it defaults to the transaction's source account.                   |
  | metadata        | bytes                  | **Optional**: A custom field for user input, which can be left blank or used to add a note.                                                                 |
  | create\_account | OperationCreateAccount | Creating accounts operation                                                                                                                                 |
  | issue\_asset    | OperationIssueAsset    | Issuing assets operation                                                                                                                                    |
  | pay\_asset      | OperationPayAsset      | Transferring assets operation                                                                                                                               |
  | set\_metadata   | OperationSetMetadata   | Setting metadata operation                                                                                                                                  |
  | pay\_coin       | OperationPayCoin       | Transferring gas assets operation                                                                                                                           |
  | log             | OperationLog           | Recording logs operation                                                                                                                                    |
  | set\_privilege  | OperationSetPrivilege  | Setting privileges operation                                                                                                                                |

#### &#x20;<a href="#operation-codes" id="operation-codes"></a>

#### Operation Codes

| Operation Code | Description             |
| -------------- | ----------------------- |
| 1              | Creating Accounts       |
| 2              | Issuing Assets          |
| 3              | Transferring Assets     |
| 4              | Setting Metadata        |
| 7              | Transferring Gas Assets |
| 8              | Recording Logs          |
| 9              | Setting Privileges      |

#### Creating Accounts

The source account creates a new account on the blockchain. Creating Accounts are divided into Creating Normal Accounts and Creating Contract Accounts.

Protobuf format as follow:

```protobuf
// Key-Value pair
message KeyPair{
    string key = 1;
    string value = 2;
    int64 version = 3;
}

// Privilege
message Signer {
    enum Limit{
        SIGNER_NONE = 0;
        SIGNER = 100;
    };
    string address = 1;
    int64 weight = 2;
}
message OperationTypeThreshold{
    Operation.Type type = 1;
    int64 threshold = 2;
}
message AccountThreshold{
    int64 tx_threshold = 1; //required, [-1,MAX(INT64)] -1: indicates no setting
    repeated OperationTypeThreshold type_thresholds = 2;
}
message AccountPrivilege {
    int64 master_weight = 1;
    repeated Signer signers = 2;
    AccountThreshold thresholds = 3;
}

// Contract
message Contract{
    enum ContractType{
        JAVASCRIPT = 0;
    }
    ContractType type = 1;
    string payload = 2;
}

//　Create Account Operation
message OperationCreateAccount{
    string dest_address = 1;
    Contract contract = 2;
    AccountPrivilege priv = 3;
    repeated KeyPair metadatas = 4; 
    int64   init_balance = 5;
    string  init_input = 6;
}
```

**Creating Normal Accounts**

> **Note**: Both `master_weight` and `tx_threshold` must be 1 in the current operation. And only the following keywords are allowed to be initialized.

* Keyword in protobuf

  | Keyword        | Type   | Description                                                                                                                 |
  | -------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- |
  | dest\_address  | string | Address of the target account. When creating a normal account, it cannot be empty                                           |
  | init\_balance  | int64  | Initial Gas value of the target account, in UGas, 1 Gas = 10^8 UGas                                                         |
  | master\_weight | int64  | Master weight of the target account, which ranges \[0, MAX(UINT32)]                                                         |
  | tx\_threshold  | int64  | The threshold for initiating a transaction below which the transaction cannot be initiated, which ranges ​​\[0, MAX(INT64)] |
* Query

  The account information is queried through the getAccount interface in HTTP.

**Creating Contract Accounts**

> **Note**: In the current operation, `master_weight` must be 0 and `tx_threshold` must be 1. And only the following keywords are allowed to be initialized

* Keyword in protobuf

  | Keyword        | Type   | Description                                                                                                    |
  | -------------- | ------ | -------------------------------------------------------------------------------------------------------------- |
  | payload        | string | Contract code                                                                                                  |
  | init\_balance  | int64  | Initial Gas value of the target account, in UGas, 1 Gas = 10^8 UGas                                            |
  | init\_input    | string | **Optional**: Provides input parameters for the `init` function in the contract code during contract creation. |
  | master\_weight | int64  | Master weight of the target account                                                                            |
  | tx\_threshold  | int64  | The threshold for initiating a transaction below which it is not possible to initiate a transaction.           |
* Query
  * The account information is queried through the getAccount interface in HTTP.
  * Query with the getTransactionHistory interface in HTTP, and the result is as follows:

    ```protobuf
    [
        {
            "contract_address": "ztxSn8xpL7c2xkxwbreVCs6EZ7KZbBvtDaLtV", //The contract account
            "operation_index": 0                                        //The operation index value in the transaction array, 0 means the first transaction
        }
    ]
    ```

#### &#x20;<a href="#issuing-assets" id="issuing-assets"></a>

#### Issuing Assets

* Function

  The **source account** in this operation issues a digital asset. Upon successful execution, the asset is added to the source account’s asset balance.
* In protobuf format

  ```protobuf
  message OperationIssueAsset{
      string code = 1;
      int64 amount = 2;
  }
  ```
* Keyword in protobuf

  | Keyword | Type   | Description                                                    |
  | ------- | ------ | -------------------------------------------------------------- |
  | code    | string | Code of the asset to be issued, which ranges \[1, 64]          |
  | amount  | int64  | Amount of the asset to be issued, which ranges (0, MAX(int64)) |

#### Transferring Assets

> **Note**: If the target account is a contract account, the current operation triggers the contract execution of the target account.

* Function

  The source account of this operation transfers an asset to the target account.
* In protobuf format

  ```protobuf
  message AssetKey{
       string issuer = 1;
       string code = 2;
       int32 type = 3;
  }
  message Asset{
       AssetKey   key = 1;
       int64      amount = 2;
  }

  //　Pay asset operation
  message OperationPayAsset{
      string dest_address = 1;
      Asset asset = 2;
      string input = 3;
  }
  ```
* Keyword in protobuf

  | Keyword       | Type   | Description                                                                                                                                                                     |
  | ------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | dest\_address | string | Address of the target account                                                                                                                                                   |
  | issuer        | string | Address of the issuer                                                                                                                                                           |
  | code          | string | Asset code which ranges \[1, 64]                                                                                                                                                |
  | amount        | int64  | The amount of the asset which ranges (0,MAX(int64))                                                                                                                             |
  | input         | string | **Optional**: If the target account is a contract, the input is passed as an argument to the `main` function of the contract code. This setting is ignored for normal accounts. |

#### Setting Metadata

* Function

  The source account of this operation modifies or adds metadata to the metadata table.
* In protobuf format

  ```protobuf
  message OperationSetMetadata{
      string  key = 1;  
      string  value = 2;
      int64   version = 3;
      bool    delete_flag = 4;
  }
  ```
* Keyword in protobuf

  | Keyword      | Type   | Description                                                                                                                                                                                                                                    |
  | ------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | key          | string | Keyword of metadata, which ranges (0, 1024].                                                                                                                                                                                                   |
  | value        | string | Content of metadata, which ranges \[0, 256K].                                                                                                                                                                                                  |
  | version      | int64  | <p><strong>Optional</strong>: Metadata version number, default is <code>0</code>.</p><ul><li><code>0</code>: No version restriction</li><li><code>>0</code>: Must match this specific version</li><li><code><0</code>: Invalid value</li></ul> |
  | delete\_flag | bool   | Whether to delete the metadata.                                                                                                                                                                                                                |

#### Setting Privileges

* Function

  Set the weights that the signer has and set the thresholds required for each operation. For details, see Assignment of Control Rights in HTTP.
* In protobuf format

  ```protobuf
  message Signer {
      enum Limit{
          SIGNER_NONE = 0;
          SIGNER = 100;
      };
      string address = 1;
      int64 weight = 2;
  }
  message OperationTypeThreshold{
      Operation.Type type = 1;
      int64 threshold = 2;
  }

  //　Set privilege object
  message OperationSetPrivilege{
      string master_weight = 1;
      repeated Signer signers = 2;
      string tx_threshold = 3;
      repeated OperationTypeThreshold type_thresholds = 4;
  }
  ```
* Keywords in protobuf

  | Keyword          | Type   | Description                                                                                                                                                                                                                                                                                                                                                           |
  | ---------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | master\_weight   | string | <p><strong>Optional</strong>: Defaults to <code>""</code>, representing the account’s master weight.</p><ul><li><code>""</code>: No change</li><li><code>"0"</code>: Set master weight to 0</li><li><code>"1"</code> to <code>"MAX(UINT32)"</code>: Assign specified weight</li><li>Others: Invalid input</li></ul>                                                   |
  | signers          | array  | **Optional**: A list of signers required for the operation. Defaults to an empty object, which means no signers are configured.                                                                                                                                                                                                                                       |
  | address          | string | **Signer Address**: The address of the signer to be configured, which must comply with Zetrix’s address verification rules.                                                                                                                                                                                                                                           |
  | weight           | int64  | <p><strong>Optional</strong>: Defaults to <code>0</code>.</p><ul><li><code>0</code>: Removes the signer</li><li><code>(0, MAX(UINT32)]</code>: Sets the signer's weight</li><li>Others: Invalid input</li></ul>                                                                                                                                                       |
  | tx\_threshold    | string | <p><strong>Optional</strong>: Defaults to <code>""</code>, indicating the minimum privilege (<code>tx\_threshold</code>) for the account.</p><ul><li><code>""</code>: Do not modify</li><li><code>"0"</code>: Set <code>tx\_threshold</code> to 0</li><li><code>"1"</code> to <code>"MAX(INT64)"</code>: Set specified weight</li><li>Others: Invalid input</li></ul> |
  | type\_thresholds | array  | **Optional**: A list of required thresholds for different operations. Defaults to an empty object, meaning no thresholds are configured.                                                                                                                                                                                                                              |
  | type             | int    | Indicates a specific **operation type** within the valid range of **(0, 100]**.                                                                                                                                                                                                                                                                                       |
  | threshold        | int64  | <p><strong>Optional</strong>: Defaults to <code>0</code>.</p><ul><li><code>0</code>: Removes the specified operation type</li><li><code>(0, MAX(INT64)]</code>: Sets the weight for the operation</li><li>Other values: Invalid input</li></ul>                                                                                                                       |

#### &#x20;<a href="#transferring-gas-assets" id="transferring-gas-assets"></a>

#### Transferring Gas Assets

> **Note**: If the **target account** is a **contract account**, this operation will **trigger the execution** of the contract code within that account.

* Function

  Two functions:

  1. The source account of this operation transfers a Gas asset to the target account.
  2. The source account of this operation creates a new account on the blockchain.
* In protobuf format

  ```protobuf
  message OperationPayCoin{
      string dest_address = 1;
      int64 amount = 2;
      string input = 3;
  }
  ```
* protobufKeyword

  | Keyword       | Type   | Description                                                                                                                                                      |
  | ------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | dest\_address | string | Receiver account                                                                                                                                                 |
  | amount        | array  | **Optional**: A list of signers required for the operation. Defaults to an empty object, meaning no signers are specified.                                       |
  | input         | string | **Optional**: If the target is a contract account, the input is passed to the `main` function of the contract code. This setting is ignored for normal accounts. |

#### Recording Logs

* Function

  The source account of this operation writes the log to the blockchain.
* In protobuf format

  ```protobuf
  message OperationLog{
      string topic = 1;
      repeated string datas = 2;
  }
  ```
* protobufKeyword

  | Keyword | Type   | Description                                                                         |
  | ------- | ------ | ----------------------------------------------------------------------------------- |
  | topic   | string | The **log topic** and **parameter length** must fall within the range **(0, 128]**. |
  | datas   | array  | **Log Content**: Each element must have a length within the range **(0, 1024]**.    |

### Error Codes

The error code is composed of two parts:

* error\_code : Error code, approximate error classification
* error\_desc : Error Description, which can accurately find the error specific information from the error description

The error list is as follows:

| Error code | Name                                        | Description                                                                                                                                        |
| ---------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| 0          | ERRCODE\_SUCCESS                            | Successful operation                                                                                                                               |
| 1          | ERRCODE\_INTERNAL\_ERROR                    | Inner service defect                                                                                                                               |
| 2          | ERRCODE\_INVALID\_PARAMETER                 | Parameters error                                                                                                                                   |
| 3          | ERRCODE\_ALRDY\_EXIST                       | Objects already exist, such as repeated transactions submitted                                                                                     |
| 4          | ERRCODE\_NOT\_EXIST                         | Objects do not exist, such as null account, transactions and blocks etc                                                                            |
| 5          | ERRCODE\_TX\_TIMEOUT                        | Transactions expired. It means the transaction has been removed from the buffer, but it still has probability to be executed                       |
| 7          | ERRCODE\_MATH\_OVERFLOW                     | Math calculation is overflown                                                                                                                      |
| 20         | ERRCODE\_EXPR\_CONDITION\_RESULT\_FALSE     | The expression returns false. It means the TX failed to be executed currently, but it still has probability to be executed in the following blocks |
| 21         | ERRCODE\_EXPR\_CONDITION\_SYNTAX\_ERROR     | The syntax of the expression returns is false. It means that the TX must fail                                                                      |
| 90         | ERRCODE\_INVALID\_PUBKEY                    | Invalid public key                                                                                                                                 |
| 91         | ERRCODE\_INVALID\_PRIKEY                    | Invalid private key                                                                                                                                |
| 92         | ERRCODE\_ASSET\_INVALID                     | Invalid assets                                                                                                                                     |
| 93         | ERRCODE\_INVALID\_SIGNATURE                 | The weight of the signature does not match the threshold of the operation                                                                          |
| 94         | ERRCODE\_INVALID\_ADDRESS                   | Invalid address                                                                                                                                    |
| 97         | ERRCODE\_MISSING\_OPERATIONS                | Absent operation of TX                                                                                                                             |
| 98         | ERRCODE\_TOO\_MANY\_OPERATIONS              | Over 100 operations in a single transaction                                                                                                        |
| 99         | ERRCODE\_BAD\_SEQUENCE                      | Invalid sequence or nonce of TX                                                                                                                    |
| 100        | ERRCODE\_ACCOUNT\_LOW\_RESERVE              | Low reserve in the account                                                                                                                         |
| 101        | ERRCODE\_ACCOUNT\_SOURCEDEST\_EQUAL         | Sender and receiver accounts are the same                                                                                                          |
| 102        | ERRCODE\_ACCOUNT\_DEST\_EXIST               | The target account already exists                                                                                                                  |
| 103        | ERRCODE\_ACCOUNT\_NOT\_EXIST                | Accounts do not exist                                                                                                                              |
| 104        | ERRCODE\_ACCOUNT\_ASSET\_LOW\_RESERVE       | Low reserve in the account                                                                                                                         |
| 105        | ERRCODE\_ACCOUNT\_ASSET\_AMOUNT\_TOO\_LARGE | Amount of assets exceeds the limitation ( int64 )                                                                                                  |
| 106        | ERRCODE\_ACCOUNT\_INIT\_LOW\_RESERVE        | Insufficient initial reserve for account creation                                                                                                  |
| 111        | ERRCODE\_FEE\_NOT\_ENOUGH                   | Low transaction fee                                                                                                                                |
| 114        | ERRCODE\_OUT\_OF\_TXCACHE                   | TX buffer is full                                                                                                                                  |
| 120        | ERRCODE\_WEIGHT\_NOT\_VALID                 | Invalid weight                                                                                                                                     |
| 121        | ERRCODE\_THRESHOLD\_NOT\_VALID              | Invalid threshold                                                                                                                                  |
| 144        | ERRCODE\_INVALID\_DATAVERSION               | Invalid data version of metadata                                                                                                                   |
| 146        | ERRCODE\_TX\_SIZE\_TOO\_BIG                 | TX exceeds upper limitation                                                                                                                        |
| 151        | ERRCODE\_CONTRACT\_EXECUTE\_FAIL            | Failure in contract execution                                                                                                                      |
| 152        | ERRCODE\_CONTRACT\_SYNTAX\_ERROR            | Failure in syntax analysis                                                                                                                         |
| 153        | ERRCODE\_CONTRACT\_TOO\_MANY\_RECURSION     | The depth of contract recursion exceeds upper limitation                                                                                           |
| 154        | ERRCODE\_CONTRACT\_TOO\_MANY\_TRANSACTIONS  | the TX submitted from the contract exceeds upper limitation                                                                                        |
| 155        | ERRCODE\_CONTRACT\_EXECUTE\_EXPIRED         | Contract expired                                                                                                                                   |
| 160        | ERRCODE\_TX\_INSERT\_QUEUE\_FAIL            | Failed to insert the TX into buffer                                                                                                                |


# Keypair

## Zetrix Keypair Guide

### Overview

This document outlines the full process of generating **Keypairs** (public/private keys), creating an address, and signing a transaction using those keys. It explains two interface methods for executing transaction calls and details the related processes. Additionally, it includes reference information for **ProtoBuf** data structures and demonstrates two ways to submit transactions:

1. **Using an interface call to generate `transaction_blob`**, and
2. **Manually generating `transaction_blob`**.

### Schematic Diagram

The following diagram ilustrates how the private, public keys and address are generated.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FeHAlilah1f389XuMcdZA%2FOption-1.png?alt=media&amp;token=b9cd031d-c7bd-43a9-a69a-eb7e923d4d3d" alt=""><figcaption></figcaption></figure>

### Generating Private Keys

Generating a private key requires multiple algorithms such as a random algorithm and `SHA256`. Generating a private key includes the following steps:

1. Generate a 256-bit random number (a private key in the mathematical sense) with a random algorithm and get a byte array, the raw private key, as shown below:

```
[17,236,24,183,207,250,207,180,108,87,224,39,189,99,246,85,138,120,236,78,228,233,41,192,124,109,156,104,235,66,194,24]
```

1. Add a 3-byte **prefix** and a 1-byte **version** number before the raw private key, and then add a 1-byte **Fill** after the raw private key to get a new byte array, as shown below:

```
[218,55,159,1,17,236,24,183,207,250,207,180,108,87,224,39,189,99,246,85,138,120,236,78,228,233,41,192,124,109,156,104,235,66,194,24,0]
```

> **Note** : For the **Prefix**, **Version**, **Checksum** and **Fill**, please refer to Table 1.

1. Perform `SHA256` calculations twice on the byte array obtained in Step
2. Take the first 4 bytes of the operation result as the byte array of the Checksum, as shown below:

```
[30,19,80,117]
```

1. Combine the byte array in Step 2 and the checksum byte array in Step 3 in order, resulting in a new byte array, as shown below:

```
[218,55,159,1,17,236,24,183,207,250,207,180,108,87,224,39,189,99,246,85,138,120,236,78,228,233,41,192,124,109,156,104,235,66,194,24,0,30,19,80,117]
```

1. Encode the byte array generated in Step 4 with Base58, and get the string starting with priv, namely the private key, as shown below:

```
privbsGZFUoRv8aXZbSGd3bwzZWFn3L5QKq74RXAQYcmfXhhZ54CLr9z
```

**note :** Now the private key is generated.

**Table 1**

| Name     | Data                                                                                                                             | Length  |
| -------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Prefix   | 0xDA 0x37 0x9F                                                                                                                   | 3 Bytes |
| Version  | 0x01                                                                                                                             | 1 Byte  |
| Fill     | 0x00                                                                                                                             | 1 Byte  |
| Checksum | After performing `SHA256` calculation twice on the byte array obtained in Step 2,take the first 4 bytes of the operation result. | 4 Bytes |

This table illustrates the **Prefix**, **Version**, **Fill** and **Checksum** used in generating the private key.

### Generating Public Keys

The public key can be generated with the `ED25519` algorithm after the private key is generated. Generating a public key includes the following steps:

1. Generate a 32-bit byte array (raw public key) by processing the raw private key with the `ED25519` algorithm. For example, the raw public key of the private key `privbsGZFUoRv8aXZbSGd3bwzZWFn3L5QKq74RXAQYcmfXhhZ54CLr9z` is shown below:

```
[21,118,76,208,23,224,218,117,50,113,250,38,205,82,148,81,162,27,130,83,208,1,240,212,54,18,225,158,198,50,87,10]
```

1. Add a 1-byte prefix in the raw public key, and then add a 1-byte version number to get a new byte array, as shown below:

```
[176,1,21,118,76,208,23,224,218,117,50,113,250,38,205,82,148,81,162,27,130,83,208,1,240,212,54,18,225,158,198,50,87,10]
```

> **Note** : For the **Prefix**, **Version** and **Checksum**, please refer to Table 2.

1. Perform `SHA256` calculation twice on the byte array in Step 2. Take the first 4 bytes of the operation result as the byte array of the Checksum, as shown below:

```
[116,171,22,107]
```

1. Combine the byte array in Step 2 and the checksum byte array in Step 3 in order, resulting in a new byte array, as shown below:

```
[176,1,21,118,76,208,23,224,218,117,50,113,250,38,205,82,148,81,162,27,130,83,208,1,240,212,54,18,225,158,198,50,87,10,116,171,22,107]
```

1. Encode the byte array in Step 4 into hexadecimal and get a hexadecimal string, namely the public key, as shown below:

```
b00115764cd017e0da753271fa26cd529451a21b8253d001f0d43612e19ec632570a74ab166b
```

> **Note** : Now the public key is generated.

**Table 2**

| Name     | Data                                                                                                                             | Length  |
| -------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Prefix   | 0xB0                                                                                                                             | 1 Byte  |
| Version  | 0x01                                                                                                                             | 1 Byte  |
| Checksum | After performing `SHA256` calculation twice on the byte array obtained in step 2, take the first 4 bytes of the operation result | 4 Bytes |

This table illustrates the Prefix, Version and Checksum used in generating the public key.

### Generating Addresses

The address can be further generated by an algorithm after generating the private key and the public key. Generating an address includes the following steps:

1. Generate a 32-bit byte array (raw public key) by processing the raw private key with the `ED25519` algorithm. For example, the raw public key of the private key `privbsGZFUoRv8aXZbSGd3bwzZWFn3L5QKq74RXAQYcmfXhhZ54CLr9z` is shown below:

```
  [21,118,76,208,23,224,218,117,50,113,250,38,205,82,148,81,162,27,130,83,208,1,240,212,54,18,225,158,198,50,87,10]
```

1. Perform `SHA256` calculation once on the raw public key and take the last 20 bytes of the operation result as the byte array, as shown below:

```
[173,148,59,51,183,193,55,160,1,133,247,80,65,13,67,190,164,114,18,220]
```

1. Add a 2-byte prefix in the byte array generated in Step 2, and then add a 1-byte version number to get a new byte array, as shown below:

   ```
   [240,38,1,173,148,59,51,183,193,55,160,1,133,247,80,65,13,67,190,164,114,18,220]
   ```

   > **Note** : For the **Prefix**, **Version** and **Checksum**, please refer to Table 3.
2. Perform `SHA256` calculation twice on the byte array in Step 3. Take the first 4 bytes of the operation result as the byte array of the Checksum, as shown below:

   ```
   [255,77,167,51]
   ```
3. Combine the byte array in Step 3 and the Checksum byte array in Step 4 in order, resulting in a new byte array, as shown below:

   ```
   [240,38,1,173,148,59,51,183,193,55,160,1,133,247,80,65,13,67,190,164,114,18,220,255,77,167,51]
   ```
4. Encode the byte array generated in Step 5 with Base58, and get the string starting with adx, namely the address, as shown below:

   ```
   ztxSixLyrba6UyVXVhUoT1wSA3nNzY5qrTift
   ```

> **Note** : Now the address is generated.

**Table 3**

| Name      | Data                                                                                                                             | Length   |
| --------- | -------------------------------------------------------------------------------------------------------------------------------- | -------- |
| Prefix    | 0xF0 0x26                                                                                                                        | 2 Bytes  |
| Version   | 0x01                                                                                                                             | 1 Byte   |
| PublicKey | Take the last 20bytes in raw public key                                                                                          | 20 Bytes |
| Checksum  | After performing `SHA256` calculation twice on the byte array obtained in step 3, take the first 4 bytes of the operation result | 4 Bytes  |

This table illustrates the Prefix, Version and Checksum used in generating the address.

### Signing Transactions

Sign the pending transaction (the byte array obtained by the inverse hexadecimal encoding of the `transaction_blob`) with the `ED25519` algorithm and the private key to get `sign_data`, the signature string.

The following example shows how to sign the transaction\_blob with `ED25519` and the private key.

The private key:

```
privbsGZFUoRv8aXZbSGd3bwzZWFn3L5QKq74RXAQYcmfXhhZ54CLr9z
```

The transaction blob:

```
0A24627551566B5555424B70444B526D48595777314D553855376E676F5165686E6F31363569109F0818C0843D20E80732146275696C642073696D706C65206163636F756E743A5F08011224627551566B5555424B70444B526D48595777314D553855376E676F5165686E6F3136356922350A246275516E6936794752574D4D454376585850673854334B35615A557551456351523670691A0608011A02080128C7A3889BAB20
```

After signing the pending transaction (the byte array obtained by the inverse hexadecimal encoding of the `transaction_blob`) with the signature interface of `ED25519` and performing hexadecimal conversion, the resulting `sign_data` is:

```
a46ee590a84abdeb8cc38ade1ae8e8a2c71bb69bdc4cd7dc0de1b74b37e2cbd1696229687f80dff4276b1a3dd3f95a9bc1d569943b337fe170317430f36d6401
```

### Methods of Submitting Transactions

There are two methods of calling the interface to execute transactions: Generating Transaction\_blobs by Calling the Interface and Generating Transaction\_blobs by Yourself.

#### Generating Transaction\_blobs by Calling the Interface

**Attention :** As the transaction\_blob is likely to be intercepted and tampered with, it is not recommended to generate transaction\_blobs in this way.

If you need to call the interface to generate transaction\_blobs, sign and submit transactions, please refer to the Serializing Transaction Data interface of http.

Calling the interface to generate a `transaction_blob` includes the following steps:

1. Call the getAccount interface to get the nonce value of the account that is to initiate a transaction. The code is shown below:

   ```http
   HTTP GET host:port/getAccount?address=accountAddress
   ```
2. Populate the json data as needed and complete filling the transaction data. The format is shown below:

   ```json
   {
       "source_address":"xxxxxxxxxxx", //The source transaction account, the originator of the transaction
       "nonce":2, //Nonce value
       "ceil_ledger_seq": 0, //Optional
       "fee_limit":1000, //Fee paid in transaction
       "gas_price": 1000, //Gas price (Not less than the configured value)
       "metadata":"0123456789abcdef", //Optional, metadata for the transaction given by users, in hexadecimal format
       "operations":[
           {
               //Populate according to specific operations
           },
           {
               //Populate according to specific operations
           }
           ......
       ]
   }
   ```

   > **Note** : The nonce value needs to be incremented by 1 based on the value obtained in Step 1.
3. By calling the `getTransactionBlob` interface, the json data generated in Step 2 is passed as a parameter, and a transaction hash and a `transaction_blob` are obtained to implement transaction serialization. The format is shown below:

   ```json
   {
       "error_code": 0,
       "error_desc": "",
       "result": {
           "hash": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //Transaction hash
           "transaction_blob": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //The hexadecimal representation after the transaction is serialized
       }
   }
   ```
4. Sign the transaction and populate the transaction data. Sign the transaction\_blob according to the previously generated private key, and then populate the json data of the submitted transaction. The format is shown below:

   ```json
   {
       "items" : [{
           "transaction_blob" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //The hexadecimal representation after the transaction is serialized
           "signatures" : [{//The first signature
               "sign_data" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //Signature data
               "public_key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //Public key
           }, {//The second signature
               "sign_data" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //Signature data
               "public_key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //Public key
           }]
       }]
   }
   ```
5. By calling the `submitTransaction` interface, the json data generated in Step 4 is passed as a parameter, the response result is obtained and transaction submission is completed. The format of the response result is shown below:

   ```json
   {
       "results": [
           {
               "error_code": 0,
               "error_desc": "",
               "hash": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //Transaction hash
           }
       ],
       "success_count": 1
   }
   ```

#### Generating Transaction\_blobs by Yourself

Generating the transaction\_blob by yourself, signing, and submitting the transaction include the following steps:

1. Call the getAccount interface to get the nonce value of the account that is to initiate a transaction. The code is shown below:

   ```http
   HTTP GET host:port/getAccount?address=accountAddress
   ```
2. Populate the transaction object `Transaction` of the protocol buffer and serialize it to get the `transaction_blob`. For details of the specific transaction data structure, please refer to ProtoBuf Data Structure.
3. Sign the transaction and populate the transaction data. Generate a public key based on the private key, sign the `transaction_blob` with the private key, and then populate the json data of the submitted transaction. The format is shown below:

   ```json
   {
       "items" : [{
           "transaction_blob" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //The hexadecimal representation after the transaction is serialized
           "signatures" : [{//The first signature
               "sign_data" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //Signature data
               "public_key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //Public key
           }, {//The second signature
               "sign_data" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", //Signature data
               "public_key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //Public key
           }]
       }]
   }
   ```
4. By calling the `submitTransaction` interface, the json data generated in Step 3 is passed as a parameter to complete the transaction submission. The response result format is shown below:

   ```json
   {
       "results": [
           {
               "error_code": 0,
               "error_desc": "",
               "hash": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //Transaction hash
           }
       ],
       "success_count": 1
   }
   ```

### ProtoBuf Data Structure

Protocol Buffer (ProtoBuf) is a lightweight and efficient structured data storage format that can be used for serializing structured data. It is ideal for data storage or RPC data exchange formats. It can be used in communication protocols, data storage and other fields of language-independent, platform-independent, scalable serialized structured data formats. Currently the APIs in `C++`, `Java`, and `Python` are available.

For more information about ProtoBuf, please refer to the [protocol](https://developers.google.com/protocol-buffers/docs/overview).

Now, we will introduce the data structure details of Protocol Buffer, and provide the file and simple test program for the protocol buffer of various languages generated by the script.

#### Data Structure

The following section describes the various ProtoBuf data structures that might be used in transactions and their uses for your reference.

**Transaction**

This data structure is for complete transactions.

```protobuf
   message Transaction {
       enum Limit{
           UNKNOWN = 0;
           OPERATIONS = 1000;
       };
       string source_address = 1; // Account address of the transaction initiator
       int64 nonce = 2; // Transaction sequence number
       int64 fee_limit = 3; // The transaction fee, by default is 1000Gas; the unit is UGas, 1 Gas = 10^8 UGas
       int64 gas_price = 4; // The packaging fee of transactions, by default is 1000; the unit is UGas,1 Gas = 10^8 UGas
       int64 ceil_ledger_seq = 5; // Block bound
       bytes metadata = 6; // Transaction metadata
       repeated Operation operations = 7; // Operation list
   }
```

**Operation**

This data structure is for operations in transactions.

```protobuf
   message Operation {
       enum Type {
           UNKNOWN = 0;
           CREATE_ACCOUNT = 1;
           ISSUE_ASSET = 2;
           PAY_ASSET = 3;
           SET_METADATA = 4;
           SET_SIGNER_WEIGHT = 5;
           SET_THRESHOLD = 6;
           PAY_COIN = 7;
           LOG = 8;
           SET_PRIVILEGE = 9;
       };
       Type type = 1; // Operation type
       string source_address = 2; // Source account address for the operation
       bytes metadata = 3; // Operation metadata

       OperationCreateAccount create_account = 4; // Create an account operation
       OperationIssueAsset issue_asset = 5; // Issue assets operation
       OperationPayAsset pay_asset = 6; // Transfer assets operation
       OperationSetMetadata set_metadata = 7; // Set metadata
       OperationSetSignerWeight set_signer_weight = 8; // Set privilege for signer
       OperationSetThreshold set_threshold = 9; // Set transaction threshold
       OperationPayCoin pay_coin = 10; // Transfer coin
       OperationLog log = 11; // Record log
       OperationSetPrivilege set_privilege = 12; // Set privilege
   }
```

**OperationCreateAccount**

This data structure is for creating accounts.

```protobuf
   message OperationCreateAccount{
       string dest_address = 1; // Target account address to be created
       Contract contract = 2; // Contract
       AccountPrivilege priv = 3; // Privilege
       repeated KeyPair metadatas = 4; // Additional info
       int64 init_balance = 5; // Initiation balance
       string init_input = 6; // Input parameter for contracts
   }
```

**Contract**

This data structure is for setting contracts.

```protobuf
   message Contract{
       enum ContractType{
            JAVASCRIPT = 0;
       }
       ContractType type = 1; // Contract type
       string payload = 2; // Contract code
   }
```

**AccountPrivilege**

This data structure is for setting account privilege.

```protobuf
   message AccountPrivilege {
       int64 master_weight = 1; // Account weight
       repeated Signer signers = 2; // Signer weight list
       AccountThreshold thresholds = 3; // Threshold
   }
```

**Signer**

This data structure is for setting signer weight.

```protobuf
   message Signer {
       enum Limit{
           SIGNER_NONE = 0;
           SIGNER = 100;
       };
       string address = 1; // Signer account address
       int64 weight = 2; // Signer weight
   }
```

**AccountThreshold**

This data structure is for setting account threshold.

```protobuf
   message AccountThreshold{
       int64 tx_threshold = 1; // Transaction threshold
       repeated OperationTypeThreshold type_thresholds = 2; // Specify the transaction threshold list for the operations. The threshold for the transactions with unspecified operation is set by tx_threshold.
   }
```

**OperationTypeThreshold**

This data structure is for operation threshold of specified types.

```protobuf
   message OperationTypeThreshold{
       Operation.Type type = 1; // Operation type
       int64 threshold = 2; // Corresponding threshold of this operation
   }
```

**OperationIssueAsset**

This data structure is for issuing assets.

```protobuf
   message OperationIssueAsset{
       string code = 1; // Asset encoding to be issued
       int64 amount = 2; // Asset amount to be issued
   }
```

**OperationPayAsset**

This data structure is for transferring assets.

```protobuf
message OperationPayAsset {
    string dest_address = 1; // Target account address
    Asset asset = 2; // Asset
    string input = 3; // Input parameter for contracts
}
```

**Asset**

This data structure is for asset.

```protobuf
message Asset{
    AssetKey key = 1; // Asset identification
    int64 amount = 2; // Asset amount
}
```

**AssetKey**

This data structure is for identifying the uniqueness of asset.

```protobuf
   message AssetKey{
       string issuer = 1; // Account address of asset issuer
       string code = 2; // Asset encoding
       int32 type = 3; // Asset type(by default is 0, which indicates the amount is not limited)
   }
```

**OperationSetMetadata**

This data structure is for setting Metadata.

```protobuf
   message OperationSetMetadata{
       string key = 1; // keyword, unique
       string value = 2; // Content
       int64 version = 3; // Version control, optional
       bool delete_flag = 4; // Whether it is deletable
   }
```

**OperationSetSignerWeight**

This data structure is for setting signer weight.

```protobuf
   message OperationSetSignerWeight{
       int64 master_weight = 1; // Self weight
       repeated Signer signers = 2; // Signer weight list
   }
```

**OperationSetThreshold**

This data structure is for setting threshold.

```protobuf
   message OperationSetThreshold{
       int64 tx_threshold = 1; // Transaction threshold
       repeated OperationTypeThreshold type_thresholds = 2; // The transaction threshold list for specified operations. The threshold for the transactions with unspecified operation is set by tx_threshold
   }
```

**OperationPayCoin**

This data structure is for sending coin.

```protobuf
   message OperationPayCoin{
       string dest_address = 1; // Target account address
       int64 amount = 2; // Coin amount
       string input = 3; // Input parameter for contracts
   }
```

**OperationLog**

This data structure is for recording log information.

```protobuf
   message OperationLog{
       string topic = 1; // Log theme
       repeated string datas = 2; // Log content
   }
```

**OperationSetPrivilege**

This data structure is for setting account privilege.

```protobuf
   message OperationSetPrivilege{
       string master_weight = 1; // Account weight
       repeated Signer signers = 2; // Signer weight list
       string tx_threshold = 3; // Transaction threshold
       repeated OperationTypeThreshold type_thresholds = 4; // The transaction threshold list for specified operations. The threshold for the transactions with unspecified operation is set by tx_threshold
   }
```

### &#x20;<a href="#examples-for-transaction-submission" id="examples-for-transaction-submission"></a>

### Examples for Transaction Submission

Scenario: Account A(`ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z`) creates account B(Generate an address by Generating Addresses in keypair).

#### &#x20;<a href="#generating-transaction_blobs-by-interface" id="generating-transaction_blobs-by-interface"></a>

#### Generating Transaction\_blobs by Interface

Generating transaction\_blobs by the interface includes the following steps:

1. Obtain the nonce value of the account to initiate a transaction by GET.

```http
GET http://seed1-node.zetrix.com/getAccount?address=ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z
```

Response message:

```json
{
    "error_code" : 0,
    "result" : {
        "address" : "ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z",
        "assets" : [
            {
                "amount" : 1000000000,
                "key" : {
                    "code" : "HNC",
                    "issuer" : "ztxSZw4A3MYYNGSAejkbb7RuZvu5wd8GUTfUE"
                }
            }
        ],
        "assets_hash" : "3bf279af496877a51303e91c36d42d64ba9d414de8c038719b842e6421a9dae0",
        "balance" : 27034700,
        "metadatas" : null,
        "metadatas_hash" : "ad67d57ae19de8068dbcd47282146bd553fe9f684c57c8c114453863ee41abc3",
        "nonce" : 5,
        "priv" : {
            "master_weight" : 1,
            "thresholds" : [{
                "tx_threshold" : 1
            }]
        }
    }
}

address: Current query account address.
assets: Account asset list.
assets_hash: Asset list hash.
balance: Account balance.
metadata: Account metadata in hexadecimal format.
metadatas_hash: Transaction metadata hash.
nonce: The sending transaction serial number, the nonce+1 returned by querying the account information interface.
priv: Privilege.
master_weight: Current account weight.
thresholds: Threshold.
tx_threshold: Transaction default threshold.
```

1. Complete populating the transaction data.

The account address of account B generated by Generating Address in keypair is `ztxSWs62LxjYERH3qo22QjGAw4hrjZNt9LaUG`, the populated json data is shown below:

```json
{
    "source_address":"ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z",
    "nonce":7,
    "ceil_ledger_seq": 0,
    "fee_limit":1000000,
    "gas_price": 1000,
    "metadata":"",
    "operations":[
        {
            "type": 1,
            "create_account": {
                "dest_address": "ztxSWs62LxjYERH3qo22QjGAw4hrjZNt9LaUG",
                "init_balance": 10000000,
                "priv": {
                    "master_weight": 1,
                    "thresholds": {
                        "tx_threshold": 1
                    }
                }
            }
        }
    ]
}
```

> **Note** : The nonce value is not 6, so this transaction would fail.

1. Serialize the transaction data.

```http
POST http://seed1-node.zetrix.com/getTransactionBlob
```

Request message:

```json
{
    "source_address":"ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z",
    "nonce":7,
    "ceil_ledger_seq": 0,
    "fee_limit":1000000,
    "gas_price": 1000,
    "metadata":"",
    "operations":[
        {
            "type": 1,
            "create_account": {
                "dest_address": "ztxSWs62LxjYERH3qo22QjGAw4hrjZNt9LaUG",
                "init_balance": 10000000,
                "priv": {
                    "master_weight": 1,
                    "thresholds": {
                        "tx_threshold": 1
                    }
                }
            }
        }
    ]
}
```

Response message:

```json
{
    "error_code": 0,
    "error_desc": "",
    "result": {
        "hash": "be4953bce94ecd5c5a19c7c4445d940c6a55fb56370f7f606e127776053b3b51",
        "transaction_blob": "0a2462755173757248314d34726a4c6b666a7a6b7852394b584a366a537532723978424e4577100718c0843d20e8073a37080122330a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a73561a0608011a0208012880ade204"
    }
}
```

1. Sign the transaction\_blob with the private key.

Import package: `import org.zetrix.encryption.key.PrivateKey;`

Private key:

```
privbvTuL1k8z27i9eyBrFDUvAVVCSxKeLtzjMMZEqimFwbNchnejS81
```

The sign\_data after being signed:

```
9C86CE621A1C9368E93F332C55FDF423C087631B51E95381B80F81044714E3CE3DCF5E4634E5BE77B12ABD3C54554E834A30643ADA80D19A4A3C924D0B3FA601
```

1. Complete populating the transaction data.

```json
{
    "items" : [{
        "transaction_blob" : "0a2462755173757248314d34726a4c6b666a7a6b7852394b584a366a537532723978424e4577100718c0843d20e8073a37080122330a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a73561a0608011a0208012880ade204",
        "signatures" : [{
            "sign_data" : "9C86CE621A1C9368E93F332C55FDF423C087631B51E95381B80F81044714E3CE3DCF5E4634E5BE77B12ABD3C54554E834A30643ADA80D19A4A3C924D0B3FA601",
            "public_key" : "b00179b4adb1d3188aa1b98d6977a837bd4afdbb4813ac65472074fe3a491979bf256ba63895"
        }]
    }]
}
```

1. Submit the transaction by POST.

```http
   POST http://seed1-node.zetrix.com/submitTransaction
```

Response message:

```json
{
    "results": [{
        "error_code": 0,
        "error_desc": "",
        "hash": "be4953bce94ecd5c5a19c7c4445d940c6a55fb56370f7f606e127776053b3b51"
    }],
    "success_count": 1 //1 represents that the submission succeeded.
}
```

#### Generating Transaction\_blobs by Yourself

Generating transaction\_blobs by yourself (take `Java` as an example) includes the following steps:

1. Obtain the nonce value of the account that is to initiate a transaction by GET.

```http
   GET http://seed1-node.zetrix.com/getAccount?address=ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z
```

Response message:

```json
{
    "error_code" : 0,
    "result" : {
        "address" : "ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z",
        "assets" : [
            {
                "amount" : 1000000000,
                "key" : {
                    "code" : "HNC",
                    "issuer" : "ztxSZw4A3MYYNGSAejkbb7RuZvu5wd8GUTfUE"
                }
            }
        ],
        "assets_hash" : "3bf279af496877a51303e91c36d42d64ba9d414de8c038719b842e6421a9dae0",
        "balance" : 27034700,
        "metadatas" : null,
        "metadatas_hash" : "ad67d57ae19de8068dbcd47282146bd553fe9f684c57c8c114453863ee41abc3",
        "nonce" : 5,
        "priv" : {
            "master_weight" : 1,
            "thresholds" : [{
                "tx_threshold" : 1
            }]
        }
    }
}

address: Current query account address.
assets: Account asset list.
assets_hash: Asset list hash.
balance: Account balance.
metadata: Account metadata in hexadecimal format.
metadatas_hash: Transaction metadata hash.
nonce: The sending transaction serial number, the nonce+1 returned by querying the account information interface.
priv: Privilege.
master_weight: Current account weight.
thresholds: Threshold.
tx_threshold: Transaction default threshold.
```

1. Populate the transaction data structure and generate a transaction\_blob.

```java
import org.zetrix.crypto.protobuf.Chain;

Chain.Transaction.Builder builder = Chain.Transaction.newBuilder();
builder.setSourceAddress("ztxSrb2CPEcE7gK7AUPLorFW8sE3JTgrKX51z");
builder.setNonce(7);

builder.setFeeLimit(1000 * 1000);
builder.setGasPrice(1000);
builder.setCeilLedgerSeq(0);
builder.setMetadata(ByteString.copyFromUtf8(""));

Chain.Operation.Builder operation = builder.addOperationsBuilder();
operation.setType(Chain.Operation.Type.CREATE_ACCOUNT);

Chain.OperationCreateAccount.Builder operationCreateAccount = Chain.OperationCreateAccount.newBuilder();
operationCreateAccount.setDestAddress("ztxSWs62LxjYERH3qo22QjGAw4hrjZNt9LaUG");
operationCreateAccount.setInitBalance(10000000);

Chain.AccountPrivilege.Builder accountPrivilegeBuilder = Chain.AccountPrivilege.newBuilder();
accountPrivilegeBuilder.setMasterWeight(1);

Chain.AccountThreshold.Builder accountThresholdBuilder = Chain.AccountThreshold.newBuilder();
accountThresholdBuilder.setTxThreshold(1);

accountPrivilegeBuilder.setThresholds(accountThresholdBuilder);
operationCreateAccount.setPriv(accountPrivilegeBuilder);
operation.setCreateAccount(operationCreateAccount);
String transaction_blob = HexFormat.byteToHex(builder.build().toByteArray());
```

The transaction\_blob obtained:

```
0a2462755173757248314d34726a4c6b666a7a6b7852394b584a366a537532723978424e4577100718c0843d20e8073a37080122330a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a73561a0608011a0208012880ade204
```

> **Note** : The nonce value is not 6, so this transaction would fail.

1. Sign the transaction\_blob with the private key.

Import package: `import org.zetrix.encryption.key.PrivateKey;`

The private key:

```
privbvTuL1k8z27i9eyBrFDUvAVVCSxKeLtzjMMZEqimFwbNchnejS81
```

The sign\_data after being signed:

```
9C86CE621A1C9368E93F332C55FDF423C087631B51E95381B80F81044714E3CE3DCF5E4634E5BE77B12ABD3C54554E834A30643ADA80D19A4A3C924D0B3FA601
```

1. Complete populating the transaction data.

```json
{
    "items" : [{
        "transaction_blob" : "0a2462755173757248314d34726a4c6b666a7a6b7852394b584a366a537532723978424e4577100718c0843d20e8073a37080122330a246275516f50326552796d4163556d33757657675138526e6a7472536e58425866417a73561a0608011a0208012880ade204",
        "signatures" : [{
            "sign_data" : "9C86CE621A1C9368E93F332C55FDF423C087631B51E95381B80F81044714E3CE3DCF5E4634E5BE77B12ABD3C54554E834A30643ADA80D19A4A3C924D0B3FA601",
            "public_key" : "b00179b4adb1d3188aa1b98d6977a837bd4afdbb4813ac65472074fe3a491979bf256ba63895"
        }]
    }]
}
```

1. Submit the transaction by POST.

```http
POST http://seed1-node.zetrix.com/submitTransaction
```

Response message:

```json
{
    "results": [{
        "error_code": 0,
        "error_desc": "",
        "hash": "be4953bce94ecd5c5a19c7c4445d940c6a55fb56370f7f606e127776053b3b51"
    }],
    "success_count": 1 //1 represents that the submission succeeded.
}
```


# SDK


# Node.js

Node.js developers can seamlessly interact with the Zetrix blockchain using the Zetrix Node.js SDK, enabling efficient integration and operation.

## Overview

The **Zetrix Node.js SDK** enables developers to easily work with the Zetrix blockchain by offering a streamlined interface for complex operations. This powerful toolkit simplifies tasks such as **account management**, **smart contract deployment**, and **transaction creation**, allowing developers to focus on building advanced applications with ease and efficiency.

## Target Audience

The **Zetrix Node.js SDK** is tailored for developers proficient in **JavaScript** and **Node.js**, aiming to build API services that interact with the Zetrix blockchain. Whether you're an experienced blockchain developer or just starting out, the SDK provides an accessible and developer-friendly entry point to building on Zetrix.

## Quick Start Guide

### Installation

Getting started with the Zetrix Node.js SDK is straightforward. Follow these steps to install the package:

```
$ npm install zetrix-sdk-nodejs
```

We also recommend using the [dotenv](https://www.npmjs.com/package/dotenv) package to conveniently manage environment variables.

```
$ npm install dotenv
```

### Prerequisites

* [Zetrix Wallet](https://www.zetrix.com/zetrix-wallet/) installed.
* A Zetrix account with sufficient balance. Claim your faucet [here](https://faucet.zetrix.com/).

### Configuration

Create a **.env** file in the root of your project and insert your key/value pairs in the following format of KEY=VALUE:

For Zetrix Testnet:

```
NODE_URL=test-node.zetrix.com
```

For Zetrix Mainnet:

```
NODE_URL=node.zetrix.com
```

## Basic Usages

Included in this section are some sample code snippets to help you get started with the SDK.

Create the `zetrix-sdk-nodejs` instance to begin using the SDK:

```javascript
'use strict';

const ZtxChainSDK = require('zetrix-sdk-nodejs');

const sdk = new ZtxChainSDK({
  host: process.env.NODE_URL,
});
```

Retrieving account balance using the SDK:

```javascript
// Retrieve account balance by passing the address
sdk.account.getBalance(address).then(resp => {
  if (resp.errorCode === 0) {
    console.log(resp.result.balance);
  }
}).catch(err => {
  console.log(err.message);
});
```

Creating a new account using the SDK:

```javascript
// Create a new account onchain
sdk.account.create().then(data => {
  console.log(data);
}).catch(err => {
  console.log(err.message);
});
```

Sample contract call using the SDK:

```javascript
// Querying a contract
const data = yield sdk.contract.call({
    optType: 2,
    // Insert contract address
    contractAddress: contractAddress, 
    // Pass input parameters as a JSON string
    input: JSON.stringify({
      // Calling the 'getCertificateBySerialNumber' query function from the smart contract
      method: 'getCertificateBySerialNumber',
      // Passing the paramets for querying
      params: {
        serialNumber: "1237"
      }
    }),
  });
```

Another [sample](https://github.com/Zetrix-Chain/zetrix-sdk-nodejs/blob/main/example/exchange.js#L621) contract invocation:

```javascript
// Invoke a contract by sending tokens
const operationInfo = await sdk.operation.contractInvokeByGasOperation({
  sourceAddress: newAddress,
  contractAddress: contractAddress,
  // 0 ZETA will be sent
  amount: 0,
  // Input destination address under "to" and number of tokens under "value"
  input: '{\"method\":\"transfer\",\"params\":{\"to\":\"ZTX3Ta7d4GyAXD41H2kFCTd2eXhDesM83rvC3\",\"value\":\"10000000\"}}',
  metadata: 'invoking contract by sending tokens. 0 ZETRIX (gas) amount is sent'
});
```

More examples can be found in the [examples](https://github.com/Zetrix-Chain/zetrix-sdk-nodejs/tree/main/example) and [test](https://github.com/Zetrix-Chain/zetrix-sdk-nodejs/tree/main/test) folder in the `zetrix-sdk-nodejs` repository.

## API References

### Account APIs

#### Creating onchain account

```
sdk.account.create()
```

Allows the user to create a new account on Zetrix. A keypair will be generated consisting of the address and the private key to the newly-created account.

#### Retrieving account information

```
sdk.account.getBalance(address)
```

Allows the user to retrieve the account balance of the given address.

Parameter:

* `address` : a string for a valid account address on Zetrix

```
sdk.account.checkValid(address)
```

Allows user to check if the account address is valid or invalid.

Parameter

* `address` : a string for an account address to be checked

```
sdk.account.getNonce(address)
```

Allows the user to get the nonce for the particular account address.

Parameter

* `address` : a string for a valid account address on Zetrix

```
sdk.account.getInfo(address)
```

Allows the user to retrieve the address, balance, nonce, other related assets, voting weightage and transaction threshold.

Parameter

* `address` : a string for a valid account address on Zetrix

```
sdk.account.getAssets(address)
```

Allows the user to retrieve the assets in the given address.

Parameter

* `address` : a string for a valid account address on Zetrix

```
sdk.account.getMetadata(object)
```

Allows the user to retrieve metadata associated with the given account address.

Parameter - JSON object with the following fields:

* `address` : a string for a valid account address on Zetrix
* `key` : The private key used to access the above address

```
sdk.account.isActivated(address)
```

Allows the user to check if the address is activated onchain.

Parameter

* `address` : a string for an account address to be checked

#### Account operation

```
sdk.operation.accountSetMetadataOperation(object)
```

Allows the user to attach/associate metadata to a particular account address.

Parameter - JSON object with the metadata (in the form of key-value pairs) you want to associate to a particular account address

```
sdk.operation.accountSetPrivilegeOperation(object)
```

Allows the user to set the privilege such as the voting weightage and transaction threshold count.

Parameter - JSON object with the following fields:

* `signers` : array containing objects that key-value pairs of "address" (Zetrix account address) and "weight" (weightage of the signer out of 100)
* `typeThresholds` : array containing objects that key-value pairs of "type" and "threshold" (threshold weightage)

### Transaction APIs

#### Creating and submitting transactions

```
sdk.transaction.buildBlob(object)
```

Allows the user to build a transaction blob before submitting a transaction. The return object will contain the transaction blob required to sign the transaction.

Parameter - JSON object with the following fields:

* `sourceAddress` : account address of sender in string
* `gasPrice` : the number of ZETA to be paid per unit of operation
* `feeLimit` : the limit to how much fees will be spent for a transaction (in ZETA)
* `nonce` : the nonce associated with the account address
* `operations` : a list containing an object with `type` (specified as a string) of the operation and the associated `data` (in an object containing key-value pairs of metadata)

```
sdk.transaction.evaluateFee(object)
```

Allows the user to evaluate the fee for making a transaction given an operation.

Parameter

* `sourceAddress` : account address of the transaction initiator in string
* `nonce` : the nonce associated with the account address
* `operations` : a list containing an object with `type` (specified as a string) of the operation and the associated `data` (in an object containing key-value pairs of metadata)
* `signtureNumber` : a random string of numbers

```
sdk.transaction.sign(object)
```

Allows the user to sign the transaction before submitting. The return object will contain the signature needed to submit the transaction to the blockchain.

Parameter - JSON object with the following fields:

* `privateKeys` : a string containing the private key to the account making the transaction stored within a list
* `blob` : Blob generated from the buildBlob function above

```
sdk.transaction.submit(object)
```

Allows the user to submit the transaction to the blockchain.

Parameter - JSON object with the following fields:

* `signature` : a list of signature objects returned by the sign() function, each containing `signData` and `publicKey`
* `blob` : Blob generated from the buildBlob function above

#### Retrieving transaction information

```
sdk.transaction.getInfo(txHash)
```

Allows the user to get information related to the transaction.

Parameter

* `txHash` : a string containing the hash of the transaction

**Sending ZETRIX & other assets**

```
sdk.operation.gasSendOperation(object)
```

Allows the user to send ZETRIX to a destination address.

Parameter - JSON object with the following fields:

* `sourceAddress` : a string of the sender's account address
* `destAddress` : a string of the receiver's account address
* `gasAmount` : a string of the amount of ZETRIX to be sent, specified in ZETA
* `metadata` : a string as a memo for the transaction

### Contract APIs

#### Invoking smart contract

```
sdk.contract.call(object)
```

Allows the user to invoke a contract.

Parameter - JSON object with the following fields:

* `contractAddress` : a string of the address of the contract to be invoked
* `gasPrice` : the number of ZETA to be paid per unit of operation
* `feeLimit` : the limit to how much fees will be spent for a transaction (in ZETA)
* `input` : a JSON string containing the method to be called and the necessary parameters
* `optType` : the operation type number

#### Retrieving smart contract information

```
sdk.contract.getAddress(txHash)
```

Allows the user to obtain the contract address from a given transaction hash.

Parameter

* `txHash` : a string of the transaction hash

```
sdk.contract.getInfo(contractAddress)
```

Allows the user to obtain contract information like the contract type and the payload for a given contract address.

Parameter

* `contractAddress` : A string of the contract address

```
sdk.contract.checkValid(contractAddress)
```

Allows the user to verify if the contract is valid.

Parameter

* `contractAddress` : A string of the contract address

#### Smart contract operations

```
sdk.operation.contractCreateOperation(object)
```

Allows the user to create a contract before it is deployed.

Parameter - JSON object with the following fields:

* `sourceAddress` : A string of the address of the account creating the contract operation
* `initBalance` : Initialize Zetrix balance for smart contract
* `type` : The operation type number (refer to this)
* `payload` : The content of the smart contract to be created
* `initInput` : Parameters passed to initialize smart contract through the `init`

```
sdk.operation.contractInvokeByGasOperation(object)
```

Allows the user to send tokens.

Parameter - JSON object with the following fields:

* `contractAddress` : A string of the contract address of the token
* `sourceAddress` : A string of the address invoking the contract
* `gasAmount` : The amount of Zetrix to be sent (defined in ZETA)
* `input` : JSON string specifying the method and parameters (destination address and amount to transfer)
* `metadata` : A string as a memo for transferring the tokens

```
sdk.operation.contractUpgradeOperation(object)
```

Allows the user to upgrade contract and the owner of the contract.

Parameter - JSON object with the following fields:

* `contractAddress` : A string of the contract address to be upgraded
* `sourceAddress` : A string of the address initiating the contract upgrade
* `sPayload` : A boolean flag indicating whether there is a new payload which contains the upgraded smart contract
* `payload` : A string of the new upgraded contract code
* `sOwner` : A boolean flag indicating whether there is a new owner for the contract
* `owner` : A string of the new contract owner
* `metadata` : Optional additional information about the upgrade

### Block APIs

#### Getting block information

```
sdk.block.getNumber()
```

Allows the user to retrieve the block height.

```
sdk.block.checkStatus()
```

Allows the user to check the latest block status.

```
sdk.block.getTransactions(blockNum)
```

Allows the user to retrieve the transactions included in the specified block.

Parameter

* `blockNum` : A string of the block number

```
sdk.block.getInfo(blockNum)
```

Allows the user to retrieve information related to the block such as the closing time of the block and the number of transactions included in the block.

Parameter

* `blockNum` : A string of the block number

```
sdk.block.getLatestInfo()
```

Allows the user to retrieve information related to the latest block such as the closing time of the block and the number of transactions included in the block.

```
sdk.block.getValidators(blockNum)
```

Allows the user to retrieve the list of validators for the given block number.

Parameter

* `blockNum` : A string of the block number

```
sdk.block.getLatestValidators()
```

Allows the user to retrieve the list of validators.

```
sdk.block.getReward(blockNum)
```

Allows the user to get the reward distributed for the given block.

Parameter

* `blockNum` : A string of the block number

```
sdk.block.getLatestReward()
```

Allows the user to get the latest reward distribution info.

```
sdk.block.getFees(blockNum)
```

Allows the user to retrieve the fees paid for creating a given block.

Parameter

* `blockNum` : A string of the block number

```
sdk.block.getLatestFees()
```

Allows the user to retrieve the latest block creation fee.

### Blockchain Interactions

```
sdk.operation.logCreateOperation(object)
```

Allows the user to create a log on the blockchain.

Parameter

* `sourceAddress` : address of the logger
* `topic` : topic of the log in string
* `data` : data to include in the log in string

### For more information on how you could access Zetrix's Node.JS SDK, please visit our [GitHub repository](https://github.com/Zetrix-Chain/zetrix-sdk-nodejs).


# Go

Go developers can now efficiently interact with the Zetrix blockchain using the Zetrix Go SDK, providing a convenient and powerful way to build blockchain-based applications.

## Overview

The **Zetrix Go SDK** equips developers with a powerful and intuitive toolkit to seamlessly interact with the Zetrix blockchain. It abstracts complex blockchain operations, enabling you to concentrate on building innovative applications. With its user-friendly API and rich feature set, the SDK streamlines tasks such as **account management**, **smart contract deployment**, and **transaction creation**.

## Target Audience

The **Zetrix Go SDK** is built for developers with a strong grasp of **Go (Golang)**. Whether you're experienced in blockchain development or just entering the field, the SDK provides a straightforward and accessible way to start building on the Zetrix platform.

## Quick Start Guide

### Installation

Getting started with the Zetrix Go SDK is straightforward. Follow these steps to install the package in your `go.mod` file:

```sh
$ go get github.com/Zetrix-Chain/zetrix-sdk-go-fork
```

Let's create a `main.go` file as your main executable file. Include these in your import statement:

```go
import (
    "github.com/Zetrix-Chain/zetrix-sdk-go-fork/src/model"
    "github.com/Zetrix-Chain/zetrix-sdk-go-fork/src/sdk"
    "fmt" // include the fmt package to print statements easily
)
```

### Prerequisites

* [Zetrix Wallet](https://www.zetrix.com/zetrix-wallet/) installed.
* A Zetrix account with sufficient balance. Claim your faucet here.

### Basic Usages

Included in this section are some sample code snippets to help you get started with the SDK.

Create a Zetrix Go SDK instance to begin using the SDK. Under the `main()` function in your `main.go` file, add the following snippet:

If you're using the Zetrix testnet, initialize the SDK with the testnet node URL:

```go
var zetrixSDK sdk.Sdk
var reqData model.SDKInitRequest
reqData.SetUrl("https://test-node.zetrix.com")
resData := zetrixSDK.Init(reqData)
if resData.ErrorCode != 0 {
	fmt.Println(resData.ErrorDesc)
} else {
	fmt.Println("ZetrixSDK initialized.")
}
```

If you're using Zetrix mainnet, initialize the SDK with the mainnet node URL:

```go
var zetrixSDK sdk.Sdk
var reqData model.SDKInitRequest
reqData.SetUrl("https://node.zetrix.com")
resData := zetrixSDK.Init(reqData)
if resData.ErrorCode != 0 {
	fmt.Println(resData.ErrorDesc)
} else {
	fmt.Println("ZetrixSDK initialized.")
}
```

Now, let's look at some simple examples.

Getting the nonce for a particular address:

```go
var reqData model.AccountGetNonceRequest
reqData.SetAddress(address) // address in a string
resData := zetrixSDK.Account.GetNonce(reqData)
if resData.ErrorCode != 0 {
    return resData.ErrorDesc
} else {
    return resData.Result.Nonce
}
```

Submitting a transaction:

```go
var reqData model.TransactionSubmitRequest
reqData.SetBlob(txBlob) // txBlob in a string
reqData.SetSignatures(signedBlob) // signedBlob in a string
resDataSubmit := zetrixSDK.Transaction.Submit(reqData)
if resDataSubmit.ErrorCode != 0 {
    return resDataSubmit.ErrorDesc
} else {
    return resDataSubmit.Result.Hash
}
```

Getting the balance of a particular address:

```go
var reqData model.AccountGetBalanceRequest
reqData.SetAddress(address) // address in a string
resData := zetrixSDK.Account.GetBalance(reqData)
if resData.ErrorCode != 0 {
    return resData.ErrorDesc
} else {
    return resData.Result.Balance
}
```

Getting transaction info:

```go
var reqData model.TransactionGetInfoRequest
reqData.SetHash(hash) // hash in a string
resData := zetrixSDK.Transaction.GetInfo(reqData)
if resData.ErrorCode != 0 {
    return resData.ErrorDesc
} else {
    return resData.Result
}
```

## API References

### Account APIs

```go
sdk.Account.CheckValid(reqData model.AccountCheckValidRequest)
```

* Purpose: Checks the validity of a given account address.
* Parameters: `reqData` (type: model.AccountCheckValidRequest) - Contains the account address to be validated.
* Return Value: `model.AccountCheckValidResponse` - Contains a boolean indicating if the address is valid and an error code.

```go
sdk.Account.Create()
```

* Purpose: Creates a new account with a public and private key pair.
* Parameters: None.
* Return Value: `model.AccountCreateResponse` - Contains the public key, private key, address, and an error code.

```go
sdk.Account.GetInfo(reqData model.AccountGetInfoRequest)
```

* Purpose: Retrieves information about an account.
* Parameters: `reqData` (type: model.AccountGetInfoRequest) - Contains the account address for which information is requested.
* Return Value: `model.AccountGetInfoResponse` - Contains account information and an error code.

```go
sdk.Account.GetNonce(reqData model.AccountGetNonceRequest)
```

* Purpose: Retrieves the nonce for a given account.
* Parameters: `reqData` (type: model.AccountGetNonceRequest) - Contains the account address for which the nonce is requested.
* Return Value: `model.AccountGetNonceResponse` - Contains the nonce and an error code.

```go
sdk.Account.GetBalance(reqData model.AccountGetBalanceRequest)
```

* Purpose: Retrieves the balance of a given account.
* Parameters: `reqData` (type: model.AccountGetBalanceRequest) - Contains the account address for which the balance is requested.
* Return Value: `model.AccountGetBalanceResponse` - Contains the balance and an error code.

```go
sdk.Account.GetAssets(reqData model.AccountGetAssetsRequest)
```

* Purpose: Retrieves the assets of a given account.
* Parameters: `reqData` (type: model.AccountGetAssetsRequest) - Contains the account address for which assets are requested.
* Return Value: `model.AccountGetAssetsResponse` - Contains the assets and an error code.

```go
sdk.Account.GetMetadata(reqData model.AccountGetMetadataRequest)
```

* Purpose: Retrieves metadata associated with a given account.
* Parameters: `reqData` (type: model.AccountGetMetadataRequest) - Contains the account address and key for which metadata is requested.
* Return Value: `model.AccountGetMetadataResponse` - Contains the metadata and an error code.

```go
sdk.Account.CheckActivated(reqData model.AccountCheckActivatedRequest)
```

* Purpose: Checks if an account is activated.
* Parameters: `reqData` (type: model.AccountCheckActivatedRequest) - Contains the account address to be checked.
* Return Value: `model.AccountCheckActivatedResponse` - Contains a boolean indicating if the account is activated and an error code.

### Contract APIs

```go
sdk.Contract.CheckValid(reqData model.ContractCheckValidRequest)
```

* Purpose: Checks the validity of a contract address.
* Parameters: `reqData` (type: model.ContractCheckValidRequest) - Contains the contract address to be validated.
* Return Value: `model.ContractCheckValidResponse` - Contains a boolean indicating if the contract address is valid and an error code.

```go
sdk.Contract.GetInfo(reqData model.ContractGetInfoRequest)
```

* Purpose: Retrieves information about a contract.
* Parameters: `reqData` (type: model.ContractGetInfoRequest) - Contains the contract address for which information is requested.
* Return Value: `model.ContractGetInfoResponse` - Contains contract information and an error code.

```go
sdk.Contract.Call(reqData model.ContractCallRequest)
```

* Purpose: Calls a contract with specified parameters.
* Parameters: `reqData` (type: model.ContractCallRequest) - Contains details such as contract address, code, input, balance, fee limit, gas price, operation type, and source address.
* Return Value: `model.ContractCallResponse` - Contains the result of the contract call and an error code.

```go
sdk.Contract.GetAddress(reqData model.ContractGetAddressRequest)
```

* Purpose: Retrieves the contract address from a transaction hash.
* Parameters: `reqData` (type: model.ContractGetAddressRequest) - Contains the transaction hash.
* Return Value: `model.ContractGetAddressResponse` - Contains contract address information and an error code.

### Transaction APIs

```go
sdk.Transaction.BuildBlob(reqData model.TransactionBuildBlobRequest)
```

* Purpose: Constructs a transaction blob from the provided transaction details.
* Parameters: `reqData` (type: model.TransactionBuildBlobRequest) - Contains transaction details such as source address, nonce, operations, etc.
* Return Value: `model.TransactionBuildBlobResponse` - Contains the transaction blob and an error code.

```go
sdk.Transaction.EvaluateFee(reqData model.TransactionEvaluateFeeRequest)
```

* Purpose: Estimates the fee required for a transaction based on its details.
* Parameters: `reqData` (type: model.TransactionEvaluateFeeRequest) - Contains transaction details such as source address, nonce, operations, etc.
* Return Value: `model.TransactionEvaluateFeeResponse` - Contains the estimated fee limit, gas price, and an error code.

```go
sdk.Transaction.Sign(reqData model.TransactionSignRequest)
```

* Purpose: Signs a transaction blob using the provided private keys.
* Parameters:
* reqData (type: model.TransactionSignRequest): Contains the transaction blob and private keys for signing.
* Return Value: `model.TransactionSignResponse` - Contains the signatures and an error code.

```go
sdk.Transaction.Submit(reqData model.TransactionSubmitRequest)
```

* Purpose: Submits a signed transaction to the blockchain network.
* Parameters: `reqData` (type: model.TransactionSubmitRequest) - Contains the transaction blob and signatures.
* Return Value: `model.TransactionSubmitResponse` - Contains the transaction hash and an error code.

```go
sdk.Transaction.GetInfo(reqData model.TransactionGetInfoRequest)
```

* Purpose: Retrieves information about a transaction using its hash.
* Parameters: `reqData` (type: model.TransactionGetInfoRequest) - Contains the transaction hash.
* Return Value: `model.TransactionGetInfoResponse` - Contains transaction details and an error code.

### Block APIs

```go
sdk.Block.GetNumber()
```

* Purpose: Retrieves the current block number from the blockchain.
* Parameters: None.
* Return Value: `model.BlockGetNumberResponse` - Contains the block number and an error code.

```go
sdk.Block.CheckStatus()
```

* Purpose: Checks if the blockchain is synchronized.
* Parameters: None.
* Return Value: `model.BlockCheckStatusResponse` - Contains a boolean indicating synchronization status and an error code.

```go
sdk.Block.GetTransactions(reqData model.BlockGetTransactionRequest)
```

* Purpose: Retrieves transactions for a specific block number.
* Parameters: `reqData` (type: model.BlockGetTransactionRequest) - Contains the block number.
* Return Value: `model.BlockGetTransactionResponse` - Contains transaction details and an error code.

```go
sdk.Block.GetInfo(reqData model.BlockGetInfoRequest)
```

* Purpose: Retrieves information about a specific block.
* Parameters: `reqData` (type: model.BlockGetInfoRequest) - Contains the block number.
* Return Value: `model.BlockGetInfoResponse` - Contains block information and an error code.

```go
sdk.Block.GetLatest()
```

* Purpose: Retrieves information about the latest block.
* Parameters: None.
* Return Value: `model.BlockGetLatestResponse` - Contains the latest block information and an error code.

```go
sdk.Block.GetValidators(reqData model.BlockGetValidatorsRequest)
```

* Purpose: Retrieves validators for a specific block number.
* Parameters: `reqData` (type: model.BlockGetValidatorsRequest) - Contains the block number.
* Return Value: `model.BlockGetValidatorsResponse` - Contains validator information and an error code.

```go
sdk.Block.GetLatestValidators()
```

* Purpose: Retrieves validators for the latest block.
* Parameters: None.
* Return Value: `model.BlockGetLatestValidatorsResponse` - Contains the latest validator information and an error code.

```go
sdk.Block.GetReward(reqData model.BlockGetRewardRequest)
```

* Purpose: Retrieves reward distribution for a specific block number.
* Parameters: `reqData` (type: model.BlockGetRewardRequest) - Contains the block number.
* Return Value: `model.BlockGetRewardResponse` - Contains reward distribution details and an error code.

```go
sdk.Block.GetLatestReward()
```

* Purpose: Retrieves the latest reward distribution.
* Parameters: None.
* Return Value: `model.BlockGetLatestRewardResponse` - Contains the latest reward distribution details and an error code.

```go
sdk.Block.GetFees(reqData model.BlockGetFeesRequest)
```

* Purpose: Retrieves fee information for a specific block number.
* Parameters: `reqData` (type: model.BlockGetFeesRequest) - Contains the block number.
* Return Value: `model.BlockGetFeesResponse` - Contains fee information and an error code.

```go
sdk.Block.GetLatestFees()
```

* Purpose: Retrieves the latest fee information.
* Parameters: None.
* Return Value: `model.BlockGetLatestFeesResponse` - Contains the latest fee information and an error code.

### For code references on Zetrix's Go SDK, please visit our [GitHub repository](https://github.com/armmarov/zetrix-sdk-go-fork).


# Java

Java developers can easily interact with the Zetrix blockchain using the Zetrix Java SDK, offering a streamlined and efficient way to build blockchain-enabled applications.

## Overview

The **Zetrix Java SDK** enables developers to interact seamlessly with the Zetrix blockchain through a high-level, intuitive API. This powerful toolkit abstracts the complexities of blockchain operations, allowing you to focus on innovation. It streamlines tasks such as **account management**, **smart contract deployment**, **transaction creation**, **block data retrieval**, and more.

## Target Audience

The **Zetrix Java SDK** is built for developers with a solid background in **Java**, especially those aiming to develop API services that interact with the Zetrix blockchain. Whether you're a veteran in blockchain or just getting started, the SDK provides an approachable and efficient path to building on Zetrix.

## Quick Start Guide

### Installation

Getting started with the Zetrix Java SDK is straightforward. In this tutorial we will be using Maven for dependency management. Follow these steps to include the [package](http://maven.bubidev.cn/#browse/browse:releases:org%2Fzetrix%2Fsdk) in your `pom.xml`.

The repositories required:

```xml
<repositories>
	<repository>
		<id>bubi-release</id>
		<name>releases</name>
		<url>http://maven.bubidev.cn/repository/releases</url>
	</repository>
	<repository>
		<id>bubi-snapshot</id>
		<name>snapshots</name>
		<url>http://maven.bubidev.cn/repository/snapshots</url>
	</repository>
	<repository>
		<id>bubi-thirdparty</id>
		<name>thirdparty</name>
		<url>http://maven.bubidev.cn/repository/thirdparty</url>
	</repository>
	<repository>
		<id>danubetech-maven-public</id>
		<url>https://repo.danubetech.com/repository/maven-public/</url>
	</repository>
</repositories>
```

The dependencies required:

```xml
<dependencies>
	<dependency>
		<groupId>org.zetrix.sdk</groupId>
		<artifactId>zetrix-sdk</artifactId>
		<version>1.0.5.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.zetrix.encryption</groupId>
		<artifactId>zetrix-encryption</artifactId>
		<version>1.0.0.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>2.0.21</version>
	</dependency>
	<dependency>
		<groupId>net.i2p.crypto</groupId>
		<artifactId>eddsa</artifactId>
		<version>0.1.0</version>
	</dependency>
</dependencies>
```

Do note that the individual environments may differ. Please create an issue [here](https://github.com/Zetrix-Chain/zetrix-sdk-java/issues) if you face any problems setting up your environment for development.

### Prerequisites

* ​[Zetrix Wallet](https://www.zetrix.com/zetrix-wallet/) installed.
* A Zetrix account with sufficient balance. Claim your faucet [here](https://faucet.zetrix.com/).

### Basic Usages <a href="#basic-usages" id="basic-usages"></a>

Included in this section are some sample code snippets to help you get started with the SDK.

Create a Zetrix Java SDK instance to begin using the SDK.

If you're using the Zetrix testnet, initialize with this URL:

```java
// Testnet node URL
SDK sdk = SDK.getInstance("https://test-node.zetrix.com");
```

If you're using the Zetrix mainnet, initialize with this URL:

```java
// Mainnet node URL
SDK sdk = SDK.getInstance("https://node.zetrix.com");
```

Let's look at some examples:

Getting the nonce for a particular address:

```java
AccountGetNonceRequest request = new AccountGetNonceRequest();
request.setAddress(address);
AccountGetNonceResponse response = sdk.getAccountService().getNonce(request);
return response.getResult().getNonce();
```

Submitting a transaction:

```java
TransactionSubmitRequest transactionSubmitRequest = new TransactionSubmitRequest();
transactionSubmitRequest.setTransactionBlob(submitTxReq.getBlob());
transactionSubmitRequest.setSignatures(signatures);
return sdk.getTransactionService().submit(transactionSubmitRequest);
```

Getting the balance of a particular address:

```java
AccountGetBalanceResponse response = sdk.getAccountService().getBalance(request);
return response.getResult().getBalance();
```

Getting transaction info:

```java
TransactionGetInfoRequest txInfo = new TransactionGetInfoRequest();
txInfo.setHash(txHash);
TransactionGetInfoResponse respInfo = sdk.getTransactionService().getInfo(txInfo);
TransactionHistory txHistory = respInfo.getResult().getTransactions()[0];
```

## API References

### Account APIs

```java
sdk.getAccountService().getNonce(AccountGetNonceRequest request);
```

* Purpose: Retrieves the nonce of an account.
* Parameters: `AccountGetNonceRequest` - Contains the address of the account to retrieve the nonce for.
* Return: `AccountGetNonceResponse` - The response object containing the account's nonce.

```java
sdk.getAccountService().getMetadata(AccountGetMetadataRequest request);
```

* Purpose: Retrieves metadata for an account.
* Parameters: `AccountGetMetadataRequest` - Contains the address and key of the metadata to retrieve.
* Return: `AccountGetMetadataResponse` - The response object containing the account's metadata.

```java
sdk.getAccountService().getBalance(AccountGetBalanceRequest request);
```

* Purpose: Retrieves the balance of an account.
* Parameters: `AccountGetBalanceRequest` - Contains the address of the account to retrieve the balance for.
* Return: `AccountGetBalanceResponse` - The response object containing the account's balance.

```java
sdk.getAccountService().getInfo(AccountGetInfoRequest request);
```

* Purpose: Retrieves information about an account.
* Parameters: `AccountGetInfoRequest` - Contains the address of the account to retrieve information for.
* Return: `AccountGetInfoResponse` - The response object containing the account information.

```java
sdk.getAccountService().checkValid(AccountCheckValidRequest request);
```

* Purpose: Checks if an account address is valid.
* Parameters: `AccountCheckValidRequest` - Contains the address to be validated.
* Return: `AccountCheckValidResponse` - The response object indicating whether the address is valid.

```java
sdk.getAccountService().create()
```

* Purpose: Creates a new account by generating a new private key, public key, and address.
* Parameters: None.
* Return: `AccountCreateResponse` - The response object containing the new account's private key, public key, and address.

```java
sdk.getAccountService().checkActivated(AccountCheckActivatedRequest request);
```

* Purpose: Checks if an account is activated.
* Parameters: `AccountCheckActivatedRequst` - Contains the address of the account to check.
* Return: `AccountCheckActivatedResponse` - The response object indicating whether the account is activated.

### Block APIs

```java
sdk.getBlockService().getNumber();
```

* Purpose: Retrieves the current block number from the blockchain.
* Parameters: None.
* Return: `BlockGetNumberResponse` - Contains the block number and any error information if applicable.

```java
sdk.getBlockService().getInfo(BlockGetInfoRequest request);
```

* Purpose: Retrieves information about a specific block.
* Parameters: `BlockGetInfoRequest` - Contains the block number for which information is requested.
* Return: `BlockGetInfoResponse` - Contains block information and any error information.

```java
sdk.getBlockService().getTransactions(BlockGetTransactionsRequest request);
```

* Purpose: Retrieves transactions for a specific block number.
* Parameters: `BlockGetTransactionsRequest` - Contains the block number for which transactions are requested.
* Return: `BlockGetTransactionsResponse` - Contains transaction details and any error information.

```java
sdk.getBlockService().checkStatus();
```

* Purpose: Checks the synchronization status of the blockchain.
* Parameters: None.
* Return: `BlockCheckStatusResponse` - Indicates whether the blockchain is synchronized and includes any error information.

```java
sdk.getBlockService().getLatestInfo();
```

* Purpose: Retrieves information about the latest block.
* Parameters: None.
* Return: `BlockGetLatestInfoResponse` - Contains the latest block information and any error information.

```java
sdk.getBlockService().getValidators(BlockGetValidatorsRequest request);
```

* Purpose: Retrieves validator information for a specific block.
* Parameters: `BlockGetValidatorsRequest` - Contains the block number for which validator information is requested.
* Return: `BlockGetValidatorsResponse` - Contains validator details and any error information.

```java
sdk.getBlockService().getLatestValidators();
```

* Purpose: Retrieves information about the latest validators.
* Parameters: None.
* Return: `BlockGetLatestValidatorsResponse` - Contains the latest validator information and any error information.

```java
sdk.getBlockService().getReward(BlockGetRewardRequest request);
```

* Purpose: Retrieves reward distribution information for a specific block.
* Parameters: `BlockGetRewardRequest` - Contains the block number for which reward information is requested.
* Return: `BlockGetRewardResponse` - Contains reward distribution details and any error information.

```java
sdk.getBlockService().getLatestReward();
```

* Purpose: Retrieves the latest reward distribution information.
* Parameters: None.
* Return: `BlockGetLatestRewardResponse` - Contains the latest reward distribution details and any error information.

```java
sdk.getBlockService().getFees(BlockGetFeesRequest request);
```

* Purpose: Retrieves fee information for a specific block.
* Parameters: `BlockGetFeesRequest` - Contains the block number for which fee information is requested.
* Return: `BlockGetFeesResponse` - Contains fee details and any error information.

```java
sdk.getBlockService().getLatestFees();
```

* Purpose: Retrieves the latest fee information.
* Parameters: None.
* Return: `BlockGetLatestFeesResponse` - Contains the latest fee details and any error information.

### Transaction APIs

```java
sdk.getTransactionService().buildBlob(TransactionBuildBlobRequest request);
```

* Purpose: Constructs a transaction blob from the given request, which includes validating the request parameters and building the transaction.
* Parameters: `TransactionBuildBlobRequest` - Contains details like source address, nonce, gas price, fee limit, metadata, and operations.
* Return: `TransactionBuildBlobResponse` - Contains the transaction blob and its hash if successful, or error details if an exception occurs.

```java
sdk.getTransactionService().parseBlob(TransactionParseBlobRequest request);
```

* Purpose: Parses a transaction blob into a readable format, converting it to JSON.
* Parameters: `TransactionParseBlobRequest` - Contains the transaction blob to be parsed.
* Return: `TransactionParseBlobResponse` - Contains the parsed transaction details in JSON format or error details if an exception occurs.

```java
sdk.getTransactionService().sign(TransactionSignRequest request);
```

* Purpose: Signs a transaction blob using the provided private keys.
* Parameters: `TransactionSignRequest` - Contains the transaction blob and an array of private keys for signing.
* Return: `TransactionSignResponse` - Contains the signatures and public keys if successful, or error details if an exception occurs.

```java
sdk.getTransactionService().submit(TransactionSubmitRequest request);
```

* Purpose: Submits a signed transaction to the blockchain network.
* Parameters: `TransactionSubmitRequest` - Contains the transaction blob and signatures.
* Return: `TransactionSubmitResponse` - Contains the transaction hash if successful, or error details if an exception occurs.

```java
sdk.getTransactionService().getInfo(TransactionGetInfoRequest request);
```

* Purpose: Retrieves information about a transaction using its hash.
* Parameters: `TransactionGetInfoRequest` - Contains the hash of the transaction to be queried.
* Return: `TransactionGetInfoResponse` - Contains transaction details or error information if an exception occurs.

```java
sdk.getTransactionService().evaluateFee(TransactionEvaluateFeeRequest request);
```

* Purpose: Evaluates the fee required for a transaction based on the provided request details.
* Parameters: `TransactionEvaluateFeeRequest` - Includes source address, nonce, signature number, metadata, and operations.
* Return: `TransactionEvaluateFeeResponse` - Contains the evaluated fee details or error information if an exception occurs.

### Contract APIs

```java
sdk.getContractService().call(ContractCallRequest request);
```

* Purpose: Calls a contract with specified parameters.
* Parameters: `ContractCallRequest` - An object containing details like source address, contract address, code, input, contract balance, gas price, and fee limit.
* Return: `ContractCallResponse` - The result of the contract call or error details if the call fails.

```java
sdk.getContractService().getInfo(ContractGetInfoRequest request);
```

* Purpose: Retrieves information about a specific contract using its address.
* Parameters: `ContractGetInfoRequest` - An object containing the contract address.
* Return: `ContractGetInfoResponse` - Contains the contract information or error details if the request fails.

```java
sdk.getContractService().checkValid(ContractCheckValidRequest request);
```

* Purpose: Checks if a given contract address is valid.
* Parameters: `ContractCheckValidRequest` - An object containing the contract address to be validated.
* Return: `ContractCheckValidResponse` - Indicates whether the contract address is valid or not.

```java
sdk.getContractService().getAddress(ContractGetAddressRequest request);
```

* Purpose: Retrieves the contract address associated with a given transaction hash.
* Parameters: `ContractGetAddressRequest` - An object containing the transaction hash.
* Return: `ContractGetAddressResponse` - Containing the contract address information or error details if the retrieval fails.

### For code references on Zetrix's Java SDK, please visit our [GitHub repository](https://github.com/Zetrix-Chain/zetrix-sdk-java).


# Interoperability

Zetrix is a public blockchain that focuses on interoperability between different blockchain networks and real-world applications. It is designed to connect with other blockchains and traditional financial systems, allowing for the transfer of assets, data, and value across multiple platforms.

#### Key Features of Zetrix Interoperability:

1. **Cross-Chain Transactions**: Zetrix enables the transfer of digital assets across different blockchain networks, allowing for seamless communication between various ecosystems (e.g., Ethereum, Hyperledger).
2. **Smart Contract Integration**: It supports smart contracts that can operate across different chains, enabling developers to build decentralized applications (dApps) that interact with multiple blockchains.
3. **Real-World Integration**: Zetrix aims to bridge the gap between digital and traditional finance by integrating with real-world applications such as banking, logistics, and supply chain management. It offers a platform for enterprises to use blockchain technology without being confined to a single ecosystem.
4. **Interoperability with MYEG**: Zetrix is notably linked to Malaysia’s e-government service provider MYEG, which seeks to leverage blockchain technology such as for National Blockchain Infrastructure, cross-border transactions, and other government services.
5. **Scalability & Security**: Zetrix aims to provide scalable solutions while maintaining the high security of transactions and data sharing across different blockchains.

These features make Zetrix particularly useful for companies or developers who are looking to build multi-chain solutions or need to work in environments that require the integration of blockchain with traditional financial services and industries.


# Verifiable Credentials

This guide will walk you through what VCs are, how Zetrix supports them, and how to use the Zetrix VC APIs to build decentralized identity and credential systems.

## Introduction to Verifiable Credentials

What Are Verifiable Credentials?

**Verifiable Credentials (VCs)** are digital credentials that are cryptographically secure, privacy-respecting, and machine-verifiable. Based on the **W3C VC standard**, they are used to represent information such as ID cards, academic degrees, and licenses in a decentralized way.

A VC typically includes:

* **Issuer** (who issued it)
* **Subject** (who it's about)
* **Claims** (the data)
* **Proof** (digital signature)

#### Why Use VCs on Zetrix?

* **Trustless Verification**: No need to call the issuer to validate a VC.
* **Data Integrity**: Credentials are tamper-evident.
* **Privacy-Preserving**: Support for selective disclosure with BBS+ signatures.
* **Decentralized Identity (DID)**: Users are identified by unique, blockchain-resolved `did:zid` identifiers.
* **Ed25519 + BbsBls**: Signature schemes used for W3C compliance and selective disclosure.

## High-Level Overview

### Roles

* **Issuer**: Entity that issues a VC.
* **Holder**: The recipient of the VC.
* **Verifier**: Entity that checks the authenticity of a VC or Verifiable Presentation (VP).

### Credential Lifecycle

1. **Template Creation**: Issuer defines the schema of the credential.
2. **VC Application**: Holder requests a VC using a defined template.
3. **VC Issuance**: Issuer fills in fixed values, signs, and issues the VC.
4. **VC Download**: Holder downloads the issued VC.
5. **VP Creation**: Holder creates a Verifiable Presentation.
6. **VP Verification**: Verifier checks the proof.
7. **VC Revocation** *(optional)*: Issuer can revoke an issued VC.

## High Level Architecture

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FSQ0IVWw6twksRTdnIeRX%2FPresentation1.png?alt=media&amp;token=e44aff6c-a74a-4779-8b00-2df2e36c666f" alt=""><figcaption></figcaption></figure>

### **Blockchain Smart Contracts Layer**

The ZID ecosystem is underpinned by smart contracts deployed on the Zetrix blockchain. These contracts serve critical roles in preserving the integrity and immutability of identity and credential data. The **Revocation List Contract (RCL)** ensures that once a Verifiable Credential (VC) is revoked, this status is permanently and publicly recorded, enabling any verifier to check its validity.

The **Trusted Dataset (TDS) contract** acts as a registry for recognized issuers and credential templates, which standardize the types of credentials that can be issued across the ecosystem.

Finally, the **DID Registry Contract** stores all decentralized identifiers (DIDs) created on the network, and supports lifecycle management operations such as ownership changes and delegation.

### Zetrix Blockchain

At the core of the architecture lies the Zetrix Layer-1 blockchai&#x6E;**,** a decentralized and high-performance infrastructure that ensures security, auditability, and immutability of all identity-related operations. All DID documents, VCs, credential templates, and revocation logs are permanently stored on-chain, making Zetrix the single source of truth for digital identity operations within the ecosystem.

### ZID Resolver

The ZID Resolver is a web service endpoint (*zid-resolver.zetrix.com)* designed to translate a decentralized identifier (DID) into its associated DID document. It interacts with the Zetrix blockchain to fetch public keys, service endpoints, and other identity metadata encoded in the DID document. This resolution process is critical for verifying the authenticity and integrity of interactions between identity holders, issuers, and verifiers.

### ZID Management Platform

Operating at *identity.zetrix.com* (to-be launched), the ZID Management Platform provides a user interface and backend services for managing the lifecycle of DIDs. This includes assigning delegates, updating attributes, and transferring ownership of DIDs. This platform ensures decentralized control over identity by empowering users with tools to manage their on-chain presence.

### Issuer Management Platform

This component facilitates issuer onboarding and template creation through both front-end (*zid-issuer.zetrix.com*) and API endpoints (*zid-issuer.zetrix.com/api*). The front-end interface is used by issuers to perform Know Your Customer (KYC) procedures and manage their credential issuance capabilities. The backend APIs enable the automation of KYC and template registration workflows, forming the administrative layer that ensures only verified issuers are authorized to operate within the ecosystem.

### ZID Digital Credential Engine

Located at *api.zetrix.com/cred*, this engine provides the core functionality required to manage the lifecycle of Verifiable Credentials. It exposes APIs for applying, issuing, downloading, and revoking credentials, as well as for creating and verifying Verifiable Presentations (VPs). Templates can also be registered via this interface, allowing for structured and interoperable credential issuance. The engine is a central orchestrator that coordinates between SDKs, smart contracts, and issuer services.

### DIDComm Mediator Server

The Mediator Server at *zid-mediator.zetrix.com* supports DIDComm messaging, facilitating encrypted, peer-to-peer communication between identity holders and verifiers or issuers. This ensures that VCs and VPs can be exchanged securely and privately over the network without relying on centralized intermediaries.

### VC SDKs (Software Development Kits)

The ZID ecosystem offers several SDKs for integrating VC functionality into applications. The Flutter SDK supports mobile development for Android and iOS platforms, while the NPM SDK caters to web and backend JavaScript environments. For cross-platform and embedded integrations, the Generic VC SDK in the form of a shared object (.so) library is provided. All SDKs offer standardized methods for applying for credentials, downloading them, creating presentations, and handling secure DIDComm-based exchanges.

### Data Flow Summary

The ecosystem functions through interconnected layers. A DID is first created using the ZID Management Platform and stored on-chain via the DID Registry Contract. An issuer undergoes KYC via the Issuer Management Platform, after which it can register credential templates. When a credential is issued, it is processed by the ZID engine. Users can retrieve their credentials via the SDKs or the MBI VC service integrated within the client's system. The integrity and revocation status of credentials can always be verified through the resolver and RCL contract, ensuring a fully decentralized and trustless identity framework.


# Issuance Workflow Overview

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F0j2IAcL6NW4Vy184yWpO%2FZetrix-Illustration-white-bg%20(1).png?alt=media&amp;token=b2a1ad32-e44c-4224-9664-f4e4d64edeb7" alt=""><figcaption></figcaption></figure>

## **Introduction**

This is an overview of the end-to-end process for issuing Verifiable Credentials (VCs) within the Zetrix ecosystem. It describes the roles, platforms, and interactions required for an Issuer to create, manage, and distribute blockchain-secured digital credentials to end-users. The workflow ensures security, trust, and interoperability across all participating systems.

## **Participants and Platforms**

### **Participants**

* **Issuer**\
  The organization responsible for managing credential issuance.
* **System integrator (SI)**

  Entity who is responsible to build the system for the Issuer. In addition, system integrator can also be an issuer.
* **End-User**\
  The individual or entity receiving the Verifiable Credential.

### **Platforms**

* **ZPlatform (**[**https://platform.zetrix.com**](https://platform.zetrix.com)**)**\
  Subscription and API management portal.
* **Zetrix Wallet**\
  Web3 wallet supporting identity and blockchain operations.
* **Identity Platform (**[**https://identity.zetrix.com**](https://identity.zetrix.com/)**)**\
  DID (Decentralized Identifier) management and BBS+ key generation.
* **ZCert Issuer Platform (**[**https://zid-issuer.zetrix.com**](https://zid-issuer.zetrix.com/)**)**\
  Credential template management and onboarding verification.
* **Backend VC Issuance System**\
  Credential issuance engine integrating with Zetrix services.

## Process Overview

### Subscription and API Provisioning

The process begins by the SI registering on the [ZPlatform](https://docs.zetrix.com/en/developer-resources/zplatform-baas-api)**.**\
Upon successful registration:

1. The Issuer subscribes to a **VC Subscription Plan**, defining usage quotas and service access.
2. An **API Key** is generated, granting secure access to Zetrix Verifiable Credential APIs.

This step ensures the Issuer has the required permissions and infrastructure to participate in the credential issuance ecosystem.

### Wallet Creation

The Issuer proceeds to create a **Zetrix Web3 Wallet**.\
This wallet provides:

* A **Wallet Address** used as the Issuer’s blockchain identity.
* A **Private Key** used for signing operations and authentication within the ecosystem.

The wallet is an essential trust anchor for subsequent identity related operations.

For more details, please refer to the [Wallet](https://docs.zetrix.com/en/wallets/supported-wallets) section.

### DID and Key Management

On the **Identity Platform**, the Issuer connects their wallet to establish their formal decentralized identity.

The following actions take place:

1. **DID Generation**\
   The system automatically creates a Decentralized Identifier (DID) linked to the Issuer’s wallet.
2. **BBS+ Key Generation**\
   A BBS+ keypair is generated for cryptographic signing.\
   This key enables:
   * Privacy-preserving credential issuance
   * Selective disclosure by end-users
   * Standards-compliant digital signatures

The DID and BBS+ keys together form the Issuer’s official cryptographic identity on Zetrix.

For more details, please refer to the [Identity Platform](https://docs.zetrix.com/en/developer-resources/generating-bbs+-key) section.

### Credential Template Configuration

The Issuer accesses the **ZCert Issuer Platform** to configure VC template. This template determine the attributes and UI design of the VC.

Activities include:

1. **Onboarding Due Diligence**\
   Organizational verification to ensure the Issuer is legitimate and authorized.
2. **VC Template Creation**\
   Templates define the structure, fields, and attributes of the Verifiable Credentials.\
   Examples VC Design include:
   * General Certificates
   * Identity Card
   * Passport

Templates ensure consistency, standardization, and alignment with predefined data schemas.

For more details, please refer to the [Issuer Platform](https://docs.zetrix.com/en/developer-resources/zcert-issuer-platform) section.

### VC Issuance

The Backend VC Issuance System integrates all previously prepared components:

* **API Key** (authorization)
* **VC Templates** (credential structure)
* **BBS+ Key** (cryptographic signing)
* **DID** (issuer identity)

The VC Engine performs the following functions:

1. Applies template rules and issuer metadata
2. Signs the credential using the BBS+ key
3. Stores issuance records in the internal database
4. Generates the final **Verifiable Credential** in the required format (e.g., JSON-LD, JWT)

The completed credential is then provided to the **End-User** for secure download or wallet import.


# Getting Started

## Authorization

All API requests require a bearer token in the header:

```json
Authorization: Bearer <token>
```

## Zetrix DID Format

Example:

```
did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb
```

## Template Design Tips

* Use `USER` fields the holder fills in.
* Use `FIXED` for fields the issuer controls.
* Use camelCase for keys (e.g., `fullName`)
* Specify field format (`STRING`, `NUMBER`), and whether it is `mandatory` (true/false)

## Sample VC Lifecycle

Let's walk through each stage step-by-step:

### 1. Template Flow (by Issuer)

**Goal**: Define the structure of a credential (schema).

**Steps:**

1. **Submit Template Payload**
   * Inputs:
     * `signedTx`, `signerId`, `signerPublicKey` (to authenticate/sign the template)
     * Template metadata like `templateName`, `issuerDid`, `credentialFormat`, etc.
2. **API Call:** `/cred/tds/template/blob/create`
   * Backend generates a `blobId` and a `blob` that needs to be signed.
3. **Submit signed blob**
   * API: `/cred/tds/template/submit`
   * Signed blob is submitted to blockchain.
   * Output: `templateId`, `txHash`

### 2. Apply VC Flow (by Holder)

**Goal**: A user (holder) applies for a credential based on a template.

**Steps:**

1. **Submit Application**
   * API: `/cred/v1/vc/apply`
   * Inputs:
     * `vcPayload`: includes `templateId`, `metadata`, and holder's public key/signature.
2. **Backend Actions**:
   * Validates the template.
   * Stores the VC application temporarily.
   * Output: VC ID and status (e.g., `APPLIED`)

### 3. Issue VC Flow (by Issuer)

**Goal**: Issuer issues a credential based on the holder’s application.

**Steps:**

1. **Create VC Payload**
   * API: `/cred/v1/vc/create`
   * Inputs: `vcId`, `data`, `issuanceDate`, `expirationDate`
   * Output:
     * `ed25519Blob` (data to be signed using Ed25519)
     * `bbsBlsBase64` (data to be signed using BBS+ for selective disclosure)
2. **Sign & Submit VC**
   * API: `/cred/v1/vc/submit`
   * Inputs:
     * `ed25519PubKey`, `ed25519SignData`
     * `bbsBlsPubKey`, `bbsBlsSignData`
     * `keyExpiry`
   * Output: Full VC Object with proof(s)

**Note**: Both signature schemes (Ed25519 and BbsBls) are used to ensure W3C compliance and support for selective disclosure.

### 4. Download VC (by Holder/Issuer)

**Goal**: Download the VC before expiry.

**Steps:**

1. **Submit Download Payload**
   * API: `/cred/v1/vc/download`
   * Inputs: `vcId`, `signVcId` (signed value of VC ID), `isIssuer` (optional)
2. **Backend fetches VC**
   * Checks temporary storage and resolves DID document.
   * Returns full VC object.

### 5. Create VP (by Holder)

**Goal**: Holder creates a **Verifiable Presentation** (VP) to selectively share claims.

**Steps:**

1. **Create VP Payload**
   * API: `/cred/v1/vp/create`
   * Inputs include selected claims and `rangeProof` conditions (e.g., age > 18)
2. **Backend generates `blobId` + `blob`** for the holder to sign.
3. **Submit signed VP**
   * API: `/cred/v1/vp/submit`
   * Output: Verifiable Presentation (VP) object

### 6. Verify VP (by Verifier)

**Goal**: Verifier checks authenticity and integrity of the VP.

**Steps:**

1. **Submit VP Payload**
   * API: `/cred/v1/vp/verify`
   * Input: Full VP object (with BbsBls signature, context)
2. **Backend resolves DIDs**
   * Verifier uses the DID of issuer and holder to check proof chain.
3. **Returns**: Verification result (valid/invalid)


# VC Encryption Process

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FndoJ7Jfl2yNmlnffzQKg%2FEncryption%20Colour%201.png?alt=media&amp;token=e1fd0a25-24f8-4a4c-88cf-70af3ec3e69d" alt=""><figcaption></figcaption></figure>

## Apply VC Process

This process defines the secure exchange of data between a Holder and an Issuer in the Verifiable Credential (VC) system. The encryption model uses a **hybrid scheme**, combining asymmetric RSA encryption for key exchange and symmetric AES/GCM encryption (with HMAC-SHA256) for securing data. Additionally, a shared key is established using the **X25519 Diffie-Hellman key exchange protocol** to ensure end-to-end confidentiality between the Holder and Issuer.

**Steps Overview**

1. **ECDH Key Generation (Holder):**\
   The Holder generates an Elliptic Curve Diffie-Hellman (ECDH) key using the Issuer’s public key and the Holder’s private key.
2. **Application Data Encryption:**\
   The Holder encrypts the VC application data using AES with the derived ECDH key.
3. **ECDH Key Encryption (RSA):**\
   The Holder encrypts the ECDH key using the Issuer’s RSA public key for secure transmission.
4. **Submit Encrypted Data:**\
   The Holder sends the encrypted application data, encrypted ECDH key, signed data, metadata, public key, and X25519 public key to the MS Credential service via a `POST /vc/apply` request.
5. **ECDH Key Decryption (Server):**\
   The MS Credential service decrypts the ECDH key using its RSA private key.
6. **Application Data Decryption:**\
   Using the decrypted ECDH key, the service decrypts the encrypted application data.
7. **Template Metadata Validation:**\
   The service validates the metadata against the template to ensure integrity.
8. **Data Storage (Redis):**\
   The service stores the encrypted application data along with the Holder’s DID and X25519 public key in Redis as an APPLIED record.
9. **Issuer Fetch Request:**\
   The Issuer retrieves the Holder’s DID and X25519 public key by calling `GET /v1/vc/enc/holder?vcId=`.
10. **ECDH Key Generation (Issuer):**\
    The Issuer generates its ECDH key using the Holder’s public key and its own private key to establish the shared secret.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FMQd1D2YIDB2XFndjPpL6%2FEncryption%20Colour%202.png?alt=media&amp;token=a5804747-be46-494e-aa7f-17df35c038c7" alt=""><figcaption></figcaption></figure>

## Issue and Download VC Process

This process defines how a Verifiable Credential (VC) is securely issued by the Issuer and later downloaded by the Holder. Like the Apply VC Process, this stage uses **hybrid encryption** combining RSA (for exchanging ECDH keys), AES/GCM with HMAC-SHA256 (for encrypting data), and Diffie-Hellman with **X25519** for shared key generation. It also introduces **ED25519** and **BBS+ signatures** for signing and verification.

### **Fetching and Key Setup**

1. The Issuer fetches the Holder’s **X25519 public key and DID** (`GET /v1/vc/enc/holder?vcId=`).
2. The Issuer generates an ECDH key using the Holder’s public key and the Issuer’s private key.
3. Issuance data is encrypted using AES with the ECDH key.
4. The ECDH key itself is encrypted using the Holder’s RSA public key.

### **Sending Encrypted Issuance Data**

5. The Issuer sends the encrypted issuance data and encrypted ECDH key to the MS Credential service (POST `/vc/create`).
6. The service decrypts the ECDH key with its RSA private key.
7. The service decrypts the issuance data with the ECDH key.
8. The service also decrypts the Holder’s earlier apply data.
9. Metadata from Holder and Issuer are merged.
10. The template metadata is validated.
11. A VC blob is created and returned to the Issuer.

### **Signing and Submitting VC Data**

12. The MS Credential service updates the encrypted apply VC data as **PENDING\_SIGN**.
13. The Issuer signs the blob with **ED25519** and **BBS+ keys**.
14. The Issuer encrypts the post VC data using AES with the ECDH key.
15. The Issuer encrypts the ECDH key using the Holder’s RSA public key.
16. The Issuer submits encrypted VC data, including the VC ID, ED25519 public key, ED25519 signature, BBS public key, BBS signature, expiry, and the encrypted ECDH key (`POST /vc/submit`).

### **Final VC Issuance**

17. MS Credential decrypts the ECDH key with its RSA private key.
18. It decrypts the submitted VC data using AES with the ECDH key.
19. It creates and verifies the final VC.
20. The VC is encrypted again using AES with the ECDH key.
21. The encrypted VC is stored in Redis as **ISSUED**.

### **Download by Holder**

21. The Holder downloads the encrypted VC using POST `/vc/download` with payload including VC ID, Issuer ID, and signed VC ID.
22. The Holder generates the ECDH key using the Issuer’s public key and the Holder’s private key.
23. The Holder decrypts the VC using AES with the derived ECDH key and stores it locally.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FBsrko53cpI9g1CjsBCcy%2FEncryption%20Colour%203.png?alt=media&amp;token=0a55dab7-d52b-4104-b9ef-88a52ad48cd7" alt=""><figcaption></figcaption></figure>

## Create and Verify VP Process

This process enables a Holder to generate a **Verifiable Presentation (VP)** from their issued **Verifiable Credential (VC)** and securely share it with a Verifier. It uses a combination of **RSA** for key exchang&#x65;**, AES/GCM** with **HMAC-SHA256** for encryption, **X25519 ECDH** for shared keys, and **ED25519** for signing.

### VP Creation by Holder

1. The Holder generates an ECDH key using their private key and the Verifier’s public key.
2. The Holder encrypts the VC using AES with the generated ECDH key.
3. The ECDH key is encrypted using the Verifier’s RSA public key.
4. The Holder sends the encrypted VC, reveal attributes, and range proof to MS Credential (`POST /vp/create`).

### Processing at MS Credential

5. MS Credential decrypts the ECDH key using its RSA private key.
6. MS Credential decrypts the VC using AES with the ECDH key.
7. MS Credential creates a blob and returns the blob to the Holder.

### Holder Preparing VP Submission

8. The Holder signs the blob with their ED25519 private key.
9. The Holder encrypts the ECDH key again using the Verifier’s RSA public key.
10. The Holder sends the encrypted VP, including `blobId`, signed blob, ED25519 public key, and encrypted ECDH key, to MS Credential (POST `/vp/submit`).

### Storing VP in Redis

11. MS Credential decrypts the ECDH key using its RSA private key.
12. MS Credential creates the VP and validates its parameters.
13. MS Credential encrypts the VP using AES with the ECDH key.
14. MS Credential stores the encrypted VP in Redis and returns a UUID to the Holder.

### Sharing with Verifier

15. The Holder shares the UUID and their public key in a QR Code with the Verifier.

### Verifier Verification Process

16. The Verifier generates an ECDH key using its private key and the Holder’s public key.
17. The Verifier encrypts the ECDH key using the Holder’s RSA public key.
18. The Verifier fetches the encrypted VP from Redis using the UUID.
19. The Verifier sends the VP data to the verification API with the UUID and encrypted ECDH key (POST `/vp/verify`).

### Final Verification by MS Credential

20. MS Credential fetches the encrypted VP from Redis.
21. MS Credential decrypts the encrypted VP using its RSA private key and the ECDH key.
22. MS Credential verifies the VP and returns the verification status to the Verifier.


# OID4VP

Learn how OpenID for Verifiable Presentations enables secure credential verification.

## OpenID for Verifiable Presentations

**OpenID for Verifiable Presentations (OID4VP)** is an OpenID Connect protocol for requesting and presenting Verifiable Credentials.

It lets a verifier request specific credential data from a holder. The holder reviews the request and shares a Verifiable Presentation only after consent.

### How it works

1. A verifier creates a presentation request.
2. The holder receives and reviews the request.
3. The holder selects credentials and approves the presentation.
4. The verifier validates the presentation and its proofs.

OID4VP supports interoperable, privacy-preserving credential exchange. Holders can share only the claims required for a transaction.

### Participants

OID4VP involves two primary participants:

* **Verifier** — The application requesting credential data. It defines the required claims and validates the returned presentation.
* **Holder** — The user controlling the credentials. The holder reviews the request and decides what to share.

An issuer also has an indirect role. It signs the credentials that the holder presents.

### Presentation requests

A presentation request describes what the verifier needs to validate. It can define:

* The credential type or schema the verifier accepts
* Required claims, such as a name, qualification, or eligibility status
* Accepted credential formats and presentation requirements

The holder's wallet uses this request to find suitable credentials. The holder should review every requested claim before approving the presentation.

### Verification and privacy

After receiving a presentation, the verifier checks the credential proof. It also confirms that the credential meets the request requirements.

Verifiers should request only the claims needed for their use case. Holders should share credentials only with trusted verifiers.

{% hint style="info" %}
OID4VP separates credential issuance from credential presentation. A verifier can validate a presentation without contacting the issuer during each verification.
{% endhint %}

### Detailed guide

<a href="https://docs.zetrix.com/oid4vp" class="button primary">Open OID4VP documentation</a>


# API Reference

This guide covers the **Zetrix Verifiable Credential (VC) system API endpoints,** organized by the major functions in the VC lifecycle: creating credential templates, issuing credentials, revoking credentials, managing **BBS+** issuer accounts, and creating/verifying verifiable presentations. Each endpoint includes its HTTP method and path, a description of its purpose, required request fields, response structure, example requests/responses, and potential error cases.

In the Verifiable Credential (VC) system, two types of APIs are provided: **encrypted-based** and **non-encrypted-based**.

* **Encrypted VC API**
  * Secures credential exchange using hybrid cryptography.
  * Combines RSA for key exchange, AES/GCM with HMAC-SHA256 for data encryption, and X25519 ECDH for shared key generation.
  * Protects sensitive data such as holder identifiers, metadata, and proofs with end-to-end security.
  * Recommended for high-assurance environments, cross-domain credential exchange, and public verification.
* **Non-Encrypted VC API**
  * Operates without cryptographic wrapping for faster processing and simpler integration.
  * Suitable where data sensitivity is lower or security is enforced at another layer (e.g., TLS or secure internal networks).
  * Provides flexibility for lightweight operations, testing, and internal trusted use cases.

## VC Template APIs

Credential **templates** define the structure and metadata for credentials that an issuer can later issue. Templates are created and registered on the Zetrix network in two steps: first building a transaction blob, then submitting it after signing. These APIs are typically used by the issuer.

### Create Template Blob

**Endpoint:** `POST /cred/tds/template/blob/create`\
**Description:** Creates a new credential template and returns a transaction blob that must be signed by the issuer. This blob represents a request to register the template on the blockchain. After obtaining the blob, the issuer should sign it with their Zetrix account private key (Ed25519) and use the **Submit Template** endpoint to finalize the template registration.

**Request Body:** *(JSON)*

* `templateName` (string): A human-readable name for the credential template (e.g., `"DrivingLicense"`).
* `issuerZid` (string): The Decentralized Identifier (DID) of the issuer creating this template. This should correspond to the issuer’s Zetrix DID.
* `credentialFormat` (array of objects): An array describing each attribute/field in the credential defined by this template. Each object in the array represents one credential field with the following properties:
  * `attribute` (string): A descriptive name of the attribute (e.g., `"Full Name"`).
  * `format` (string): The expected format of the attribute’s value (e.g., `"string"`, `"date"`, `"image/png"` depending on the attribute).
  * `key` (string): A unique key or identifier for the attribute (e.g., `"fullName"`). This will be used as the field name in credential data.
  * `mandatory` (boolean): Whether this attribute is mandatory (`true`) or optional (`false`) for credential issuance.
  * `type` (number): A code or indicator for the data type or category of the attribute. (For example, `1` might indicate a text string, `2` an image, etc., as defined by the system.)
* `version` (string): Version identifier for this template (e.g., `"1.0"`). Allows template updates or variations to be tracked.
* `remark` (string): An optional remark or description for the template. This can include any additional information or notes about the template.

**Response Body:** *(JSON)*

* `blobId` (string): An identifier for the created transaction blob (used to reference the blob in the submit call).
* `blob` (string): The transaction blob in hex string or base64 format. This blob encodes the template creation operation and must be signed by the issuer’s private key before submission.

**Example Request:**

```json
{
    "templateName": "DrivingLicense",
    "issuerZid": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb",
    "credentialFormat": [
        {
            "attribute": "Name",
            "format": "STRING",
            "key": "name",
            "mandatory": true,
            "type": "USER"
        },
        {
            "attribute": "Class",
            "format": "STRING",
            "key": "class",
            "mandatory": true,
            "type": "USER"
        }, 
        {
            "attribute": "Gender",
            "format": "STRING",
            "key": "gender",
            "mandatory": false,
            "type": "USER"
        },
        {
            "attribute": "Age",
            "format": "STRING",
            "key": "age",
            "mandatory": true,
            "type": "USER"
        },
        {
            "attribute": "Id no.",
            "format": "STRING",
            "key": "idNo",
            "mandatory": true,
            "type": "FIXED"
        }
    ],
    "version": "1.0.0",
    "remark": "test remark"
        
}

```

**Example Response:**

```json
{
  "blobId": "be48f912-3a9f-4d00-90f5-2d9e6c8e7f01",
  "blob": "0a0c0b0a0931323334...5f6e" 
}
```

**Error Cases:**

* `400 Bad Request` – Missing or invalid fields (e.g., a required field like `templateName` is empty, or an attribute format is incorrect).
* `401 Unauthorized` – The caller is not authenticated or not allowed to create templates (e.g. invalid API token).
* `409 Conflict` – The template name is already in use or a similar template already exists (if the system enforces unique template names or IDs).
* `500 Internal Server Error` – An unexpected error occurred on the server (e.g., database or blockchain interaction failure).

### Create Template

**Endpoint:** POST `/cred/tds/template/create`

**Description:** Initiates the creation of a new credential template definition. The issuer specifies the structure, attributes, and rules that will govern credentials issued under this template. The response returns a transaction blob that must be signed before the template can be registered on the Zetrix blockchain. Use this as the first step in defining a credential template.

**Request Body:** *(JSON)*

* `templateName` (string): A human-readable name for the credential template (e.g., `"DrivingLicenseTemplate"`).
* `issuerZID(`string): The Decentralized Identifier (DID) of the issuer creating this template. This should correspond to the issuer’s Zetrix DID.
* `issuerPrivateKey(`string): The issuer’s confidential private key used to sign transaction blobs and credential data for authenticity on the Zetrix blockchain.
* `credentialFormat` (array of objects): An array describing each attribute/field in the credential defined by this template. Each object in the array represents one credential field with the following properties:
  * `attribute` (string): A descriptive name of the attribute (e.g., `"Full Name"`).
  * `format` (string): The expected format of the attribute’s value (e.g., `"string"`, `"date"`, `"image/png"` depending on the attribute).
  * `key` (string): A unique key or identifier for the attribute (e.g., `"fullName"`). This will be used as the field name in credential data.
  * `mandatory` (boolean): Whether this attribute is mandatory (`true`) or optional (`false`) for credential issuance.
  * `type` (number): A code or indicator for the data type or category of the attribute. (For example, `1` might indicate a text string, `2` an image, etc., as defined by the system.)
* `version` (string): Version identifier for this template (e.g., `"1.0"`). Allows template updates or variations to be tracked.
* `remark` (string): An optional remark or description for the template. This can include any additional information or notes about the template.

**Response Body:** *(JSON)*

* `templateId`(string): Unique identifier of the credential template registered on the Zetrix blockchain.
* `txHash` (string): Transaction hash that records the template registration on the Zetrix blockchain.

**Example Request:**

```json
{
    "templateName": "PASSPORT MALAYSIA",
    "issuerZid": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb",
    "issuerPrivateKey": "privBrhqgrF5zYTBQmGQnhMvaPccXRpnc31W29XhaRmCwoz44SqVeNM9",
    "credentialFormat": [
        {
            "attribute": "Full Name",
            "format": "STRING",
            "key": "name",
            "mandatory": true,
            "type": "USER"
        },
        {
            "attribute": "Class",
            "format": "STRING",
            "key": "class",
            "mandatory": false,
            "type": "USER"
        },
        {
            "attribute": "Age",
            "format": "STRING",
            "key": "age",
            "mandatory": false,
            "type": "USER"
        },
        {
            "attribute": "Gender",
            "format": "STRING",
            "key": "gender",
            "mandatory": false,
            "type": "USER"
        },
        {
            "attribute": "Id No",
            "format": "NUMBER",
            "key": "idNo",
            "mandatory": true,
            "type": "FIXED"
        },
        {
            "attribute": "Height",
            "format": "NUMBER",
            "key": "height",
            "mandatory": true,
            "type": "APPLICATION"
        }
    ],
    "version": "1.0.0",
    "remark": "test remark"
}
```

**Example Response:**

```json
{
    "object": {
        "templateId": "did:zid:01ac71495075ad9b6d611315e39b2466647281c448d72ba7aea2437a2f0eafad",
        "txHash": "0003ced4581b2dfe10d307d59659bed09cdb01a46066bf84b0f7cc2cbed96eb2"
    },
    "messages": []
}
```

### Submit Template

**Endpoint:** POST `/cred/tds/template/submit`\
**Description:** Finalizes the registration of a credential template on the Zetrix blockchain. The issuer must provide the signed transaction blob (from the **Create Template Blob** step). Upon successful submission, the template becomes available for credential issuance. Use this after signing the blob returned by the create endpoint.

**Request Body:** *(JSON)*

* `blobId` (string): The identifier of the template transaction blob obtained from the create step.
* `signBlob` (string): The signed transaction blob generated from the create step, required to finalize template or credential submission on the Zetrix blockchain.
* `publicKey` (string): The public key corresponding to the private key used for signing. This should match one of the keys in the `signerList` from the template creation (usually the issuer’s Ed25519 public key).

**Response Body:** *(JSON)*

* `templateId` (string): A unique identifier assigned to the newly created template. This ID will be used to reference the template in subsequent operations (such as credential issuance).
* `txHash` (string): A hash or transaction ID associated with the template registration on-chain. This can be used for audit or verification purposes to confirm the template was recorded on Zetrix.

**Example Request:**

```json
{
    "blobId": "320AE2388C9F38DD62F1633AE2A8E2B6",
    "signerList": [
         {
            "signBlob": "F0EE813BDC5D033C5017DC2DDC2EB1937824708C3FD472AA7007BC045D92971536A9D33C890AE3301EFCDC705EAE4662A400C3F515A73E46FC44E810CE84F805",
            "publicKey": "b0010d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb43fad909"
        }
    ]   
}
```

**Example Response:**

```json
{
    "object": {
        "templateId": "did:zid:66a960f2e709b8baa1259fcd2901b6f9afa4e03d60556e93c04a4322b6606f5c",
        "txHash": "a6f284d27aba2dfebfd6d2e916fdc039b7d420b7eb2940dd19119e6993588993"
    },
    "messages": []
}

```

**Error Cases:**

* `400 Bad Request` – The provided blob or signature is missing or malformed (e.g., wrong length or format).
* `401 Unauthorized` – The signature does not match the issuer’s public key, or the caller is not permitted to submit this template.
* `404 Not Found` – The `blobId` does not correspond to a valid pending template (for example, if it was already submitted or expired).
* `500 Internal Server Error` – An error occurred while processing the transaction (for instance, failure to write to the blockchain).

## VC Issuance APIs

Once a template is in place, these APIs manage the issuance of verifiable credentials to holders. The typical flow is: a holder applies for a credential, the issuer creates the credential (generating required signatures and transaction blob), the issuer submits the credential to finalize issuance, and then the credential can be downloaded by the holder or issuer.

### Apply VC (by holder)

**(Non-encrypted) Endpoint:** POST `/cred/v1/vc/apply`

**(Encrypted) Endpoint:** POST `/cred/v1/vc/enc/apply`

\
**Description:** Initiates a credential issuance request by a holder. The holder (or an application acting on behalf of the holder) calls this to apply for a credential of a given template. This step usually provides the data required for the credential and registers a request that the issuer can review/approve. The output is a VC request ID used to track the issuance process.

**(Non-encrypted) Request Body:** *(JSON)*

* `templateId` (string): The identifier of the credential template the holder is applying for. This should be a valid `templateId` obtained from the issuer (for example, the ID returned by the template submission).
* `metadata` (array of objects): The data values for the credential’s attributes, as required by the template. Each entry should provide one attribute’s value:
  * `key` (string): The attribute key, exactly as defined in the template’s `credentialFormat`.
  * `value` (string): The value the holder provides for this attribute. The format/type of this value should conform to what the template specifies (e.g., string, date).\
    \&#xNAN;*For example, if the template requires `fullName` and `licenseNumber`, the holder must provide those values.*
* `signData:`
* `holderPublicKey` (string, optional): The holder’s public key (for example, an Ed25519 public key corresponding to the holder’s DID). This may be provided if the system requires associating a specific key with the request (e.g., to later verify the holder’s presentation or for auditing). In many cases, this can be omitted if the holder’s DID document will be used to fetch keys.

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted application data consist of signed data, metadata, public key, and X25519 public key. Refer to VC Encryption Process- Apply VC Process.

**Response Body:** *(JSON)*

* `vcId` (string): A unique identifier for the VC issuance request. This ID represents the pending credential application. It will be used by the issuer to create the credential and can be used by the holder to query status or download the final VC.
* `status` (string): The status of the request. Typically, a new application will be in a status such as `"Pending"` (or similar) indicating it is awaiting issuer action. The status may be updated to `"Approved"`, `"Issued"`, `"Rejected"`, etc., depending on the workflow (for this API reference, the initial status is pending issuance).

**(Non-encrypted) Example Request:**

```json
{
    "data": [
        {
            "templateId": "did:zid:7380129d526a274ee507a5f806e4b8d88c2b7f34040897bf03571df7d1c6c9f0",
            "metadata": {
                "name": "Ali bin Abu",
                "class": "B2",
                "age": "21",
                "gender": "Male"
            }
        },
        {
            "templateId": "did:zid:551aba03d76f420b0b041df212a365f4d97c9abc1955107bd46480cafaf07c90",
            "metadata": {
                "course": "Science Computer",
                "cgpa": "3.9"      
            }
        }
    ],
    "signData":"6A670EDD9887B774B48A6403BBFF04A88ADFB7BDB6A70E5FF49C0DB0E5FE32783C19FB1EC3511B848FEB6D3D78620FF5803A7D1425D850B9C04D44BCA7D57003",
    "publicKey": "b0012c8c214c958e0f28e8e3aac60a38abd161e3135efa33bb1c4233e0c6a4518a1780176809"
}


```

**(Encrypted) Example Request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `secretKey` | UJugVbU79RHI5gF6g3pMVw\_YnoZxdrFqA5hGm7PkBcoKsyTj-paiOBKcgRApDP2KmCfbGcBtvrnEjO0GhsIFoDGxueE8oK8rWNIFWN4Swdl4Yimdf45C5\_x30b6Z4t3za8osfYdSn0kgOAdRo3khMRjr3XNEiGDVl1CjcV2mHmaFRu\_6TsBc9ZB7w95UBhKWTl6U7zMRNnZni6envSFRdz3IMthp9UMWmU2MyWqCUXdaZzEkKOOskQMdgpsXdOdnSJgsEPB75VAwhwiiPcp1n4AFjrUqSkGJcggxoP54brdSjbk4MNFbNVlXBfEqAPMBMG639vYj27\_mDTB1RFhSQA== |

**Request Body:** *(JSON)*

<pre class="language-json"><code class="lang-json"><strong>aIg5AyAg33xNGs7JnqxZB39XPa8bR8Hcf2_S438xVH0A9kxUZADCt7eQl7ipMs5nm4EODsXaT_4S2I7BBS0qw-NVdqgj86XZls3PuZky7Ae84yG1ASZvHAB63ed6VBpKB_D3d3PnfRt1vIXpR2Oe_8yo9OrFiHqnV4h-LNWnnpTdV-2EHTfwnJzun1Fxq-79gzolreBcfYNfxjujNKe6Jr0hLS9gGxBZQgQ-y-GGeDeEoXjmTuCDeMnTiC77-nD31JGFyV5mC9uaLorCUX3FyQgFZn8Jr9anVgrrlb_Cjhj7YlnBforlojQgeGRddTfpcd_WMNhWsjifE-s8wFDnzxyWStq6tNXd_mSYL4r0Z8EWP_zFlIN-lynsMgZewDLTnjefDwhaoEmjZC_1FiUiHI_cU-dDzyjMQQHYZp0JNBU7IHcVFUHCv2MKrNSVvVSkK1YhgGtvQouGG6fKigqub2CGZnwKXUbPKiUdxeGd1vvzi1G7FSg8Pa98WgKU9gROMMMpmWxkS7UN2WALrcHCV1hOyOl32hI92d6DJq6Q0JXNo1Gzyzx1uckNxj9n8N7OAINqge_gbNateht1I_wwzIGofjR_Mr6NdvDZ8l41sgo9f9poiiiY3jT6ZQ76RapWCIYVqef65KeLKoGn9M0-_dr3UhKC
</strong></code></pre>

**Example Response:**

```json
{
    "object": {
        "vcId": "did:zid:6421ca70444138f3495d5f50ddd174dfedec06d668fb697070b0a849771d7768",
        "status": "APPLIED"
    },
    "messages": []
}

```

**Error Cases:**

* `400 Bad Request` – Missing required fields or invalid data format (e.g., a mandatory attribute value is not provided or has the wrong type).
* `404 Not Found` – The specified `templateId` does not exist or is not available for issuance.
* `401 Unauthorized` – If authentication is required, this error can occur if the holder is not properly authenticated or not allowed to apply for this credential.
* `409 Conflict` – A duplicate request already exists (for example, the holder already applied for this credential and it’s still pending).
* `500 Internal Server Error` – An unexpected server error occurred while recording the application (database error, etc.).

### Create VC (by issuer)

**(Non-encrypted)Endpoint:** POST `/cred/v1/vc/create`

**(Encrypted) Endpoint:** POST /cred/v1/vc/enc/create

\
**Description:** Used by the issuer to create (prepare) a verifiable credential in response to a holder’s application. This call will assemble the credential data from the template and the holder’s provided information, and produce the necessary cryptographic elements for the credential. Specifically, it generates the credential’s BBS+ signature (which the issuer must produce) and a blockchain transaction blob for recording the credential status on-chain. The issuer should call this after approving or deciding to issue the credential for a given `vcId`. The credential is not yet final until the **Submit VC** step is completed.

**(Non-encrypted) Request Body:** *(JSON)*

* `vcId` (string): The identifier of the VC request (from the **Apply VC** step) that the issuer is fulfilling. This links the create operation to the holder’s application and the associated template.
* `issuanceData`(string)`:`The credential content or claims to be issued based on the selected template.
* `expiredDate`(string)`:`The credential content or claims to be issued based on the selected template.
* `templateId`(string)`:`The unique identifier of the credential template used for issuance.
* `metadata`(string)Additional information or attributes that provide context to the credential issuance.

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted issuance data {`vcId, issuanceData, expiredDate, templateId, metadata}` . Refer to VC Encryption Process- Apply VC Process.

**Response Body:** *(JSON)*

* `ed25519Blob` (string): A cryptographic blob generated using the Ed25519 private key that contains the signed transaction or credential data, enabling verification of authenticity and integrity on the blockchain.
* bbsBlsBase64 (string): The BBS+ signature in base64/hex format for the credential (same as provided in the request, or regenerated). This is included in the response for reference, confirming the signature that will be embedded in the credential. The issuer should retain this value as it forms part of the credential's proof.

**(Non-encrypted) Example Request:**

```json
{
    "vcId": "did:zid:6421ca70444138f3495d5f50ddd174dfedec06d668fb697070b0a849771d7768",
    "issuanceDate": "2025-01-01",
    "expirationDate": "2026-01-01",
    "data": [
        {
            "templateId": "did:zid:7380129d526a274ee507a5f806e4b8d88c2b7f34040897bf03571df7d1c6c9f0",
            "metadata": {
                "idNo": "abc12345"
            }
        },
        {
            "templateId": "did:zid:551aba03d76f420b0b041df212a365f4d97c9abc1955107bd46480cafaf07c90",
            "metadata": {
                "id": "gg1233222"    
            }
        }
    ]
}


```

**(Encrypted) Example Request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `secretKey` | UJugVbU79RHI5gF6g3pMVw\_YnoZxdrFqA5hGm7PkBcoKsyTj-paiOBKcgRApDP2KmCfbGcBtvrnEjO0GhsIFoDGxueE8oK8rWNIFWN4Swdl4Yimdf45C5\_x30b6Z4t3za8osfYdSn0kgOAdRo3khMRjr3XNEiGDVl1CjcV2mHmaFRu\_6TsBc9ZB7w95UBhKWTl6U7zMRNnZni6envSFRdz3IMthp9UMWmU2MyWqCUXdaZzEkKOOskQMdgpsXdOdnSJgsEPB75VAwhwiiPcp1n4AFjrUqSkGJcggxoP54brdSjbk4MNFbNVlXBfEqAPMBMG639vYj27\_mDTB1RFhSQA== |

**Request Body:** *(JSON)*

```json
CImvIwjmub7nGUMAiKCM-dCB9-c3CMdI-zwjBD-ZO1gzNczenc5ni7tJmJzOIoaMWeKi0KhcHfoFCcJED75-lXMd3--gA1Z5Kq-b-tIN5VZk1v9JheJVFz5e2w8-0D2vfeFyrV-dGjHpBFIlT3cGpBxoW-fhHKXVa6YBXP6uuAt49LsnYKG3O0ng9dr88KuQBFr2oezCIoz82Q8p3B7-a4nJg0_j_m4c4Yz6zM0LFQRYZqG6kcsewm0X9NgupywP_tPowPnfwDYLwJU1SW7ktNshv3UtkZR_QRpVpBg8GHLC4cTBr2SvHn8ZSs_gZCdv2NMNJVv2feyFtAtKqIaXHR7AthYZ0dzyQPevd4ZMmXA59I0=
```

**Example Response:**

```json
{
    "object": {
        "ed25519Blob": "65794a68624763694f694a465a45525451534a392e65794a4159323975644756346443493657794a6f64485277637a6f764c336433647935334d793576636d63764d6a41784f43396a636d566b5a57353061574673637939324d534973496d68306448427a4f693876647a4e705a433576636d63766332566a64584a7064486b76596d4a7a4c335978496977696148523063484d364c7939305a584e304c5735765a475575656d5630636d6c344c6d4e766253396e5a58524259324e766457353054575630595552686447455f5957526b636d567a637a31615646677a556b6449546d316b65454649537a56484d6e5a76527a64726232397a6332464465453569626c7069644868324a6d746c655431305a573177624746305a5639665a476c6b4f6e70705a446f334d7a67774d5449355a4455794e6d45794e7a526c5a5455774e3245315a6a67774e6d5530596a686b4f44686a4d6d49335a6a4d304d4451774f446b33596d59774d7a55334d57526d4e325178597a5a6a4f575977496977696148523063484d364c7939305a584e304c5735765a475575656d5630636d6c344c6d4e766253396e5a58524259324e766457353054575630595552686447455f5957526b636d567a637a31615646677a556b6449546d316b65454649537a56484d6e5a76527a64726232397a6332464465453569626c7069644868324a6d746c655431305a573177624746305a5639665a476c6b4f6e70705a446f314e544668596d45774d3251334e6d59304d6a42694d4749774e44466b5a6a49784d6d457a4e6a566d4e4751354e324d3559574a6a4d546b314e5445774e324a6b4e4459304f44426a59575a685a6a4133597a6b77496c3073496d4e795a57526c626e52705957785464574a715a574e30496a7037496d526c5a334a6c5a554e6c636e52705a6d6c6a5958526c496a7037496d4e6e634745694f69497a4c6a6b694c434a6a62335679633255694f694a5459326c6c626d4e6c49454e76625842316447567949697769615751694f694a6e5a7a45794d7a4d794d6a4969665377695a484a70646d6c755a30787059325675633255694f6e73695957646c496a6f694d6a45694c434a6a6247467a63794936496b4979496977695a3256755a475679496a6f69545746735a534973496d6c6b546d38694f694a68596d4d784d6a4d304e534973496d3568625755694f694a4262476b67596d6c754945466964534a394c434a705a434936496d52705a447036615751364d6d4d34597a49784e474d354e54686c4d4759794f4755345a544e6859574d324d47457a4f4746695a4445324d57557a4d544d315a575a684d7a4e69596a466a4e44497a4d325577597a5a684e4455784f4745784e794a394c434a6c65484270636d463061573975524746305a534936496a49774d6a59744d4445744d4446554d4441364d4441364d44426149697769615751694f694a6b61575136656d6c6b4f6a59304d6a466a595463774e4451304d544d345a6a4d304f54566b4e5759314d47526b5a4445334e47526d5a57526c597a41325a4459324f475a694e6a6b334d446377596a42684f4451354e7a63785a4463334e6a67694c434a7063334e315957356a5a555268644755694f6949794d4449314c5441784c544178564441774f6a41774f6a417757694973496d6c7a6333566c63694936496d52705a447036615751364d4751304f446b784e6d5534596a426d4d5441794f5464694d44497a596a59344d475a694e3246694d6a4d324e3251315a5749774d32457859545a69596a67334e6d51324d32517859546c6d4e5459334e32526a59694973496e5235634755694f6c7369566d567961575a7059574a735a554e795a57526c626e5270595777694c434a45636d6c326157356e54476c6a5a57357a5a534973496b526c5a334a6c5a554e6c636e52705a6d6c6a5958526c496c3139",
        "bbsBlsBase64": [
            "aWQ6IGRpZDp6aWQ6MmM4YzIxNGM5NThlMGYyOGU4ZTNhYWM2MGEzOGFiZDE2MWUzMTM1ZWZhMzNiYjFjNDIzM2UwYzZhNDUxOGExNw==",
            "ZHJpdmluZ0xpY2Vuc2UubmFtZTogQWxpIGJpbiBBYnU=",
            "ZHJpdmluZ0xpY2Vuc2UuY2xhc3M6IEIy",
            "ZHJpdmluZ0xpY2Vuc2UuYWdlOiAyMQ==",
            "ZHJpdmluZ0xpY2Vuc2UuZ2VuZGVyOiBNYWxl",
            "ZHJpdmluZ0xpY2Vuc2UuaWRObzogYWJjMTIzNDU=",
            "ZGVncmVlQ2VydGlmaWNhdGUuY291cnNlOiBTY2llbmNlIENvbXB1dGVy",
            "ZGVncmVlQ2VydGlmaWNhdGUuY2dwYTogMy45",
            "ZGVncmVlQ2VydGlmaWNhdGUuaWQ6IGdnMTIzMzIyMg=="
        ]
    },
    "messages": []
}

```

**Error Cases:**

* `400 Bad Request` – The request is missing required data or has invalid format (for instance, no BBS+ signature provided, or the signature is the wrong format).
* `404 Not Found` – The `vcId` does not correspond to a valid pending application (e.g., if it was already processed or never existed).
* `403 Forbidden` – The issuer’s DID does not match the template’s issuer or the issuer is not authorized to issue this credential.
* `409 Conflict` – The credential might have already been created or is in a state that cannot be created again (to avoid duplicate issuance).
* `500 Internal Server Error` – A server error occurred while assembling the credential (e.g., issues in retrieving template or holder data, or internal cryptographic failure).

### Submit VC (by issuer)

**(Non-encrypted)Endpoint:** POST `/cred/v1/vc/submit`

**(Encrypted) Endpoint:** POST `/cred/v1/vc/enc/submit`

\
**Description:** Finalizes the issuance of the verifiable credential. The issuer calls this after signing the transaction blob obtained from **Create VC**. This will submit the issuance transaction to the Zetrix blockchain (recording the credential’s existence and status) and finalize the credential object. On success, the credential is officially issued and can be delivered to the holder. The response includes the complete VC in a verifiable format.

**(Non-encrypted) Request Body:** *(JSON)*

* `vcId` (string): Unique identifier of the issued Verifiable Credential.
* `ed25519PubKey`(string): The issuer’s ED25519 public key used for verifying the credential signature.
* `ed25519SignData` (string): Signature of the credential data generated with the issuer’s ED25519 private key.
* `bbsBlsPubKey` (string): The issuer’s BBS+ public key used for verifying selective disclosure proofs.
* `bbsBlsSignData` (string): Signature of the credential data generated with the issuer’s BBS+ private key.
* `keyExpiry` (string): Expiry timestamp of the signing key pair to ensure key validity and rotation.

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted VC data {`vcId, ed25519PubKey, ed25519SignData, bbsBlsPubKey , bbsBlsSignData, keyExpiry }` . Refer to VC Encryption Process- Issue and Download VC Process.

**Response Body:** *(JSON)*

* `vcObject` (object): The issued Verifiable Credential, in its full JSON representation. This will typically include standard VC fields such as `@context`, `id` (which may incorporate the `vcId`), `type`, `issuer`, `credentialSubject` (containing the holder’s DID and the attributes with values), and `proof`. The `proof` section will include the BBS+ signature (often encoded as a proof value) and related metadata (like the public key or verification method, and type of proof). It may also include a `credentialStatus` entry indicating where the credential’s status (e.g., revocation status) is recorded (for example, referencing a blockchain registry or contract).
* `downloadExpiryDate` (string): A timestamp indicating how long the issued credential will be available for download via the **Download VC** endpoint. The credential might be stored temporarily on the server; this field informs the issuer/holder of the cutoff time to fetch it. After this expiry, the credential might be purged for security, requiring the issuer to re-share if needed.

**(Non-encrypted) Example Request:**

```json
{
    "vcId": "did:zid:6421ca70444138f3495d5f50ddd174dfedec06d668fb697070b0a849771d7768",
    "ed25519PubKey": "b0010d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb43fad909",
    "ed25519SignData": "D75ED9C72E8D95BEDED02058143267C41DD9943BE1235C3201D59BB73BE8BAB4A28424F057C220C6E650D36DB45EDB2DC58AA34E30672AB454A3A4E075B88E03",
    "bbsBlsPubKey": "zmGHfsGYtRbh6MfDQegV976maR1FwAJxFnboew8wydSVd2YwprnhXQvBDUYnQ13PCeifouGzeecE3dko8F6KTEGkZtuDFLBYfAJHSCzpk9ukfXWqX9ykpz326RSWPxjeagQp",
    "bbsBlsSignData": "ukFiZpQ2quVC4mTgEuzyF8lVqOExC5HGBWnCHcxCuR7jPuZOhnWT9Lrg4w9YVqcM1QlHj0EpPUsTGYCnZA1-_pPAZYyLHjrPGZEv5rJADJRUkj6ocu7HgDxf5tnwvzFVyFABEjt0Ac4E9mBfHIrcLPA",
    "keyExpiry": 2592000
}


```

**(Encrypted) Example Request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `secretKey` | UJugVbU79RHI5gF6g3pMVw\_YnoZxdrFqA5hGm7PkBcoKsyTj-paiOBKcgRApDP2KmCfbGcBtvrnEjO0GhsIFoDGxueE8oK8rWNIFWN4Swdl4Yimdf45C5\_x30b6Z4t3za8osfYdSn0kgOAdRo3khMRjr3XNEiGDVl1CjcV2mHmaFRu\_6TsBc9ZB7w95UBhKWTl6U7zMRNnZni6envSFRdz3IMthp9UMWmU2MyWqCUXdaZzEkKOOskQMdgpsXdOdnSJgsEPB75VAwhwiiPcp1n4AFjrUqSkGJcggxoP54brdSjbk4MNFbNVlXBfEqAPMBMG639vYj27\_mDTB1RFhSQA== |

**Request Body:** *(JSON)*

```json
cKyWw4_ixz0lPtchJr1VeWEpoWL2Jvf_hRbmJTMYa4cKMLhKv7-bNe-PFcNXkgwGacsBzH47JFANYdltLdK32f-BEnG4D_gu0o9aimUobXYKHVGCNseHEnKV5YCBwHBhiCXPSg3wDnzTQctYIui8Wu75ec8ODh3uiyYPFi8dMLboRVPMddRGun7vmWIa246PgjX9Yn7OyjXotGXx5bDfZ05c6NUh7PS7-K5gPUB2BSQ_tfc6ps81mYkW58inpgqlBz3WPzqsM86CCTTGAyZLsyUIjtyCy3Es5raaLir25N6_OZ7tTqGjqkKnYXpfhnwGhn2d9VtMAd5PFmDNFO4oJQUQtkK0YNLXOs1cga9rkHD7sJd7buXuy7g4bc4AhMj2ciI5tKSWCByWMfoBbzsTRw3T75kGtZO04yZFTZbvexHos_8dv_KCosKck6UvfpcBexJZjbOTFgI-auy1CB1mKcghKwagwIkuxjAli6P-jX89n-uGf8gwWl6KGtFRhIphX9j_eGSWjcYZGjCfJImfy6uCRVovyZJ2OW_DXLufGatKE6F7OguWWJtS3r821Kdnv3n5uegtnI2W7OkEApYUmC3Jh13Xa98YZzZcMrCo2bHwjNBG4DwsIAo4RGOuRyaezC9Ikki-PLhVTFn59qnYECipb9CSlG1oaNDJfy18u017d6kjAw9mFN3Qr8J3kiG4xxUIypdw4aCZ3chPpxIieH15VONRFsKSQ4zgdmWODgYRxRJmA8DjcjjodDRMyyqofdKm_W_j_76HajLDdSVGc5g5S8645N73XYduPT48F-hRX_HlApZE8woNxtjBtNZslsahf-aLoM6kYqsI16X2bG04YPQOdLxrJhr-R5DvAmjUNc7EgIVg4sSGGv5uCSCosMEzZvIg9maDPNVw5MKzZsuf0AJuTQTz
```

**Example Response (partial):**

```json
{
    "object": {
        "vc": {
            "id": "did:zid:6421ca70444138f3495d5f50ddd174dfedec06d668fb697070b0a849771d7768",
            "type": [
                "VerifiableCredential",
                "DrivingLicense",
                "DegreeCertificate"
            ],
            "issuer": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb",
            "issuanceDate": "2025-01-01T00:00:00Z",
            "expirationDate": "2026-01-01T00:00:00Z",
            "credentialSubject": {
                "id": "did:zid:2c8c214c958e0f28e8e3aac60a38abd161e3135efa33bb1c4233e0c6a4518a17",
                "drivingLicense": {
                    "name": "Ali bin Abu",
                    "class": "B2",
                    "age": "21",
                    "gender": "Male",
                    "idNo": "abc12345"
                },
                "degreeCertificate": {
                    "course": "Science Computer",
                    "cgpa": "3.9",
                    "id": "gg1233222"
                }
            },
            "proof": [
                {
                    "type": "BbsBlsSignature2020",
                    "created": "2025-03-07T07:06:44.747608Z",
                    "proofPurpose": "assertionMethod",
                    "proofValue": "ukFiZpQ2quVC4mTgEuzyF8lVqOExC5HGBWnCHcxCuR7jPuZOhnWT9Lrg4w9YVqcM1QlHj0EpPUsTGYCnZA1-_pPAZYyLHjrPGZEv5rJADJRUkj6ocu7HgDxf5tnwvzFVyFABEjt0Ac4E9mBfHIrcLPA",
                    "verificationMethod": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb#delegate-1"
                },
                {
                    "type": "Ed25519Signature2020",
                    "created": "2025-03-07T07:06:44.750767Z",
                    "proofPurpose": "assertionMethod",
                    "verificationMethod": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb#controllerKey",
                    "jws": "eyJhbGciOiJFZERTQSJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSIsImh0dHBzOi8vdzNpZC5vcmcvc2VjdXJpdHkvYmJzL3YxIiwiaHR0cHM6Ly90ZXN0LW5vZGUuemV0cml4LmNvbS9nZXRBY2NvdW50TWV0YURhdGE_YWRkcmVzcz1aVFgzUkdITm1keEFISzVHMnZvRzdrb29zc2FDeE5iblpidHh2JmtleT10ZW1wbGF0ZV9fZGlkOnppZDo3MzgwMTI5ZDUyNmEyNzRlZTUwN2E1ZjgwNmU0YjhkODhjMmI3ZjM0MDQwODk3YmYwMzU3MWRmN2QxYzZjOWYwIiwiaHR0cHM6Ly90ZXN0LW5vZGUuemV0cml4LmNvbS9nZXRBY2NvdW50TWV0YURhdGE_YWRkcmVzcz1aVFgzUkdITm1keEFISzVHMnZvRzdrb29zc2FDeE5iblpidHh2JmtleT10ZW1wbGF0ZV9fZGlkOnppZDo1NTFhYmEwM2Q3NmY0MjBiMGIwNDFkZjIxMmEzNjVmNGQ5N2M5YWJjMTk1NTEwN2JkNDY0ODBjYWZhZjA3YzkwIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImRlZ3JlZUNlcnRpZmljYXRlIjp7ImNncGEiOiIzLjkiLCJjb3Vyc2UiOiJTY2llbmNlIENvbXB1dGVyIiwiaWQiOiJnZzEyMzMyMjIifSwiZHJpdmluZ0xpY2Vuc2UiOnsiYWdlIjoiMjEiLCJjbGFzcyI6IkIyIiwiZ2VuZGVyIjoiTWFsZSIsImlkTm8iOiJhYmMxMjM0NSIsIm5hbWUiOiJBbGkgYmluIEFidSJ9LCJpZCI6ImRpZDp6aWQ6MmM4YzIxNGM5NThlMGYyOGU4ZTNhYWM2MGEzOGFiZDE2MWUzMTM1ZWZhMzNiYjFjNDIzM2UwYzZhNDUxOGExNyJ9LCJleHBpcmF0aW9uRGF0ZSI6IjIwMjYtMDEtMDFUMDA6MDA6MDBaIiwiaWQiOiJkaWQ6emlkOjY0MjFjYTcwNDQ0MTM4ZjM0OTVkNWY1MGRkZDE3NGRmZWRlYzA2ZDY2OGZiNjk3MDcwYjBhODQ5NzcxZDc3NjgiLCJpc3N1YW5jZURhdGUiOiIyMDI1LTAxLTAxVDAwOjAwOjAwWiIsImlzc3VlciI6ImRpZDp6aWQ6MGQ0ODkxNmU4YjBmMTAyOTdiMDIzYjY4MGZiN2FiMjM2N2Q1ZWIwM2ExYTZiYjg3NmQ2M2QxYTlmNTY3N2RjYiIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJEcml2aW5nTGljZW5zZSIsIkRlZ3JlZUNlcnRpZmljYXRlIl19.RDc1RUQ5QzcyRThEOTVCRURFRDAyMDU4MTQzMjY3QzQxREQ5OTQzQkUxMjM1QzMyMDFENTlCQjczQkU4QkFCNEEyODQyNEYwNTdDMjIwQzZFNjUwRDM2REI0NUVEQjJEQzU4QUEzNEUzMDY3MkFCNDU0QTNBNEUwNzVCODhFMDM"
                }
            ],
            "@context": [
                "https://www.w3.org/2018/credentials/v1",
                "https://w3id.org/security/bbs/v1",
                "https://test-node.zetrix.com/getAccountMetaData?address=ZTX3RGHNmdxAHK5G2voG7koossaCxNbnZbtxv&key=template__did:zid:7380129d526a274ee507a5f806e4b8d88c2b7f34040897bf03571df7d1c6c9f0",
                "https://test-node.zetrix.com/getAccountMetaData?address=ZTX3RGHNmdxAHK5G2voG7koossaCxNbnZbtxv&key=template__did:zid:551aba03d76f420b0b041df212a365f4d97c9abc1955107bd46480cafaf07c90"
            ]
        },
        "downloadExpiryDate": 1743923204755
    },
    "messages": []
}


```

**Error Cases:**

* `400 Bad Request` – The signature is missing or invalid, or the blobId is not provided.
* `401 Unauthorized` – The signature does not match the issuer’s known public key (verification failed), or the issuer is not authorized to submit this credential.
* `404 Not Found` – The blobId is not recognized (e.g., if the create step was not done or the blob has expired), or the corresponding VC request was not found.
* `409 Conflict` – The credential has already been submitted/issued (duplicate submission) or was revoked by the time of submission (unlikely scenario).
* `500 Internal Server Error` – A server or blockchain error occurred during submission (e.g., failure writing to blockchain or assembling the final VC object).

### Download VC (by issuer or holder)

**(Non-encrypted)Endpoint:** POST `/cred/v1/vc/download`

**(Encrypted) Endpoint:** POST `/cred/v1/vc/enc/download`\
**Description:** Retrieves a previously issued verifiable credential. This endpoint can be used by the holder (to download the credential that was issued to them) or by the issuer (to retrieve the credential, for example to send it through another channel). Typically, this would be called after the **Submit VC** step, using the provided `vcId`. The credential must still be available (not expired from temporary storage) for this call to succeed. The response is the VC in JSON format.

**(Non-encrypted) Request:**

* `vcId` (string): Unique identifier of the issued Verifiable Credential.
* `signVcId:`The signed identifier of the Verifiable Credential, ensuring authenticity and integrity.
* `isIssuer:`Indicates whether the entity performing the action is the credential issuer (`true`) or not (`false`).

**Response Body:** *(JSON)*\
The full Verifiable Credential object in JSON, identical to the `vcObject` returned in the Submit VC step. This includes all fields of the credential (`context, id, type, issuer, credentialSubject, credentialStatus if any, and proof with BBS+ signature`). This allows the holder to store or view their credential, and the issuer to archive it if needed.

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted VC data {`vcId, signVcId, isIssuer}` . Refer to VC Encryption Process- Issue and Download VC Process.

**(Non-encrypted) Example Request:**

```json
{
    "vcId": "did:zid:9d449e8fa06cd970b6a17c6dbf9b56211184f90bd9730d2f4728faddea7f03d8",
    "signVcId": "F40D10AD190481B4AD82D4E39222C7B432000DCC334794204E0CD45F76DA54137E20AD18C7D80D925D2C26B3B79DDCEB6D86A2152258974C463E1C689428120C",
    "isIssuer": false
}
```

**(Encrypted) Example Request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `secretKey` | UJugVbU79RHI5gF6g3pMVw\_YnoZxdrFqA5hGm7PkBcoKsyTj-paiOBKcgRApDP2KmCfbGcBtvrnEjO0GhsIFoDGxueE8oK8rWNIFWN4Swdl4Yimdf45C5\_x30b6Z4t3za8osfYdSn0kgOAdRo3khMRjr3XNEiGDVl1CjcV2mHmaFRu\_6TsBc9ZB7w95UBhKWTl6U7zMRNnZni6envSFRdz3IMthp9UMWmU2MyWqCUXdaZzEkKOOskQMdgpsXdOdnSJgsEPB75VAwhwiiPcp1n4AFjrUqSkGJcggxoP54brdSjbk4MNFbNVlXBfEqAPMBMG639vYj27\_mDTB1RFhSQA== |

**Request Body:** *(JSON)*

```postman_json
sHaMF3ysLD7E9KZqW3AiEe05p9k_zAn8QiEM822w9ghiazIf22brMEkNY8FyLT2JrCJK-Bn7S8DAxtokezyyV1D2c40_xt48DFoqIJZrcWzRqYJjH6XShNA4S11quqkZQB2mnVmASsKKfe04oyqY_0yeWU7hmkD-GftXFuYeKtz76AZqLsY3Cgsh3xL7aXNHwYF7qMSt1rJ4w2FfS6_VcDswFLpj5E5LEyZqP5NXAWo5EilOsiLeDlg-lHZTNT3SX1damQwTpjxh83J2SShGDE2JdzG3UiAZswYgdjsMGkyxzuKOcRfrLZfhbfasZlM4M81qgLb7M9T9KfYzWgg7bVLSHzkYmA-IzJvdoyvq
```

**Example Response (full VC):**

```json
{
    "object": {
        "id": "did:zid:6421ca70444138f3495d5f50ddd174dfedec06d668fb697070b0a849771d7768",
        "type": [
            "VerifiableCredential",
            "DrivingLicense",
            "DegreeCertificate"
        ],
        "issuer": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb",
        "issuanceDate": "2025-01-01T00:00:00Z",
        "expirationDate": "2026-01-01T00:00:00Z",
        "credentialSubject": {
            "id": "did:zid:2c8c214c958e0f28e8e3aac60a38abd161e3135efa33bb1c4233e0c6a4518a17",
            "drivingLicense": {
                "name": "Ali bin Abu",
                "class": "B2",
                "age": "21",
                "gender": "Male",
                "idNo": "abc12345"
            },
            "degreeCertificate": {
                "course": "Science Computer",
                "cgpa": "3.9",
                "id": "gg1233222"
            }
        },
        "proof": [
            {
                "type": "BbsBlsSignature2020",
                "created": "2025-03-07T07:06:44.747608Z",
                "proofPurpose": "assertionMethod",
                "proofValue": "ukFiZpQ2quVC4mTgEuzyF8lVqOExC5HGBWnCHcxCuR7jPuZOhnWT9Lrg4w9YVqcM1QlHj0EpPUsTGYCnZA1-_pPAZYyLHjrPGZEv5rJADJRUkj6ocu7HgDxf5tnwvzFVyFABEjt0Ac4E9mBfHIrcLPA",
                "verificationMethod": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb#delegate-1"
            },
            {
                "type": "Ed25519Signature2020",
                "created": "2025-03-07T07:06:44.750767Z",
                "proofPurpose": "assertionMethod",
                "verificationMethod": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb#controllerKey",
                "jws": "eyJhbGciOiJFZERTQSJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSIsImh0dHBzOi8vdzNpZC5vcmcvc2VjdXJpdHkvYmJzL3YxIiwiaHR0cHM6Ly90ZXN0LW5vZGUuemV0cml4LmNvbS9nZXRBY2NvdW50TWV0YURhdGE_YWRkcmVzcz1aVFgzUkdITm1keEFISzVHMnZvRzdrb29zc2FDeE5iblpidHh2JmtleT10ZW1wbGF0ZV9fZGlkOnppZDo3MzgwMTI5ZDUyNmEyNzRlZTUwN2E1ZjgwNmU0YjhkODhjMmI3ZjM0MDQwODk3YmYwMzU3MWRmN2QxYzZjOWYwIiwiaHR0cHM6Ly90ZXN0LW5vZGUuemV0cml4LmNvbS9nZXRBY2NvdW50TWV0YURhdGE_YWRkcmVzcz1aVFgzUkdITm1keEFISzVHMnZvRzdrb29zc2FDeE5iblpidHh2JmtleT10ZW1wbGF0ZV9fZGlkOnppZDo1NTFhYmEwM2Q3NmY0MjBiMGIwNDFkZjIxMmEzNjVmNGQ5N2M5YWJjMTk1NTEwN2JkNDY0ODBjYWZhZjA3YzkwIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImRlZ3JlZUNlcnRpZmljYXRlIjp7ImNncGEiOiIzLjkiLCJjb3Vyc2UiOiJTY2llbmNlIENvbXB1dGVyIiwiaWQiOiJnZzEyMzMyMjIifSwiZHJpdmluZ0xpY2Vuc2UiOnsiYWdlIjoiMjEiLCJjbGFzcyI6IkIyIiwiZ2VuZGVyIjoiTWFsZSIsImlkTm8iOiJhYmMxMjM0NSIsIm5hbWUiOiJBbGkgYmluIEFidSJ9LCJpZCI6ImRpZDp6aWQ6MmM4YzIxNGM5NThlMGYyOGU4ZTNhYWM2MGEzOGFiZDE2MWUzMTM1ZWZhMzNiYjFjNDIzM2UwYzZhNDUxOGExNyJ9LCJleHBpcmF0aW9uRGF0ZSI6IjIwMjYtMDEtMDFUMDA6MDA6MDBaIiwiaWQiOiJkaWQ6emlkOjY0MjFjYTcwNDQ0MTM4ZjM0OTVkNWY1MGRkZDE3NGRmZWRlYzA2ZDY2OGZiNjk3MDcwYjBhODQ5NzcxZDc3NjgiLCJpc3N1YW5jZURhdGUiOiIyMDI1LTAxLTAxVDAwOjAwOjAwWiIsImlzc3VlciI6ImRpZDp6aWQ6MGQ0ODkxNmU4YjBmMTAyOTdiMDIzYjY4MGZiN2FiMjM2N2Q1ZWIwM2ExYTZiYjg3NmQ2M2QxYTlmNTY3N2RjYiIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJEcml2aW5nTGljZW5zZSIsIkRlZ3JlZUNlcnRpZmljYXRlIl19.RDc1RUQ5QzcyRThEOTVCRURFRDAyMDU4MTQzMjY3QzQxREQ5OTQzQkUxMjM1QzMyMDFENTlCQjczQkU4QkFCNEEyODQyNEYwNTdDMjIwQzZFNjUwRDM2REI0NUVEQjJEQzU4QUEzNEUzMDY3MkFCNDU0QTNBNEUwNzVCODhFMDM"
            }
        ],
        "@context": [
            "https://www.w3.org/2018/credentials/v1",
            "https://w3id.org/security/bbs/v1",
            "https://test-node.zetrix.com/getAccountMetaData?address=ZTX3RGHNmdxAHK5G2voG7koossaCxNbnZbtxv&key=template__did:zid:7380129d526a274ee507a5f806e4b8d88c2b7f34040897bf03571df7d1c6c9f0",
            "https://test-node.zetrix.com/getAccountMetaData?address=ZTX3RGHNmdxAHK5G2voG7koossaCxNbnZbtxv&key=template__did:zid:551aba03d76f420b0b041df212a365f4d97c9abc1955107bd46480cafaf07c90"
        ]
    },
    "messages": []
}

```

**Error Cases:**

* `400 Bad Request` – If `vcId` is missing or in an invalid format in the request.
* `401 Unauthorized` – The requester is not authorized to download this credential (for example, the `vcId` does not belong to the holder making the request, or no valid auth token provided).
* `404 Not Found` – No credential found for the given `vcId`, or it’s no longer available for download (e.g., if the download window expired or the credential never existed).
* `410 Gone` – The credential was available only temporarily and the period has lapsed (the `vcId` was valid but the stored credential has been removed).
* `500 Internal Server Error` – An unexpected error on the server while retrieving the credential.

## VC Revocation APIs

These APIs allow an issuer to revoke an issued credential, invalidating it so it will no longer be considered valid by verifiers. Revocation is typically a two-step process (create a revocation transaction blob, then submit it after signing) similar to template creation and credential issuance.

### Create Revoke VC Blob

**Endpoint:** POST `/cred/v1/vc/revoke/create-blob`\
**Description:** Initiates the revocation of a verifiable credential. The issuer calls this to build a revocation transaction for a given credential, which returns a blob to be signed. Revoking a credential typically updates its status on-chain (for example, updating a revocation registry or marking the credential as revoked in a smart contract). This step does not yet revoke the credential; it only prepares the transaction.

**Request Body:** *(JSON)*

* `vcId` (string): The identifier of the credential to be revoked. This is the same ID used during issuance (and present in the credential’s `id` field). The system will use this to locate the credential record or status entry on-chain.
* `remark` (string, optional): A human-readable reason for revocation. This reason might be recorded in logs or off-chain storage for audit purposes (e.g., “Credential revoked due to expiration” or “Holder requested revocation”). It is not typically part of the on-chain transaction (which usually just flips a status), but may be stored in an off-chain database.
* `issuerAddress`(string): The blockchain address of the credential issuer, used to identify and verify the source of credential issuance.

**Response Body:** *(JSON)*

* `blobId` (string): The identifier for the revocation transaction blob.
* `blob` (string): The revocation transaction blob (hex/base64 string) that needs to be signed by the issuer’s private key. This blob encodes the action of revoking the credential identified by `vcId`.

**Example Request:**

```json
{
    "vcId": "did:zid:f88afee30394b52c054e676baba135ace09015770747196a212e857bff1629ff",
    "remark": "test revoke",
    "issuerAddress": "ZTX3LU2NyoRPmgZqMHwiwupr6us5Lv9by3pUo"
}
```

**Example Response:**

```json
{
    "object": {
        "blobId": "94FD5A0F5F312A0E420EC1FB412FBE5A",
        "blob": "0A255A5458334C55324E796F52506D675A714D48776977757072367573354C763962793370556F104622DD01080712255A5458334C55324E796F52506D675A714D48776977757072367573354C763962793370556F62B1010A255A5458334D6D6F7671313535677A7244364D6564693662433570474B4169355933514D77781A87017B226D6574686F64223A227265766F6B65222C22706172616D73223A7B2272656D61726B223A2274657374207265766F6B65222C2276634964223A226469643A7A69643A66383861666565333033393462353263303534653637366261626131333561636530393031353737303734373139366132313265383537626666313632396666227D7D30B68901380A"
    },
    "messages": []
}
```

**Error Cases:**

* `400 Bad Request` – Missing `vcId`, or the request is malformed.
* `404 Not Found` – The specified `vcId` does not correspond to an issued credential (perhaps it was never issued or already revoked).
* `403 Forbidden` – The caller is not the issuer of that credential or not authorized to revoke it. Only the original issuer (or an authorized delegate) should revoke a credential.
* `409 Conflict` – The credential is already revoked or a revocation is already in progress for this credential.
* `500 Internal Server Error` – Server error while generating the revocation blob (e.g., inability to fetch credential status from chain).

### Submit Revoke VC

**Endpoint:** POST `/cred/v1/vc/revoke/submit`\
**Description:** Finalizes the credential revocation by submitting the signed revocation transaction to the blockchain. After this call succeeds, the credential identified by the given `vcId` is considered revoked. Verifiers checking the credential’s status will see it as revoked (invalid). This endpoint should be called after the issuer signs the blob from the create step.

**Request Body:** *(JSON)*

* `blobId` (string): The identifier of the revocation transaction blob (obtained from the create step).
* `signBlob` (string): A signed cryptographic blob used to authorize and finalize blockchain transactions for credential or template operations.
* `publicKey` (string): The Ed25519 public key of the issuer corresponding to the signature, to verify the signature. This should match the issuer’s DID and the key that was used in issuance.

**Response Body:** *(JSON)*

* `vcId` (string): The identifier of the credential that was revoked (echoing the input for clarity).
* `status` (string): The new status of the credential. Typically, this will be `"Revoked"` to indicate the credential is now revoked. In some implementations, this might also include a transaction hash or confirmation of revocation. For example, the response could include a blockchain transaction ID for the revocation or a timestamp of revocation, but at minimum the status is updated.

**Example Request:**

```json
{
    "blobId": "DE629ACA66639EE4E37A5A2B93A37BF7",
    "signerList": [
        {
            "signBlob": "47569120F80E52225B64F39E32A0C4872A1A512DBE171393FC3737370A09F9D8C7AFB065BDF29239F3F58845AD1607149A6288F6E17F3B800548C0B2F6E3E604",
            "publicKey": "b0010d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb43fad909"
        }
    ]
}
```

**Example Response:**

```json
{
    "object": {
        "txHash": "32c7f76868e62c15a59d9cafd217005ce0674ea177b56bb2d3c5f38599058041"
    },
    "messages": []
}

```

**Error Cases:**

* `400 Bad Request` – The signature is missing or invalid, or the blobId is not provided.
* `401 Unauthorized` – The signature does not match the issuer’s known public key (signature verification failed), or the caller is not authorized to revoke this credential.
* `404 Not Found` – The blobId is not recognized (e.g., if the create step was not done or already submitted). It could also mean the credential was not found (if an incorrect vcId was somehow used).
* `409 Conflict` – The credential is already revoked (the revocation transaction may have been submitted previously, possibly by another process).
* `500 Internal Server Error` – An error occurred during submission (for example, a blockchain failure or network issue).

## BbsBls Issuer Account APIs

The Zetrix VC system uses BBS+ digital signatures (BbsBls) for credentials, enabling zero-knowledge proof presentations. These endpoints help manage the issuer’s BBS+ key pair. Typically, the issuer will derive a BBS+ key from a seed (such as a wallet mnemonic or seed phrase) and use it to sign credential data. These APIs are mostly utilities for issuers: in many cases, issuers may manage keys client-side, but the API provides a way to derive and use keys if needed.

### Create Account from Seed

**Endpoint:** POST `/cred/bbs/create`\
**Description:** Derives a BBS+ issuer account (key pair) from a given seed. This is usually used to get the BBS+ public key corresponding to a seed phrase or seed value that the issuer controls. The BBS+ public key is needed to include in DIDs or to share with verifiers so they can verify credentials. The seed is used to deterministically generate the BBS+ private/public key pair. (This does not create an account on the blockchain; it’s purely cryptographic key derivation.)

**Request :** *(JSON)*

* `authorization:` must be sent with all client requests. The authorization helps the server to validate the request source.
* `seed` (string): A seed used to generate the BBS+ keys. This can be a mnemonic phrase or a hex string/base64 string representing the seed bytes. The exact format depends on implementation: for example, it could be a 32-byte hex string derived from a 12-word mnemonic. The seed provided should be kept secure, as it determines the private key. *(If a mnemonic phrase is used, it should be a single string with words separated by spaces.)*

**Response Body:** *(JSON)*

* `publicKeyMultibase` (string): The issuer’s public key encoded in Multibase format, allowing interoperable representation of keys across different systems and encoding schemes.
* `privateKeyMultibase`(string): The issuer’s private key encoded in Multibase format, used for cryptographic signing operations and must be kept strictly confidential.

**Example Request:**

```json
{
  "seed": "trust toward breeze vapor enforce banana brief unfold carpet adjust obey parade"
}
```

**Example Response:**

```json
{
    "object": {
        "publicKeyMultibase": "zmGHfsGYtRbh6MfDQegV976maR1FwAJxFnboew8wydSVd2YwprnhXQvBDUYnQ13PCeifouGzeecE3dko8F6KTEGkZtuDFLBYfAJHSCzpk9ukfXWqX9ykpz326RSWPxjeagQp",
        "privateKeyMultibase": "zMUD9RhqyST16EWBUvSdeQkvE2dMz5oQCTxMCbxT5wHo"
    },
    "messages": []
}
```

*(The publicKey string is truncated for brevity. It would be a long base64 string.)*

**Error Cases:**

* `400 Bad Request` – The seed is missing or not in a valid format (e.g., wrong number of words in mnemonic, or invalid hex string).
* `401 Unauthorized` – If the API requires authentication (to prevent unauthorized key derivation) and the call is not authenticated.
* `500 Internal Server Error` – The server encountered an error during key generation (for example, if the seed phrase couldn’t be parsed or an internal library error occurred).

### Sign Data

**Endpoint:** POST `/cred/bbs/vc/sign`\
**Description:** Signs an array of data messages using the issuer’s BBS+ secret key. This is used to produce the BBS+ signature that will go into a Verifiable Credential. The messages to sign should correspond to the credential’s attributes (and possibly other fixed fields like a context or nonce, depending on implementation). The output is a BBS+ signature that can later be verified with the issuer’s BBS+ public key. Typically, the issuer will use the same seed as in **Create Account** to derive the secret key and sign the credential attributes.

**Request:** *(JSON)*

* `authorization:` must be sent with all client requests. The authorization helps the server to validate the request source.
* `publicKeyMultibase` (string): The issuer’s public key encoded in Multibase format, allowing interoperable representation of keys across different systems and encoding schemes.
* `data` (strings): The list of messages (attribute values) to sign.

**Response Body:** *(JSON)*

* `signature` (string): The BBS+ signature over the provided messages, encoded as a base64 string (or hex string depending on the system conventions). This signature will be used as the `bbsBlsSignature` in the **Create VC** call. It incorporates all messages in a single compact signature that allows selective disclosure proofs later. The length of this string is typically fixed (for example, 112 bytes in base64 for BBS+ sig).

**Example Request:**

```json
{
    "publicKeyMultibase": "zmGHfsGYtRbh6MfDQegV976maR1FwAJxFnboew8wydSVd2YwprnhXQvBDUYnQ13PCeifouGzeecE3dko8F6KTEGkZtuDFLBYfAJHSCzpk9ukfXWqX9ykpz326RSWPxjeagQp",
    "privateKeyMultibase": "zMUD9RhqyST16EWBUvSdeQkvE2dMz5oQCTxMCbxT5wHo",
    "data": [
            "aWQ6IGRpZDp6aWQ6YmE0ZjFmY2Y2ODgzMWE1YzY4OWRmYWEyMTk1ZGExYTNhN2MzNzkzMDIyOGY4ODY2MTFmOTM2ZmVkMGRmNjZiOQ==",
            "cGFzc3BvcnRNYWxheXNpYS5uYW1lOiBBbGkgYmluIEFidQ==",
            "cGFzc3BvcnRNYWxheXNpYS5jbGFzczogQjI=",
            "cGFzc3BvcnRNYWxheXNpYS5hZ2U6IDIx",
            "cGFzc3BvcnRNYWxheXNpYS5nZW5kZXI6IE1hbGU="
        ]
}
```

**Example Response:**

```json
{
    "object": {
        "signData": "uoULOVqFq4SQ-6sBZe_paCOGhOhcZcT64sNp9RlyhJDYQGPijNPPXJgTCm0bKqWmGbmHxe2iXKF2oPhWlqgBa-49J8-QGETTPiYmA5udXW882IuoLALYxrlZELsS5QhdX0FjRBEcYxdkuA6pmMR45Lg"
    },
    "messages": []
}
```

**Error Cases:**

* `400 Bad Request` – Missing seed or messages, or the messages array is empty. Also if a message is in an invalid format (e.g., not a string).
* `401 Unauthorized` – If the API requires auth and the call is not authorized to perform signing (to protect misuse of signing).
* `500 Internal Server Error` – If signing fails due to internal errors (for example, if the seed is incorrect or the cryptographic operation encountered an issue).

## Verifiable Presentation APIs

Verifiable Presentations (VPs) allow a credential holder to prove certain information from their credentials to a verifier. In Zetrix’s VC system (using BBS+), a holder can generate a proof that selectively discloses some attributes of their credential (and optionally proves statements about others, like ranges) without revealing the entire credential. The VP APIs help create and verify these presentations. Typically, the holder will use **Create VP** and **Submit VP** to produce a presentation, and a verifier will use **Verify VP** to check its validity.

### Create VP Blob

**(Non-encrypted) Endpoint:** POST `/cred/v1/vp/create`

**(Encrypted) Endpoint:** POST `/cred/v1/vp/enc/create`

\
**Description:** Creates a verifiable presentation object (unsigned) from a given credential and disclosure requirements. The holder calls this to prepare a presentation by specifying which credential to present and which attributes to reveal or prove. The endpoint returns a presentation blob that the holder must then sign (to prove possession) or finalize. This step performs the heavy cryptographic computation of generating a selective disclosure proof using the BBS+ signature from the credential.

**(Non-encrypted) Request Body:** *(JSON)*

* `vc`(object): The verifiable credential to be presented, provided in JSON format. This should be the full credential that was issued (as obtained from the download or issuance step), including its proof (BBS+ signature). The service will extract the credential’s data and proof from this object. *(Alternatively, some implementations might accept a `vcId` and fetch the credential if it’s stored, but in this context, providing the credential object ensures the holder has it and controls it.)*
* `vc.id` (string)**:** Unique identifier (DID) of the Verifiable Credential.
* `vc.type`**`(`**&#x61;rray of string)**:** Array of credential types; defines the base type (`VerifiableCredential`) and the specific credential type (`PASSPORT MALAYSIA`).
* `vc.issuer`(string)**:** DID of the credential issuer (organization or authority that issues the VC).
* `vc.validFrom`(string)**:** Start date and time (ISO 8601) when the credential becomes valid.
* `vc.validUntil`(string)**:** Expiration date and time (ISO 8601) after which the credential is no longer valid.
* `vc.credentialSubject.id`(string)**:** DID of the credential subject (the individual or entity to whom the VC is issued).
* `vc.proof.type`(string)**:**&#x53;ignature type used for cryptographic proof (e.g., `BbsBlsSignature2020`, `Ed25519Signature2020`).
* `vc.proof.created`(string)**:** Timestamp (ISO 8601) when the proof was generated.
* `vc.proof.proofPurpose`(string)**:**&#x50;urpose of the proof (e.g., `assertionMethod` to assert authenticity).
* `vc.proof.proofValue` (string)**:**&#x54;he actual cryptographic proof value for BBS+ signatures.
* `vc.proof.verificationMethod`(string)**:** DID URL of the verification method (public key reference).
* `vc.proof.jws`(string)**:** JSON Web Signature (JWS) string created with ED25519, binding the VC data to the issuer’s key.
* `vc.@context`(string)**:** Array of JSON-LD contexts that define semantic meaning, including W3C VC data model, security vocabularies, and custom Zetrix metadata.

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted VP data {reveal attributes and range proof} . Refer to Create and Verify VP Process.

**Response Body:** *(JSON)*

* `blobId` (string): An identifier for the presentation blob that was created.
* `blob` (string): The unsigned Verifiable Presentation data in a serialized form (likely JSON, possibly encoded as needed). This blob includes the disclosed information (attributes listed in `revealedAttributes`) and the cryptographic proof data for hidden attributes (including any range proofs). However, it may not yet contain a proof of holder possession (i.e., a signature from the holder’s DID). The holder needs to sign this blob (or a subset of it) with their own key to prove that they are the legitimate holder of the credential. After signing, the holder will use **Submit VP Signed Data** to complete the VP.

  The `blob` essentially contains a Verifiable Presentation object with everything except the holder's signature. It will reference the credential (or include a derived proof of it) and list revealed fields. The holder’s signing step will typically add a `proof` section indicating the holder’s verification method and signature.

**(Non-encrypted) Example Request:**

```json
{
    "vc": {
        "id": "did:zid:6421ca70444138f3495d5f50ddd174dfedec06d668fb697070b0a849771d7768",
        "type": [
            "VerifiableCredential",
            "DrivingLicense",
            "DegreeCertificate"
        ],
        "issuer": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb",
        "issuanceDate": "2025-01-01T00:00:00Z",
        "expirationDate": "2026-01-01T00:00:00Z",
        "credentialSubject": {
            "id": "did:zid:2c8c214c958e0f28e8e3aac60a38abd161e3135efa33bb1c4233e0c6a4518a17",
            "drivingLicense": {
                "name": "Ali bin Abu",
                "class": "B2",
                "age": "21",
                "gender": "Male",
                "idNo": "abc12345"
            },
            "degreeCertificate": {
                "course": "Science Computer",
                "cgpa": "3.9",
                "id": "gg1233222"
            }
        },
        "proof": [
            {
                "type": "BbsBlsSignature2020",
                "created": "2025-03-07T07:06:44.747608Z",
                "proofPurpose": "assertionMethod",
                "proofValue": "ukFiZpQ2quVC4mTgEuzyF8lVqOExC5HGBWnCHcxCuR7jPuZOhnWT9Lrg4w9YVqcM1QlHj0EpPUsTGYCnZA1-_pPAZYyLHjrPGZEv5rJADJRUkj6ocu7HgDxf5tnwvzFVyFABEjt0Ac4E9mBfHIrcLPA",
                "verificationMethod": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb#delegate-1"
            },
            {
                "type": "Ed25519Signature2020",
                


```

*(In the above example, the holder will reveal `fullName` and `expiryDate` openly. They will not reveal `licenseNumber` but instead prove that it lies between 900000000 and 999999999, perhaps to show the license number is within a certain format or range. The `challenge` is a random UUID from the verifier.)*

**(Encrypted) Example Request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                           |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `secretKey` | dyv1KFrmUzcWA\_dtytgYQmFP2vuFK9k\_3gj9tFvJc8W4nfEU628FpQPoDnhLgR\_ep5uBGgAECWUW-uiBWYZL5YfOc42IgZh46FtrNd2sy6gfVG8jzSdikpb5iwdN6Ptfpb3bSTq\_SIIPvHuPrzFhb7IXePXX8pPSLE1qQ0vZ9hT43ISb6d5jIIpBYTIZApuACKYcMngpU7neUSwgjd\_48Py4wF-grVnJon5pZYbhIfrzDR-IHckaXjHH4iHHCNamANaBxxZCmFV4UHMnKHKuSkhMDUZwpyd707CRbnAVgF\_6NqBlmlDgE\_04CmI-ztK-M9EmenTjmgKEw0ZL3pWZyg== |

**Request Body:** *(JSON)*

```postman_json
VfPKszAiX3phb_nWRkzaoxKJgy9QbUmkNjthHKQVPJZa7lrnzan3QI6ZR-Ol7pMz2XIHmqHkkxGWIP5I_LYTcmQW2FA-YPKQXs3ZIaFKt40znXS8ruIv9pIua3agfH6nL1sIn-tIZulvEXz0T6HL3kX6_NsCdbBdo_bMoJH9r6PWB10WFegA0lHcn_tCGO5ekAE4zeaaKaWS5wPhSA1DssrpRR_rgGGyEANESDryszfBzFkAkgfdPvDcmXXtE8HMESfQFmaHuOLjIRXh6R7Due1lk4jJGftmx12tTZYig62JQYWulGxfUWCMS7rGGBXMpDRqWsUMf-NhUXOKOQc9oFQ3VGf3qqcHKTje7oowZavk_BKpmflG7bTa6kaWGMxGBAKGhFQr0K0XgipupmYKWZhvykxagx9XMMuPYR5Mkqk3sp4AYfWLyFXf9aD9LOGaUK8E0i71PYoLbp5BvQFw_oTxKSgQDMCWv305X_O3F-oVChU6AjHv4eKovIHM3G4K_mQclvTNMhxGgMs9Qz59acwe2DsHBiLGhiew7TRVjDf6ooweaV6qUbGb-z0pPK0ZvfsGNFMs_k4Tmoq7WnbeNSR0WJBft0SIu_IzpmYpwlp-zYqEF7JvRm-AGYCYPB-3gRvVRRO0evyBF5x1kvB944TaQgZFgu13EN1dqiV7wsFUHFcEvgwnJS-7i2PcHwZz3zvnUpaFC5jv0TyCBdp7_tI8oVVu2u1ku4oIsAwMTiLK8hIDYhYBIEiIeJpJ832e-WqX6wotzN6xPtIOaidREmOBaJ4DEpV51sg0iS_4C4OGimFxc60jpa1s5qy5Js22XPY7EFkhAa9lwl6dCJs8J-_DVo3ImpmM88clVOXC_t4uJ1HSC6tCwcKfG2JJi_MnzVEpsNlCPT_b7sYDYrdIW1Rew01PaDk6kroxcWS2VzU-civUE2ZWjuQN8air-reGNhZjV0n4fWP3TIc11LfUUq-rc6q8S3L2JtQcv4s7mLcBg8nJ1sD33wl1WxzyJlQ39eYsf9dySxkWKpuW8o8lV4SO2v1VqLXzrx8O94y1vtI-4OABB4i0Ws5P72RtDNATj4MtXfUsa7bLVujoU0fAGKxIfkg3dN8Q03XsD8hESie-TfTtdxvalYEb8jDXjqVawzgJ0YGvMgyqLJgiAG9qtLxrlfDc9ehV8bdw69XngThbQZcOu_CNRcnDezOQMB3pRi0ZRMZhLtaEl3yJPWYsp88k7TBNppqdKlM6vUd8TfYBtoBuIn8Br5t_prpdB0ZkdSiwpCLKuRKLKUDImidqjs37wzErc4CyhsJ9Z5NNiFhMcukya_qX43SCrIqPS2VzjqFJGzgj2WkZJzJgMB06695DGg9IZn1KYHkiV5jJNwJhiMaRNjGBkqcKcHZZFSeI88RNTukEUlySorLJ1bCvSSKU3AOprTGzbNF1QxjL4poW-NwfXJd3GqGpXNgvzzg9uzyhI-XLlvYRg2FkD8wR7beYMsOm9KqH9yJFE3HQPf1DISPK3y2muLsUCP8vtQ0XJ0N8Zr8j3Z-gIcJ5rYgrSqnSJa-RPY_dNn1fppScnWewDLdoakjMzlQV8xaqoYAt0CLWsbxrdQwxLgT0Pd_gtfU7LBsNdxEdRwjb3cXtXsLdwXy2ofms3FIJBEoHJSXVL9Qaq3FvFv4ZoRgaMk4YgHesBA_rZRbXq_OvTbeGaC3D2mShcWmAPDy3ejJcU3JexWykllLIgFqIQw9r2mOuPpcvczEvW-mskoJ4XOCTMNvqeTOc5XjKibGLZ6VfeMyj0kKVPFrd4EeCwTdaWJLjersOYmpB7tk9sruuLxioGF4vahM3bsAhTsQvxnSZjojuwG6dTGyqCpHgF6BBoYi3Y_aHbRfqTAVtL79DjzBotQ5VNuWhZk_ricmzCXll4DuVezYNx1oc4PfTgF0w214iWlFWlnNhxLvPaBCGZ4AACng2Nhn-wyAWV9HQJI0ChG1DKa_fWuwt_o1j6k8noZh1HZAmfed9Lh-KYitlsw3x-mu1qYiuETNK8AnOMGZFoy1yTPRhc-7Z5tghumqnV_sZhce0tohnByxSEKXxeaa76h1TPGfGAPGkwZSb2EbQrIYG37pmAyKSG3uLxgb-33q7j71m79OifEoX40-Bt5cQtPKSJbuzerrmmjH-EYxu9DL_eim_O1YejteBbUuqA6a6lLu3CvNRiyemrmGy8hBneOAae--QWyAvO8Jv4GCWjuBsH63EHbz4mz8_dazR5xmaoc9sLSCUwoOxQidHesBTQHvsxNMRbFTRtfWUMgqqX2h4y_4JfkvI0q8In5AzIgGqsNBBZLPqO2kFAX-pmd_QuWxHIO3bQUOOjBhEwnYDWm8Lh8XG4JU8Qw7gTy5E7-4ibATsMBE15ZD8rWzJm0HQCA-4xRCT-TecJcwDHLrX2mNC08pcy8rmNZ9KWa8Ih7P2AmVpO_5eBPJaFP_43c8hx-VG7x6BJTeIl6HY2uowQrc7OfEHUjo12lbbyaDSqXCoPZ1e9ubwOeSKmRF-OdALhyqdDxj6XghHZ1L6ec_9BDySnglqVxP3h6bEjhT5mtHRUdqYNib9eYrj4h43DxtztLjd2q8smHBWkttFfmL8CfTAG8ZFgTPoKDaLUvE1XT1vF--53pkXK-1GYmdsqKImqB7Ss2PHAv3HBIC1rZp_rw_dN7dbsDUBxOYkRaVwiELv6DEpEUKSieq-bvz54aD33sNllat7aUNBhD9rENK216PTkUTamSygwuA-Scr44hhA9N5sBzSa-dLVeTRqGo1T9mo71SmUZLFgD6AXYgZxENJOrxKL-zqDIOBomLOXi5827MosoxKrG-06HPzIizTZfCgF8FhD989j17-c0aSRhH8CfnV1axpjlfmpXa3RjW3m-m6XKcLBkFfIQKl_QF8OmZ4o-JKbkHRyK1vNiCDE_Qlbo1jTlQDGFZtFrH9BomgKoZ_eE-Bl4OVPkKtDQQUmsi_ceTEHHW0_Y9PN_Ot6vt_iMHjT69GLoiWxuu4ttvhW3YmZ9sFlpMXt6D5NEMkMEwcHM7XVFtL_E6Lzq5lA5MhMxkZfPqQiP0xOSaOrrY4KubcdXXMrvhKz6tLOeBHBQ6eEWtqrgVkFetdN1LDMWblYLbSMiYmGPW8f673KXjjYKW3-KHr24iy8OBjZ-IVULPr2vnHsvyVJj0YkMqXI8TuumiwJO1qJFoYQMbBqhscG6MG1KEWhmaHxkb6gm1oaJL3PyCHbdMeb3BJ5MFQU7zaAS9tby680NRKHnAezER85dpNDr7RZ_4NUzJSQ9IlnyxEbt7fLDiRY_Yd747zp-X1tm6lcTvnhSLwchXz4NUFAikCRInUvIvQYC5y0DU5tmcNaNVrlUcgsbRprB8naGv5DYWFVniOK8Mhp9sgrsY_Qb79V05ld9LI9KUv7aJ-6OpDRw4bfnEDPvzkM7PImYAe_EePLYfZtpcPOvls0qzq6-RGRzWR8b1xfVUmrVnlakFAPjD_Xnc6zcvbcY2kyyIlJ4x7daysXd4wpYAasqvymcw_279UY-_U4gkVeahvswktWoY8LB34NfYZHMlbsRd1NvbwkhxAS1BN73XX91Y25gKO4RAa6ZX3uVtJJr6EjiVaUVw==
```

**Example Response:**

```json
{
    "object": {
        "blobId": "55C2535A215617074C457F4BD84051A6",
        "blob": "65794a68624763694f694a465a45525451534a392e65794a4159323975644756346443493657794a6f64485277637a6f764c336433647935334d793576636d63764d6a41784f43396a636d566b5a57353061574673637939324d534973496d68306448427a4f693876647a4e705a433576636d63766332566a64584a7064486b76596d4a7a4c335978496c3073496d68766247526c63694936496d52705a44703661575136596d45305a6a466d593259324f44677a4d574531597a59344f57526d595745794d546b315a47457859544e684e324d7a4e7a6b7a4d4449794f4759344f4459324d54466d4f544d325a6d566b4d47526d4e6a5a694f534973496e5235634755694f6c7369566d567961575a7059574a735a5642795a584e6c626e526864476c7662694a644c434a325a584a705a6d6c68596d786c51334a6c5a47567564476c68624349365733736951474e76626e526c654851694f6c73696148523063484d364c79393364336375647a4d7562334a6e4c7a49774d54677659334a6c5a47567564476c6862484d76646a45694c434a6f64485277637a6f764c33637a6157517562334a6e4c334e6c59335679615852354c324a69637939324d534973496d68306448427a4f6938766447567a644331756232526c4c6e706c64484a706543356a623230765a32563051574e6a623356756445316c64474645595852685032466b5a484a6c63334d39576c52594d32466b526d35616358566c5558525a53314a56546d525864323434536c526c4e6a6457643052684d55567951535a725a586b39644756746347786864475666583252705a447036615751364d5759335a5759325a57526b4e5445324e5459784d7a67345a6a67314d7a59794d4449335a6a45785a544669595751324f4455794e44426d5a6d457759545668596d55775a445934596a51354e6a4a6b5a546c6b4e794a644c434a6a636d566b5a5735306157467355335669616d566a6443493665794a705a434936496d52705a44703661575136596d45305a6a466d593259324f44677a4d574531597a59344f57526d595745794d546b315a47457859544e684e324d7a4e7a6b7a4d4449794f4759344f4459324d54466d4f544d325a6d566b4d47526d4e6a5a694f534973496e426863334e7762334a305457467359586c7a615745694f6e73695957646c496a6f694d6a45694c434a6a6247467a63794936496b4979496977695a3256755a475679496a6f69545746735a534973496d3568625755694f694a4262476b67596d6c754945466964534a3966537769615751694f694a6b61575136656d6c6b4f6d466a5a6d557a4e544e6a597a63794d5441304d5459785a44646d4e6a46694f5451784d44466c59575a6c596a6b32596a41784d5759784d47466c4e546779596a55304f4449314d7a4d315a575a6959545134593245694c434a7063334e315a5849694f694a6b61575136656d6c6b4f6a426b4e4467354d545a6c4f4749775a6a45774d6a6b33596a41794d3249324f44426d596a6468596a497a4e6a646b4e5756694d444e684d574532596d49344e7a5a6b4e6a4e6b4d5745355a6a55324e7a646b593249694c434a77636d39765a6949365733736959334a6c5958526c5a434936496a49774d6a55744d4463744d6a52554d4463364e5451364d6a59754e5463794e6a51774e54417757694973496e42796232396d554856796347397a5a534936496d467a6332567964476c76626b316c644768765a434973496e42796232396d566d4673645755694f694a3161485a6d4e7a513356335236626d4a54635856365956645a576d7849616a4258634774556445704b557a4179616b356d625639564f47746b6348466d555746756456564c55557777543368425245685a6255565651304670566d633057457044574642734f5551784f48424a64476c59626b52705248687355326c66516e4250615568454e6d56485a6e5669636b566f58314e575a304630646b70575157705155486c7155444254624568564c533079576b784861315278593370365a6b3936555464545832396e4969776964486c775a534936496b4a6963304a7363314e705a323568644856795a5449774d6a41694c434a325a584a705a6d6c6a595852706232354e5a58526f623251694f694a6b61575136656d6c6b4f6a426b4e4467354d545a6c4f4749775a6a45774d6a6b33596a41794d3249324f44426d596a6468596a497a4e6a646b4e5756694d444e684d574532596d49344e7a5a6b4e6a4e6b4d5745355a6a55324e7a646b5932496a5a4756735a5764686447564c5a586b744e434a394c48736959334a6c5958526c5a434936496a49774d6a55744d4463744d6a52554d4463364e5451364d6a59754e5463324e6a4d304f54417757694973496d703363794936496d5635536d686952324e7054326c4b526c7046556c525255306f354c6d5635536b465a4d6a6c315a4564574e47524453545a58655570765a45685364324e3662335a4d4d32517a5a486b314d3031354e585a6a62574e3254577042654539444f57706a62565a72576c63314d474658526e4e6a65546b7954564e4a63306c746144426b53454a3654326b34646d5236546e4261517a56325932316a646d4d79566d706b574570775a456872646c6c74536e704d4d316c3453576c3361574649556a426a5345303254486b354d467059546a424d567a5632576b645664575674566a426a625777305447314f646d4a544f57356157464a4357544a4f646d52584e5442555631597757565653614752485256395a56314a7259323157656d4e364d574657526d64365756645352324a736348686b56315a535a455a7354465673566b3961526d517a596d706f53315a4856544a4f4d566f7a556b644665464a59536b4a4b625852735a5651784d4670584d58646952305977576c59355a6c704862477450626e4277576b5276654670715a477861616c7073576b64524d5531555754464f616b56365430526f625539455658704f616b6c335457706b62553155526d784e5630706f576b525a4e4535555354424e523170745756524361453558526d6c6156454a72546d706f61553545617a4a4e62564a73543164524d306c734d484e4a62553535576c645362474a75556e425a563368555a46644b63567058546a424a616e41335357317361306c7162326c6152327872543235776346704563476c5a56464a7454566461616c7071575452505245313457565257616b35715a7a56615231706f5756524a65453955566d745a56455a6f54544a464d316c3654544e50564531335457704a4e4670715a7a524f616c6c345456645a4e553136576d316156314633576b645a4d6b35745354564a6158647059306447656d4d7a516e5a6a626c4a4f5756643461475659546e425a55306b325a586c4b61466f7956576c5061556c3554564e4a63306c74546e4e5a57453536535770766156467153576c4d51307075576c63316131705953576c506155704f5756643462456c7064326c6962555a30576c4e4a4e6b6c72526e4e6855304a70595663305a314658536a464a626a453554454e4b6346704453545a4a62564a77576b52774e6d465855545a5a56303574576c524e4d553079546d704f656b6c345455525265453571526d744f4d6c6b795456644a4e5535455258644e56315a6f576d315761553955576d6c4e52455634576d704664316c585654465052457070546c52524e4531715658704e656c5a73576d314b614535456147705a55306c7a53573173656d4d7a566d786a61556b32535731536346704563445a6856314532545564524d4539456133684f62565530575770436255315551586c50564752705455524a656c6c715754524e52317070546a4a476155317154544a4f4d6c4578576c644a643030795258685a564670705757706e4d30357455544a4e4d6c4634575652736255355557544e4f4d6c4a7157576c4a63306c75556a566a523156705432787a61565a74566e6c68563170775756644b63317056546e6c6156314a73596d355363466c5864326c4d5130705255565a4f564656464f564e5751304a4f55565634516c6457546b70525530706b54454e4b4d6c6c586548426152567035596a49776155397053586c4e52456b785446524265457855515868575245463354327042643039715158645861556c7a5357356161474a4862477457567a5577595664336155397053586c4e52456b795446524265457855515868575245463354327042643039715158645861556f354c6b317161455a4f61305a43546c525a4d6b355554544a52656d63775456524f516b35715258644f61315635556c52724d464a5653544e5052555a45556b52424e5531565354524e52453078556d7046656c4a56556b645052456b31556b564e4d453955556b565052476434556d7057513031465258704f61306c365558706b5256465562454e4f656b4579546a42524d553545576b4e5256456b30556d706e656b353657545252565646345456526e656b3545617a4e4e565646345556525a656c4a456245565356565a45545770426555314657544a5256455a46546e706a4e55314559794973496e42796232396d554856796347397a5a534936496d467a6332567964476c76626b316c644768765a434973496e5235634755694f694a465a4449314e54453555326c6e626d463064584a6c4d6a41794d434973496e5a6c636d6c6d61574e6864476c76626b316c644768765a434936496d52705a447036615751364d4751304f446b784e6d5534596a426d4d5441794f5464694d44497a596a59344d475a694e3246694d6a4d324e3251315a5749774d32457859545a69596a67334e6d51324d32517859546c6d4e5459334e32526a59694e6a62323530636d39736247567953325635496e31644c434a306558426c496a7062496c5a6c636d6c6d6157466962475644636d566b5a57353061574673496977695545465455314250556c51675455464d51566c545355456958537769646d467361575247636d3974496a6f694d6a41794e5330774d5330774d5651774d446f774d446f774d466f694c434a32595778705a46567564476c73496a6f694d6a41794e6930774d5330774d5651774d446f774d446f774d466f6966563139"
    },
    "messages": []
}
```

*(For readability, the blob content is shown as a snippet. In practice, `blob` will be a JSON string or structure containing the Verifiable Presentation with the proof of the credential. The proof inside the blob at this stage is likely a **BbsBlsSignatureProof2020** (or similar) that contains the derived proof from the BBS+ signature, which shows consistency of hidden attributes and correctness of revealed ones. The holder’s own signature is not yet included.)*

**Error Cases:**

* `400 Bad Request` – Missing or invalid input (e.g., no `vcObject` provided, or the credential object is malformed; requesting to reveal an attribute that isn’t in the credential; rangeProof parameters invalid such as min > max).
* `401 Unauthorized` – If the holder is not authorized to create a VP for the given credential (e.g., the credential’s holder DID does not match the authenticated user). Typically, the holder should only present their own credential.
* `404 Not Found` – If a `vcId` was expected instead of `vcObject` and not found (not applicable in our assumed interface where `vcObject` is given).
* `500 Internal Server Error` – The server encountered an error during proof generation (could be due to cryptographic library issues or memory constraints if the credential is large). This could also happen if the credential’s proof is not valid (e.g., if the BBS+ signature in `vcObject` failed verification against issuer’s public key, meaning the credential is suspect).

### Submit VP Signed Data

**(Non-encrypted) Endpoint:** POST `/cred/v1/vp/submit`

**(Encrypted) Endpoint:** POST `/cred/v1/vp/enc/submit`

**Description:** Completes the verifiable presentation by incorporating the holder’s signature (or proof of holder) into the presentation blob. The holder calls this after **Create VP Blob**, providing their signature over the blob (usually covering the digest of the presentation and the verifier’s challenge). This produces the final Verifiable Presentation that can be given to a verifier. Essentially, this step adds a layer of proof that the presentation is furnished by the holder in possession of the credential, preventing anyone else from reusing the presentation.

**(Non-encrypted) Request Body:** *(JSON)*

* `blobId` (string): The identifier of the presentation blob from the create step.
* `ed25519SignData` (string): Signature of the credential data generated with the issuer’s ED25519 private key.
* `ed25519PubKey` (string): The issuer’s ED25519 public key used for verifying the credential signature.

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted VP data {`blobId,` `ed25519SignData,` `ed25519PubKey`} . Refer to Create and Verify VP Process.

**Response Body:** *(JSON)*

* `vpObject` (object): The completed Verifiable Presentation. This is a JSON object containing the Verifiable Presentation data, now including the holder’s proof. It will have a structure like:
  * `@context`: including both credentials and security contexts.
  * `type`: typically `["VerifiablePresentation"]` (and any specific sub-types if defined).
  * `verifiableCredential`: containing the proof of the credential (not the full original credential, but the derived proof or reference created in the blob step) along with any revealed attributes.
  * `proof`: an array or object that now includes the holder’s proof. For example, one proof might be the `BbsBlsSignatureProof2020` from the credential (already in place), and another might be a `Ed25519Signature2018` or similar from the holder. The holder’s proof will include the `verificationMethod` (the holder’s DID key id), the `challenge` (nonce) if any, a timestamp, and the actual signature (`proofValue` or `jws` depending on the format).

This `vpObject` is what the holder will deliver to the verifier (e.g., via QR code or API). It is a complete Verifiable Presentation that can be independently verified.

**(Non-encrypted) Example Request:**

```json
{
    "blobId": "DE629ACA66639EE4E37A5A2B93A37BF7",
    "ed25519SignData": "0B2BD318A79E5A676ACDEFCF6625DF1347A0C6DDEA45CFAA1EDD3E0D06096CE1BF8866CA3619E10153342C65C08A8F20DE798D0EF37834C9BF1C7844F9A53305",
    "ed25519PubKey": "b001ba4f1fcf68831a5c689dfaa2195da1a3a7c37930228f886611f936fed0df66b94a10ec51"
}
```

*(In this example, `signature` might be an Ed25519 signature in JWS format or raw base64. The `publicKey` is a placeholder for the holder’s public key. In practice, the holder’s DID and key could be resolved by the server, but it’s provided here for verification.)*

**(Encrypted) Example request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                           |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `secretKey` | dyv1KFrmUzcWA\_dtytgYQmFP2vuFK9k\_3gj9tFvJc8W4nfEU628FpQPoDnhLgR\_ep5uBGgAECWUW-uiBWYZL5YfOc42IgZh46FtrNd2sy6gfVG8jzSdikpb5iwdN6Ptfpb3bSTq\_SIIPvHuPrzFhb7IXePXX8pPSLE1qQ0vZ9hT43ISb6d5jIIpBYTIZApuACKYcMngpU7neUSwgjd\_48Py4wF-grVnJon5pZYbhIfrzDR-IHckaXjHH4iHHCNamANaBxxZCmFV4UHMnKHKuSkhMDUZwpyd707CRbnAVgF\_6NqBlmlDgE\_04CmI-ztK-M9EmenTjmgKEw0ZL3pWZyg== |

**Request Body:** *(JSON)*

```postman_json
UbWc320b8hQabsj9emEFIM3lu20Jc0m_8DA-NwRbwA6x5_DZgycjoPbLf8xbS3fYb1Pz4ZrNu0CNseQCX-XY3A9b14GtZpJ7cttefpH5D8UkNTVHDGLtWZohkonisi2CG9U94WegeQjCHQeuNm5dJLubRtFvtPIxlexHGeqd5xp4TV4T23ZMHTib8_hlbFAvrgwygNWeg-Y6W80DEE8DMQExoUFov4Sdx-h_3B0ihFO-VoTCkvuKVnTOsPOhABoZxfeJfuk6h5QYBcbaEJgeQ2vsFfhetiQ4urIdVXJ6iDrItSs1iYvoLHNsbt0TyVZiOsJLHwFpMa0vTYps6I2Rg_Dl3WP28jZSJjBx5h4fBWIdUJR-8bF8ZdGEDF8cWQYD3csaIyM0eNghOT-TpmyeW-7qtL4Lic_7u3PEDaY=
```

**Example Response (partial VP):**

```json
{
  "vpObject": {
    "@context": [
      "https://www.w3.org/2018/credentials/v1", 
      "https://w3id.org/security/bbs/v1",
      "https://w3id.org/security/v2"
    ],
    "type": ["VerifiablePresentation"],
    "verifiableCredential": [
      {
        "@context": ["https://www.w3.org/2018/credentials/v1"],
        "type": ["VerifiableCredential", "DrivingLicenseCredential"],
        "issuer": "did:zid:123456789abcdef",
        "credentialSubject": {
          "id": "did:zid:holder12345",
          "fullName": "Alice Chen",
          "expiryDate": "2030-12-31"
        },
        "proof": {
          "type": "BbsBlsSignatureProof2020",
          "verificationMethod": "did:zid:123456789abcdef#bbs-key",
          "proofValue": "tZ3v...WXYZ==",
          "nonce": "MTIzNDU2Nzg5..."
        }
      }
    ],
    "proof": {
      "type": "Ed25519Signature2018",
      "created": "2025-04-07T02:00:00Z",
      "verificationMethod": "did:zid:holder12345#key-1",
      "challenge": "b25f5e9c-7d7b-4f1e-92d3-123456789abc",
      "proofPurpose": "authentication",
      "proofValue": "zSign...abcd=="
    }
  }
}
```

*(In the `vpObject` above, the `verifiableCredential` array contains a credential object with only the revealed attributes and a proof that those attributes are valid (BBS+ proof). The final `proof` at the presentation level is the holder’s signature, which includes the challenge from the verifier. The combination of these proves that the issuer originally issued a credential to the holder and that the holder is now presenting it with certain info revealed.)*

**Error Cases:**

* `400 Bad Request` – Missing blobId or signature, or signature format is invalid. This can also occur if the holder’s publicKey is not provided when required or does not match the expected format.
* `401 Unauthorized` – The signature provided does not match the holder’s DID or public key (verification of the holder’s signature failed). The holder might not be the legitimate owner of the credential if this fails.
* `404 Not Found` – The blobId is not found or has expired (perhaps the create step was not done or was done too long ago).
* `500 Internal Server Error` – The server encountered an error combining the proof or verifying the holder’s signature. This could also cover cases where the underlying credential proof is invalid (although that would ideally be caught earlier), or other internal issues.

### Verify VP

**(Non-encrypted) Endpoint:** POST `/cred/v1/vp/verify`

**(Encrypted) Endpoint:** POST `/cred/v1/vp/enc/verify`

**Description:** Verifies a verifiable presentation. A verifier (or any relying party) uses this endpoint to check the authenticity and validity of a presented credential. This involves verifying the holder’s signature, the credential’s BBS+ proof, and checking the credential’s status (whether it’s revoked or expired) and that any disclosed data satisfies requirements (including range proofs). The endpoint returns whether the presentation is valid and may include the disclosed data.

**(Non-encrypted) Request Body:** *(JSON)*

* `vp` (object): The Verifiable Presentation to verify, provided as a JSON object. This should be the full presentation as obtained from the holder (for example, exactly what was returned by the **Submit VP** step or what the holder’s wallet produced). It contains both the credential proof and the holder’s proof. The service will use this object to perform all necessary verifications.\
  \&#xNAN;*(Note: In some contexts, the VP might be passed as a base64 string or a JWT. Here we assume JSON for simplicity, which aligns with the earlier endpoints.)*

**(Encrypted) Request Body:** *(JSON)*

* Header: `secretKey` : Encrypted ECDH key.
* Encrypted VP data {`vp`} . Refer to Create and Verify VP Process.

**Response Body:** *(JSON)*

* `verified` (boolean): `true` if the presentation and the credential within it are cryptographically valid and not revoked/expired; `false` if any verification step fails.
* `vcDetails` (object): If `verified` is true, this object contains the attributes from the credential that were revealed and verified. It will map attribute keys to their values as presented. For example: `"fullName": "Alice Chen", "expiryDate": "2030-12-31"`. These are the pieces of information the verifier is allowed to see and trust. Attributes that were not revealed will not appear here. For range proofs, the verifier might not get the exact value but knows the range condition was satisfied; the response might include a note like `"licenseNumber": "Verified in range 900000000-999999999"` or similar to indicate a successful range check (the exact format may vary, but including the fact of verification is useful).
* `errors` (array of strings, optional): If verification failed (`verified = false`), this may list the reasons for failure. Possible errors could be `"Invalid holder signature"`, `"Credential revoked on 2025-01-01"`, `"Expired credential"`, `"BBS+ proof invalid or not matching issuer key"`, etc. Each error string describes one issue found.

**(Non-encrypted) Example Request:**

```json
{
  "vpObject": {
    "@context": [...],
    "type": ["VerifiablePresentation"],
    "verifiableCredential": [ 
      { 
        /* credential proof object as seen in VP */ 
      } 
    ],
    "proof": { 
      /* holder's proof object */ 
    }
  }
}
```

**(Encrypted) Example Request:**

**Header:**

| Key         | Value                                                                                                                                                                                                                                                                                                                                                           |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `secretKey` | dyv1KFrmUzcWA\_dtytgYQmFP2vuFK9k\_3gj9tFvJc8W4nfEU628FpQPoDnhLgR\_ep5uBGgAECWUW-uiBWYZL5YfOc42IgZh46FtrNd2sy6gfVG8jzSdikpb5iwdN6Ptfpb3bSTq\_SIIPvHuPrzFhb7IXePXX8pPSLE1qQ0vZ9hT43ISb6d5jIIpBYTIZApuACKYcMngpU7neUSwgjd\_48Py4wF-grVnJon5pZYbhIfrzDR-IHckaXjHH4iHHCNamANaBxxZCmFV4UHMnKHKuSkhMDUZwpyd707CRbnAVgF\_6NqBlmlDgE\_04CmI-ztK-M9EmenTjmgKEw0ZL3pWZyg== |

**Request Body:** *(JSON)*

```postman_json
hxtxXa3VqAS51w6K6CIDyztFPhEc52-pljUIpjxYLY2AgtAZfZSSbnn9AfTM30cOISXfupnYryXoSljpw-z-FbScRZTzuzXbp8f3r6d-C2myBiGQsAYjubnmmwYIVWZfzg2lq-aFmgXJjlisP0tbV-1gDB2OGCc8lNM-KeIL9_vxaxzXm7dfCZDrQFmTdTL4W6BUbKUpo2E0as63D4o5M5aAL0HzR9TccnRAN2C4Qe3JMi_x6ElUrN_qyxs_fyoaEf6jUlMAGnFMpv5GK_tutuMiRJfv0cUeyeG3lvJ53h86GQtWE6lpAJZcBLCkF9q-QSGQZ-AiRu1_1UVW2mgiTs5LdrttOBPfQRHMF8dkbD_A71gt-ZMNAQRoaJeFF5SN5syliqY_zAehpem3IfsoTcMd0DKvS2bhYCEBsVnLuQ-4Z2tyIda0kCditlCwg-2FinBSGc8BquVrRFB1Q9XGbZjR8kPPLbFx4rH9q6kCToYrRsvXzcLue5Viis0xX3_IEq4pv3PSTNcG9JDolAZ6tFU-fHBTzhb8LEJkan_oX54dmEdaKUXnnBWqfq3s7tYHH894v8PTHkJgxPnEMWQsSvHXkGXaYsiMLRopFeuME3XZOCeb1E6dQ1MfEyDzMpOMXqG2Y_0F9RJcIQcHm1Ky5ujJPtu8Byx1sIvAjUWjJCMfpNafhcJxpzjM3bhRj9OLKYW3Sg6-mCWyQGAvzPFVWnjvHzPVkUmJ4oXDwKjr5CICGFs6kQL5CD1dlbWzL_TL4zHRw4J0OVCnlDxsHD_87wnf0c9xY8DMsQ0PIB5MGlVtx80gxndbKbuTIUTMmsE5YtfQGzyRMEeyu8GrsIJvXOzF_odFjuZ2cur_sXRmfFdkE0hk8ycuB_qJiZZPLe-mDrAo2DHwPsI5vCNDvPMYSVFF2gzx6CztRTb4elRH9S72q6Y2-1R29w0261k_jvR4--UWKpijdkpX0UxFsc_uyF0GYHXxDQQsZTaVVHO0P1cQ43WAxUfYDrpDEDJ04uC7Z-uAK8erJ-jfByQ8QiP3mVWWQOvJq4vmPPUG_5CsubFvKxAVsF8pqaKCeWVQfZ5H6VCwIMtDTIy6aks0tzdKAabbsml7JXPqPMKmaZd-67bhWWPMpWIeS13_zfbRqaGHfuyf1p9EE5q4vwYXRMlyXcC5SvsVVW5INe8ezIAGQ7KiqQVgjrbyiZeq4HiFShL5yLq9NAnm7vTCcDtUwCVU6m1sTU4wlo114UNF_PmUXoDVteJLYrj65XkpB3mRCu728gzWXsM0oUm3PWecaqRJDWm-KqMA0ljhgmrCyGPv8n-sf2udy-SUzD7nwYl5E6TKkkqcwwbYh4Y647RU6eXpg8FyBdCFZLyWaGUXQE-f8S8ihwc8oRgb9088A4JRO3GnjtCEAiQkK6L8nf-eQZRAEw9Z_3CghKuU0V_2Hg8d4es2XbODvM8M0L1oW3LEVPcejPYvoTCS6Rv-9BpV-hoDcpuYtkXHZlUbM5IU34U9C5D4Gb-v9CXUtS6SfEw3DI6G72dkJmjh37Xpf6kmUEoG4iwogdUcfpe9zQBTsKFWreNX1RHYe4Cy7o1ShpZJlmuzGRstFt-h6Qp8YrsnVYLJERfaMslnRKDaD_FbGTZsi_NE85sX1IPWbQGfBRLWB84KCtPDKmBU1UbHS4nMCELXB1XEYIj7v2-_b7oyLlsT8aEC2TBaaDmgQjdjFVXQ1n3r_x_65UkI6DBEFvWGBlARZzqYWKd2wLgjuPhyglri1HqK1Nbe1hyftrefSeyJ7PpIrv2ZJo1OYfKSXhEFR5qPaT5DrfwJTXc4mySXf4ld3mz7bVMG1wTSWXlGT6Cg1IiO5OuigL8DQbqR082Ycb3n1S-vcxBGJ_pVoKR8r87P_80dggZBwfPWOFNcbkq4gL2VprVTI1mjU9W8qh3IW6JiBTLZbkw-YrgAU4--ng8woJs0dCqwPOLMcwcSE-JA9jlpGifBa1p0pmVyRuufUQl-BGVRUQ-5B79s3RRbJ5j0jMt5T6wOsAKUtNx5ZZdqUl5TQFsW1kOtl7ikq97qIAajzytbWyBzna8cifE8QGmuhT0AXZWdzVXW_f8LliOLy6Y6EkyPU3RmawzuzNKfJ6gLQznL1fTeKKdc9BJiXEJoWSJpI-NZ-YnNDykinQz7T4gGyQypHN-spqqsX_buy1PS3XfRCbybv26IHW_7mDrzr5iX1QAb5ToOBZsCKh-VxbfgyX1-vAj6p75wBVMl6Fy7T_vNId3u9gZW4ouU-eErL84qcGcfZYFEC35x1omLli5Gm3FrJ1hdk5wX1qkbFuImqGwJqSChLQhcRLBHE-1XKXSDwHb2O7LjnJIcKhjWTYNvlTG4wwiZsFxLUIuPUDaVdFHCNETAg0j1lXOKXt3_qWMGfxc7lWwXu1cgwVJDAozfuByKJ_8t9Lcbn2zbYVPB6QYoB9z5Mp9zL6eVv71ZeogWlhy4MUlQTRfgJaDNTaTy5h01neqtCG5Rt2ZG5YY9I_3EvcXFbJ773czIzsA6AJnISLmUqNduQo44zFupiJ8MNC-HfcObOpcGM1nJwBvIb16X0WD20va6fs_rPfIHfDHSOF-Q2avFhTJDWb20kZVhjVhZl5IBi_b49P2CZWAjzUETgCah1KPlKGVFOWvqzRI2mHBaVbDbu4NULy-XGVJilbsdBHklJz_byU5WdmZyx2iONGtpMEavvqxYoYiafOb_tPS8qNGT6rYposqkILjsXeCwj7Jy2Xj8AJovtQSgT8xC3s3jrFfu99TNumRN1vCGmTeoZdCLq1IGwsP5BVnodICOPTvBaY_WKdkcRj99V31idCBaTtBSFPIIfB60HJ5gCbVoLDZCZqouJd59wcSoPox-sT_5OEdsKWy3Kj7VKpeIDLFpt1RokZ4fiXKv9yP-66XtSgvNE8XIWNpNYf4GqELPlnlrNiazNYy7gPrYshAd1j2cR26GxaLVAM489ykVtGU0xV0x5-QtwHRr0_p-MATvNXXKTwIXtLSuBHQoiYDzBxR78pzuq-DR3XCMWfQuUhOc1RV4-AjaKcr0VEVfWHAEuEP5BiRIXOMmnWfQbBuL9qHuVIqokVK7W_eig9_i_J7RiewFYhO5GBuNVfjbGElyEnBqHPHDCCPi3351UEJFC_jga_2AV-UpZJefbs1yiFAL-rfeZOVczkGdUX5I4BeTe7ONxWOS_iDj-e9zwlkZtuwWamvlPZvbRsJcbyLoRhMV4khDLGGynr3dLgFzDxBoArDIxu8HrSDG6L6oZlgYMw2J58HGJlQ2vY6MeFn5r6Xjpd0wk2ZkFzfLjpjgZ_lVVbw6UspfmIQChngGzOb6wXcJS6TeYBIQ8o_8AO3edBnjmE1pRWYWR8BeDnunPAln1FCMlexCYSijLMLX98kIGtTuo_n03L9DujDhJdiAIEOJAnkI_z1louBOyUMQkP8NuOGBQ9SKFYkVNDn_qM7Boelxy3Z-unNfMuQJRHHKg2opRvEZ2IWdXFcZ5ow4Rr6FzlMO0SqWOCsA3K6ZQZxUZVj4kyCfvb0Ph7XJH-LDyRY3_67435QWoUPBfEypsF3zfY9zvugtNdVEosxNvLYLa7iX8Q-jlpHq7mfGwmnTCUii3-TP8ZyNxdu8Y4zdfZHDpgl3aA5xL3D7ZyFPl4x2WKqffLqsVgbqTe5uAy3D89QqsFT7JHqwxV2_DX12m7uohD34MExDm17eHBovy2wuy6IUN78V88LkxnS6Axt28m4dG7dpypgvE5zHK8jkPTVnZeQf9arTltAJKcOXUt9jQVBmc-UZ2PUNTzOjbV3TTnmA7gSOXI2XlHY_lpJ_XxUPdIbTQslW4FmERiUKSg4O11m8SBs5KP5pzpoDJejdKarnTQlayLacjbW4835SNKIJyfQwPIHV2i5Xj9r3oYvJPwVO-uygiSM0bevGJZ1gzL6rE0ykZ7GBBoygve5BrV_VaL12riwHlbs9U788_evc-OrJASA5kw2I28jXIGtMUKoGZK02tcW_ZgAQHwbteXH0ymweqlgTlnbRtuvFzBGLrtUWoRVrFkuOuRzf7zUESq6tUQue_6CnsLJYD-cG2--9R6DeqnfLmtIgAQ_qTzl7hJQvahrlRHp5NAs3u3Dit8ZDtIPyMFpyjY30Qr9SnHr3ZgLh_xlx_1dbixf1dTmbfVG85tR0RSI50nZ0_vU4fuuZ4OtSZly_0b7YlU06NFZ6uRYKOZJudTeGgdaCVx_3Ao74aCv2Ssxsfs0g9CCC0TsM_0nQrF2aUi8ddI1n0sjylfdS0AkR_d7XiwcLNqZcIftaB7nsBxxq0_TLpaZl3AAfwSemIJYkVP33QFOAeY5inqUlU615jCoTAVSSmXXuSL-s-zpXOOSr__C510gfMc76DlbomxrdzM-xI-o8ScYK5RvvvH62VGjOy4if_SNhvrfK77bVqMbzWwQsoIt-ExXomKZGSZL8kZaOI37ae83zM_a6CPzut-qIvj_v5zoNn-JEbCT4w49xQGj9HNAxLjbKz35IGdQpdgzKvligfzKHdGhe_04JxMVIbdttdtbazFuenzEcU-vAj1ENqDF6oNKKCWxfQTOoohIrfwuuiEovaLdIRhd9nUqWLBSRQQG8faDi1tcdini-mXe420zAQibkGWkIH4tIvMGZV8LuxpKgTHQijYZdv59XZZixOCrTaveLXydOqPCHf40N3x5bdmnmsfaKINO9JPkX_xG1i7W8CAiK4X0YYsxKFpNv_mwToam0qJdiO6JE8fKpLpBcD9Se-T43IjiNB3OW2lRJxgk1Gbq7Qt9Z63vUwTIbWRoeQtLjFynFwNMCWIzx028OpWrM9j7RqEqZUaXoPl7CmxoqSJvPbsC8o4ab-D6Yye4yfJ7ukku4XMv7f6-UkPauxV4aBjS4MIfg6rH4LJyh_qXl_XfPcc906ppi_I4OXat7L2xsmVoyCyjbcGTawg1OgAIwN8uso-Z1glZJUhTZXznk180yK8ZaS_eEnGSliT0Lnont5eTjuwqcI-lnjvNkHII7xuPad87lCyqJTDk_U0ABaJD17LIYvhdCMCREl1_uJk7kHf2eHP1m3jVp3RKsSLlnOl6tYHm0TnUgTniRi1QCzaf-faotaodUdTJrKOF4TzBng5SywjfhXnq1Bx3Am7iub-NqEhDuKqZU23DkNbsLlAawRQpFN4jcMk465OR5cRceB57HIN0NmYICfAxyfAh3onLvnM4bYsbPN4-2R4xDfsFMwLCrq2l3fS5bC5HybXv7PGY_6kilsB0qnK-SIv8OhY4LvA0gbE7RvV3YOzpImtvMUdA1DCX0t9DgfSZLcHn8dlVKVWNaXRqbCmxBGGn6oqFi2nV2INt1hXuKQi11DE6vkDS1HsSk8vENd0hfc7XXpBkGN9mZ7zBydabPNarUpMpQlaUaCcSK5itd3s0I-hafml05N9iB7_Y77_QGgmnT434wP-9VDpmobuzmaiqvb-p4F6ZN1zD6N3nlrF4t5M4L9-TewouSqVG3CoQa7diN_e2vwYuxcY6Jh3hYWKFrJXoh2jZ9TH181T9QBnK_B_FabPqfrt7aoK9xlvyEJPvtkpfoqhhoLaeUaMmsHUqYalULnF4s3Hvm04iH7Zz4gVQBwYUtuMFJyyb05i-J3iQuNVSNar5ALKeOq2bZ7PDbM11N6AyHvhqucuGfCNGEcbhD70aB9mAORX-OvxjJTHMZoZE9eQzyVnOi4G2d_tYPm9sYEwnc2I63MHPIamPafKRo2MtpgBM-ow6i1hgMHm3umCyahHouQz-vFxS-gkNpedUJ7FNjKaVHxA4oj8B2rzG47ujLtIk2-wILdfWEpuRyU9KMT9d8WQJ56JNQGJ6vK6MxENDaapwv7UyMzUsDTEqmdpgmAEMTy1MlIdwfZVac3JuhG8srYCxPpeIBVyFXTAmkBOZQMCH4JE5Tzy5x5QraJ2aW6fYgqIKD3Ly43P3PG2t4XY7SvcIi1L4lTRXGo_V5hcYKDLXOhSFPn8oYM3DpQK75Ex7s596kONQsvFqbmKaavdaU6OQCd8RHPPFrS8YfbUvTrG6Q6IvMhtMglliW_XtgywvPnQh4jUb9Zk4tgHAyCYzXvxibvh8u4ipXKPSchMVQKsdDVKgZwYeSH0xngHEq1v6MIHPXUwgHGwrPghvuEuLQfFoADMNvOZ67qCPhEcy2PicnXvnPnB4hUsbNRDoSS26ewdNW73j10rfl38dMFm71E4VXVb1jc5IK7uSEr7o0TFPYcFdp8NW8mdlRn31mrWBlCsRDaiYEVc4oV7i5WOhXH1Ua-zO_evuyyBoFvC5hjXCluCYPzm6bxIovCb-VsTPKr-NT_3jMaKXXeBrB4qA1Lf_M9hBpJ65BjwcrhR0c9CeMfhLaymuLZh0c15-KtKMlB0tgwfjW28Bw406z3pSoywnU1Wem40K5jNTKqkUNdSprscjRsIoqIN2BntJAyX5Q2ARXj2F4wJYVNt06QfARc4ZkXvmWCWoAwjro5aRcpKqD2siAqbBGE5brpk9gQBrt9n-SRzxRoMOyU_TYCE_qoikSKBN5MkDVnyFxZGtlGV6q3wPqpYTs6fpzHsbXyG1RZYfGTlvhQSEaW0Rdl-whi4Zovvr7jqIx-qLZo_bI0FyGkxtEK1upmsRnqMuEYlPFUmRY5DCF80eGRtGicZPUtjTBmGTxV6Mq5SuZ2PeVjUMpVicjAQ-UG3SrKcdNUqhXf2PLpsqz6aFTcEzoZoTIORhyTWAz-_gPx7yQXzArm7NWFsxlTXYK8a-6NX4zsWl0_NnwOjotJiI-h-KT8o4wmWm9zpEreuWbgP_WovLSMLpKTJhxKvSfZ_c1iWheEnR3LTTODGSl9cZYhbV4b7kcq6jHrU-UrodMhVREe4ao8hShH9rx7UgA43HH6k5He_8-TETuaaKdiomcLM96vc5Olvh_E2_vxUjQoPq4ylHUlRp3d3La6BuaYdvuXKsywUKqr5X4zIlKdHsnOI6N4M2Prvf7yFPGIIO0vNlvKYr2QRoESzI-a7j1fUv4NMY9kv_RpWE5FQ9qyw_MFs2jMYVqsxBJ3wcTE7ueTPXajIT4LaL9UxzLi_zmLhvY1a-bLfnIJrYIj7jiSv4TZbZdTZInByTMghnovaD4JqxsTTw2XwloSExlEQa5tly964XZPTBP4GQcWAHjWzd0m2i5HB9YmTYKH9W_pnoIgW7fKh4wJpvMwBbPNrXhQf7a8SG3alXHjeBfsThAaWDMpioMywJ4SgSVC7_5bOPP89k_niI7iQ2xSghUnavWgFqXp3KxMNyi2dRz6ZePtuUb9fXTnu2M-ueWoKI4J8xRCgkRd5czuTbFBjZXkB2kAU3PsFj2drM2uwaJuKS_lxXvEE-IkANZWphlQdeA49xqO1JzA5DNdJT_hW0Orrjk7NjrHVAZMebJ85HaK9vSVxoIdA-9M60lfx295mXJgSwguO8X1wuJPbc55JRLph2q9CzlTVc1UXovzaokspgNBaMhDeE0lBXLITvJUC9Ydt-1n7aJHHdpG1qY5AQiA_Bcb_QJQ438L7FclzSLSPQ7CMHzFQg_p6eMb7st8yP-F-4pyJ9c3HU-zrOsZeWi4-WlUdP4UMuqZudq36ELhtVZplHAHFSaZ0_S1tF8xxvPiknFnaVaNyncsihAB8x5DxEb5Q-01r8ZezEKC4nGds20Mr4dhbHoi2DhYWWVuTPCbuam8y0zkavANfgRnzjJmHsJ11S3FMJhLW6xTiqVJGlrXB24OXVbGV4ftpO12wQ-8kBrbGWHpzAv7GZyzCraUs5RBLdv5RnucNlDAYuMJPlox1HkEHxsiJ4XqR7RyMKME0MkXcnWjNwpuzt7lP2TUqZI-NCizJzRBPfiOZ7FFBYwRIaxyxzL-bcHtI1bDtcbByWryoujl6Wu3d6T1R6LM_XoIT8H_UmEd5A8P9S_FVTWK_LTVDvEjNwjzbSvX7Oh480xgD8NFI_geTMGBu1lpmjygwaIofOi8tH28jLgupSQHEoIpLcvLQRsBNim7D7mKe0H2tw82ruk7yYfnmlovu5yqPMKa4u2XwxtUJkkRd9OCEnhvPh-WYXkUVOeBNrsF5ffYSr_Yd4oyBYE8wg0vo2qo2a4erQoYIvAqfTc70FIRYV9EOHYhddJevVyxD4pKxgThTetmBJ51bAHyUESHB_Z56yyNgEyWMtorUmaHSPrf7-gEpHoMo6hXmCrfg4uZfEE4mA4DUsF9bwUVOdmAWCH2VHDl4_rEE36nwv0Rkno_LoD5iTdY0-nZogmndhs5Vvl9DbVUWr3DtzSnq3QpkAGNnmrTbBHC58qQF3CL0Y7BWV2Xs14GoZclzVKRa94QaVphOMSD_alysDncSjo0SEgynSoDQyZiss9j4nceWNLEmbBSHk0qoTVheuYNM4-XI2D9ndZFlcxDP-EbJJD4nr4_LKq9jGfXytdYD0TvONQMyo3HYKkK2ARl1_9xaIGUcqdUU7r5JgUsyrqoLGfi8UL_-fWGaKGlmrFzlo5FeLpg4Zi2B0GUbh5AS-OE_dfNPQfJYa7KLyOAuLeR0pQI2PNwxd3f1MTfRspmx0gH90BEil5t0Pssvn4eywoOa68xzt0axTkePd1SeZjvCIhskS1xrI=
```

**Example Response (verified case):**

```json
{
    "object": {
        "errMsg": null,
        "vcDetail": [
            {
                "id": "did:zid:acfe353cc72104161d7f61b94101eafeb96b011f10ae582b54825335efba48ca",
                "issuer": "did:zid:0d48916e8b0f10297b023b680fb7ab2367d5eb03a1a6bb876d63d1a9f5677dcb",
                "validFrom": "2025-01-01T00:00:00Z",
                "validUntil": "2026-01-01T00:00:00Z",
                "credentialSubject": {
                    "id": "did:zid:ba4f1fcf68831a5c689dfaa2195da1a3a7c37930228f886611f936fed0df66b9",
                    "passportMalaysia": {
                        "name": "Ali bin Abu",
                        "class": "B2",
                        "age": "21",
                        "gender": "Male"
                    }
                }
            }
        ],
        "verified": true
    },
    "messages": []
```

*(In this example, the licenseNumber wasn’t revealed, but the verifier knows it was in the specified range, hence a checkmark or note is given instead of a value.)*

**Example Response (failure case):**

```json
{
  "verified": false,
  "status": "revoked",
  "errors": [
    "Credential status is revoked as of 2025-04-01",
    "Holder signature invalid"
  ]
}
```

*(This example shows a scenario where verification failed. It indicates the credential had been revoked and additionally the holder’s signature didn’t match, either of which would invalidate the VP.)*

**Error Cases:**

* `400 Bad Request` – The provided `vpObject` is missing or not a valid presentation format. For instance, if required fields are missing or the JSON is malformed.
* `500 Internal Server Error` – An unexpected error occurred during verification. This could be due to an inability to reach the DID resolver (to fetch issuer or holder public keys), or a failure in cryptographic verification that didn’t properly set an error message. If this occurs, `verified` might be false by default.

During verification, the following checks are performed internally (each must pass for `verified` to be true):

* **Signature Checks:** The holder’s signature on the presentation is verified using the holder’s public key (retrieved via `publicKey` provided or via the holder’s DID document). The BBS+ proof inside the VP is verified using the issuer’s BBS+ public key (retrieved from the issuer’s DID document, presumably via the DID Resolver).
* **Data Integrity:** It ensures that the revealed attributes in the VP match the values that were originally signed in the credential (the BBS+ proof ties them). Any tampering would break the proof verification.
* **Non-Disclosure:** It confirms that no more information than requested is revealed (i.e., hidden attributes remain hidden except for what the proof inherently reveals, like perhaps the bounds in a range proof).
* **Status Check:** The credential’s status (often indicated by `credentialStatus.id` in the VC) is checked on-chain (or in the relevant registry) to ensure the credential is not revoked or expired. If the VC has an expiry date, that is also checked to ensure it’s still valid at verification time.
* **Challenge Check:** If a `challenge` (nonce) was included in the VP, verify that it matches what was expected (this prevents replays – usually the verifier provides the challenge and knows what to expect).

If all checks pass, the presentation is valid and the disclosed information can be trusted by the verifier. Otherwise, the presentation should be rejected.


# Blockchain as a Services(BaaS)

**Blockchain as a Service (BaaS)** is a **cloud-based blockchain infrastructure** that enables customers to create, deploy and manage blockchain applications without the complexity of setting up and managing their own blockchain infrastructure. BaaS is an **end-to-end solution** that provides all the necessary tools and services to create and run a blockchain network, including development tools, infrastructure, security, and support services.

BaaS providers offer access to blockchain nodes and operate them on behalf of their customers. They offer a range of services, including blockchain hosting, development kits, smart contract management, and integration with other platforms.

By harnessing the power of cloud technology and blockchain, BaaS providers offer a low-cost and convenient way for businesses to access the benefits of blockchain technology without having to invest in expensive hardware infrastructure, specialized software and IT expertise.

Some of the advantages of BaaS include:

1. Easy and quick deployment: BaaS platforms provide a simple and easy way to create, manage, and deploy blockchain applications.
2. Seamless integration: BaaS can integrate with existing enterprise systems and third-party applications, creating a seamless infrastructure that streamlines workflows and reduces business costs.
3. Cost-effective: BaaS eliminates the initial costs associated with setting up and running a blockchain infrastructure, as well as the maintenance and upgrade costs.
4. Scalability: BaaS can scale up and down to meet the needs of businesses of all sizes, allowing them to access the benefits of blockchain technology without having to invest in expensive hardware infrastructure.


# Zetrix Service

Zetrix API services.

A Zetrix BaaS API allows developers to interact with the underlying blockchain network and utilize its features and functionality through a standardized interface. Some common capabilities provided by a BaaS API include:

1. **Blockchain Account Management:** APIs to create, configure, and manage account API provides programmatic access on a blockchain network.
2. **Smart Contract Deployment and Execution**: APIs to deploy smart contracts to the blockchain network and invoke their functions. This includes functions for compiling, deploying, and interacting with smart contracts.
3. **Crosschain Blockchain** APIs: Typically use a set of methods to interact with smart contracts and other systems across different blockchain networks.
4. **Transaction and Data Management:** APIs for creating, signing, and submitting transactions to the blockchain network. They may also provide functionality for querying transaction status, retrieving transaction history, and managing data on the blockchain.
5. **Verifiable Credential :** APIs for managing user identities, permissions, and access controls on the blockchain network. Zetrix Verifiable Credential Certs and its API allow you to generate and digitally sign Verifiable Credentials.

The **endpoints for Zetrix BaaS API** for both mainnet and testnet are defined as

1. <https://api-sandbox.zetrix.com> (Zetrix Testnet)
2. <https://api-v2.zetrix.com> (Zetrix Mainnet)

Access to BaaS services requires users to register an account on [ZPlatform](https://docs.zetrix.com/en/developer-resources/zplatform-baas-api).

#### Authorization

All API requests must include **both** the API Gateway key and the access token:

* **API Gateway Key:** Include in the header `X-API-Key`.
* **Access Token:** Include in the header `Authorization: Bearer <access_token>`.

#### Access Token

```http
Authorization : Bearer <ACCESS_TOKEN>
```

#### API Gateway Authentication

All requests to the Zetrix API Gateway **must** include the following header:

**Testnet**

```http
X-API-Key:ehg7q2i6aN8jY6BbHqN5q42KsHQFRwl260jqAkAU
```

**Mainnet**

```http
X-API-Key:OOXtr6biOR6eJa2Rjj9En4PwDxxl0U2haUohaxrC
```

**Example (curl)**

```bash
curl -X GET https://<api-endpoint> \
  -H "X-API-Key: ehg7q2i6aN8jY6BbHqN5q42KsHQFRwl260jqAkAU" \
  -H "Authorization: Bearer <your_access_token>" \
  -H "Content-Type: application/json"
```

**Notes**

* The `X-API-Key` header is **required** for all API Gateway requests.
* Requests without a valid API key will be rejected with an authorization error.


# Core

Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply.

## Get current block height

> Returns the current (latest) block height of the Zetrix blockchain. The block height is a sequential integer representing the most recently confirmed block.\
> \
> \*\*Use Cases:\*\*\
> \- Verify the network is active and progressing\
> \- Use as a reference point for auditing transaction timing\
> \- Monitor chain health during integration testing

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ResponseWrapperLong":{"type":"object","properties":{"object":{"type":"integer","format":"int64","description":"The numeric value (e.g., block height)."},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/core/block-height":{"get":{"tags":["Core"],"summary":"Get current block height","operationId":"getBlockHeight","description":"Returns the current (latest) block height of the Zetrix blockchain. The block height is a sequential integer representing the most recently confirmed block.\n\n**Use Cases:**\n- Verify the network is active and progressing\n- Use as a reference point for auditing transaction timing\n- Monitor chain health during integration testing","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"responses":{"200":{"description":"Current block height.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperLong"}}}}}}}}}
```

## Get blockchain overview

> Returns a comprehensive snapshot of the Zetrix blockchain's current state, including transaction counts, account counts, TPS metrics, average block generation time, and the latest ledgers and transactions.\
> \
> \*\*Returned Metrics:\*\*\
> \- \`blockchainHeight\` — Current block height\
> \- \`transactionNum\` — Total transactions on-chain\
> \- \`accountNum\` — Total accounts created\
> \- \`txTpsMax\` / \`currentTps\` — Maximum and current transactions per second\
> \- \`blockAverageGeneTime\` — Average block generation time in milliseconds\
> \- \`netStatus\` — Network health status (\`NORMAL\`, \`DEGRADED\`)\
> \- \`lastLedgerList\` — Most recent blocks\
> \- \`lastTxList\` — Most recent transactions

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ResponseWrapperDSMonitoringBlockchain":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/DSMonitoringBlockchain"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringBlockchain":{"type":"object","description":"Comprehensive blockchain network statistics.","properties":{"chainId":{"type":"integer","format":"int64"},"chainName":{"type":"string"},"blockchainHeight":{"type":"integer","format":"int64"},"transactionNum":{"type":"integer","format":"int64"},"accountNum":{"type":"integer","format":"int64"},"txTpsMax":{"type":"integer","format":"int32"},"currentTps":{"type":"integer","format":"int32"},"txNumLastDay":{"type":"integer","format":"int64"},"blockAverageGeneTime":{"type":"integer","format":"int32"},"netStatus":{"type":"string"},"lastLedgerList":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringLedger"}},"lastTxList":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringTx"}}}},"DSMonitoringLedger":{"type":"object","properties":{"seq":{"type":"integer","format":"int64","description":"Block sequence number."},"txNum":{"type":"integer","format":"int64","description":"Transactions in this block."},"ledgerAge":{"type":"integer","format":"int64","description":"Age in milliseconds."}}},"DSMonitoringTx":{"type":"object","properties":{"senderAddress":{"type":"string"},"txHash":{"type":"string"},"txTime":{"type":"integer","format":"int64"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/core/blockchain-info":{"get":{"tags":["Core"],"summary":"Get blockchain overview","operationId":"getBlockchainInfo","description":"Returns a comprehensive snapshot of the Zetrix blockchain's current state, including transaction counts, account counts, TPS metrics, average block generation time, and the latest ledgers and transactions.\n\n**Returned Metrics:**\n- `blockchainHeight` — Current block height\n- `transactionNum` — Total transactions on-chain\n- `accountNum` — Total accounts created\n- `txTpsMax` / `currentTps` — Maximum and current transactions per second\n- `blockAverageGeneTime` — Average block generation time in milliseconds\n- `netStatus` — Network health status (`NORMAL`, `DEGRADED`)\n- `lastLedgerList` — Most recent blocks\n- `lastTxList` — Most recent transactions","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"responses":{"200":{"description":"Blockchain overview and statistics.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperDSMonitoringBlockchain"}}}}}}}}}
```

## Get node statistics

> Returns aggregated statistics for all validator and synchronous nodes on the Zetrix network.\
> \
> \*\*Returned Data:\*\*\
> \- \`total\` — Total number of nodes\
> \- \`validatorNodeStat\` — Online/offline/warning counts for validator nodes\
> \- \`synchronousNodeStat\` — Online/offline/warning counts for sync nodes\
> \
> \*\*Use Cases:\*\*\
> \- Monitor network health and node availability\
> \- Alert on high offline or warning node counts

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ResponseWrapperDSMonitoringNodeStatWrapper":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/DSMonitoringNodeStatWrapper"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringNodeStatWrapper":{"type":"object","properties":{"total":{"type":"integer","format":"int32","description":"Total nodes across all types."},"validatorNodeStat":{"$ref":"#/components/schemas/DSMonitoringNodeStat"},"synchronousNodeStat":{"$ref":"#/components/schemas/DSMonitoringNodeStat"}}},"DSMonitoringNodeStat":{"type":"object","properties":{"total":{"type":"integer","format":"int32"},"onlineCount":{"type":"integer","format":"int32"},"offlineCount":{"type":"integer","format":"int32"},"warnCount":{"type":"integer","format":"int32"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/core/node-stat":{"get":{"tags":["Core"],"summary":"Get node statistics","operationId":"getNodeStat","description":"Returns aggregated statistics for all validator and synchronous nodes on the Zetrix network.\n\n**Returned Data:**\n- `total` — Total number of nodes\n- `validatorNodeStat` — Online/offline/warning counts for validator nodes\n- `synchronousNodeStat` — Online/offline/warning counts for sync nodes\n\n**Use Cases:**\n- Monitor network health and node availability\n- Alert on high offline or warning node counts","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"responses":{"200":{"description":"Node statistics for validator and synchronous nodes.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperDSMonitoringNodeStatWrapper"}}}}}}}}}
```

## Get paginated node list

> Returns a paginated list of blockchain nodes, filterable by node type. Each entry includes address, status, type, OS, block sync state, and certificate/license expiry.\
> \
> \*\*Parameters:\*\*\
> \- \`nodeType\` — Filter by type: \`VALIDATOR\` or \`SYNCHRONOUS\`\
> \- \`pageNo\` — Page number (1-based)\
> \- \`pageSize\` — Records per page

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ResponseWrapperDSMonitoringPagination":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/DSMonitoringPagination"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringPagination":{"type":"object","properties":{"pageNum":{"type":"integer","format":"int32"},"pageSize":{"type":"integer","format":"int32"},"total":{"type":"integer","format":"int32"},"content":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringNodeList"}}}},"DSMonitoringNodeList":{"type":"object","description":"Details of an individual blockchain node.","properties":{"nodeName":{"type":"string","description":"Human-readable node name."},"nodeAddress":{"type":"string","description":"Zetrix address of the node."},"consensusAddress":{"type":"string"},"nodeType":{"type":"string","description":"`VALIDATOR` or `SYNCHRONOUS`."},"nodeStatus":{"type":"string","description":"`ONLINE`, `OFFLINE`, or `WARN`."},"operatingSystem":{"type":"string"},"blockSeq":{"type":"string","description":"Latest synced block number."},"blockHash":{"type":"string"},"expirationTime":{"type":"string"},"certEndTime":{"type":"string"},"licenseEndTime":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/core/node-list":{"get":{"tags":["Core"],"summary":"Get paginated node list","operationId":"getNodeList","description":"Returns a paginated list of blockchain nodes, filterable by node type. Each entry includes address, status, type, OS, block sync state, and certificate/license expiry.\n\n**Parameters:**\n- `nodeType` — Filter by type: `VALIDATOR` or `SYNCHRONOUS`\n- `pageNo` — Page number (1-based)\n- `pageSize` — Records per page","parameters":[{"$ref":"#/components/parameters/X-API-Key"},{"name":"nodeType","in":"query","required":true,"description":"Type of node to list. Accepted values: `VALIDATOR`, `SYNCHRONOUS`.","schema":{"type":"string"}},{"name":"pageNo","in":"query","required":true,"description":"Page number (1-based).","schema":{"type":"integer","format":"int32"}},{"name":"pageSize","in":"query","required":true,"description":"Number of records per page.","schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Paginated node list.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperDSMonitoringPagination"}}}}}}}}}
```

## Get node count by geography

> Returns the count of blockchain nodes grouped by geography code. Useful for visualizing the geographic distribution of the Zetrix network.\
> \
> \*\*Response:\*\*\
> A list of objects, each with a \`geographyCode\` (numeric ISO region identifier) and a \`total\` node count for that region.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ResponseWrapperListDSMonitoringNode":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringNode"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringNode":{"type":"object","description":"Node count for a geographic region.","properties":{"geographyCode":{"type":"integer","format":"int32","description":"Numeric ISO country/region code."},"total":{"type":"integer","format":"int32","description":"Number of nodes in this region."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/core/node-count":{"get":{"tags":["Core"],"summary":"Get node count by geography","operationId":"getNodeInfo","description":"Returns the count of blockchain nodes grouped by geography code. Useful for visualizing the geographic distribution of the Zetrix network.\n\n**Response:**\nA list of objects, each with a `geographyCode` (numeric ISO region identifier) and a `total` node count for that region.","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"responses":{"200":{"description":"Node counts grouped by geography code.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperListDSMonitoringNode"}}}}}}}}}
```

## Get total ZTX supply

> Returns the total supply of ZTX tokens ever created on the Zetrix blockchain — the maximum possible supply including all tokens in circulation, locked, or staked.\
> \
> \*\*Note:\*\* Returns a string to preserve precision for large integer values.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}}},"paths":{"/ztx/core/total-supply":{"get":{"tags":["Core"],"summary":"Get total ZTX supply","operationId":"getTotalSupply","description":"Returns the total supply of ZTX tokens ever created on the Zetrix blockchain — the maximum possible supply including all tokens in circulation, locked, or staked.\n\n**Note:** Returns a string to preserve precision for large integer values.","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"responses":{"200":{"description":"Total ZTX token supply as a string.","content":{"*/*":{"schema":{"type":"string"}}}}}}}}}
```

## Get circulating ZTX supply

> Returns the current circulating supply of ZTX tokens — the amount actively in circulation, excluding locked, burned, or reserved tokens.\
> \
> \*\*Note:\*\* Returns a string to preserve precision for large integer values.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Core","description":"Blockchain network monitoring endpoints. Retrieve block height, blockchain statistics, node lists, node counts by geography, total ZTX supply, and circulating supply."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}}},"paths":{"/ztx/core/circulation-supply":{"get":{"tags":["Core"],"summary":"Get circulating ZTX supply","operationId":"getCirculationSupply","description":"Returns the current circulating supply of ZTX tokens — the amount actively in circulation, excluding locked, burned, or reserved tokens.\n\n**Note:** Returns a string to preserve precision for large integer values.","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"responses":{"200":{"description":"Current circulating ZTX supply as a string.","content":{"*/*":{"schema":{"type":"string"}}}}}}}}}
```


# Transaction

Full transaction lifecycle operations on the Zetrix blockchain. Covers generating, signing, parsing, submitting, and querying both **standard transactions** (user pays gas) and **paymaster-sponsored transactions** (gas-free for users). Typical standard flow: generate blob → sign blob → submit → query.

## Generate transaction blob

> Generates a serialized transaction blob for a standard transaction where the \*\*user pays gas fees\*\*.\
> \
> \*\*Flow:\*\*\
> 1\. Call this endpoint with \`txInitiator\` (the address paying gas) and \`operations\`\
> 2\. Receive \`blob\` and \`hash\`\
> 3\. Sign using \`/tx/sign-blob\` or your own Ed25519 signer\
> 4\. Submit via \`/tx/submit\`\
> \
> \*\*Operations:\*\*\
> The \`operations\` array defines what the transaction does. The \`type\` field is a numeric string:\
> \- \`1\` = Create Account\
> \- \`2\` = Built-in points transfer\
> \- \`3\` = Call contract\
> \- \`4\` = Create contract\
> \- \`5\` = Set up account metadata\
> \- \`6\` = Set account privilege\
> \- \`7\` = Upgrade contract content\
> \- \`8\` = Upgrade contract owner\
> \
> \*\*Note:\*\* For gas-free transactions, use \`/tx/paymaster/generate-blob\` instead.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Transaction","description":"Full transaction lifecycle operations on the Zetrix blockchain. Covers generating, signing, parsing, submitting, and querying both **standard transactions** (user pays gas) and **paymaster-sponsored transactions** (gas-free for users). Typical standard flow: generate blob → sign blob → submit → query."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"GenerateBlobReqDto":{"type":"object","description":"Request to generate a transaction blob where the user pays gas fees.","required":["operations","txInitiator"],"properties":{"txInitiator":{"type":"string","description":"Zetrix address of the account initiating and paying gas for the transaction."},"operations":{"type":"array","description":"List of operations to execute.","items":{"$ref":"#/components/schemas/OperationsEntity"}},"chainCode":{"type":"string","description":"Chain code identifier. Defaults to `\"0\"`.","default":"0"}}},"OperationsEntity":{"type":"object","description":"A single operation to execute in a transaction. The fields used depend on the operation `type`.","properties":{"type":{"type":"string","description":"Operation type as a numeric string. `1` = Create Account, `2` = Built-in points transfer, `3` = Call contract, `4` = Create contract, `5` = Set up account metadata, `6` = Set account privilege, `7` = Upgrade contract content, `8` = Upgrade contract owner.","enum":["1","2","3","4","5","6","7","8"]},"toAddress":{"type":"string","description":"Destination Zetrix address for transfer-type operations."},"fromAddress":{"type":"string","description":"Source address override (defaults to `txInitiator` if omitted)."},"amount":{"type":"string","description":"Amount in drops (1 ZETRIX = 10^6 drops)."},"inputStr":{"type":"string","description":"JSON-encoded input for contract invocation operations."},"payload":{"type":"string","description":"Contract payload or bytecode (used in contract deployment)."},"precision":{"type":"string","description":"Asset precision (used in asset issuance)."},"metadata":{"type":"string","description":"Optional arbitrary metadata string attached to the operation."}}},"ResponseWrapperGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/GenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"GenerateBlobRespDto":{"type":"object","description":"Response for transaction blob generation.","required":["blob","hash"],"properties":{"blob":{"type":"string","description":"Hex-encoded serialized transaction blob. Sign before submitting."},"hash":{"type":"string","description":"SHA-256 transaction hash. Required when calling `/tx/sign-blob`."},"actualFee":{"type":"integer","format":"int64","description":"Estimated transaction fee in gas units."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/generate-blob":{"post":{"tags":["Transaction"],"summary":"Generate transaction blob","operationId":"generateBlob","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Generates a serialized transaction blob for a standard transaction where the **user pays gas fees**.\n\n**Flow:**\n1. Call this endpoint with `txInitiator` (the address paying gas) and `operations`\n2. Receive `blob` and `hash`\n3. Sign using `/tx/sign-blob` or your own Ed25519 signer\n4. Submit via `/tx/submit`\n\n**Operations:**\nThe `operations` array defines what the transaction does. The `type` field is a numeric string:\n- `1` = Create Account\n- `2` = Built-in points transfer\n- `3` = Call contract\n- `4` = Create contract\n- `5` = Set up account metadata\n- `6` = Set account privilege\n- `7` = Upgrade contract content\n- `8` = Upgrade contract owner\n\n**Note:** For gas-free transactions, use `/tx/paymaster/generate-blob` instead.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateBlobReqDto"}}}},"responses":{"200":{"description":"Transaction blob generated successfully. Sign the `blob` and submit via `/tx/submit`.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperGenerateBlobRespDto"}}}}}}}}}
```

## Sign transaction blob

> Signs a transaction blob using one or more private keys. A convenience helper for Ed25519 signing on the server side.\
> \
> \*\*Output:\*\*\
> Returns a \`listSigner\` array — one entry per key — each containing \`signBlob\` (signature) and \`publicKey\`. Pass this directly to \`/tx/submit\` or \`/contract/submit\`.\
> \
> \*\*Security Note:\*\*\
> You are transmitting private keys over the network. Ensure HTTPS is used. For higher-security environments, consider client-side signing instead.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Transaction","description":"Full transaction lifecycle operations on the Zetrix blockchain. Covers generating, signing, parsing, submitting, and querying both **standard transactions** (user pays gas) and **paymaster-sponsored transactions** (gas-free for users). Typical standard flow: generate blob → sign blob → submit → query."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"BlobDataReqDto":{"type":"object","description":"Request body for server-side blob signing.","properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob to sign."},"hash":{"type":"string","description":"64-character transaction hash associated with the blob.","minLength":64,"maxLength":64},"privateKeys":{"type":"array","description":"List of Ed25519 private keys (each exactly 56 characters). One `SignerEntity` is returned per key.","minItems":1,"items":{"type":"string","minLength":56,"maxLength":56}}}},"ResponseWrapperListSignerEntity":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/SignerEntity"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/sign-blob":{"post":{"tags":["Transaction"],"summary":"Sign transaction blob","operationId":"signBlob","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Signs a transaction blob using one or more private keys. A convenience helper for Ed25519 signing on the server side.\n\n**Output:**\nReturns a `listSigner` array — one entry per key — each containing `signBlob` (signature) and `publicKey`. Pass this directly to `/tx/submit` or `/contract/submit`.\n\n**Security Note:**\nYou are transmitting private keys over the network. Ensure HTTPS is used. For higher-security environments, consider client-side signing instead.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BlobDataReqDto"}}}},"responses":{"200":{"description":"Blob signed. Use the returned `listSigner` in `/tx/submit` or `/contract/submit`.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperListSignerEntity"}}}}}}}}}
```

## Submit transaction

> Submits a \*\*signed transaction blob\*\* synchronously to the Zetrix blockchain where the user pays gas fees. Blocks until the transaction is confirmed or rejected.\
> \
> \*\*Pre-conditions:\*\*\
> \- \`blob\` from \`/tx/generate-blob\`\
> \- \`listSigner\` from \`/tx/sign-blob\` or your own signer\
> \
> \*\*After submission:\*\*\
> Use the returned \`hash\` to track via \`/tx/query\`.\
> \
> \*\*Note:\*\* For gas-free submission, use \`/tx/paymaster/submit\` instead.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Transaction","description":"Full transaction lifecycle operations on the Zetrix blockchain. Covers generating, signing, parsing, submitting, and querying both **standard transactions** (user pays gas) and **paymaster-sponsored transactions** (gas-free for users). Typical standard flow: generate blob → sign blob → submit → query."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"SubmitTxReqDto":{"type":"object","description":"Request body for submitting a signed transaction.","required":["blob","listSigner"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob from `/tx/generate-blob`. Must not be modified."},"listSigner":{"type":"array","description":"List of signers. At least one entry required.","minItems":1,"items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseWrapperTxSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/TxSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"TxSubmitRespDto":{"type":"object","properties":{"hash":{"type":"string","description":"Transaction hash confirming successful broadcast."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/submit":{"post":{"tags":["Transaction"],"summary":"Submit transaction","operationId":"submit","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Submits a **signed transaction blob** synchronously to the Zetrix blockchain where the user pays gas fees. Blocks until the transaction is confirmed or rejected.\n\n**Pre-conditions:**\n- `blob` from `/tx/generate-blob`\n- `listSigner` from `/tx/sign-blob` or your own signer\n\n**After submission:**\nUse the returned `hash` to track via `/tx/query`.\n\n**Note:** For gas-free submission, use `/tx/paymaster/submit` instead.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmitTxReqDto"}}}},"responses":{"200":{"description":"Transaction submitted and confirmed. Use `hash` to query status.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperTxSubmitRespDto"}}}}}}}}}
```

## Parse transaction blob

> Decodes a hex-encoded transaction blob and returns its human-readable contents: source address, operations, nonce, gas parameters, and chain ID.\
> \
> \*\*Use Cases:\*\*\
> \- Verify what operations are encoded before signing\
> \- Debug or audit transaction contents\
> \- Display transaction details to users for confirmation\
> \
> \*\*Note:\*\* Read-only — does not interact with the blockchain.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Transaction","description":"Full transaction lifecycle operations on the Zetrix blockchain. Covers generating, signing, parsing, submitting, and querying both **standard transactions** (user pays gas) and **paymaster-sponsored transactions** (gas-free for users). Typical standard flow: generate blob → sign blob → submit → query."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ParseBlobReqDto":{"type":"object","description":"Request to parse a transaction blob.","required":["blob"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob to decode."}}},"ResponseWrapperTransactionParseBlobResult":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/TransactionParseBlobResult"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"TransactionParseBlobResult":{"type":"object","description":"Decoded contents of a transaction blob.","properties":{"sourceAddress":{"type":"string","description":"Address that initiated the transaction."},"feeLimit":{"type":"integer","format":"int64","description":"Maximum gas fee allowed."},"gasPrice":{"type":"integer","format":"int64","description":"Gas price per unit."},"nonce":{"type":"integer","format":"int64","description":"Transaction sequence number."},"chainId":{"type":"integer","format":"int64","description":"Zetrix chain identifier."},"operations":{"type":"array","items":{"$ref":"#/components/schemas/OperationFormat"}}}},"OperationFormat":{"type":"object","description":"Decoded operation from a parsed blob.","properties":{"type":{"type":"string"},"sourceAddress":{"type":"string"},"metadata":{"type":"string"},"sendGas":{"$ref":"#/components/schemas/GasSendInfo"},"sendAsset":{"$ref":"#/components/schemas/AssetSendInfo"},"setMetadata":{"$ref":"#/components/schemas/AccountSetMetadataInfo"},"log":{"$ref":"#/components/schemas/LogInfo"}}},"GasSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"amount":{"type":"integer","format":"int64"},"input":{"type":"string"}}},"AssetSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"input":{"type":"string"}}},"AccountSetMetadataInfo":{"type":"object","properties":{"key":{"type":"string"},"value":{"type":"string"},"version":{"type":"integer","format":"int64"},"deleteFlag":{"type":"boolean"}}},"LogInfo":{"type":"object","properties":{"topic":{"type":"string"},"datas":{"type":"array","items":{"type":"string"}}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/parse-blob":{"post":{"tags":["Transaction"],"summary":"Parse transaction blob","operationId":"parseBlob","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Decodes a hex-encoded transaction blob and returns its human-readable contents: source address, operations, nonce, gas parameters, and chain ID.\n\n**Use Cases:**\n- Verify what operations are encoded before signing\n- Debug or audit transaction contents\n- Display transaction details to users for confirmation\n\n**Note:** Read-only — does not interact with the blockchain.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ParseBlobReqDto"}}}},"responses":{"200":{"description":"Blob parsed. Returns decoded transaction details.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperTransactionParseBlobResult"}}}}}}}}}
```

## Query transaction by hash

> Retrieves the status and full details of a submitted transaction using its transaction hash.\
> \
> For \`txStatus\` lifecycle codes and \`errorCode\` definitions, refer to the \[Zetrix WebSocket Error Codes]\(<https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes).\\>
> \
> \*\*Note:\*\* For paymaster transactions, allow a few seconds after submission before querying as processing is asynchronous.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Transaction","description":"Full transaction lifecycle operations on the Zetrix blockchain. Covers generating, signing, parsing, submitting, and querying both **standard transactions** (user pays gas) and **paymaster-sponsored transactions** (gas-free for users). Typical standard flow: generate blob → sign blob → submit → query."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ResponseWrapperTxQueryRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/TxQueryRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"TxQueryRespDto":{"type":"object","description":"Transaction query result.","properties":{"txStatus":{"type":"string","description":"Numeric transaction lifecycle status code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"txContent":{"$ref":"#/components/schemas/TransactionHistory"}}},"TransactionHistory":{"type":"object","description":"Full on-chain transaction record.","properties":{"hash":{"type":"string","description":"Transaction hash."},"ledgerSeq":{"type":"integer","format":"int64","description":"Block number the transaction was confirmed in."},"actualFee":{"type":"string","description":"Actual fee paid in drops."},"errorCode":{"type":"integer","format":"int32","description":"On-chain execution error code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"errorDesc":{"type":"string","description":"Error description if the transaction failed."},"closeTime":{"type":"integer","format":"int64","description":"Block close timestamp in milliseconds."},"txSize":{"type":"integer","format":"int64","description":"Transaction size in bytes."},"transaction":{"$ref":"#/components/schemas/TransactionInfo"},"signatures":{"type":"array","items":{"$ref":"#/components/schemas/Signature"}},"contractTxHashes":{"type":"array","items":{"type":"string"},"description":"Internal hashes from contract execution."}}},"TransactionInfo":{"type":"object","properties":{"sourceAddress":{"type":"string"},"feeLimit":{"type":"integer","format":"int64"},"gasPrice":{"type":"integer","format":"int64"},"nonce":{"type":"integer","format":"int64"},"chainId":{"type":"integer","format":"int64"}}},"Signature":{"type":"object","properties":{"signData":{"type":"string"},"publicKey":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/query":{"get":{"tags":["Transaction"],"summary":"Query transaction by hash","operationId":"queryTransaction","description":"Retrieves the status and full details of a submitted transaction using its transaction hash.\n\nFor `txStatus` lifecycle codes and `errorCode` definitions, refer to the [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes).\n\n**Note:** For paymaster transactions, allow a few seconds after submission before querying as processing is asynchronous.","parameters":[{"$ref":"#/components/parameters/X-API-Key"},{"name":"hash","in":"query","required":true,"description":"The 64-character transaction hash to look up.","schema":{"type":"string","minLength":64,"maxLength":64}}],"responses":{"200":{"description":"Transaction details returned.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperTxQueryRespDto"}}}}}}}}}
```


# Contract

Smart contract operations on the Zetrix blockchain. Covers blob generation, signing, submitting, read-only querying, and invocation history filtering for deployed contracts. Includes both standard (user pays gas) and paymaster-sponsored (gas-free) contract invocations.

## Generate contract invocation blob

> Generates a transaction blob for invoking a smart contract method. Either \`contractKey\` (a registered alias) or \`contractAddress\` (on-chain address) must be provided. If both are given, \`contractAddress\` takes precedence.\
> \
> \*\*Flow:\*\*\
> 1\. Call this endpoint with contract identifier, method name, and input parameters\
> 2\. Sign the returned \`blob\` using \`/contract/sign-blob\`\
> 3\. Submit via \`/contract/submit\`\
> \
> \*\*Value:\*\*\
> For payable contract methods, specify \`value\` in drops (1 ZETRIX = 10^6 drops). Use \`0\` for non-payable methods.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Contract","description":"Smart contract operations on the Zetrix blockchain. Covers blob generation, signing, submitting, read-only querying, and invocation history filtering for deployed contracts. Includes both standard (user pays gas) and paymaster-sponsored (gas-free) contract invocations."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ContractInvokeGenerateBlobReqDto":{"type":"object","description":"Request to generate a blob for a smart contract invocation.","required":["method"],"properties":{"contractKey":{"type":"string","description":"Registered contract alias. Either this or `contractAddress` must be provided."},"contractAddress":{"type":"string","description":"On-chain contract address. Takes precedence over `contractKey` if both are given."},"method":{"type":"string","description":"Contract method to invoke."},"inputParameters":{"type":"object","additionalProperties":{},"description":"Method input parameters. Structure depends on the contract's ABI."},"txInitiator":{"type":"string","description":"Address of the transaction initiator (pays gas).","minLength":37,"maxLength":37},"sourceAddress":{"type":"string","description":"Optional source address override."},"value":{"type":"integer","format":"int64","description":"ZTX value in drops to send with the invocation. Use `0` for non-payable methods."}}},"ResponseWrapperContractGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ContractGenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ContractGenerateBlobRespDto":{"type":"object","description":"Response for contract invocation blob generation.","properties":{"blob":{"type":"string","description":"Hex-encoded contract invocation blob."},"hash":{"type":"string","description":"Transaction hash."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/generate-blob":{"post":{"tags":["Contract"],"summary":"Generate contract invocation blob","operationId":"invokeGenerateBlobByKey","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Generates a transaction blob for invoking a smart contract method. Either `contractKey` (a registered alias) or `contractAddress` (on-chain address) must be provided. If both are given, `contractAddress` takes precedence.\n\n**Flow:**\n1. Call this endpoint with contract identifier, method name, and input parameters\n2. Sign the returned `blob` using `/contract/sign-blob`\n3. Submit via `/contract/submit`\n\n**Value:**\nFor payable contract methods, specify `value` in drops (1 ZETRIX = 10^6 drops). Use `0` for non-payable methods.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractInvokeGenerateBlobReqDto"}}}},"responses":{"200":{"description":"Contract invocation blob generated. Sign using `/contract/sign-blob` then submit via `/contract/submit`.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperContractGenerateBlobRespDto"}}}}}}}}}
```

## Sign contract invocation blob

> Signs a contract invocation blob using a single private key. Server-side Ed25519 signing convenience endpoint.\
> \
> \*\*Input:\*\*\
> \- \`blob\` — The hex-encoded blob from \`/contract/generate-blob\`\
> \- \`privateKey\` — A 56-character Ed25519 private key\
> \
> \*\*Output:\*\*\
> A \`SignerEntity\` list with \`signBlob\` (signature) and \`publicKey\`. Pass as \`listSigner\` to \`/contract/submit\`.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Contract","description":"Smart contract operations on the Zetrix blockchain. Covers blob generation, signing, submitting, read-only querying, and invocation history filtering for deployed contracts. Includes both standard (user pays gas) and paymaster-sponsored (gas-free) contract invocations."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ContractInvokeSignBlobReqDto":{"type":"object","description":"Request to sign a contract invocation blob using a single private key.","properties":{"blob":{"type":"string","description":"Hex-encoded contract invocation blob to sign."},"privateKey":{"type":"string","description":"56-character Ed25519 private key of the transaction initiator.","minLength":56,"maxLength":56}}},"ResponseWrapperListSignerEntity":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/SignerEntity"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/sign-blob":{"post":{"tags":["Contract"],"summary":"Sign contract invocation blob","operationId":"invokeSignBlob","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Signs a contract invocation blob using a single private key. Server-side Ed25519 signing convenience endpoint.\n\n**Input:**\n- `blob` — The hex-encoded blob from `/contract/generate-blob`\n- `privateKey` — A 56-character Ed25519 private key\n\n**Output:**\nA `SignerEntity` list with `signBlob` (signature) and `publicKey`. Pass as `listSigner` to `/contract/submit`.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractInvokeSignBlobReqDto"}}}},"responses":{"200":{"description":"Blob signed. Use the returned `listSigner` array in `/contract/submit`.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperListSignerEntity"}}}}}}}}}
```

## Submit signed contract invocation

> Submits a signed contract invocation blob to the Zetrix blockchain. Final step in the standard contract invocation flow.\
> \
> \*\*Pre-conditions:\*\*\
> \- \`blob\` from \`/contract/generate-blob\`\
> \- \`listSigner\` from \`/contract/sign-blob\` or your own signer\
> \- \`hash\` — 64-character transaction hash from the generate step\
> \- \`initiator\` — 37-character address of the transaction initiator\
> \
> \*\*After Submission:\*\*\
> Use the returned \`hash\` with \`/tx/query\` to confirm on-chain status.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Contract","description":"Smart contract operations on the Zetrix blockchain. Covers blob generation, signing, submitting, read-only querying, and invocation history filtering for deployed contracts. Includes both standard (user pays gas) and paymaster-sponsored (gas-free) contract invocations."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ContractInvokeSubmitReqDto":{"type":"object","description":"Request to submit a signed contract invocation blob to the blockchain.","properties":{"blob":{"type":"string","description":"Hex-encoded signed blob from `/contract/generate-blob`."},"hash":{"type":"string","description":"64-character transaction hash from the generate step.","minLength":64,"maxLength":64},"initiator":{"type":"string","description":"37-character Zetrix address of the transaction initiator.","minLength":37,"maxLength":37},"listSigner":{"type":"array","description":"Signers with their signatures and public keys.","items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseWrapperContractSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ContractSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ContractSubmitRespDto":{"type":"object","properties":{"hash":{"type":"string","description":"Transaction hash confirming contract invocation was broadcast."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/submit":{"post":{"tags":["Contract"],"summary":"Submit signed contract invocation","operationId":"invokeSubmit","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Submits a signed contract invocation blob to the Zetrix blockchain. Final step in the standard contract invocation flow.\n\n**Pre-conditions:**\n- `blob` from `/contract/generate-blob`\n- `listSigner` from `/contract/sign-blob` or your own signer\n- `hash` — 64-character transaction hash from the generate step\n- `initiator` — 37-character address of the transaction initiator\n\n**After Submission:**\nUse the returned `hash` with `/tx/query` to confirm on-chain status.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractInvokeSubmitReqDto"}}}},"responses":{"200":{"description":"Contract invocation submitted. Use the returned `hash` to query the result.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperContractSubmitRespDto"}}}}}}}}}
```

## Query smart contract (read-only)

> Performs a \*\*read-only\*\* query against a deployed smart contract. No transaction is created, no gas is consumed, and no state change occurs.\
> \
> \*\*Use Cases:\*\*\
> \- Check token balances\
> \- Read contract configuration\
> \- Verify ownership or access rights\
> \- Fetch metadata stored in the contract\
> \
> \*\*Response:\*\*\
> The \`object\` field contains the raw JSON returned by the contract method. Its structure varies per contract and method.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Contract","description":"Smart contract operations on the Zetrix blockchain. Covers blob generation, signing, submitting, read-only querying, and invocation history filtering for deployed contracts. Includes both standard (user pays gas) and paymaster-sponsored (gas-free) contract invocations."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ContractQueryReqDto":{"type":"object","description":"Request for a read-only smart contract query.","properties":{"contractKey":{"type":"string","description":"Registered contract alias in the Zetrix platform."},"method":{"type":"string","description":"Read-only contract method to call."},"inputParameters":{"type":"object","additionalProperties":{},"description":"Input parameters for the method. Structure depends on the contract's ABI."}}},"ResponseWrapperJSONObject":{"type":"object","properties":{"object":{"type":"object","additionalProperties":{},"description":"Dynamic JSON response from the smart contract method."},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/query":{"post":{"tags":["Contract"],"summary":"Query smart contract (read-only)","operationId":"query","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Performs a **read-only** query against a deployed smart contract. No transaction is created, no gas is consumed, and no state change occurs.\n\n**Use Cases:**\n- Check token balances\n- Read contract configuration\n- Verify ownership or access rights\n- Fetch metadata stored in the contract\n\n**Response:**\nThe `object` field contains the raw JSON returned by the contract method. Its structure varies per contract and method.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractQueryReqDto"}}}},"responses":{"200":{"description":"Contract query result. The `object` field contains the method's return value.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperJSONObject"}}}}}}}}}
```

## Filter contract call history

> Retrieves a paginated history of smart contract invocations, filtered by query parameters.\
> \
> \*\*Supported Filter Parameters:\*\*\
> \- \`contractKey\` — Filter by contract alias\
> \- \`method\` — Filter by contract method name\
> \- \`txInitiator\` — Filter by initiator address\
> \- \`status\` — \`INITIATED\` or \`SUBMITTED\`\
> \- \`page\` — Page number (1-based)\
> \- \`pageSize\` — Records per page\
> \
> \*\*Example:\*\*\
> \`\`\`\
> GET /contract/history/filter?contractKey=my-token-contract\&method=transfer\&page=1\&pageSize=20\
> \`\`\`

````json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Contract","description":"Smart contract operations on the Zetrix blockchain. Covers blob generation, signing, submitting, read-only querying, and invocation history filtering for deployed contracts. Includes both standard (user pays gas) and paymaster-sponsored (gas-free) contract invocations."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"MultiValueMapStringString":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"description":"Multi-value map for flexible filter parameters."},"ResponseWrapperResponsePaginatedContractUsageHistoryRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ResponsePaginatedContractUsageHistoryRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ResponsePaginatedContractUsageHistoryRespDto":{"type":"object","properties":{"page":{"type":"integer","format":"int64"},"pageSize":{"type":"integer","format":"int64"},"totalPages":{"type":"integer","format":"int32"},"totalElements":{"type":"integer","format":"int64"},"content":{"type":"array","items":{"$ref":"#/components/schemas/ContractUsageHistoryRespDto"}}}},"ContractUsageHistoryRespDto":{"type":"object","description":"A single contract invocation history record.","properties":{"id":{"type":"integer","format":"int64","description":"Internal record ID."},"address":{"type":"string","description":"Contract on-chain address."},"contractKey":{"type":"string","description":"Contract alias key."},"txInitiator":{"type":"string","description":"Address that initiated the transaction."},"method":{"type":"string","description":"Contract method called."},"inputParameters":{"type":"string","description":"JSON-serialized input parameters."},"txHash":{"type":"string","description":"Transaction hash."},"status":{"type":"string","enum":["INITIATED","SUBMITTED"],"description":"Invocation status."},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/history/filter":{"get":{"tags":["Contract"],"summary":"Filter contract call history","operationId":"filterHistory","description":"Retrieves a paginated history of smart contract invocations, filtered by query parameters.\n\n**Supported Filter Parameters:**\n- `contractKey` — Filter by contract alias\n- `method` — Filter by contract method name\n- `txInitiator` — Filter by initiator address\n- `status` — `INITIATED` or `SUBMITTED`\n- `page` — Page number (1-based)\n- `pageSize` — Records per page\n\n**Example:**\n```\nGET /contract/history/filter?contractKey=my-token-contract&method=transfer&page=1&pageSize=20\n```","parameters":[{"$ref":"#/components/parameters/X-API-Key"},{"name":"contractKey","in":"query","required":false,"description":"Filter by contract key (registered alias).","schema":{"type":"string"}},{"name":"method","in":"query","required":false,"description":"Filter by contract method name.","schema":{"type":"string"}},{"name":"txInitiator","in":"query","required":false,"description":"Filter by transaction initiator address.","schema":{"type":"string"}},{"name":"status","in":"query","required":false,"description":"Filter by status.","schema":{"type":"string","enum":["INITIATED","SUBMITTED"]}},{"name":"page","in":"query","required":false,"description":"Page number (1-based).","schema":{"type":"integer","default":1}},{"name":"pageSize","in":"query","required":false,"description":"Records per page.","schema":{"type":"integer","default":20}},{"name":"mapParam","in":"query","required":true,"description":"Multi-value map combining all filter parameters above.","schema":{"$ref":"#/components/schemas/MultiValueMapStringString"}}],"responses":{"200":{"description":"Paginated contract history returned.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperResponsePaginatedContractUsageHistoryRespDto"}}}}}}}}}
````


# Paymaster

Gas-free transaction and contract invocation operations where the **Paymaster service sponsors the gas fee** on behalf of the user. Ideal for onboarding new users who don't hold ZTX tokens. Flow: generate paymaster blob → sign blob → submit paymaster.

## Generate paymaster transaction blob

> Generates a gas-free transaction blob using the Zetrix Paymaster service. The Paymaster allocates a nonce from its pool and sponsors the gas fee when the transaction is submitted.\
> \
> \*\*Flow:\*\*\
> 1\. Call this endpoint with \`userAddress\` and \`operations\`\
> 2\. Receive \`blob\`, \`blobId\`, and reservation expiry (\`expiresAt\`)\
> 3\. Sign the blob using \`/tx/sign-blob\`\
> 4\. Submit via \`/tx/paymaster/submit\` within \`timeoutMinutes\`\
> \
> \*\*Pool Selection:\*\*\
> Auto-selected unless \`paymasterPoolId\` or \`poolType\` (\`NORMAL\`, \`PREMIUM\`, \`CORPORATE\`) is specified.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Paymaster","description":"Gas-free transaction and contract invocation operations where the **Paymaster service sponsors the gas fee** on behalf of the user. Ideal for onboarding new users who don't hold ZTX tokens. Flow: generate paymaster blob → sign blob → submit paymaster."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"PaymasterGenerateBlobReqDto":{"type":"object","description":"Request to generate a paymaster-sponsored transaction blob (gas-free for users).","required":["operations","userAddress"],"properties":{"userAddress":{"type":"string","description":"Zetrix address of the user initiating the transaction. Gas covered by the Paymaster."},"operations":{"type":"array","description":"List of operations to execute.","items":{"$ref":"#/components/schemas/OperationsEntity"}},"chainCode":{"type":"string","description":"Chain code identifier. Defaults to `\"0\"`.","default":"0"},"paymasterPoolId":{"type":"integer","format":"int64","description":"Specific paymaster pool ID. Auto-selected if not provided."},"operationType":{"type":"string","description":"Operation type label for tracking."},"targetAddress":{"type":"string","description":"Target address for tracking purposes."},"amount":{"type":"string","description":"Transaction amount for tracking (optional)."},"metadata":{"type":"object","additionalProperties":{},"description":"Additional metadata for tracking."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Minutes the nonce reservation is valid. Defaults to 10.","default":10},"minPoolBalance":{"type":"integer","format":"int64","description":"Minimum required pool balance in drops (optional)."},"poolType":{"type":"string","description":"Preferred paymaster pool type.","enum":["NORMAL","PREMIUM","CORPORATE"]}}},"OperationsEntity":{"type":"object","description":"A single operation to execute in a transaction. The fields used depend on the operation `type`.","properties":{"type":{"type":"string","description":"Operation type as a numeric string. `1` = Create Account, `2` = Built-in points transfer, `3` = Call contract, `4` = Create contract, `5` = Set up account metadata, `6` = Set account privilege, `7` = Upgrade contract content, `8` = Upgrade contract owner.","enum":["1","2","3","4","5","6","7","8"]},"toAddress":{"type":"string","description":"Destination Zetrix address for transfer-type operations."},"fromAddress":{"type":"string","description":"Source address override (defaults to `txInitiator` if omitted)."},"amount":{"type":"string","description":"Amount in drops (1 ZETRIX = 10^6 drops)."},"inputStr":{"type":"string","description":"JSON-encoded input for contract invocation operations."},"payload":{"type":"string","description":"Contract payload or bytecode (used in contract deployment)."},"precision":{"type":"string","description":"Asset precision (used in asset issuance)."},"metadata":{"type":"string","description":"Optional arbitrary metadata string attached to the operation."}}},"ResponseWrapperPaymasterGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/PaymasterGenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"PaymasterGenerateBlobRespDto":{"type":"object","description":"Response for paymaster transaction blob generation.","required":["blob","blobId","expiresAt","hash","paymasterAddress","paymasterNonce","paymasterPoolId","timeoutMinutes"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob. Sign and submit via `/tx/paymaster/submit`."},"hash":{"type":"string","description":"Transaction hash. Required when calling `/tx/sign-blob`."},"blobId":{"type":"string","description":"Unique ID for this paymaster reservation. Required in `/tx/paymaster/submit`."},"paymasterAddress":{"type":"string","description":"Paymaster address that will sponsor the gas fee."},"paymasterNonce":{"type":"integer","format":"int64","description":"Nonce allocated from the paymaster pool."},"paymasterPoolId":{"type":"integer","format":"int64","description":"ID of the paymaster pool used."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units (1 ZETRIX = 10^6 units)."},"expiresAt":{"type":"string","format":"date-time","description":"Nonce reservation expiry. Submit before this time."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Duration in minutes the reservation is valid."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/paymaster/generate-blob":{"post":{"tags":["Paymaster"],"summary":"Generate paymaster transaction blob","operationId":"generatePaymasterBlob","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Generates a gas-free transaction blob using the Zetrix Paymaster service. The Paymaster allocates a nonce from its pool and sponsors the gas fee when the transaction is submitted.\n\n**Flow:**\n1. Call this endpoint with `userAddress` and `operations`\n2. Receive `blob`, `blobId`, and reservation expiry (`expiresAt`)\n3. Sign the blob using `/tx/sign-blob`\n4. Submit via `/tx/paymaster/submit` within `timeoutMinutes`\n\n**Pool Selection:**\nAuto-selected unless `paymasterPoolId` or `poolType` (`NORMAL`, `PREMIUM`, `CORPORATE`) is specified.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymasterGenerateBlobReqDto"}}}},"responses":{"200":{"description":"Paymaster blob generated. Sign and submit via `/tx/paymaster/submit` before `expiresAt`.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperPaymasterGenerateBlobRespDto"}}}}}}}}}
```

## Submit paymaster transaction

> Submits a signed paymaster transaction blob for asynchronous processing. Returns immediately with \`QUEUED\` status.\
> \
> \*\*Pre-conditions:\*\*\
> \- \`blobId\` from a valid, non-expired \`/tx/paymaster/generate-blob\` call\
> \- \`blob\` signed by the user's private key\
> \- Submitted before \`expiresAt\`\
> \
> \*\*Async Processing:\*\*\
> The Paymaster adds its gas-sponsoring signature and broadcasts the transaction. Poll \`/tx/query\` with \`txHash\` to check final status.\
> \
> \*\*Response Fields:\*\*\
> \- \`status\` — Initially \`QUEUED\`\
> \- \`txHash\` — Use this to query the final result

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Paymaster","description":"Gas-free transaction and contract invocation operations where the **Paymaster service sponsors the gas fee** on behalf of the user. Ideal for onboarding new users who don't hold ZTX tokens. Flow: generate paymaster blob → sign blob → submit paymaster."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"PaymasterSubmitReqDto":{"type":"object","description":"Request body for submitting a paymaster-sponsored transaction or contract invocation.","required":["blob","blobId","listSigner"],"properties":{"blobId":{"type":"string","description":"Unique ID of the paymaster blob reservation from generate-blob."},"blob":{"type":"string","description":"The hex-encoded transaction blob returned during blob generation."},"listSigner":{"type":"array","description":"User's signature(s) on the blob.","items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseWrapperPaymasterSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/PaymasterSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"PaymasterSubmitRespDto":{"type":"object","description":"Response after queuing a paymaster-sponsored transaction.","properties":{"txHash":{"type":"string","description":"Transaction hash. Poll `/tx/query` with this for final status."},"blobId":{"type":"string","description":"Paymaster blob reservation ID."},"nonce":{"type":"integer","format":"int64","description":"Nonce used from the paymaster pool."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring the gas fee."},"status":{"type":"string","description":"Processing status. Initially `QUEUED`; becomes `SUCCESS` or `FAILED` after processing."},"submittedAt":{"type":"string","format":"date-time","description":"Timestamp when queued."},"blockNumber":{"type":"integer","format":"int64","description":"Block number confirmed in (populated post-confirmation)."},"gasUsed":{"type":"integer","format":"int64","description":"Actual gas units consumed."},"gasFeePaid":{"type":"integer","format":"int64","description":"Total gas fee paid by paymaster in drops."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/tx/paymaster/submit":{"post":{"tags":["Paymaster"],"summary":"Submit paymaster transaction","operationId":"submitPaymasterTransaction","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Submits a signed paymaster transaction blob for asynchronous processing. Returns immediately with `QUEUED` status.\n\n**Pre-conditions:**\n- `blobId` from a valid, non-expired `/tx/paymaster/generate-blob` call\n- `blob` signed by the user's private key\n- Submitted before `expiresAt`\n\n**Async Processing:**\nThe Paymaster adds its gas-sponsoring signature and broadcasts the transaction. Poll `/tx/query` with `txHash` to check final status.\n\n**Response Fields:**\n- `status` — Initially `QUEUED`\n- `txHash` — Use this to query the final result","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymasterSubmitReqDto"}}}},"responses":{"200":{"description":"Transaction queued for paymaster processing. Poll `/tx/query` using `txHash` for final status.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperPaymasterSubmitRespDto"}}}}}}}}}
```

## Generate paymaster contract invocation blob

> Generates a gas-free contract invocation blob using the Paymaster service. Either \`contractKey\` or \`contractAddress\` must be provided. If both are given, \`contractAddress\` takes precedence.\
> \
> \*\*Flow:\*\*\
> 1\. Call this endpoint with the user's address, contract identifier, method, and input parameters\
> 2\. Receive \`blob\`, \`blobId\`, and expiry info\
> 3\. Sign the blob using \`/tx/sign-blob\`\
> 4\. Submit via \`/contract/paymaster/submit\` before \`expiresAt\`\
> \
> \*\*Pool Selection:\*\*\
> Auto-selected unless \`paymasterPoolId\` or \`poolType\` (\`NORMAL\`, \`PREMIUM\`, \`CORPORATE\`) is specified.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Paymaster","description":"Gas-free transaction and contract invocation operations where the **Paymaster service sponsors the gas fee** on behalf of the user. Ideal for onboarding new users who don't hold ZTX tokens. Flow: generate paymaster blob → sign blob → submit paymaster."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"ContractPaymasterGenerateBlobReqDto":{"type":"object","description":"Request to generate a paymaster-sponsored contract invocation blob.","required":["method","userAddress"],"properties":{"contractKey":{"type":"string","description":"Registered contract alias. Either this or `contractAddress` must be provided."},"contractAddress":{"type":"string","description":"On-chain contract address. Takes precedence over `contractKey` if both are given."},"method":{"type":"string","description":"Contract method to invoke."},"inputParameters":{"type":"object","additionalProperties":{},"description":"Method input parameters as key-value map."},"userAddress":{"type":"string","description":"User's Zetrix address (initiator). Gas covered by the Paymaster.","minLength":37,"maxLength":37},"value":{"type":"integer","format":"int64","description":"ZTX value in drops. Use `0` for non-payable methods."},"chainCode":{"type":"string","description":"Chain code identifier. Defaults to `\"0\"`.","default":"0"},"paymasterPoolId":{"type":"integer","format":"int64","description":"Specific paymaster pool ID. Auto-selected if not provided."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Nonce reservation timeout in minutes. Defaults to 10.","default":10},"minPoolBalance":{"type":"integer","format":"int64","description":"Minimum required paymaster pool balance in drops."},"poolType":{"type":"string","description":"Preferred paymaster pool type.","enum":["NORMAL","PREMIUM","CORPORATE"]},"metadata":{"type":"object","additionalProperties":{},"description":"Additional metadata for tracking."}}},"ResponseWrapperContractPaymasterGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ContractPaymasterGenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ContractPaymasterGenerateBlobRespDto":{"type":"object","description":"Response for paymaster-sponsored contract invocation blob generation.","required":["blob","blobId","expiresAt","hash","paymasterAddress","paymasterNonce","paymasterPoolId","timeoutMinutes"],"properties":{"blob":{"type":"string","description":"Hex-encoded blob. Sign and submit via `/contract/paymaster/submit`."},"hash":{"type":"string","description":"Transaction hash."},"blobId":{"type":"string","description":"Paymaster reservation ID. Required in `/contract/paymaster/submit`."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring gas."},"paymasterNonce":{"type":"integer","format":"int64","description":"Reserved nonce."},"paymasterPoolId":{"type":"integer","format":"int64","description":"Paymaster pool ID."},"contractAddress":{"type":"string","description":"Resolved on-chain contract address."},"method":{"type":"string","description":"Contract method being invoked."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units."},"expiresAt":{"type":"string","format":"date-time","description":"Nonce reservation expiry. Submit before this time."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Timeout duration in minutes."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/paymaster/generate-blob":{"post":{"tags":["Paymaster"],"summary":"Generate paymaster contract invocation blob","operationId":"generatePaymasterBlob_1","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Generates a gas-free contract invocation blob using the Paymaster service. Either `contractKey` or `contractAddress` must be provided. If both are given, `contractAddress` takes precedence.\n\n**Flow:**\n1. Call this endpoint with the user's address, contract identifier, method, and input parameters\n2. Receive `blob`, `blobId`, and expiry info\n3. Sign the blob using `/tx/sign-blob`\n4. Submit via `/contract/paymaster/submit` before `expiresAt`\n\n**Pool Selection:**\nAuto-selected unless `paymasterPoolId` or `poolType` (`NORMAL`, `PREMIUM`, `CORPORATE`) is specified.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractPaymasterGenerateBlobReqDto"}}}},"responses":{"200":{"description":"Paymaster contract blob generated. Sign and submit via `/contract/paymaster/submit` before expiry.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperContractPaymasterGenerateBlobRespDto"}}}}}}}}}
```

## Submit paymaster contract invocation

> Queues a signed contract invocation blob for asynchronous Paymaster processing. Returns immediately with \`QUEUED\` status. The Paymaster adds its gas-sponsoring signature and broadcasts the transaction.\
> \
> \*\*Required fields:\*\*\
> \- \`blobId\` — from \`/contract/paymaster/generate-blob\`\
> \- \`blob\` — signed by the user\
> \- \`listSigner\` — user's signature(s)\
> \
> \*\*Tracking:\*\*\
> Poll \`/tx/query\` with \`txHash\` to check final on-chain status.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"Paymaster","description":"Gas-free transaction and contract invocation operations where the **Paymaster service sponsors the gas fee** on behalf of the user. Ideal for onboarding new users who don't hold ZTX tokens. Flow: generate paymaster blob → sign blob → submit paymaster."}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"PaymasterSubmitReqDto":{"type":"object","description":"Request body for submitting a paymaster-sponsored transaction or contract invocation.","required":["blob","blobId","listSigner"],"properties":{"blobId":{"type":"string","description":"Unique ID of the paymaster blob reservation from generate-blob."},"blob":{"type":"string","description":"The hex-encoded transaction blob returned during blob generation."},"listSigner":{"type":"array","description":"User's signature(s) on the blob.","items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseWrapperPaymasterSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/PaymasterSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"PaymasterSubmitRespDto":{"type":"object","description":"Response after queuing a paymaster-sponsored transaction.","properties":{"txHash":{"type":"string","description":"Transaction hash. Poll `/tx/query` with this for final status."},"blobId":{"type":"string","description":"Paymaster blob reservation ID."},"nonce":{"type":"integer","format":"int64","description":"Nonce used from the paymaster pool."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring the gas fee."},"status":{"type":"string","description":"Processing status. Initially `QUEUED`; becomes `SUCCESS` or `FAILED` after processing."},"submittedAt":{"type":"string","format":"date-time","description":"Timestamp when queued."},"blockNumber":{"type":"integer","format":"int64","description":"Block number confirmed in (populated post-confirmation)."},"gasUsed":{"type":"integer","format":"int64","description":"Actual gas units consumed."},"gasFeePaid":{"type":"integer","format":"int64","description":"Total gas fee paid by paymaster in drops."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/contract/paymaster/submit":{"post":{"tags":["Paymaster"],"summary":"Submit paymaster contract invocation","operationId":"submitPaymasterTransaction_1","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"description":"Queues a signed contract invocation blob for asynchronous Paymaster processing. Returns immediately with `QUEUED` status. The Paymaster adds its gas-sponsoring signature and broadcasts the transaction.\n\n**Required fields:**\n- `blobId` — from `/contract/paymaster/generate-blob`\n- `blob` — signed by the user\n- `listSigner` — user's signature(s)\n\n**Tracking:**\nPoll `/tx/query` with `txHash` to check final on-chain status.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymasterSubmitReqDto"}}}},"responses":{"200":{"description":"Contract invocation queued for paymaster processing.","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperPaymasterSubmitRespDto"}}}}}}}}}
```


# HSM

Hardware Security Module — Thales Luna Cloud (DPoD)

## Create HSM key pair

> Generates an Ed25519 key pair on the HSM partition. Returns the Zetrix address and raw public key hex. The returned address is used as the identifier for subsequent sign requests.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"HSM","description":"Hardware Security Module — Thales Luna Cloud (DPoD)"}],"servers":[{"url":"https://api-sandbox.zetrix.com","description":"Sandbox Environment – Use this for development and testing."}],"security":[{"Authorization":[]}],"components":{"securitySchemes":{"Authorization":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Bearer access token. Include in all requests as: `Authorization: Bearer <your_access_token>`"}},"parameters":{"X-API-Key":{"name":"X-API-Key","in":"header","required":true,"description":"API key for authentication. Include in all requests.","schema":{"type":"string"}}},"schemas":{"HsmCreateAccountReqDto":{"type":"object","description":"Request to create an HSM-backed Ed25519 key pair","properties":{"label":{"type":"string","description":"Optional caller-supplied label suffix. Final key label = ZETRIX_<label> if provided, else ZETRIX_<uuid>."},"purpose":{"type":"string","description":"Optional purpose description for this key"},"password":{"type":"string","description":"User password used to encrypt the HSM key label in DB storage","minLength":8,"maxLength":128}},"required":["password"]},"ResponseWrapperHsmCreateAccountRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/HsmCreateAccountRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"HsmCreateAccountRespDto":{"type":"object","description":"Response for HSM key pair creation","properties":{"publicKeyHex":{"type":"string","description":"Raw Ed25519 public key as hex string (64 hex chars = 32 bytes)"},"zetrixAddress":{"type":"string","description":"Zetrix blockchain address derived from the public key (e.g. ZTX3...). Use this as the identifier in subsequent sign requests."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}},"paths":{"/ztx/hsm/create-account":{"post":{"tags":["HSM"],"summary":"Create HSM key pair","operationId":"createAccount","description":"Generates an Ed25519 key pair on the HSM partition. Returns the Zetrix address and raw public key hex. The returned address is used as the identifier for subsequent sign requests.","parameters":[{"$ref":"#/components/parameters/X-API-Key"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HsmCreateAccountReqDto"}}}},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperHsmCreateAccountRespDto"}}}}}}}}}
```

## Sign blob with HSM

> Signs a hex-encoded transaction blob using the HSM-stored Ed25519 private key identified by the Zetrix address. The returned SignerEntity can be used directly in /tx/submit or /contract/submit.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"HSM","description":"Hardware Security Module — Thales Luna Cloud (DPoD)"}],"servers":[{"url":"https://public-api-sandbox.zetrix.com"}],"security":[],"paths":{"/api/hsm/sign-blob":{"post":{"tags":["HSM"],"summary":"Sign blob with HSM","operationId":"signBlobHsm","description":"Signs a hex-encoded transaction blob using the HSM-stored Ed25519 private key identified by the Zetrix address. The returned SignerEntity can be used directly in /tx/submit or /contract/submit.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HsmBlobDataReqDto"}}}},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperListSignerEntity"}}}}}}}},"components":{"schemas":{"HsmBlobDataReqDto":{"type":"object","description":"Request to sign a transaction blob using the HSM","properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob to sign (obtained from /tx/generate-blob or /contract/generate-blob)"},"password":{"type":"string","description":"User password used to decrypt the stored HSM key label","minLength":8,"maxLength":128},"address":{"type":"string","description":"Zetrix address returned by /hsm/create-account"}},"required":["blob","password","address"]},"ResponseWrapperListSignerEntity":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/SignerEntity"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## Sign message with HSM

> Signs a UTF-8 message using the HSM-stored Ed25519 private key identified by the Zetrix address.

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"tags":[{"name":"HSM","description":"Hardware Security Module — Thales Luna Cloud (DPoD)"}],"servers":[{"url":"https://public-api-sandbox.zetrix.com"}],"security":[],"paths":{"/api/hsm/sign-message":{"post":{"tags":["HSM"],"summary":"Sign message with HSM","operationId":"signMessageHsm","description":"Signs a UTF-8 message using the HSM-stored Ed25519 private key identified by the Zetrix address.","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HsmMessageDataReqDto"}}}},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperListSignerEntity"}}}}}}}},"components":{"schemas":{"HsmMessageDataReqDto":{"type":"object","description":"Request to sign a UTF-8 message using the HSM","properties":{"message":{"type":"string","description":"UTF-8 message to sign"},"password":{"type":"string","description":"User password used to decrypt the stored HSM key label","minLength":8,"maxLength":128},"address":{"type":"string","description":"Zetrix address returned by /hsm/create-account"}},"required":["message","password","address"]},"ResponseWrapperListSignerEntity":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/SignerEntity"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```


# Models

## The HsmCreateAccountReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"HsmCreateAccountReqDto":{"type":"object","description":"Request to create an HSM-backed Ed25519 key pair","properties":{"label":{"type":"string","description":"Optional caller-supplied label suffix. Final key label = ZETRIX_<label> if provided, else ZETRIX_<uuid>."},"purpose":{"type":"string","description":"Optional purpose description for this key"},"password":{"type":"string","description":"User password used to encrypt the HSM key label in DB storage","minLength":8,"maxLength":128}},"required":["password"]}}}}
```

## The HsmCreateAccountRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"HsmCreateAccountRespDto":{"type":"object","description":"Response for HSM key pair creation","properties":{"publicKeyHex":{"type":"string","description":"Raw Ed25519 public key as hex string (64 hex chars = 32 bytes)"},"zetrixAddress":{"type":"string","description":"Zetrix blockchain address derived from the public key (e.g. ZTX3...). Use this as the identifier in subsequent sign requests."}}}}}}
```

## The HsmBlobDataReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"HsmBlobDataReqDto":{"type":"object","description":"Request to sign a transaction blob using the HSM","properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob to sign (obtained from /tx/generate-blob or /contract/generate-blob)"},"password":{"type":"string","description":"User password used to decrypt the stored HSM key label","minLength":8,"maxLength":128},"address":{"type":"string","description":"Zetrix address returned by /hsm/create-account"}},"required":["blob","password","address"]}}}}
```

## The HsmMessageDataReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"HsmMessageDataReqDto":{"type":"object","description":"Request to sign a UTF-8 message using the HSM","properties":{"message":{"type":"string","description":"UTF-8 message to sign"},"password":{"type":"string","description":"User password used to decrypt the stored HSM key label","minLength":8,"maxLength":128},"address":{"type":"string","description":"Zetrix address returned by /hsm/create-account"}},"required":["message","password","address"]}}}}
```

## The ResponseWrapperHsmCreateAccountRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperHsmCreateAccountRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/HsmCreateAccountRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"HsmCreateAccountRespDto":{"type":"object","description":"Response for HSM key pair creation","properties":{"publicKeyHex":{"type":"string","description":"Raw Ed25519 public key as hex string (64 hex chars = 32 bytes)"},"zetrixAddress":{"type":"string","description":"Zetrix blockchain address derived from the public key (e.g. ZTX3...). Use this as the identifier in subsequent sign requests."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The SignerEntity object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}}}}}
```

## The SubmitTxReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"SubmitTxReqDto":{"type":"object","description":"Request body for submitting a signed transaction.","required":["blob","listSigner"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob from `/tx/generate-blob`. Must not be modified."},"listSigner":{"type":"array","description":"List of signers. At least one entry required.","minItems":1,"items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}}}}}
```

## The BlobDataReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"BlobDataReqDto":{"type":"object","description":"Request body for server-side blob signing.","properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob to sign."},"hash":{"type":"string","description":"64-character transaction hash associated with the blob.","minLength":64,"maxLength":64},"privateKeys":{"type":"array","description":"List of Ed25519 private keys (each exactly 56 characters). One `SignerEntity` is returned per key.","minItems":1,"items":{"type":"string","minLength":56,"maxLength":56}}}}}}}
```

## The PaymasterSubmitReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"PaymasterSubmitReqDto":{"type":"object","description":"Request body for submitting a paymaster-sponsored transaction or contract invocation.","required":["blob","blobId","listSigner"],"properties":{"blobId":{"type":"string","description":"Unique ID of the paymaster blob reservation from generate-blob."},"blob":{"type":"string","description":"The hex-encoded transaction blob returned during blob generation."},"listSigner":{"type":"array","description":"User's signature(s) on the blob.","items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}}}}}
```

## The PaymasterSubmitRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"PaymasterSubmitRespDto":{"type":"object","description":"Response after queuing a paymaster-sponsored transaction.","properties":{"txHash":{"type":"string","description":"Transaction hash. Poll `/tx/query` with this for final status."},"blobId":{"type":"string","description":"Paymaster blob reservation ID."},"nonce":{"type":"integer","format":"int64","description":"Nonce used from the paymaster pool."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring the gas fee."},"status":{"type":"string","description":"Processing status. Initially `QUEUED`; becomes `SUCCESS` or `FAILED` after processing."},"submittedAt":{"type":"string","format":"date-time","description":"Timestamp when queued."},"blockNumber":{"type":"integer","format":"int64","description":"Block number confirmed in (populated post-confirmation)."},"gasUsed":{"type":"integer","format":"int64","description":"Actual gas units consumed."},"gasFeePaid":{"type":"integer","format":"int64","description":"Total gas fee paid by paymaster in drops."}}}}}}
```

## The OperationsEntity object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"OperationsEntity":{"type":"object","description":"A single operation to execute in a transaction. The fields used depend on the operation `type`.","properties":{"type":{"type":"string","description":"Operation type as a numeric string. `1` = Create Account, `2` = Built-in points transfer, `3` = Call contract, `4` = Create contract, `5` = Set up account metadata, `6` = Set account privilege, `7` = Upgrade contract content, `8` = Upgrade contract owner.","enum":["1","2","3","4","5","6","7","8"]},"toAddress":{"type":"string","description":"Destination Zetrix address for transfer-type operations."},"fromAddress":{"type":"string","description":"Source address override (defaults to `txInitiator` if omitted)."},"amount":{"type":"string","description":"Amount in drops (1 ZETRIX = 10^6 drops)."},"inputStr":{"type":"string","description":"JSON-encoded input for contract invocation operations."},"payload":{"type":"string","description":"Contract payload or bytecode (used in contract deployment)."},"precision":{"type":"string","description":"Asset precision (used in asset issuance)."},"metadata":{"type":"string","description":"Optional arbitrary metadata string attached to the operation."}}}}}}
```

## The PaymasterGenerateBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"PaymasterGenerateBlobReqDto":{"type":"object","description":"Request to generate a paymaster-sponsored transaction blob (gas-free for users).","required":["operations","userAddress"],"properties":{"userAddress":{"type":"string","description":"Zetrix address of the user initiating the transaction. Gas covered by the Paymaster."},"operations":{"type":"array","description":"List of operations to execute.","items":{"$ref":"#/components/schemas/OperationsEntity"}},"chainCode":{"type":"string","description":"Chain code identifier. Defaults to `\"0\"`.","default":"0"},"paymasterPoolId":{"type":"integer","format":"int64","description":"Specific paymaster pool ID. Auto-selected if not provided."},"operationType":{"type":"string","description":"Operation type label for tracking."},"targetAddress":{"type":"string","description":"Target address for tracking purposes."},"amount":{"type":"string","description":"Transaction amount for tracking (optional)."},"metadata":{"type":"object","additionalProperties":{},"description":"Additional metadata for tracking."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Minutes the nonce reservation is valid. Defaults to 10.","default":10},"minPoolBalance":{"type":"integer","format":"int64","description":"Minimum required pool balance in drops (optional)."},"poolType":{"type":"string","description":"Preferred paymaster pool type.","enum":["NORMAL","PREMIUM","CORPORATE"]}}},"OperationsEntity":{"type":"object","description":"A single operation to execute in a transaction. The fields used depend on the operation `type`.","properties":{"type":{"type":"string","description":"Operation type as a numeric string. `1` = Create Account, `2` = Built-in points transfer, `3` = Call contract, `4` = Create contract, `5` = Set up account metadata, `6` = Set account privilege, `7` = Upgrade contract content, `8` = Upgrade contract owner.","enum":["1","2","3","4","5","6","7","8"]},"toAddress":{"type":"string","description":"Destination Zetrix address for transfer-type operations."},"fromAddress":{"type":"string","description":"Source address override (defaults to `txInitiator` if omitted)."},"amount":{"type":"string","description":"Amount in drops (1 ZETRIX = 10^6 drops)."},"inputStr":{"type":"string","description":"JSON-encoded input for contract invocation operations."},"payload":{"type":"string","description":"Contract payload or bytecode (used in contract deployment)."},"precision":{"type":"string","description":"Asset precision (used in asset issuance)."},"metadata":{"type":"string","description":"Optional arbitrary metadata string attached to the operation."}}}}}}
```

## The PaymasterGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"PaymasterGenerateBlobRespDto":{"type":"object","description":"Response for paymaster transaction blob generation.","required":["blob","blobId","expiresAt","hash","paymasterAddress","paymasterNonce","paymasterPoolId","timeoutMinutes"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob. Sign and submit via `/tx/paymaster/submit`."},"hash":{"type":"string","description":"Transaction hash. Required when calling `/tx/sign-blob`."},"blobId":{"type":"string","description":"Unique ID for this paymaster reservation. Required in `/tx/paymaster/submit`."},"paymasterAddress":{"type":"string","description":"Paymaster address that will sponsor the gas fee."},"paymasterNonce":{"type":"integer","format":"int64","description":"Nonce allocated from the paymaster pool."},"paymasterPoolId":{"type":"integer","format":"int64","description":"ID of the paymaster pool used."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units (1 ZETRIX = 10^6 units)."},"expiresAt":{"type":"string","format":"date-time","description":"Nonce reservation expiry. Submit before this time."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Duration in minutes the reservation is valid."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}}}}}
```

## The PlatformSignDataEntity object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}}}}}
```

## The GenerateBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"GenerateBlobReqDto":{"type":"object","description":"Request to generate a transaction blob where the user pays gas fees.","required":["operations","txInitiator"],"properties":{"txInitiator":{"type":"string","description":"Zetrix address of the account initiating and paying gas for the transaction."},"operations":{"type":"array","description":"List of operations to execute.","items":{"$ref":"#/components/schemas/OperationsEntity"}},"chainCode":{"type":"string","description":"Chain code identifier. Defaults to `\"0\"`.","default":"0"}}},"OperationsEntity":{"type":"object","description":"A single operation to execute in a transaction. The fields used depend on the operation `type`.","properties":{"type":{"type":"string","description":"Operation type as a numeric string. `1` = Create Account, `2` = Built-in points transfer, `3` = Call contract, `4` = Create contract, `5` = Set up account metadata, `6` = Set account privilege, `7` = Upgrade contract content, `8` = Upgrade contract owner.","enum":["1","2","3","4","5","6","7","8"]},"toAddress":{"type":"string","description":"Destination Zetrix address for transfer-type operations."},"fromAddress":{"type":"string","description":"Source address override (defaults to `txInitiator` if omitted)."},"amount":{"type":"string","description":"Amount in drops (1 ZETRIX = 10^6 drops)."},"inputStr":{"type":"string","description":"JSON-encoded input for contract invocation operations."},"payload":{"type":"string","description":"Contract payload or bytecode (used in contract deployment)."},"precision":{"type":"string","description":"Asset precision (used in asset issuance)."},"metadata":{"type":"string","description":"Optional arbitrary metadata string attached to the operation."}}}}}}
```

## The GenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"GenerateBlobRespDto":{"type":"object","description":"Response for transaction blob generation.","required":["blob","hash"],"properties":{"blob":{"type":"string","description":"Hex-encoded serialized transaction blob. Sign before submitting."},"hash":{"type":"string","description":"SHA-256 transaction hash. Required when calling `/tx/sign-blob`."},"actualFee":{"type":"integer","format":"int64","description":"Estimated transaction fee in gas units."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}}}}}
```

## The ParseBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ParseBlobReqDto":{"type":"object","description":"Request to parse a transaction blob.","required":["blob"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob to decode."}}}}}}
```

## The ContractInvokeGenerateBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractInvokeGenerateBlobReqDto":{"type":"object","description":"Request to generate a blob for a smart contract invocation.","required":["method"],"properties":{"contractKey":{"type":"string","description":"Registered contract alias. Either this or `contractAddress` must be provided."},"contractAddress":{"type":"string","description":"On-chain contract address. Takes precedence over `contractKey` if both are given."},"method":{"type":"string","description":"Contract method to invoke."},"inputParameters":{"type":"object","additionalProperties":{},"description":"Method input parameters. Structure depends on the contract's ABI."},"txInitiator":{"type":"string","description":"Address of the transaction initiator (pays gas).","minLength":37,"maxLength":37},"sourceAddress":{"type":"string","description":"Optional source address override."},"value":{"type":"integer","format":"int64","description":"ZTX value in drops to send with the invocation. Use `0` for non-payable methods."}}}}}}
```

## The ContractInvokeSignBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractInvokeSignBlobReqDto":{"type":"object","description":"Request to sign a contract invocation blob using a single private key.","properties":{"blob":{"type":"string","description":"Hex-encoded contract invocation blob to sign."},"privateKey":{"type":"string","description":"56-character Ed25519 private key of the transaction initiator.","minLength":56,"maxLength":56}}}}}}
```

## The ContractInvokeSubmitReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractInvokeSubmitReqDto":{"type":"object","description":"Request to submit a signed contract invocation blob to the blockchain.","properties":{"blob":{"type":"string","description":"Hex-encoded signed blob from `/contract/generate-blob`."},"hash":{"type":"string","description":"64-character transaction hash from the generate step.","minLength":64,"maxLength":64},"initiator":{"type":"string","description":"37-character Zetrix address of the transaction initiator.","minLength":37,"maxLength":37},"listSigner":{"type":"array","description":"Signers with their signatures and public keys.","items":{"$ref":"#/components/schemas/SignerEntity"}}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}}}}}
```

## The ContractQueryReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractQueryReqDto":{"type":"object","description":"Request for a read-only smart contract query.","properties":{"contractKey":{"type":"string","description":"Registered contract alias in the Zetrix platform."},"method":{"type":"string","description":"Read-only contract method to call."},"inputParameters":{"type":"object","additionalProperties":{},"description":"Input parameters for the method. Structure depends on the contract's ABI."}}}}}}
```

## The ContractPaymasterGenerateBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractPaymasterGenerateBlobReqDto":{"type":"object","description":"Request to generate a paymaster-sponsored contract invocation blob.","required":["method","userAddress"],"properties":{"contractKey":{"type":"string","description":"Registered contract alias. Either this or `contractAddress` must be provided."},"contractAddress":{"type":"string","description":"On-chain contract address. Takes precedence over `contractKey` if both are given."},"method":{"type":"string","description":"Contract method to invoke."},"inputParameters":{"type":"object","additionalProperties":{},"description":"Method input parameters as key-value map."},"userAddress":{"type":"string","description":"User's Zetrix address (initiator). Gas covered by the Paymaster.","minLength":37,"maxLength":37},"value":{"type":"integer","format":"int64","description":"ZTX value in drops. Use `0` for non-payable methods."},"chainCode":{"type":"string","description":"Chain code identifier. Defaults to `\"0\"`.","default":"0"},"paymasterPoolId":{"type":"integer","format":"int64","description":"Specific paymaster pool ID. Auto-selected if not provided."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Nonce reservation timeout in minutes. Defaults to 10.","default":10},"minPoolBalance":{"type":"integer","format":"int64","description":"Minimum required paymaster pool balance in drops."},"poolType":{"type":"string","description":"Preferred paymaster pool type.","enum":["NORMAL","PREMIUM","CORPORATE"]},"metadata":{"type":"object","additionalProperties":{},"description":"Additional metadata for tracking."}}}}}}
```

## The ContractPaymasterGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractPaymasterGenerateBlobRespDto":{"type":"object","description":"Response for paymaster-sponsored contract invocation blob generation.","required":["blob","blobId","expiresAt","hash","paymasterAddress","paymasterNonce","paymasterPoolId","timeoutMinutes"],"properties":{"blob":{"type":"string","description":"Hex-encoded blob. Sign and submit via `/contract/paymaster/submit`."},"hash":{"type":"string","description":"Transaction hash."},"blobId":{"type":"string","description":"Paymaster reservation ID. Required in `/contract/paymaster/submit`."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring gas."},"paymasterNonce":{"type":"integer","format":"int64","description":"Reserved nonce."},"paymasterPoolId":{"type":"integer","format":"int64","description":"Paymaster pool ID."},"contractAddress":{"type":"string","description":"Resolved on-chain contract address."},"method":{"type":"string","description":"Contract method being invoked."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units."},"expiresAt":{"type":"string","format":"date-time","description":"Nonce reservation expiry. Submit before this time."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Timeout duration in minutes."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}}}}}
```

## The ResponseMessage object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The TxSubmitRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"TxSubmitRespDto":{"type":"object","properties":{"hash":{"type":"string","description":"Transaction hash confirming successful broadcast."}}}}}}
```

## The ContractSubmitRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractSubmitRespDto":{"type":"object","properties":{"hash":{"type":"string","description":"Transaction hash confirming contract invocation was broadcast."}}}}}}
```

## The ContractGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractGenerateBlobRespDto":{"type":"object","description":"Response for contract invocation blob generation.","properties":{"blob":{"type":"string","description":"Hex-encoded contract invocation blob."},"hash":{"type":"string","description":"Transaction hash."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}}}}}
```

## The TxQueryRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"TxQueryRespDto":{"type":"object","description":"Transaction query result.","properties":{"txStatus":{"type":"string","description":"Numeric transaction lifecycle status code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"txContent":{"$ref":"#/components/schemas/TransactionHistory"}}},"TransactionHistory":{"type":"object","description":"Full on-chain transaction record.","properties":{"hash":{"type":"string","description":"Transaction hash."},"ledgerSeq":{"type":"integer","format":"int64","description":"Block number the transaction was confirmed in."},"actualFee":{"type":"string","description":"Actual fee paid in drops."},"errorCode":{"type":"integer","format":"int32","description":"On-chain execution error code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"errorDesc":{"type":"string","description":"Error description if the transaction failed."},"closeTime":{"type":"integer","format":"int64","description":"Block close timestamp in milliseconds."},"txSize":{"type":"integer","format":"int64","description":"Transaction size in bytes."},"transaction":{"$ref":"#/components/schemas/TransactionInfo"},"signatures":{"type":"array","items":{"$ref":"#/components/schemas/Signature"}},"contractTxHashes":{"type":"array","items":{"type":"string"},"description":"Internal hashes from contract execution."}}},"TransactionInfo":{"type":"object","properties":{"sourceAddress":{"type":"string"},"feeLimit":{"type":"integer","format":"int64"},"gasPrice":{"type":"integer","format":"int64"},"nonce":{"type":"integer","format":"int64"},"chainId":{"type":"integer","format":"int64"}}},"Signature":{"type":"object","properties":{"signData":{"type":"string"},"publicKey":{"type":"string"}}}}}}
```

## The TransactionHistory object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"TransactionHistory":{"type":"object","description":"Full on-chain transaction record.","properties":{"hash":{"type":"string","description":"Transaction hash."},"ledgerSeq":{"type":"integer","format":"int64","description":"Block number the transaction was confirmed in."},"actualFee":{"type":"string","description":"Actual fee paid in drops."},"errorCode":{"type":"integer","format":"int32","description":"On-chain execution error code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"errorDesc":{"type":"string","description":"Error description if the transaction failed."},"closeTime":{"type":"integer","format":"int64","description":"Block close timestamp in milliseconds."},"txSize":{"type":"integer","format":"int64","description":"Transaction size in bytes."},"transaction":{"$ref":"#/components/schemas/TransactionInfo"},"signatures":{"type":"array","items":{"$ref":"#/components/schemas/Signature"}},"contractTxHashes":{"type":"array","items":{"type":"string"},"description":"Internal hashes from contract execution."}}},"TransactionInfo":{"type":"object","properties":{"sourceAddress":{"type":"string"},"feeLimit":{"type":"integer","format":"int64"},"gasPrice":{"type":"integer","format":"int64"},"nonce":{"type":"integer","format":"int64"},"chainId":{"type":"integer","format":"int64"}}},"Signature":{"type":"object","properties":{"signData":{"type":"string"},"publicKey":{"type":"string"}}}}}}
```

## The TransactionInfo object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"TransactionInfo":{"type":"object","properties":{"sourceAddress":{"type":"string"},"feeLimit":{"type":"integer","format":"int64"},"gasPrice":{"type":"integer","format":"int64"},"nonce":{"type":"integer","format":"int64"},"chainId":{"type":"integer","format":"int64"}}}}}}
```

## The Signature object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"Signature":{"type":"object","properties":{"signData":{"type":"string"},"publicKey":{"type":"string"}}}}}}
```

## The TransactionParseBlobResult object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"TransactionParseBlobResult":{"type":"object","description":"Decoded contents of a transaction blob.","properties":{"sourceAddress":{"type":"string","description":"Address that initiated the transaction."},"feeLimit":{"type":"integer","format":"int64","description":"Maximum gas fee allowed."},"gasPrice":{"type":"integer","format":"int64","description":"Gas price per unit."},"nonce":{"type":"integer","format":"int64","description":"Transaction sequence number."},"chainId":{"type":"integer","format":"int64","description":"Zetrix chain identifier."},"operations":{"type":"array","items":{"$ref":"#/components/schemas/OperationFormat"}}}},"OperationFormat":{"type":"object","description":"Decoded operation from a parsed blob.","properties":{"type":{"type":"string"},"sourceAddress":{"type":"string"},"metadata":{"type":"string"},"sendGas":{"$ref":"#/components/schemas/GasSendInfo"},"sendAsset":{"$ref":"#/components/schemas/AssetSendInfo"},"setMetadata":{"$ref":"#/components/schemas/AccountSetMetadataInfo"},"log":{"$ref":"#/components/schemas/LogInfo"}}},"GasSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"amount":{"type":"integer","format":"int64"},"input":{"type":"string"}}},"AssetSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"input":{"type":"string"}}},"AccountSetMetadataInfo":{"type":"object","properties":{"key":{"type":"string"},"value":{"type":"string"},"version":{"type":"integer","format":"int64"},"deleteFlag":{"type":"boolean"}}},"LogInfo":{"type":"object","properties":{"topic":{"type":"string"},"datas":{"type":"array","items":{"type":"string"}}}}}}}
```

## The OperationFormat object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"OperationFormat":{"type":"object","description":"Decoded operation from a parsed blob.","properties":{"type":{"type":"string"},"sourceAddress":{"type":"string"},"metadata":{"type":"string"},"sendGas":{"$ref":"#/components/schemas/GasSendInfo"},"sendAsset":{"$ref":"#/components/schemas/AssetSendInfo"},"setMetadata":{"$ref":"#/components/schemas/AccountSetMetadataInfo"},"log":{"$ref":"#/components/schemas/LogInfo"}}},"GasSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"amount":{"type":"integer","format":"int64"},"input":{"type":"string"}}},"AssetSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"input":{"type":"string"}}},"AccountSetMetadataInfo":{"type":"object","properties":{"key":{"type":"string"},"value":{"type":"string"},"version":{"type":"integer","format":"int64"},"deleteFlag":{"type":"boolean"}}},"LogInfo":{"type":"object","properties":{"topic":{"type":"string"},"datas":{"type":"array","items":{"type":"string"}}}}}}}
```

## The GasSendInfo object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"GasSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"amount":{"type":"integer","format":"int64"},"input":{"type":"string"}}}}}}
```

## The AssetSendInfo object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"AssetSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"input":{"type":"string"}}}}}}
```

## The AccountSetMetadataInfo object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"AccountSetMetadataInfo":{"type":"object","properties":{"key":{"type":"string"},"value":{"type":"string"},"version":{"type":"integer","format":"int64"},"deleteFlag":{"type":"boolean"}}}}}}
```

## The LogInfo object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"LogInfo":{"type":"object","properties":{"topic":{"type":"string"},"datas":{"type":"array","items":{"type":"string"}}}}}}}
```

## The ContractUsageHistoryRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ContractUsageHistoryRespDto":{"type":"object","description":"A single contract invocation history record.","properties":{"id":{"type":"integer","format":"int64","description":"Internal record ID."},"address":{"type":"string","description":"Contract on-chain address."},"contractKey":{"type":"string","description":"Contract alias key."},"txInitiator":{"type":"string","description":"Address that initiated the transaction."},"method":{"type":"string","description":"Contract method called."},"inputParameters":{"type":"string","description":"JSON-serialized input parameters."},"txHash":{"type":"string","description":"Transaction hash."},"status":{"type":"string","enum":["INITIATED","SUBMITTED"],"description":"Invocation status."},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}
```

## The ResponsePaginatedContractUsageHistoryRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponsePaginatedContractUsageHistoryRespDto":{"type":"object","properties":{"page":{"type":"integer","format":"int64"},"pageSize":{"type":"integer","format":"int64"},"totalPages":{"type":"integer","format":"int32"},"totalElements":{"type":"integer","format":"int64"},"content":{"type":"array","items":{"$ref":"#/components/schemas/ContractUsageHistoryRespDto"}}}},"ContractUsageHistoryRespDto":{"type":"object","description":"A single contract invocation history record.","properties":{"id":{"type":"integer","format":"int64","description":"Internal record ID."},"address":{"type":"string","description":"Contract on-chain address."},"contractKey":{"type":"string","description":"Contract alias key."},"txInitiator":{"type":"string","description":"Address that initiated the transaction."},"method":{"type":"string","description":"Contract method called."},"inputParameters":{"type":"string","description":"JSON-serialized input parameters."},"txHash":{"type":"string","description":"Transaction hash."},"status":{"type":"string","enum":["INITIATED","SUBMITTED"],"description":"Invocation status."},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}
```

## The DSMonitoringBlockchain object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringBlockchain":{"type":"object","description":"Comprehensive blockchain network statistics.","properties":{"chainId":{"type":"integer","format":"int64"},"chainName":{"type":"string"},"blockchainHeight":{"type":"integer","format":"int64"},"transactionNum":{"type":"integer","format":"int64"},"accountNum":{"type":"integer","format":"int64"},"txTpsMax":{"type":"integer","format":"int32"},"currentTps":{"type":"integer","format":"int32"},"txNumLastDay":{"type":"integer","format":"int64"},"blockAverageGeneTime":{"type":"integer","format":"int32"},"netStatus":{"type":"string"},"lastLedgerList":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringLedger"}},"lastTxList":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringTx"}}}},"DSMonitoringLedger":{"type":"object","properties":{"seq":{"type":"integer","format":"int64","description":"Block sequence number."},"txNum":{"type":"integer","format":"int64","description":"Transactions in this block."},"ledgerAge":{"type":"integer","format":"int64","description":"Age in milliseconds."}}},"DSMonitoringTx":{"type":"object","properties":{"senderAddress":{"type":"string"},"txHash":{"type":"string"},"txTime":{"type":"integer","format":"int64"}}}}}}
```

## The DSMonitoringLedger object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringLedger":{"type":"object","properties":{"seq":{"type":"integer","format":"int64","description":"Block sequence number."},"txNum":{"type":"integer","format":"int64","description":"Transactions in this block."},"ledgerAge":{"type":"integer","format":"int64","description":"Age in milliseconds."}}}}}}
```

## The DSMonitoringTx object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringTx":{"type":"object","properties":{"senderAddress":{"type":"string"},"txHash":{"type":"string"},"txTime":{"type":"integer","format":"int64"}}}}}}
```

## The DSMonitoringNodeStatWrapper object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringNodeStatWrapper":{"type":"object","properties":{"total":{"type":"integer","format":"int32","description":"Total nodes across all types."},"validatorNodeStat":{"$ref":"#/components/schemas/DSMonitoringNodeStat"},"synchronousNodeStat":{"$ref":"#/components/schemas/DSMonitoringNodeStat"}}},"DSMonitoringNodeStat":{"type":"object","properties":{"total":{"type":"integer","format":"int32"},"onlineCount":{"type":"integer","format":"int32"},"offlineCount":{"type":"integer","format":"int32"},"warnCount":{"type":"integer","format":"int32"}}}}}}
```

## The DSMonitoringNodeStat object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringNodeStat":{"type":"object","properties":{"total":{"type":"integer","format":"int32"},"onlineCount":{"type":"integer","format":"int32"},"offlineCount":{"type":"integer","format":"int32"},"warnCount":{"type":"integer","format":"int32"}}}}}}
```

## The DSMonitoringPagination object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringPagination":{"type":"object","properties":{"pageNum":{"type":"integer","format":"int32"},"pageSize":{"type":"integer","format":"int32"},"total":{"type":"integer","format":"int32"},"content":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringNodeList"}}}},"DSMonitoringNodeList":{"type":"object","description":"Details of an individual blockchain node.","properties":{"nodeName":{"type":"string","description":"Human-readable node name."},"nodeAddress":{"type":"string","description":"Zetrix address of the node."},"consensusAddress":{"type":"string"},"nodeType":{"type":"string","description":"`VALIDATOR` or `SYNCHRONOUS`."},"nodeStatus":{"type":"string","description":"`ONLINE`, `OFFLINE`, or `WARN`."},"operatingSystem":{"type":"string"},"blockSeq":{"type":"string","description":"Latest synced block number."},"blockHash":{"type":"string"},"expirationTime":{"type":"string"},"certEndTime":{"type":"string"},"licenseEndTime":{"type":"string"}}}}}}
```

## The DSMonitoringNodeList object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringNodeList":{"type":"object","description":"Details of an individual blockchain node.","properties":{"nodeName":{"type":"string","description":"Human-readable node name."},"nodeAddress":{"type":"string","description":"Zetrix address of the node."},"consensusAddress":{"type":"string"},"nodeType":{"type":"string","description":"`VALIDATOR` or `SYNCHRONOUS`."},"nodeStatus":{"type":"string","description":"`ONLINE`, `OFFLINE`, or `WARN`."},"operatingSystem":{"type":"string"},"blockSeq":{"type":"string","description":"Latest synced block number."},"blockHash":{"type":"string"},"expirationTime":{"type":"string"},"certEndTime":{"type":"string"},"licenseEndTime":{"type":"string"}}}}}}
```

## The DSMonitoringNode object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"DSMonitoringNode":{"type":"object","description":"Node count for a geographic region.","properties":{"geographyCode":{"type":"integer","format":"int32","description":"Numeric ISO country/region code."},"total":{"type":"integer","format":"int32","description":"Number of nodes in this region."}}}}}}
```

## The MultiValueMapStringString object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"MultiValueMapStringString":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"description":"Multi-value map for flexible filter parameters."}}}}
```

## The ResponseWrapperTxSubmitRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperTxSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/TxSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"TxSubmitRespDto":{"type":"object","properties":{"hash":{"type":"string","description":"Transaction hash confirming successful broadcast."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperListSignerEntity object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperListSignerEntity":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/SignerEntity"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"SignerEntity":{"type":"object","description":"A signer object containing a signature and public key pair. Used in transaction/contract submission requests.","properties":{"signBlob":{"type":"string","description":"Hex-encoded Ed25519 signature of the transaction blob."},"publicKey":{"type":"string","description":"Hex-encoded Ed25519 public key of the signer. Must be exactly 76 characters.","minLength":76,"maxLength":76}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperPaymasterSubmitRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperPaymasterSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/PaymasterSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"PaymasterSubmitRespDto":{"type":"object","description":"Response after queuing a paymaster-sponsored transaction.","properties":{"txHash":{"type":"string","description":"Transaction hash. Poll `/tx/query` with this for final status."},"blobId":{"type":"string","description":"Paymaster blob reservation ID."},"nonce":{"type":"integer","format":"int64","description":"Nonce used from the paymaster pool."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring the gas fee."},"status":{"type":"string","description":"Processing status. Initially `QUEUED`; becomes `SUCCESS` or `FAILED` after processing."},"submittedAt":{"type":"string","format":"date-time","description":"Timestamp when queued."},"blockNumber":{"type":"integer","format":"int64","description":"Block number confirmed in (populated post-confirmation)."},"gasUsed":{"type":"integer","format":"int64","description":"Actual gas units consumed."},"gasFeePaid":{"type":"integer","format":"int64","description":"Total gas fee paid by paymaster in drops."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperPaymasterGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperPaymasterGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/PaymasterGenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"PaymasterGenerateBlobRespDto":{"type":"object","description":"Response for paymaster transaction blob generation.","required":["blob","blobId","expiresAt","hash","paymasterAddress","paymasterNonce","paymasterPoolId","timeoutMinutes"],"properties":{"blob":{"type":"string","description":"Hex-encoded transaction blob. Sign and submit via `/tx/paymaster/submit`."},"hash":{"type":"string","description":"Transaction hash. Required when calling `/tx/sign-blob`."},"blobId":{"type":"string","description":"Unique ID for this paymaster reservation. Required in `/tx/paymaster/submit`."},"paymasterAddress":{"type":"string","description":"Paymaster address that will sponsor the gas fee."},"paymasterNonce":{"type":"integer","format":"int64","description":"Nonce allocated from the paymaster pool."},"paymasterPoolId":{"type":"integer","format":"int64","description":"ID of the paymaster pool used."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units (1 ZETRIX = 10^6 units)."},"expiresAt":{"type":"string","format":"date-time","description":"Nonce reservation expiry. Submit before this time."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Duration in minutes the reservation is valid."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/GenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"GenerateBlobRespDto":{"type":"object","description":"Response for transaction blob generation.","required":["blob","hash"],"properties":{"blob":{"type":"string","description":"Hex-encoded serialized transaction blob. Sign before submitting."},"hash":{"type":"string","description":"SHA-256 transaction hash. Required when calling `/tx/sign-blob`."},"actualFee":{"type":"integer","format":"int64","description":"Estimated transaction fee in gas units."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperTransactionParseBlobResult object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperTransactionParseBlobResult":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/TransactionParseBlobResult"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"TransactionParseBlobResult":{"type":"object","description":"Decoded contents of a transaction blob.","properties":{"sourceAddress":{"type":"string","description":"Address that initiated the transaction."},"feeLimit":{"type":"integer","format":"int64","description":"Maximum gas fee allowed."},"gasPrice":{"type":"integer","format":"int64","description":"Gas price per unit."},"nonce":{"type":"integer","format":"int64","description":"Transaction sequence number."},"chainId":{"type":"integer","format":"int64","description":"Zetrix chain identifier."},"operations":{"type":"array","items":{"$ref":"#/components/schemas/OperationFormat"}}}},"OperationFormat":{"type":"object","description":"Decoded operation from a parsed blob.","properties":{"type":{"type":"string"},"sourceAddress":{"type":"string"},"metadata":{"type":"string"},"sendGas":{"$ref":"#/components/schemas/GasSendInfo"},"sendAsset":{"$ref":"#/components/schemas/AssetSendInfo"},"setMetadata":{"$ref":"#/components/schemas/AccountSetMetadataInfo"},"log":{"$ref":"#/components/schemas/LogInfo"}}},"GasSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"amount":{"type":"integer","format":"int64"},"input":{"type":"string"}}},"AssetSendInfo":{"type":"object","properties":{"destAddress":{"type":"string"},"input":{"type":"string"}}},"AccountSetMetadataInfo":{"type":"object","properties":{"key":{"type":"string"},"value":{"type":"string"},"version":{"type":"integer","format":"int64"},"deleteFlag":{"type":"boolean"}}},"LogInfo":{"type":"object","properties":{"topic":{"type":"string"},"datas":{"type":"array","items":{"type":"string"}}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperTxQueryRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperTxQueryRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/TxQueryRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"TxQueryRespDto":{"type":"object","description":"Transaction query result.","properties":{"txStatus":{"type":"string","description":"Numeric transaction lifecycle status code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"txContent":{"$ref":"#/components/schemas/TransactionHistory"}}},"TransactionHistory":{"type":"object","description":"Full on-chain transaction record.","properties":{"hash":{"type":"string","description":"Transaction hash."},"ledgerSeq":{"type":"integer","format":"int64","description":"Block number the transaction was confirmed in."},"actualFee":{"type":"string","description":"Actual fee paid in drops."},"errorCode":{"type":"integer","format":"int32","description":"On-chain execution error code. See [Zetrix WebSocket Error Codes](https://docs.zetrix.com/en/developer-resources/api/websocket#error-codes)."},"errorDesc":{"type":"string","description":"Error description if the transaction failed."},"closeTime":{"type":"integer","format":"int64","description":"Block close timestamp in milliseconds."},"txSize":{"type":"integer","format":"int64","description":"Transaction size in bytes."},"transaction":{"$ref":"#/components/schemas/TransactionInfo"},"signatures":{"type":"array","items":{"$ref":"#/components/schemas/Signature"}},"contractTxHashes":{"type":"array","items":{"type":"string"},"description":"Internal hashes from contract execution."}}},"TransactionInfo":{"type":"object","properties":{"sourceAddress":{"type":"string"},"feeLimit":{"type":"integer","format":"int64"},"gasPrice":{"type":"integer","format":"int64"},"nonce":{"type":"integer","format":"int64"},"chainId":{"type":"integer","format":"int64"}}},"Signature":{"type":"object","properties":{"signData":{"type":"string"},"publicKey":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperContractSubmitRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperContractSubmitRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ContractSubmitRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ContractSubmitRespDto":{"type":"object","properties":{"hash":{"type":"string","description":"Transaction hash confirming contract invocation was broadcast."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperContractGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperContractGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ContractGenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ContractGenerateBlobRespDto":{"type":"object","description":"Response for contract invocation blob generation.","properties":{"blob":{"type":"string","description":"Hex-encoded contract invocation blob."},"hash":{"type":"string","description":"Transaction hash."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperContractPaymasterGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperContractPaymasterGenerateBlobRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ContractPaymasterGenerateBlobRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ContractPaymasterGenerateBlobRespDto":{"type":"object","description":"Response for paymaster-sponsored contract invocation blob generation.","required":["blob","blobId","expiresAt","hash","paymasterAddress","paymasterNonce","paymasterPoolId","timeoutMinutes"],"properties":{"blob":{"type":"string","description":"Hex-encoded blob. Sign and submit via `/contract/paymaster/submit`."},"hash":{"type":"string","description":"Transaction hash."},"blobId":{"type":"string","description":"Paymaster reservation ID. Required in `/contract/paymaster/submit`."},"paymasterAddress":{"type":"string","description":"Paymaster address sponsoring gas."},"paymasterNonce":{"type":"integer","format":"int64","description":"Reserved nonce."},"paymasterPoolId":{"type":"integer","format":"int64","description":"Paymaster pool ID."},"contractAddress":{"type":"string","description":"Resolved on-chain contract address."},"method":{"type":"string","description":"Contract method being invoked."},"actualFee":{"type":"integer","format":"int64","description":"Estimated fee in gas units."},"expiresAt":{"type":"string","format":"date-time","description":"Nonce reservation expiry. Submit before this time."},"timeoutMinutes":{"type":"integer","format":"int32","description":"Timeout duration in minutes."},"platformSignData":{"$ref":"#/components/schemas/PlatformSignDataEntity"}}},"PlatformSignDataEntity":{"type":"object","description":"Optional platform co-signature data, present when the platform pre-signs the blob.","properties":{"publicKey":{"type":"string","description":"Platform's public key."},"signBlob":{"type":"string","description":"Platform's signature of the blob."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperJSONObject object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperJSONObject":{"type":"object","properties":{"object":{"type":"object","additionalProperties":{},"description":"Dynamic JSON response from the smart contract method."},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperDSMonitoringBlockchain object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperDSMonitoringBlockchain":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/DSMonitoringBlockchain"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringBlockchain":{"type":"object","description":"Comprehensive blockchain network statistics.","properties":{"chainId":{"type":"integer","format":"int64"},"chainName":{"type":"string"},"blockchainHeight":{"type":"integer","format":"int64"},"transactionNum":{"type":"integer","format":"int64"},"accountNum":{"type":"integer","format":"int64"},"txTpsMax":{"type":"integer","format":"int32"},"currentTps":{"type":"integer","format":"int32"},"txNumLastDay":{"type":"integer","format":"int64"},"blockAverageGeneTime":{"type":"integer","format":"int32"},"netStatus":{"type":"string"},"lastLedgerList":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringLedger"}},"lastTxList":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringTx"}}}},"DSMonitoringLedger":{"type":"object","properties":{"seq":{"type":"integer","format":"int64","description":"Block sequence number."},"txNum":{"type":"integer","format":"int64","description":"Transactions in this block."},"ledgerAge":{"type":"integer","format":"int64","description":"Age in milliseconds."}}},"DSMonitoringTx":{"type":"object","properties":{"senderAddress":{"type":"string"},"txHash":{"type":"string"},"txTime":{"type":"integer","format":"int64"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperDSMonitoringNodeStatWrapper object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperDSMonitoringNodeStatWrapper":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/DSMonitoringNodeStatWrapper"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringNodeStatWrapper":{"type":"object","properties":{"total":{"type":"integer","format":"int32","description":"Total nodes across all types."},"validatorNodeStat":{"$ref":"#/components/schemas/DSMonitoringNodeStat"},"synchronousNodeStat":{"$ref":"#/components/schemas/DSMonitoringNodeStat"}}},"DSMonitoringNodeStat":{"type":"object","properties":{"total":{"type":"integer","format":"int32"},"onlineCount":{"type":"integer","format":"int32"},"offlineCount":{"type":"integer","format":"int32"},"warnCount":{"type":"integer","format":"int32"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperDSMonitoringPagination object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperDSMonitoringPagination":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/DSMonitoringPagination"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringPagination":{"type":"object","properties":{"pageNum":{"type":"integer","format":"int32"},"pageSize":{"type":"integer","format":"int32"},"total":{"type":"integer","format":"int32"},"content":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringNodeList"}}}},"DSMonitoringNodeList":{"type":"object","description":"Details of an individual blockchain node.","properties":{"nodeName":{"type":"string","description":"Human-readable node name."},"nodeAddress":{"type":"string","description":"Zetrix address of the node."},"consensusAddress":{"type":"string"},"nodeType":{"type":"string","description":"`VALIDATOR` or `SYNCHRONOUS`."},"nodeStatus":{"type":"string","description":"`ONLINE`, `OFFLINE`, or `WARN`."},"operatingSystem":{"type":"string"},"blockSeq":{"type":"string","description":"Latest synced block number."},"blockHash":{"type":"string"},"expirationTime":{"type":"string"},"certEndTime":{"type":"string"},"licenseEndTime":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperListDSMonitoringNode object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperListDSMonitoringNode":{"type":"object","properties":{"object":{"type":"array","items":{"$ref":"#/components/schemas/DSMonitoringNode"}},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"DSMonitoringNode":{"type":"object","description":"Node count for a geographic region.","properties":{"geographyCode":{"type":"integer","format":"int32","description":"Numeric ISO country/region code."},"total":{"type":"integer","format":"int32","description":"Number of nodes in this region."}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperLong object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperLong":{"type":"object","properties":{"object":{"type":"integer","format":"int64","description":"The numeric value (e.g., block height)."},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```

## The ResponseWrapperResponsePaginatedContractUsageHistoryRespDto object

```json
{"openapi":"3.1.0","info":{"title":"Zetrix Microservice API","version":"1.0.0"},"components":{"schemas":{"ResponseWrapperResponsePaginatedContractUsageHistoryRespDto":{"type":"object","properties":{"object":{"$ref":"#/components/schemas/ResponsePaginatedContractUsageHistoryRespDto"},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ResponseMessage"}},"success":{"type":"boolean"},"timestamp":{"type":"string","format":"date-time"},"traceId":{"type":"string"}}},"ResponsePaginatedContractUsageHistoryRespDto":{"type":"object","properties":{"page":{"type":"integer","format":"int64"},"pageSize":{"type":"integer","format":"int64"},"totalPages":{"type":"integer","format":"int32"},"totalElements":{"type":"integer","format":"int64"},"content":{"type":"array","items":{"$ref":"#/components/schemas/ContractUsageHistoryRespDto"}}}},"ContractUsageHistoryRespDto":{"type":"object","description":"A single contract invocation history record.","properties":{"id":{"type":"integer","format":"int64","description":"Internal record ID."},"address":{"type":"string","description":"Contract on-chain address."},"contractKey":{"type":"string","description":"Contract alias key."},"txInitiator":{"type":"string","description":"Address that initiated the transaction."},"method":{"type":"string","description":"Contract method called."},"inputParameters":{"type":"string","description":"JSON-serialized input parameters."},"txHash":{"type":"string","description":"Transaction hash."},"status":{"type":"string","enum":["INITIATED","SUBMITTED"],"description":"Invocation status."},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"ResponseMessage":{"type":"object","description":"A response message indicating informational, warning, or error details.","properties":{"type":{"type":"string","description":"Severity: `INFO`, `WARNING`, or `ERROR`.","enum":["INFO","ERROR","WARNING"]},"errorCode":{"type":"integer","format":"int32","description":"Numeric error code (0 = no error)."},"message":{"type":"string","description":"Human-readable description."}}}}}}
```


# Core

Blockchain Node List API, Node Stat API, Node Count API, Block Height, Total Supply, Circulation Supply and Blockchain Information API.

Each of these APIs serves a specific purpose within the context of blockchain networks. They enable developers and users to gather insights, monitor network health, and access various data points related to nodes and the overall blockchain system.

The **Node List API** provides detailed information about a specific node in a blockchain network. It allows you to retrieve various details related to a particular node, such as node address, node status, block height, network connectivity, and other relevant metadata. This API is particularly useful for monitoring and analyzing individual nodes within the network and assessing their performance and status.

The **Node Stat API** provides statistical information and metrics related to individual nodes in a blockchain network. It allows users to retrieve data about the performance, status, and behavior of specific nodes within the network.

The **Blockchain Information API** provides comprehensive data and information about the blockchain network as a whole. It includes various endpoints to access essential blockchain details, such as the current block height, transaction history, chain name, transaction list and other relevant information. This API is typically used to obtain an overview of the blockchain network and to retrieve historical and real-time data about the blockchain's operation.

The **Node Count API** provides information about the number of active nodes in a blockchain network. It typically returns a count or statistical data indicating the total number of nodes currently participating in the network. This API helps monitor the health and decentralization of the blockchain network by tracking the number of active nodes and ensuring a robust network infrastructure.

The **Total Supply API** provides information about the total amount of tokens that have been created or issued on the blockchain. This includes tokens that are currently in circulation as well as tokens that are locked, reserved, or otherwise not actively circulating. This API is used to understand the maximum or current issuance of the blockchain’s native token.

The **Circulating Supply API** provides information about the number of tokens that are actively circulating in the market. It excludes tokens that are locked, burned, reserved, or held in non-circulating accounts. This API is commonly used for market analysis, token economics evaluation, and price-related metrics.

### Node list

```
GET HTTP /ztx/core/node-list?nodeType=VALIDATOR_NODE&pageNo=1&pageSize=100
```

CURL Command

```bash
curl GET https://{endpoint}/ztx/core/node-list?nodeType=VALIDATOR_NODE&pageNo=1&pageSize=100
```

* Function

To view list of node running.

* Return Value

```json
{
    "object": {
        "pageNum": 1,
        "pageSize": 100,
        "content": [
            {
                "chainId": null,
                "nodeName": "Node 21",
                "nodeAddress": "ZTX3XY22vmRwWuKxn7UNuXdpLANfBx5Gx9bca",
                "consensusAddress": null,
                "monitored": null,
                "nodeType": null,
                "nodeStatus": "RUNNING",
                "operatingSystem": null,
                "expirationTime": null,
                "expirationTimeDay": null,
                "certEndTime": null,
                "certEndTimeDay": null,
                "licenseEndTime": null,
                "licenseEndTimeDay": null,
                "blockSeq": null,
                "blockHash": null
            },
            ........................
            {
                "chainId": null,
                "nodeName": "Node 1",
                "nodeAddress": "ZTX3RuTB1VcoNi7pmBUDFvAXe3HB6rKf7jeW2",
                "consensusAddress": null,
                "monitored": null,
                "nodeType": null,
                "nodeStatus": "RUNNING",
                "operatingSystem": null,
                "expirationTime": null,
                "expirationTimeDay": null,
                "certEndTime": null,
                "certEndTimeDay": null,
                "licenseEndTime": null,
                "licenseEndTimeDay": null,
                "blockSeq": null,
                "blockHash": null
            },

}
```

### Node stat

```
GET HTTP /ztx/core/node-stat
```

CURL Command

```bash
curl GET https://{endpoint}/ztx/core/node-stat
```

* Function

To view statistics of node running.

* Return Value

```json
{
    "object": {
        "total": 38,
        "validatorNodeStat": {
            "total": 35,
            "onlineCount": 31,
            "offlineCount": 4,
            "warnCount": 0
        },
        "synchronousNodeStat": {
            "total": 3,
            "onlineCount": 0,
            "offlineCount": 1,
            "warnCount": 1
        }
    },
    "messages": []
}

```

### Blockchain info

```
GET HTTP /ztx/core/blockchain-info
```

CURL Command

```bash
curl GET https://{endpoint}/ztx/core/blockchain-info
```

* Function

To view overall of blockchain information.

* Return Value

```json
{
    "object": {
        "chainId": 1635227727,
        "transactionNum": 1138594,
        "accountNum": 109614,
        "blockchainHeight": 1342741,
        "txTpsMax": 6,
        "currentTps": 0,
        "txNumLastDay": 90,
        "txNumPs": 0,
        "blockAverageGeneTime": 36,
        "preBlockGeneTime": 21,
        "netStatus": "NORMAL",
        "operationTime": 568,
        "updateTime": 1689041401239,
        "chainName": "ZETRIX Genesis Chain",
        "lastLedgerList": [
            {
                "seq": 1342741,
                "txNum": 0,
                "ledgerAge": 24
            },
            {
                "seq": 1342740,
                "txNum": 0,
                "ledgerAge": 84
            },
            {
                "seq": 1342739,
                "txNum": 0,
                "ledgerAge": 144
            },
            {
                "seq": 1342738,
                "txNum": 0,
                "ledgerAge": 204
            },
            {
                "seq": 1342737,
                "txNum": 0,
                "ledgerAge": 264
            }
        ],
        "lastTxList": [
            {
                "senderAddress": "ZTX3TMHqen5SSFhgDRPapLwR7MXn5UYuQBzsS",
                "txHash": "ac343453c7fe8b60773739582f363efbd1d2af60def3296dc7b96563cd4a2a01",
                "txTime": 1689040801000
            },
            {
                "senderAddress": "ZTX3Uz3b6CTXXDNQfv6W4Kuje98CDqqVH6wkB",
                "txHash": "83770bb477e5a0f37699e0c76cf93041201659320c81b2b654ba176b35bcfc10",
                "txTime": 1689040038000
            },
            {
                "senderAddress": "ZTX3TMHqen5SSFhgDRPapLwR7MXn5UYuQBzsS",
                "txHash": "7ee4f74edc949cb4dacdbfe65d635cdc339676d560f5b9efcef1fd7e8c5c44e5",
                "txTime": 1689037205000
            },
            {
                "senderAddress": "ZTX3K4ShVibYSf22yTu4SMH3ZUBn2KwiFG1jQ",
                "txHash": "9b9c995362d7dc4ea023d38b9c0fd2440937c9600860bc99fb42732a888a16c9",
                "txTime": 1689036655000
            },
            {
                "senderAddress": "ZTX3K4ShVibYSf22yTu4SMH3ZUBn2KwiFG1jQ",
                "txHash": "f4cf7bfc7a20a3498a6cd8b607fba1f23c786c1418e05561cbc4b305f0c75966",
                "txTime": 1689036628000
            }
        ]
    },
    "messages": []
}

```

### Node count

```
GET HTTP /ztx/core/node-count
```

CURL Command

```bash
curl GET https://{endpoint}/ztx/core/node-count
```

* Function

To view node running based on geographical. Geography Code is refer as follow:

| geographyCode | Region        |
| ------------- | ------------- |
| 0             | Asia          |
| 1             | Europe        |
| 2             | Africa        |
| 3             | Oceania       |
| 4             | North America |
| 5             | South America |

* Return Value

```json
{
    "object": [
        {
            "geographyCode": 0,
            "total": 12
        },
        {
            "geographyCode": 1,
            "total": 6
        },
        {
            "geographyCode": 4,
            "total": 3
        },
        {
            "geographyCode": 5,
            "total": 2
        },
        {
            "geographyCode": 3,
            "total": 6
        },
        {
            "geographyCode": 2,
            "total": 6
        }
    ],
    "messages": []
}
```

### Block Height

```
GET HTTP /ztx/core/block-height
```

CURL Command

```bash
GET https://{endpoint}/ztx/core/block-height
```

* Function

To get latest block height from the node

* Return Value

```json
{
    "object": "1582107",
    "messages": []
}
```

### Total Supply

```
GET HTTP /ztx/core/total-supply
```

CURL Command

```bash
GET https://{endpoint}/ztx/core/total-supply
```

* Function

To get latest total supply from the node.

* Return Value.

```
1157075644.000000
```

### Circulation Supply

```
GET HTTP /ztx/core/circulation-supply
```

CURL Command

```bash
GET https://{endpoint}/ztx/core/circulation-supply
```

* Function

To get latest circulation supply from the node.

* Return Value.

```
273453899.844711
```


# Transaction

A **Zetrix Transaction Blockchain API** allows developers to send and receive transactions, read data, and access smart contract functions on a blockchain programmatically.

To create a transaction, you typically need to provide the sender's address, the recipient's address, the amount of the cryptocurrency to send, and a transaction fee, which is paid to the miners who verify and process the transaction. Once the transaction is created, it is broadcast to the network and added to a pool of unconfirmed transactions.

The **Zetrix Transaction Blockchain API** allows developers to interact with these unconfirmed transactions, retrieve information about them, and monitor their status in real-time. You can also use the transaction API to inspect the details of a confirmed transaction, including the amount sent, the recipient, and the timestamp of the transaction.

#### Generate Blob

```
POST HTTP /ztx/tx/generate-blob
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/tx/generate-blob
```

* Function

To generate blob based on input account.

* The body is in json data.

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure.

```json
{
  "operations": [
    {
      "amount": "string",
      "fromAddress": "string",
      "inputStr": "string",
      "payload": "string",
      "precision": "string",
      "toAddress": "string",
      "type": "string"
    }
  ],
  "txInitiator": "string"
}
```

"type" field can be depicted as follows:

```
1 - CREATE_ACCOUNT - Creating account
2 - TRANSFER - Transfer token
3 - CALL_CONTRACT - Query or invoking contract
4 - CREATE_CONTRACT - Creating new contract
5 - SET_METADATA - Set metadata
```

* Return Value

```json
{
  "messages": [
    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": {
    "blob": "string",
    "hash": "string",
    "platformSignData": {
      "publicKey": "string",
      "signBlob": "string"
    }
  }
}
```

For example, to transfer Zetrix coin, developer can provide the following info in the payload where type is equals to 2.

```json
{
    "txInitiator": "ZTX3ZAikPMsNRCFoituy9TpYULvzKwz6NDRQi",
    "operations": [
        {
            "amount": "1",
            "inputStr": "",
            "fromAddress": "ZTX3ZAikPMsNRCFoituy9TpYULvzKwz6NDRQi",
            "type": "2",
            "toAddress": "ZTX3Lsfv96VEB98tV771wwgrUPT8sNNq8Wf9A",
            "precision": "",
            "payload": ""
        }
    ]
}
```

Response from the example :

```json
{
    "object": {
        "blob": "0A255A5458335A41696B504D734E5243466F6974757939547059554C767A4B777A364E4452516910022256080712255A5458335A41696B504D734E5243466F6974757939547059554C767A4B777A364E44525169622B0A255A5458334C7366763936564542393874563737317777677255505438734E4E71385766394110C0843D30AE71380A",
        "hash": "8a4adfda356da062c608d33cbd8db40c703dc123c4f718e4b6444a152fc50e3f",
        "platformSignData": null
    },
    "messages": []
}
```

#### Parse Blob

```
POST HTTP /ztx/tx/parse-blob
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/tx/parse-blob
```

* Function

To parse a blob.

* The body is in json data.

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure.

```json
{
  "blob": "string"
}
```

* Return Value

```json
{
  "messages": [
    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": {
    "chainId": 0,
    "feeLimit": 0,
    "gasPrice": 0,
    "nonce": 0,
    "operations": [
      {
        "createAccount": {
          "contract": {
            "owner": "string",
            "payload": "string",
            "type": 0
          },
          "destAddress": "string",
          "initBalance": 0,
          "initInput": "string",
          ....
          }
        },
        "issueAsset": {
          "amount": 0,
          "code": "string"
        },
        ....
      }
    ],
    "sourceAddress": "string"
  }
}
```

#### Query Transaction By Hash

```
GET HTTP /ztx/tx/query
```

CURL Command

```bash
curl GET https://{endpoint}/ztx/tx/query?hash=<TX_HASH>
```

* Function

To query a transaction.

* The body is in json data.

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure.

| Name | Description      | Format |
| ---- | ---------------- | ------ |
| hash | transaction hash | string |

```json
hash
```

* Return Value

```json
{
  "messages": [
    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": {
    "txContent": {
      "actualFee": "string",
      "closeTime": 0,
      "contractTxHashes": [
        "string"
      ],
      "errorCode": 0,
      "errorDesc": "string",
      "hash": "string",
      "ledgerSeq": 0,
      "signatures": [
        {
          "publicKey": "string",
          "signData": "string"
        }
      ],
      "transaction": {
        "chainId": 0,
        "feeLimit": 0,
        "gasPrice": 0,
        "metadata": "string",
        "nonce": 0,
        ...
        "sourceAddress": "string"
      },
      "trigger": {
        "transaction": {
          "hash": "string"
        }
      },
      "txSize": 0
    },
    "txStatus": "string"
  }
}
```

#### Sign Blob

```
POST HTTP /ztx/tx/sign-blob
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/tx/sign-blob
```

* Function

To sign transaction blob.

* The body is in json data.

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure.

```json
{
  "blob": "string",
  "hash": "string",
  "privateKeys": [
    "string"
  ]
}
```

* Return Value

```json
{
  "messages": [
    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": [
    {
      "publicKey": "string",
      "signBlob": "string"
    }
  ]
}
```

#### Submit Transaction

```
POST HTTP /ztx/tx/submit
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/tx/submit
```

* Function

To submit transaction.

* The body is in json data.

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure.

```json
{
  "blob": "string",
  "hash": "string",
  "initiator": "string",
  "listSigner": [
    {
      "publicKey": "string",
      "signBlob": "string"
    }
  ]
}
```

* Return Value

```json
{
  "messages": [
    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": {
    "hash": "string"
  }
}
```


# Contract

A **Contract Blockchain API** allows you to interact with smart contracts on a Zetrix blockchain network programmatically. Smart contracts are agreements that execute automatically when certain conditions are met, and they are stored on the blockchain.

With a **Contract Blockchain API,** developers can automate the interaction with these smart contracts, allowing them to build decentralized applications (DApps) and more complex blockchain-based systems.

This API typically uses a set of methods to interact with smart contracts, including methods to write data to the blockchain, read data from the blockchain, and execute smart contract functions.

#### Query Contract

```
HTTP POST /ztx/contract/query-address
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/contract/query-address
```

* Function

To query all the contract based contract key.

* The body is in json format

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure. Example：

```json
{
    "address": "",
    "method": "",
    "inputParameters": {
    }
}
```

* Return Value

```json
{
    "object": {
        "result": {
            "type": "string",
            "value": ""
        }
    },
    "messages": [],
    "success": true,
    "timestamp": "",
    "traceId": ""
}
```

#### Invoke Contract – History Filter

* Query Parameters

| Parameter       | Type    | Required | Description                                     |
| --------------- | ------- | -------- | ----------------------------------------------- |
| address         | string  | No       | Contract address                                |
| status          | string  | No       | Transaction status (INITIATED, SUBMITTED, etc.) |
| contractKey     | string  | No       | Contract key                                    |
| txInitiator     | string  | No       | Transaction initiator address                   |
| txHash          | string  | No       | Transaction hash                                |
| method          | string  | No       | Contract method name                            |
| createdDateFrom | string  | No       | Start date (ISO format)                         |
| createdDateTo   | string  | No       | End date (ISO format)                           |
| page            | integer | No       | Page number (default: 0)                        |
| pageSize        | integer | No       | Page size (default: 10)                         |
| sort            | string  | No       | Field to sort by                                |
| isAsc           | boolean | No       | Sort ascending (true/false)                     |

```
HTTP GET /ztx/contract/history/filter
```

CURL Command

```bash
curl GET 'https://{endpoint}/ztx/contract/history/filter
```

* Function

Retrieve contract transaction history with optional filtering and pagination.

* Return Value

```json
{
  "object": {
    "page": 0,
    "pageSize": 10,
    "totalPages": 2,
    "totalElements": 17,
    "content": [
      {
        "id": 1,
        "address": "string",
        "contractKey": "string",
        "txInitiator": "string",
        "method": "string",
        "inputParameters": "string",
        "txHash": "string",
        "status": "string",
        "createdAt": "string",
        "updatedAt": "string"
      }
    ]
  },
  "messages": [],
  "success": true,
  "timestamp": "yyyy-MM-dd HH:mm:ss",
  "traceId": "string"
}

```

#### Invoke Contract - Generate Blob

```
HTTP POST /ztx/contract/generate-blob
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/contract/generate-blob
```

* Function

Generate a blob.

* The body is in json format

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure. Example：

```json
{
  "contractKey": "string",
  "inputParameters": {},
  "method": "string",
  "txInitiator": "string"
}
```

* Return Value

<pre class="language-json"><code class="lang-json">{
<strong>  "messages": [
</strong>    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": {
    "blob": "string",
    "hash": "string",
    "platformSignData": {
      "publicKey": "string",
      "signBlob": "string"
    }
  }
}
</code></pre>

#### Invoke Contract - Sign Blob

```
HTTP POST /ztx/contract/sign-blob
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/contract/sign-blob
```

* Function

To sign transaction blob.

* The body is in json format

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure. Example：

```json
{
  "privateKey": "",
  "blob": ""
}
```

* Return Value

```json
{
    "object": [
        {
            "signBlob": "",
            "publicKey": ""
        }
    ],
    "messages": [],
    "success": true,
    "timestamp": "",
    "traceId": ""
}
```

#### Invoke Contract - Submit

```
HTTP POST /ztx/contract/submit
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/contract/submit
```

* Function

To invoke data to contract.

* The body is in json format

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure. Example：

```json
{
  "blob": "string",
  "hash": "string",
  "initiator": "string",
  "listSigner": [
    {
      "publicKey": "string",
      "signBlob": "string"
    }
  ]
}
```

* Return Value

```json
{
  "messages": [
    {
      "errorCode": 0,
      "message": "string",
      "type": "INFO"
    }
  ],
  "object": {
    "hash": "string"
  }
}
```


# Paymaster

## Overview

The Paymaster API enables **gas-sponsored transactions** on the Zetrix blockchain by allowing users to delegate transaction fee payments to a managed Paymaster account.

This API is designed to:

* Remove the requirement for end users to hold ZTX for gas fees.
* Provide secure and fair **paymaster rotation.**
* Ensure correct **nonce management** across concurrent transactions.
* Improve transaction reliability through tracking and recovery mechanisms.

The Paymaster service acts as an intermediary between client applications and the Zetrix blockchain, handling nonce allocation, paymaster selection, transaction submission, and failure recovery.

***

## Transaction Flow

1. **Generate Blob**\
   Client requests the Paymaster API to generate an unsigned transaction blob.
2. **Client Signs Blob**\
   The unsigned blob is signed locally using the user’s private key.
3. **Submit Blob**\
   The signed blob is submitted back to the Paymaster API for paymaster signing and on-chain submission.
4. **Transaction Tracking & Recovery**\
   The system tracks the transaction status and performs automatic recovery if a transaction is dropped or stuck.

## Paymaster API Specification

### Generate Blob

#### Authorization

Authorization must be sent with all client requests. The Bearer Access Token needed to authenticate and authorize user to access the API

#### **Request**

```bash
POST /ztx/tx/paymaster/generate-blob
```

**CURL Command**

```bash
curl POST https://{endpoint}/ztx/tx/paymaster/generate-blob
```

#### Root Parameters

| Field         | Type   | Required | Description                               |
| ------------- | ------ | -------- | ----------------------------------------- |
| userAddress   | string | ✅        | Wallet address initiating the transaction |
| operationType | string | ✅        | Logical operation category                |
| metadata      | object | ❌        | Custom metadata for tracking              |
| operations    | array  | ✅        | List of transaction operations            |

| Type | Params                                                                                                                                                                                                                                                     | Values                                                                                                                                                                                                                                    |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HEAD | `Authorization`                                                                                                                                                                                                                                            | `string`                                                                                                                                                                                                                                  |
| POST | <p><code>operations\[]</code></p><ul><li><code>amount</code></li><li><code>inputStr</code></li><li><code>fromAddress</code></li><li><code>type</code></li><li><code>toAddress</code></li><li><code>precision</code></li><li><code>payload</code></li></ul> | <p><code>Array\[]</code></p><ul><li><code>String</code></li><li><code>String</code></li><li><code>String</code></li><li><code>String</code></li><li><code>String</code></li><li><code>String</code></li><li><code>String</code></li></ul> |

**amount**

`amount` is amount that need to be transfer to other wallet.

**inputStr**

`inputStr` is general field for memos.

**type**

`type` is type of transaction, below is the list of type:

1. Create Account
2. Transfer
3. Call Contract
4. Create Contract
5. Set Metadata
6. Account Set Privilege
7. Upgrade Contract Content
8. Upgrade Contract Owner

**toAddress**

`toAddress` is wallet account address to receive transactions.

**precision**

`precision` is precision is decimal places for amount transfer, default is 6

**payload**

`precision` is precision is decimal places for amount transfer, default is 6

#### Function

To Generate a blob for a given transaction data.

#### Request Body

The body is in json format.

Here body transfer is the transaction data. For specific json format and parameters, see transaction structure. Example：

```json
{
  "userAddress": "ZTX3QkbTjJsc7xDbwRtuHn826cAYF79uKR3rt",
  "operationType": "TEST_TRANSACTION",
  "metadata": {
    "id": "tx_pm_5"
  },
  "operations": [
    {
      "amount": "1.5",
      "inputStr": "",
      "fromAddress": "ZTX3QkbTjJsc7xDbwRtuHn826cAYF79uKR3rt",
      "type": "2",
      "toAddress": "ZTX3b69xfJZbiC8WbrtE2Ez27zri3a6K9B5pt",
      "precision": "",
      "payload": ""
    }
  ],
}'

```

#### Response

```json
{
    "object": {
        "blob": "0A255A5458334D4B46654B4A413342524165693747737A6D48526F79597259596F6B79554A4551100E2256080712255A545833516B62546A4A73633778446277527475486E383236634159463739754B52337274622B0A255A54583362363978664A5A62694338576272744532457A32377A72693361364B394235707410E0C65B30E45F3805",
        "hash": "054197b910b77a240f440ea5ca4c4dc0074023dc566fa749fc967efece92327f",
        "platformSignData": null,
        "actualFee": null,
        "blobId": "BLOB-3F1B883A021D4424",
        "paymasterAddress": "ZTX3MKFeKJA3BRAei7GszmHRoyYrYYokyUJEQ",
        "paymasterNonce": 14,
        "paymasterPoolId": 2,
        "expiresAt": "2026-04-06T09:28:30.072942652",
        "timeoutMinutes": 10
    },
    "messages": [],
    "success": true,
    "timestamp": "2026-04-06 09:18:30",
    "traceId": "74851775-6903-400c-abf7-ec1d37a7b9fc"
}
```

### Submit Blob

Submit signed blob for create transaction

#### Authorization

Authorization must be sent with all client requests. The Bearer Access Token needed to authenticate and authorize user to access the API

**Request**

```bash
POST /ztx/tx/paymaster/submit
```

CURL Command

```bash
curl POST https://{endpoint}/ztx/tx/paymaster/submit
```

| Type | Params                                                                                                   | Values                                                                                        |
| ---- | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| HEAD | `Authorization`                                                                                          | `String`                                                                                      |
| POST | `blobId`                                                                                                 | `String`                                                                                      |
| POST | `blob`                                                                                                   | `String`                                                                                      |
| POST | <p><code>listSigners\[]</code></p><ul><li><code>signBlob</code></li><li><code>publicKey</code></li></ul> | <p><code>Array\[]</code></p><ul><li><code>String</code></li><li><code>String</code></li></ul> |
| POST | `paymasterAddress`                                                                                       | `String`                                                                                      |

**blobId**

`blobId` is Identifier returned from `generate-blob`

**blob**

`blob` is transaction blob that need to signed

**signBlob**

`signBlob` is generated blob that have been signed by user wallet private key

**publicKey**

`publicKey` is user wallet public key

**paymasterAddress**

`paymasterAddress` is wallet address of paymaster resulted from /tx/generate-blob

#### Function

To submit a blob for execute transaction.

#### Request Body

The body is in json format.

Here body transfer is the transaction data. For specific json format and parameters, see transaction structure. Example：

```json
{
    "blobId": "BLOB-FCC1642A329D4768",
    "blob": "0A255A545833475548766172366278637948637A6543796D6153334B535341356B75775556445510032256080712255A545833516B62546A4A73633778446277527475486E383236634159463739754B52337274622B0A255A54583362363978664A5A62694338576272744532457A32377A72693361364B394235707410E0C65B3080FA01380A",
    "listSigner": [
        {
            "signBlob": "BD966E7A15599505B018CB623391BA5C58ABEB1054CC3043C36A0F3D7993BBAA3B65244ED7B158BB7A2D63CC5A0F6B8D2F535D1FB758B8E5B1CF5541CA5CC204",
            "publicKey": "b001eff30af3427a38c5cd021f5ac28578d27c3bd1ab53fc4d2789c1f8cb1827e83c58de414a"
        }
    ]
}
```

#### Response

```json
{
    "object": {
        "hash": "a4e42e4c0f8be1eb089bdc0d9a9a6fe0e465f3e1956771157889bcdd2f767452",
        "paymasterAddress": "ZTX3cpRnFgi24PMUvnqxCBb7Lc8rJZuqEcTnR",
        "message": "Success"
    },
    "messages": []
}
```

## Paymaster Smart Contract

### Generate Blob

#### Authorization

Authorization must be sent with all client requests. The Bearer Access Token needed to authenticate and authorize user to access the API

**Request**

```bash
POST /ztx/contract/paymaster/generate-blob
```

**CURL Command**

```bash
curl POST https://{endpoint}/ztx/contract/paymaster/generate-blob
```

| Type | Params                                                                                          | Values                                                                                        |
| ---- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| HEAD | `Authorization`                                                                                 | `String`                                                                                      |
| POST | `userAddress`                                                                                   | `String`                                                                                      |
| POST | `contractAddress`                                                                               | `String`                                                                                      |
| POST | `method`                                                                                        | `String`                                                                                      |
| POST | <p><code>inputParameters</code></p><ul><li><code>to</code></li><li><code>value</code></li></ul> | <p><code>Array\[]</code></p><ul><li><code>String</code></li><li><code>String</code></li></ul> |

**address**

`address` is contract address

**method**

`method` is invoke method in smart contract to interact\
\
**inputParameters**

`inputParameters` is input data that required for invoke method

**sourceAddress**

`inputParameters` is owner of smart contract

#### Function

To generate a blob from a given transaction data.

#### Request Body

The body is in json format

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure. Example：

```json
{
    "userAddress":"ZTX3QkbTjJsc7xDbwRtuHn826cAYF79uKR3rt",
    "contractAddress": "ZTX3ZfbJ8AT8u8W7dx3g5tqbJ7nnGoYCszaj6",
    "method": "transfer",
    "inputParameters": {
        "to": "ZTX3b69xfJZbiC8WbrtE2Ez27zri3a6K9B5pt",
        "value": "500000000"
    }
}
```

#### Response

```json
{
    "object": {
        "blob": "0A255A5458334D4B46654B4A413342524165693747737A6D48526F79597259596F6B79554A4551100F22B601080712255A545833516B62546A4A73633778446277527475486E383236634159463739754B52337274628A010A255A5458335A66624A384154387538573764783367357471624A376E6E476F5943737A616A361A617B226D6574686F64223A227472616E73666572222C22706172616D73223A7B22746F223A225A54583362363978664A5A62694338576272744532457A32377A72693361364B3942357074222C2276616C7565223A22353030303030303030227D7D30FCBD02380A",
        "hash": "97f8c9f0721cecc871848e099412aae325c4f1fb1288863ad855465007123ab4",
        "platformSignData": null,
        "blobId": "BLOB-FD7247F70FF84BF3",
        "paymasterAddress": "ZTX3MKFeKJA3BRAei7GszmHRoyYrYYokyUJEQ",
        "paymasterNonce": 15,
        "paymasterPoolId": 2,
        "expiresAt": "2026-04-06T09:42:42.448084207",
        "timeoutMinutes": 10,
        "contractAddress": "ZTX3ZfbJ8AT8u8W7dx3g5tqbJ7nnGoYCszaj6",
        "method": "transfer",
        "actualFee": 40700
    },
    "messages": [],
    "success": true,
    "timestamp": "2026-04-06 09:32:42",
    "traceId": "7cd09ac8-448f-49e9-87ff-82bf366ed62b"
}
```

### Submit Invoke Blob

#### Authorization

Authorization must be sent with all client requests. The Bearer Access Token needed to authenticate and authorize user to access the API

**Request**

```bash
POST /ztx/contract/paymaster/submit
```

**CURL Command**

```bash
curl POST https://{endpoint}/ztx/contract/paymaster/submit
```

| Type | Params                                                                                                   | Values                                                                                    |
| ---- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| HEAD | `Authorization`                                                                                          | `String`                                                                                  |
| POST | `blobId`                                                                                                 | `String`                                                                                  |
| POST | `blob`                                                                                                   | `String`                                                                                  |
| POST | <p><code>listSigners\[]</code></p><ul><li><code>signBlob</code></li><li><code>publicKey</code></li></ul> | <p><code>Array\[]</code></p><p><br><code>String]</code></p><p><code>String</code><br></p> |

**blobId**

`blobId` is Identifier returned from `generate-blob`

**blob**

`blob` is transaction blob that need to signed

**signBlob**

`signBlob` is generated blob that have been signed by user wallet private key

**publicKey**

`publicKey` is user wallet public key

**initiator**

`initiator` is wallet address of paymaster resulted from /contract/generate-blob

#### Function

To submit a blob to execute a transaction.

#### Request Body

The body is in json format

Here body transfer is the transaction data. For specific json format and parameters, see Transaction Structure. Example：

```json
{
    "blobId": "BLOB-3F6BCE4AA08D4D88",
    "blob": "0A255A5458335A3176633233554A6B576B38765139733754576B7070725846336A4255636A346F102F22B601080712255A545833516B62546A4A73633778446277527475486E383236634159463739754B52337274628A010A255A5458335A66624A384154387538573764783367357471624A376E6E476F5943737A616A361A617B226D6574686F64223A227472616E73666572222C22706172616D73223A7B22746F223A225A54583362363978664A5A62694338576272744532457A32377A72693361364B3942357074222C2276616C7565223A22353030303030303030227D7D30FCBD02380A",
    "listSigner": [
        {
            "signBlob": "1481CAE9D963C98C903AB02C26A74FF6AE3B5FF0351144933CC0E748E7182E2723A584228DCB663D0EECA3F45A70431C4DB772AE13ADD247D897D18A28237001",
            "publicKey": "b001eff30af3427a38c5cd021f5ac28578d27c3bd1ab53fc4d2789c1f8cb1827e83c58de414a"
        }
    ]
}'

```

#### Response

```json
{
    "object": {
        "hash": "a4e42e4c0f8be1eb089bdc0d9a9a6fe0e465f3e1956771157889bcdd2f767452",
        "paymasterAddress": "ZTX3cpRnFgi24PMUvnqxCBb7Lc8rJZuqEcTnR",
        "message": "Success"
    },
    "messages": []
}
```


# Zetrix Oraclize

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FJzFB1ozWUdmptkZ6GJIH%2Fimage.png?alt=media&amp;token=45ef657e-2d26-4e58-8cdb-e80944946fbf" alt=""><figcaption></figcaption></figure>

Zetrix Oraclize has been developed to remove the limitation of communication between Smart Contract and outside world. Zetrix Oraclize supports common Rest API methods such as GET, POST, PUT, DELETE Basic and Bearer token authentication methods are supported to establish secure communication.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FfnGbxXZrLIxWA0I2cO64%2FArchitecture%20Oraclize.png?alt=media&amp;token=d39f3e8e-04e9-47b6-8eb5-496ef4816ee1" alt=""><figcaption><p>Design Architecture</p></figcaption></figure>

Zetrix Oraclize also a blockchain oracle service that enables smart contracts on blockchain platforms to interact with external data sources such as APIs, web services, and traditional databases. It achieves this by providing a secure bridge that connects smart contracts to off-chain data, thus avoiding the need for developers to manually input the data. Zetrix Oraclize is designed to provide developers with reliable, transparent, and efficient access to external data, allowing them to build more sophisticated smart contracts and decentralized applications.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FF0hDbInLKz3sOHfo5hml%2Foperationflow.jpg.png?alt=media&amp;token=6c89c320-5e88-418b-8ae6-4c589ba236aa" alt=""><figcaption><p>Operation flow</p></figcaption></figure>

When using Zetrix Oraclize, developers specify an API call in their smart contract, which is then sent to Oraclize along with the payment required for the call. Oraclize then retrieves the data from the specified data source, verifies the authenticity of the data, and sends it back to the smart contract. The data is then processed by the smart contract according to the programmed logic.

Overall, Zetrix Oraclize provides a useful tool for developers seeking to build more complex and data-heavy smart contracts, as it enables the contracts to interact with external data sources in a secure and efficient way.

## Integration With Oraclize Contract

1. First, need to ensure that have Oraclize and its associated libraries properly installed in the smart contract code.
2. Define the `payCoin` function in the smart contract. This function should accept any necessary parameters and perform the necessary checks and validations before triggering the Oraclize Contract function `queryOraclize`.
3. In the `payCoin` function, calculation the cost of the Oraclize query based on its execution cost. The `oraclize_getPrice` function is used to retrieve the cost of the query in ZTX or the relevant cryptocurrency.
4. If the value passed in by the caller is less than the calculated oraclizeCost, the function will revert and throw an error notifying the caller that the funds are insufficient. If it is more than oraclizeCost, the function will refund the extra funds to the caller's account.
5. Once the payment has been made, then trigger the `queryOraclize` function in the Oraclize Contract, along with any necessary parameters such as the amount of cryptocurrency to be queried.

Overall, by triggering the `payCoin` function, can trigger the Oraclize Contract and retrieve external data using Oraclize, while automatically paying the necessary fees based on the execution cost of the query."

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FLc2B7T8bSMiFkKBABQKE%2FIntegration%20with%20oraclize%20contract.png?alt=media&amp;token=5fbab2c9-986b-45ff-8990-74a9745999e5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F5qdnCrS2oQzaRddT9CnN%2FIntegration%20with%20oraclize%20contract%202.png?alt=media&amp;token=957c3732-6014-402f-86a2-739500e889c3" alt=""><figcaption><p>Call payCoin function to trigger Oraclize Contract function “queryOraclize”. The payment is based on execution cost set in Oraclize Contract</p></figcaption></figure>

## Integration Protocol For Request

| Item            | Description                                                                               |
| --------------- | ----------------------------------------------------------------------------------------- |
| URL             | Eg) [http://xxx.com](http://xxx.com/)                                                     |
| method          | POST, GET, PUT, DELETE                                                                    |
| headers         | <p>Key Value Json form</p><p>Eg )</p><p>{</p><p>“Authorization”: “Bearer xxx”</p><p>}</p> |
| body            | <p>Key Value Json form</p><p>Eg )</p><p>{</p><p>“id”: “xxx”</p><p>}</p>                   |
| callbackAddress | User Contract Address (ZTX….)                                                             |
| callbackMethod  | Predefined Method in User Contract                                                        |

## Integration Protocol For Response

| Item    | Description                 |
| ------- | --------------------------- |
| object  | Json Object                 |
| message | String                      |
| status  | String “SUCCESS” / “FAILED” |

## Example (Request)

Caller Contract : <https://test-explorer.zetrix.com/account/ZTX3WMzq13j47z6HjzLnwRqqwqEdiP1bw93Dp>

Oraclize Contract : <https://test-explorer.zetrix.com/account/ZTX3QLowAYiRnj8ifaHDhUax9CfD1h5CrTB1w>

## Call GET Request from Caller Contract

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FpWt3WZ0eRiEtj7S54Wmk%2Fimage.png?alt=media&amp;token=98c94d10-c35c-4522-b830-d1e548846cfc" alt=""><figcaption></figcaption></figure>

## Example (Response)

Caller Contract : <https://test-explorer.zetrix.com/account/ZTX3WMzq13j47z6HjzLnwRqqwqEdiP1bw93Dp>

Oraclize Contract : <https://test-explorer.zetrix.com/account/ZTX3QLowAYiRnj8ifaHDhUax9CfD1h5CrTB1w>

## Get Response from Oraclize Contract

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FWzIn5ySZ1tejulQns0Pw%2Fimage.png?alt=media&amp;token=d0d31b36-36a5-4b08-b15d-e2a1eddd1d12" alt=""><figcaption></figcaption></figure>


# Scheduler Contract

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FKJpG91rTZn57UxhQHhOe%2Fimage.png?alt=media&amp;token=b6af474f-78fd-47eb-9c78-28bb7802b1c3" alt=""><figcaption></figcaption></figure>

The **Scheduler Contract in Zetrix Blockchain** is designed to support a standard interface for communication with other smart contracts. It enables seamless interaction between different contracts and facilitates task scheduling and execution based on a predefined cron job timing. Here's a breakdown of its functionality:

1. **Standard Interface:** The Scheduler Contract provides a standardized interface that other smart contracts can use to communicate with it. This interface likely includes functions for registering and deregistering tasks.
2. **Task Registration:** Smart contracts that require scheduled execution of specific tasks can communicate with the Scheduler Contract to register those tasks. During registration, the smart contract specifies the details of the task, such as the function to be executed, the timing for execution, and any required parameters.
3. **Cron Job Timing:** The Scheduler Contract utilizes a cron job timing mechanism to automatically execute the registered tasks based on the specified schedule. Cron job timing allows for the precise configuration of task execution intervals, such as daily, weekly, monthly, or custom-defined intervals.
4. **Automatic Execution:** Once a task is registered with the Scheduler Contract, it will be automatically executed according to the specified cron job timing. This eliminates the need for manual intervention or triggering of task execution by external parties.

By leveraging the Scheduler Contract's standard interface, smart contracts within the Zetrix Blockchain ecosystem can seamlessly interact with the Scheduler Contract, register their tasks, and rely on the automatic execution based on the defined schedule. This functionality simplifies the management of scheduled tasks within the blockchain network, streamlines communication between contracts, and enhances the efficiency of decentralized applications built on Zetrix Blockchain.

## Design Architecture

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FLk90CZUvYAp5bJ6bFyDv%2Fimage.png?alt=media&amp;token=591ee80e-08be-4459-bae7-d8bd271fb713" alt=""><figcaption></figcaption></figure>

In the Zetrix Blockchain ecosystem, users can connect to the Scheduler Contract using a standard protocol from their Smart Contract or SDK. This allows for seamless integration and interaction between various components. Here's an explanation of the process:

1. **User Integration:** Users can integrate their Smart Contracts or SDKs with the Scheduler Contract using a standard protocol. This protocol provides a set of functions and methods that enable communication and interaction with the Scheduler Contract.
2. **Periodic List Check**: A common scheduler, which is a component outside the Scheduler Contract, periodically checks the running list stored within the Scheduler Contract. This check occurs every 40 seconds or after the maximum block validation time.
3. **Task Owner's Balance Check:** Before executing a task, the common scheduler verifies the remaining balance of the task owner. This check ensures that the owner has sufficient funds or resources to cover the execution of the task.
4. **Callback Trigger:** Upon reaching the set cron timing, the common scheduler triggers the callback function in the Scheduler Contract. The cron timing specifies when a task should be executed based on a predetermined schedule.
5. **Delegation to Callback Address:** The Scheduler Contract delegates the task execution by making a call to the callback address specified during task registration. This ensures that the desired function or operation defined in the callback address is executed as per the task's requirements.

By connecting their Smart Contracts or SDKs to the Scheduler Contract using the standard protocol, users can effectively schedule and execute tasks based on the defined cron timing.

## Operation Flow

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FIQ6U8bCRHYVVClVtXV2N%2Fimage.png?alt=media&amp;token=4da50a4f-ad9b-4518-adc0-8cbcba8a878f" alt=""><figcaption><p>Operation Flow</p></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Fu8RVxX79Vg8xTh8mU3MF%2Fimage.png?alt=media&amp;token=bee7e74b-e084-4407-9376-7032c2e1d4aa" alt=""><figcaption><p>Operation flow</p></figcaption></figure>

## Communication With Scheduler Contract

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F5MmMjh060ftho0MHm5DO%2Fimage.png?alt=media&amp;token=b9d61f0a-3d94-46cf-b096-1e8b43dfd51d" alt=""><figcaption></figcaption></figure>

## Protocol For Registration

| Item            | Description                                                                 |
| --------------- | --------------------------------------------------------------------------- |
| taskName        | Example: ”My Task”                                                          |
| cronTime        | Example: 0 0/1 \* \* \* \*                                                  |
| callbackAddress | User Contract Address (ZTX….)                                               |
| callbackMethod  | Predefined Method in User Contract                                          |
| callbackParams  | <p>Key Value json form</p><p>example:</p><p>{</p><p>“id”: “xxx”</p><p>}</p> |

## Example (Register Task)

Scheduler Contract : <https://test-explorer.zetrix.com/account/ZTX3Kfprq7zvFb8KXNEAbWZSZScZfVuFJCtuA>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FaP7ti7OneqRt1vlBd34V%2Fimage.png?alt=media&amp;token=1044e62b-fc58-4f24-8d68-a44e0d89aca1" alt=""><figcaption></figcaption></figure>

## Example (Running Task)

Scheduler Contract : <https://test-explorer.zetrix.com/account/ZTX3Kfprq7zvFb8KXNEAbWZSZScZfVuFJCtuA>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FfnYdNiD2JyWlmPlXHQHI%2Fimage.png?alt=media&amp;token=b9a035eb-1254-439e-acc0-da1b17970825" alt=""><figcaption></figcaption></figure>


# TradeTrust API

## TradeTrust API overview

The TradeTrust API lets applications create and manage TradeTrust document workflows.

It is part of the `myeg-z2-service` platform. The API follows OpenAPI `3.1.0`.

Use it to integrate document issuance, verification, and related TradeTrust operations.

### Get started

1. Obtain a JWT from the shared BaaS authentication service.
2. Select the server that matches your environment.
3. Send the bearer token with every API request.
4. Include an API key for sandbox and v2 gateway endpoints.

### Request authentication

All TradeTrust endpoints require a bearer token. Gateway-hosted environments may also require an API key.

#### `bearerAuth`

* **Type:** HTTP `bearer` (JWT)

Send the OAuth2 JWT in the `Authorization` header:

```http
Authorization: Bearer <access-token>
```

Authentication runs before request routing. Unauthenticated requests return `401`, including unknown paths.

#### `apiKeyAuth`

* **Type:** API key in header `X-API-Key`

The AWS API Gateway key is required on `api-sandbox` and `api-v2` servers.

```http
X-API-Key: <api-key>
```

This key does not replace the bearer token. The gateway validates it before requests reach this service. Omit it when port-forwarding to a pod.

### API reference

Use the endpoint reference for operation paths, request schemas, and response details.

***


# Trade Trust Credentials

Issue and verify a verifiable credential through core-engine.

## Complete a signed credential

> Hand back the signed credential from the matching \<code>prepare\</code> call and get the finished one.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"CompleteCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/complete</code> — hand back the signed credential from\n the matching <code>prepare</code> call and get the finished one.\n\n <p><code>preparationId</code> is single-use and expires (core-engine's pending store has a ~15 minute\n TTL); a stale one is a 404, mapped by <code>CustomExceptionHandler</code>'s generic core-engine bucket.","properties":{"preparationId":{"type":"string","minLength":1},"signedVerifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1}},"required":["preparationId","signedVerifiableCredential"]},"ResponseWrapperCompletedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/CompletedCredentialRespDto"}}},"CompletedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/complete</code> (and <code>/issue</code>, which ends at the\n same step) — the assembled, signed credential.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}}}}}},"paths":{"/tradetrust/credentials/complete":{"post":{"tags":["TradeTrust Credentials"],"summary":"Complete a signed credential","description":"Hand back the signed credential from the matching <code>prepare</code> call and get the finished one.","operationId":"complete","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompleteCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperCompletedCredentialRespDto"}}}}}}}}}
```

## Issue a credential in one call

> Issue a credential in one call: \<code>prepare\</code> -\&gt; core-engine signs -\&gt; \<code>complete\</code>.\
> &#x20;Sends the issuer's private key to core-engine — see this class's javadoc.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"IssueCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/issue</code> — the same build as\n {@link PrepareCredentialReqDto PrepareCredentialReqDto}, plus the issuer's key pair for <b>delegated signing</b>\n (BT-2620's chosen signing model: <code>prepare</code> -&gt; core-engine's <code>/credentials/sign</code>\n -&gt; <code>complete</code>, in one call).\n\n <p><b>This sends the issuer's private key to core-engine.</b> See {@link MultikeyDto MultikeyDto} and the\n SDK's <code>signRemote</code> javadoc for the custody note.","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"type":{"type":"array","items":{"type":"string"}},"context":{"type":"array","items":{"type":"string"}},"validFrom":{"type":"string"},"expirationDate":{"type":"string"},"statusPurpose":{"type":"string","pattern":"(?i)^(revocation|suspension)$"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}},"keyPair":{"$ref":"#/components/schemas/MultikeyDto"}},"required":["credentialSubject","issuerDid","keyPair"]},"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]},"ResponseWrapperCompletedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/CompletedCredentialRespDto"}}},"CompletedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/complete</code> (and <code>/issue</code>, which ends at the\n same step) — the assembled, signed credential.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}}}}}},"paths":{"/tradetrust/credentials/issue":{"post":{"tags":["TradeTrust Credentials"],"summary":"Issue a credential in one call","description":"Issue a credential in one call: <code>prepare</code> -&gt; core-engine signs -&gt; <code>complete</code>.\n Sends the issuer's private key to core-engine — see this class's javadoc.","operationId":"issue","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IssueCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperCompletedCredentialRespDto"}}}}}}}}}
```

## Prepare a credential for signing

> Build the unsigned credential and the spec for signing it. The caller signs, then calls \<code>complete\</code>.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"PrepareCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/prepare</code> — build the unsigned credential and the\n spec for signing it. <code>issuerDid</code> and <code>credentialSubject</code> are required; everything\n else defaults server-side in core-engine.\n\n <p><code>statusPurpose</code> attaches a status-list entry, which is what later makes the credential\n revocable; a plain string here (not the SDK's own enum) so this DTO — and the OpenAPI document\n generated from it — stays independent of the SDK's type, per BT-2620's design.","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"type":{"type":"array","items":{"type":"string"}},"context":{"type":"array","items":{"type":"string"}},"validFrom":{"type":"string"},"expirationDate":{"type":"string"},"statusPurpose":{"type":"string","pattern":"(?i)^(revocation|suspension)$"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}}},"required":["credentialSubject","issuerDid"]},"ResponseWrapperPreparedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/PreparedCredentialRespDto"}}},"PreparedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/prepare</code> — the unsigned document plus its\n signing spec.\n\n <p><code>preparationId</code> is single-use and expires (~15 minutes); pass it unmodified to\n <code>complete</code> or <code>issue</code> alongside the signed document.","properties":{"preparationId":{"type":"string"},"unsignedVerifiableCredential":{"type":"object","additionalProperties":{}},"signingSpec":{"$ref":"#/components/schemas/SigningSpecRespDto"}}},"SigningSpecRespDto":{"type":"object","description":"Exactly how core-engine expects a prepared document to be signed — part of\n {@link PreparedCredentialRespDto PreparedCredentialRespDto}. Pass <code>mandatoryPointers</code> to the signer verbatim; core-engine\n derives it from what it actually built, so reconstructing it silently drops fields from the base proof.","properties":{"mandatoryPointers":{"type":"array","items":{"type":"string"}},"cryptoSuite":{"type":"string"},"expectedIssuerDid":{"type":"string"}}}}},"paths":{"/tradetrust/credentials/prepare":{"post":{"tags":["TradeTrust Credentials"],"summary":"Prepare a credential for signing","description":"Build the unsigned credential and the spec for signing it. The caller signs, then calls <code>complete</code>.","operationId":"prepare","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PrepareCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperPreparedCredentialRespDto"}}}}}}}}}
```

## Revoke or suspend a credential

> Revoke, un-revoke or suspend one credential — \<code>revoked\</code> chooses the direction and\
> &#x20;\<code>purpose\</code> chooses the list, so this one route covers all four.\
> \
> &#x20;\<p>The caller signs the mutation; this service only forwards it and never handles issuer key\
> &#x20;material. See {@link RevokeCredentialReqDto RevokeCredentialReqDto} for the exact string to sign.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"RevokeCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/revoke</code> — flip one status-list bit, authorized by\n the issuer's own signature.\n\n <p><strong>This service cannot revoke on your behalf, by design.</strong> core-engine only ever\n verifies a status mutation, never signs one, so the authorization has to come from whoever holds\n the issuer key. This route is a pass-through: it carries <code>nonce</code>, <code>timestamp</code> and\n <code>signature</code> to core-engine and touches no key material at all — unlike\n <code>/credentials/issue</code>, no {@link MultikeyDto MultikeyDto} appears here and none may ever be added.\n\n <p>Sign this exact string with the issuer's P-256 key, SHA-256 prehashed, as a 64-byte compact\n <code>r‖s</code> pair, hex-encoded:\n\n <pre>STATUS-MUTATE|{issuerDid}|{purpose}|{index}|{revoked}|{nonce}|{timestamp}</pre>\n\n <p>The Java SDK's <code>CredentialsClient.statusMutationMessage(...)</code> builds it, and\n <code>Signatures.derToCompactRs</code> converts a JCA signature to the wire form — <code>SHA256withECDSA</code>\n already prehashes and emits DER, and both mistakes yield a well-formed signature that fails with\n only \"signature invalid\" to go on.\n\n <p>One route covers all four operations. <code>revoked</code> chooses the direction, <code>purpose</code>\n chooses the list: <code>revocation</code> + <code>true</code> revokes, <code>revocation</code> + <code>false</code>\n un-revokes, and <code>suspension</code> does the same to the suspension list. <code>revoked</code> is boxed\n and required so an omitted field is a 400 rather than a silent un-revoke.\n\n <p>Two server-side rules make a naive retry fail. <code>timestamp</code> must be within ~60s of\n core-engine's clock, and it must be strictly newer than the last accepted mutation for this\n <code>index</code> — so a retry has to be re-signed with a fresh timestamp, never replayed.","properties":{"issuerDid":{"type":"string","minLength":1},"purpose":{"type":"string","description":"Which list to write to. Same two values <code>prepare</code>'s <code>statusPurpose</code> accepts.","minLength":1,"pattern":"(?i)^(revocation|suspension)$"},"index":{"type":"integer","format":"int32","description":"The credential's own <code>credentialStatus.statusListIndex</code>. Read it off the credential\n rather than guessing: an unallocated index can be written, and a credential later issued into\n it would be born revoked.","minimum":0},"revoked":{"type":"boolean"},"nonce":{"type":"string","description":"Any unique value; it is signed, so it cannot be swapped after the fact.","minLength":1},"timestamp":{"type":"string","description":"ISO-8601, and part of the signed message — not a header this service adds.","minLength":1},"signature":{"type":"string","description":"Hex-encoded 64-byte compact <code>r‖s</code> P-256 signature over the canonical message above.","minLength":1}},"required":["index","issuerDid","nonce","purpose","revoked","signature","timestamp"]},"ResponseWrapperStatusUpdateRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/StatusUpdateRespDto"}}},"StatusUpdateRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/revoke</code> — the status-list entry's state after the\n write, echoed back from core-engine.\n\n <p>Every field is an echo of what was applied, not a fresh read, so treat it as confirmation that\n the mutation was accepted rather than as the list's current contents. The bit is visible to\n verifiers on the next <code>GET</code> of the status list, which core-engine signs fresh on each\n request — there is no cache to wait out.","properties":{"issuerId":{"type":"string"},"purpose":{"type":"string"},"index":{"type":"integer","format":"int32"},"revoked":{"type":"boolean"}}}}},"paths":{"/tradetrust/credentials/revoke":{"post":{"tags":["TradeTrust Credentials"],"summary":"Revoke or suspend a credential","description":"Revoke, un-revoke or suspend one credential — <code>revoked</code> chooses the direction and\n <code>purpose</code> chooses the list, so this one route covers all four.\n\n <p>The caller signs the mutation; this service only forwards it and never handles issuer key\n material. See {@link RevokeCredentialReqDto RevokeCredentialReqDto} for the exact string to sign.","operationId":"revoke","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RevokeCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperStatusUpdateRespDto"}}}}}}}}}
```

## Sign a prepared credential

> Have core-engine sign a prepared credential without completing it — the middle step of\
> &#x20;\<code>prepare\</code> -\&gt; sign -\&gt; \<code>complete\</code>, for callers who want to see the unsigned\
> &#x20;document first. Sends the issuer's private key to core-engine, like \<code>issue\</code>.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"SignCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/sign</code> — have core-engine apply the issuer's key to\n a credential built by an earlier <code>prepare</code>, without completing it.\n\n <p>This is the middle step of <code>prepare</code> -&gt; sign -&gt; <code>complete</code>, exposed on its own.\n <code>/credentials/issue</code> already runs all three in one call; the reason to take them separately\n is to see the unsigned document (and its <code>signingSpec</code>) before anything is signed, and to\n keep the <code>complete</code> call under your own control. The result still has to go to\n <code>complete</code> — signing alone does not produce a finished credential.\n\n <p><b>This sends the issuer's private key to core-engine</b>, exactly as <code>issue</code> does — see\n {@link MultikeyDto MultikeyDto}. If that is not acceptable, do not use this route: sign the document from\n <code>prepare</code> yourself and call <code>complete</code> directly. That path exists precisely so key\n custody can stay on your side.\n\n <p>Requires <code>ALLOW_ISSUER_SIGNING=true</code> on core-engine, which defaults to off. Where it is\n off this route answers 400 no matter how well-formed the request is — the same condition that\n gates <code>issue</code> and <code>ebl/mint</code>.\n\n <p><code>preparationId</code> is single-use and expires (~15 minutes), and <code>keyPair.controller</code>\n must equal the <code>issuerDid</code> the preparation was created for; core-engine rejects a mismatch\n rather than signing with the wrong identity.","properties":{"preparationId":{"type":"string","minLength":1},"keyPair":{"$ref":"#/components/schemas/MultikeyDto"}},"required":["keyPair","preparationId"]},"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]},"ResponseWrapperSignedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/SignedCredentialRespDto"}}},"SignedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/sign</code> — the signed (and derived) credential.\n\n <p>Deliberately a separate type from {@link CompletedCredentialRespDto CompletedCredentialRespDto} despite the identical\n shape: that one is a finished credential, this one is <strong>not</strong>. Pass this document,\n unmodified, to <code>complete</code> together with the same <code>preparationId</code> to get the finished\n one. Nothing has been recorded anywhere until you do.","properties":{"signedVerifiableCredential":{"type":"object","additionalProperties":{}}}}}},"paths":{"/tradetrust/credentials/sign":{"post":{"tags":["TradeTrust Credentials"],"summary":"Sign a prepared credential","description":"Have core-engine sign a prepared credential without completing it — the middle step of\n <code>prepare</code> -&gt; sign -&gt; <code>complete</code>, for callers who want to see the unsigned\n document first. Sends the issuer's private key to core-engine, like <code>issue</code>.","operationId":"sign","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperSignedCredentialRespDto"}}}}}}}}}
```

## Get the status list

> The signed Bitstring Status List credential for one issuer and purpose — the whole list, not\
> &#x20;one credential's state. To check a single credential use \<code>/verify\</code>, which resolves\
> &#x20;revocation itself.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"ResponseWrapperStatusListRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/StatusListRespDto"}}},"StatusListRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/credentials/status/{issuerDid</code>/{purpose}} — the signed Bitstring\n Status List credential for one issuer and purpose.\n\n <p>This is the document verifiers fetch to decide whether a credential has been revoked. It is\n signed by core-engine's own status-responder identity, deliberately separate from any issuer key:\n the issuer authorizes each individual bit flip, core-engine signs the aggregate.\n\n <p>Reading it is not how you check one credential — <code>POST /credentials/verify</code> already\n resolves revocation for you. Fetch this when you want the whole picture, e.g. to show an issuer\n everything they have revoked.","properties":{"statusListCredential":{"type":"object","additionalProperties":{}}}}}},"paths":{"/tradetrust/credentials/status/{issuerDid}/{purpose}":{"get":{"tags":["TradeTrust Credentials"],"summary":"Get the status list","description":"The signed Bitstring Status List credential for one issuer and purpose — the whole list, not\n one credential's state. To check a single credential use <code>/verify</code>, which resolves\n revocation itself.","operationId":"statusList","parameters":[{"name":"issuerDid","in":"path","required":true,"schema":{"type":"string"}},{"name":"purpose","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperStatusListRespDto"}}}}}}}}}
```

## Verify a credential

> Check signature, issuer binding and (if declared) revocation. Read the response's\
> &#x20;\<code>valid\</code> AND \<code>trusted\</code> fields — never \<code>valid\</code> alone.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Credentials","description":"Issue and verify a verifiable credential through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"VerifyCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/verify</code> — check signature, issuer binding and\n (if declared) revocation. Open on core-engine's side, but this service still requires its own\n caller auth like every other route (no addition to <code>SecurityConfig.PUBLIC_PATHS</code>).\n\n <p><code>trustedIssuers</code> is optional; when supplied, the response's <code>trusted</code> field\n reports whether the credential's issuer is on it.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1},"trustedIssuers":{"type":"array","items":{"type":"string"}}},"required":["verifiableCredential"]},"ResponseWrapperVerifyCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/VerifyCredentialRespDto"}}},"VerifyCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/verify</code> — returned for both outcomes; a failed\n verification is a value (<code>valid: false</code>), never an error.\n\n <p><b>Read <code>valid</code> AND <code>trusted</code> — never <code>valid</code> alone.</b> <code>valid</code> means\n cryptographically genuine, issuer-bound and not revoked/suspended; it says nothing about whether\n the issuer should be accepted. <code>trusted</code> answers that, and is only populated when the\n request supplied <code>trustedIssuers</code> — otherwise it stays <code>null</code>, which is not the same\n as <code>false</code>.","properties":{"valid":{"type":"boolean"},"issuer":{"type":"string"},"trusted":{"type":"boolean"},"status":{"type":"string","description":"<code>null</code> when the credential carries no <code>credentialStatus</code> entry.","enum":["ACTIVE","REVOKED","SUSPENDED","UNKNOWN"]},"checks":{"type":"array","items":{"$ref":"#/components/schemas/VerifyCheckRespDto"}}}},"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}},"paths":{"/tradetrust/credentials/verify":{"post":{"tags":["TradeTrust Credentials"],"summary":"Verify a credential","description":"Check signature, issuer binding and (if declared) revocation. Read the response's\n <code>valid</code> AND <code>trusted</code> fields — never <code>valid</code> alone.","operationId":"verify_1","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VerifyCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperVerifyCredentialRespDto"}}}}}}}}}
```


# Trade Trust Finality

How final an L2 transaction is, via core-engine.

## Get transaction finality

> Confirmation depth and L1 settlement for one transaction. Read \<code>confirmations\</code> and\
> &#x20;\<code>l1Settled\</code>; \<code>final\</code> means only "mined" here.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust Finality","description":"How final an L2 transaction is, via core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"ResponseWrapperFinalityRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/FinalityRespDto"}}},"FinalityRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/finality/{txHash</code>} — how final an L2 transaction is.\n\n <p><strong>On Z2, <code>final</code> adds little to <code>/tx/status</code>'s <code>SUCCESS</code>.</strong> Zetrix\n L2 runs QBFT, which is deterministic and does not reorg, so a transaction is final the moment it is\n mined: <code>final</code> is exactly <code>confirmations &gt;= 1</code>, not a threshold anyone can tune. The two\n fields worth reading are <code>confirmations</code> (which <code>/tx/status</code> cannot give you without a\n second call for the chain head) and <code>l1Settled</code>.\n\n <p>Takes any transaction hash, including one this service never submitted.","properties":{"l2Block":{"type":"integer","format":"int32","description":"<code>null</code> when the node has no receipt for this hash — still pending, or never existed."},"confirmations":{"type":"integer","format":"int32"},"l1Settled":{"type":"boolean","description":"Whether the batch containing this transaction has settled on L1. <code>null</code> means not\n checked, which is not the same as false: core-engine only answers this when an L1 settlement\n checker is configured on its side."},"final":{"type":"boolean","description":"The wire field is <code>final</code>, which cannot be a Java identifier — bound explicitly rather\n than relying on Jackson deriving it from the <code>isFinal()</code> getter."}}}}},"paths":{"/tradetrust/finality/{txHash}":{"get":{"tags":["TradeTrust Finality"],"summary":"Get transaction finality","description":"Confirmation depth and L1 settlement for one transaction. Read <code>confirmations</code> and\n <code>l1Settled</code>; <code>final</code> means only \"mined\" here.","operationId":"finality","parameters":[{"name":"txHash","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperFinalityRespDto"}}}}}}}}}
```


# Trade Trust E BL

Mint, verify, and move a transferable record (eBL) through core-engine.

## Complete and mint an eBL

> Hand back the signed record and get the mint transaction — still unsent; see this class's javadoc.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblCompleteMintReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/complete-mint</code> — hand back the signed record and get the\n mint transaction. <code>beneficiary</code> and <code>holder</code> default to <code>from</code> server-side.","properties":{"preparationId":{"type":"string","minLength":1},"signedVerifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1},"from":{"type":"string","description":"Must hold <code>MINTER_ROLE</code> on the registry.","minLength":1},"beneficiary":{"type":"string"},"holder":{"type":"string"}},"required":["from","preparationId","signedVerifiableCredential"]},"ResponseWrapperEblCompleteMintRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblCompleteMintRespDto"}}},"EblCompleteMintRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/complete-mint</code> (and <code>/mint</code>, which ends at the same\n step) — the assembled record, its assigned token id, and the still-unsent mint transaction.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}},"tokenId":{"type":"string","description":"0x-prefixed 32-byte hex token id, assigned during signing rather than at prepare time."},"unsignedMintTx":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/complete-mint":{"post":{"tags":["TradeTrust eBL"],"summary":"Complete and mint an eBL","description":"Hand back the signed record and get the mint transaction — still unsent; see this class's javadoc.","operationId":"completeMint","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblCompleteMintReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperEblCompleteMintRespDto"}}}}}}}}}
```

## Mint an eBL in one call

> Mint a transferable record in one call: \<code>prepare-mint\</code> -\&gt; core-engine signs -\&gt;\
> &#x20;\<code>complete-mint\</code>. One step still to do: sign and broadcast the returned\
> &#x20;\<code>unsignedMintTx\</code>. Sends the issuer's private key to core-engine — see\
> &#x20;{@link com.myeg.z2.tradetrust.dto.req.MultikeyDto com.myeg.z2.tradetrust.dto.req.MultikeyDto}.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblMintReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/mint</code> — the same build as {@link EblPrepareMintReqDto EblPrepareMintReqDto},\n plus the issuer's key pair for delegated signing and the minting address. One call, but\n <code>from</code> must still sign and broadcast the returned <code>unsignedMintTx</code> — the token does\n not exist until that is mined.\n\n <p><b>This sends the issuer's private key to core-engine.</b> See {@link MultikeyDto MultikeyDto}.","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"tokenRegistry":{"type":"string","minLength":1},"chainId":{"type":"integer","format":"int64"},"chain":{"type":"string"},"context":{"type":"array","items":{"type":"string"}},"expirationDate":{"type":"string"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}},"from":{"type":"string","description":"Must hold <code>MINTER_ROLE</code> on the registry.","minLength":1},"beneficiary":{"type":"string","description":"Initial owner of title to the goods (Title Escrow beneficiary). Defaults to <code>from</code>."},"holder":{"type":"string","description":"Initial holder / possessor. Defaults to <code>from</code>."},"keyPair":{"$ref":"#/components/schemas/MultikeyDto"}},"required":["credentialSubject","from","issuerDid","keyPair","tokenRegistry"]},"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]},"ResponseWrapperEblCompleteMintRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblCompleteMintRespDto"}}},"EblCompleteMintRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/complete-mint</code> (and <code>/mint</code>, which ends at the same\n step) — the assembled record, its assigned token id, and the still-unsent mint transaction.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}},"tokenId":{"type":"string","description":"0x-prefixed 32-byte hex token id, assigned during signing rather than at prepare time."},"unsignedMintTx":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/mint":{"post":{"tags":["TradeTrust eBL"],"summary":"Mint an eBL in one call","description":"Mint a transferable record in one call: <code>prepare-mint</code> -&gt; core-engine signs -&gt;\n <code>complete-mint</code>. One step still to do: sign and broadcast the returned\n <code>unsignedMintTx</code>. Sends the issuer's private key to core-engine — see\n {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto com.myeg.z2.tradetrust.dto.req.MultikeyDto}.","operationId":"mint","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblMintReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperEblCompleteMintRespDto"}}}}}}}}}
```

## Deploy a Token Registry

> Deploy a brand-new Token Registry — where an eBL flow starts, since \<code>prepare-mint\</code> and\
> &#x20;\<code>mint\</code> both require a \<code>tokenRegistry\</code> and there is no default.\
> \
> &#x20;\<p>Unsigned like every other write: the paying address signs and broadcasts it, and needs gas.\
> &#x20;Afterwards read the new registry's address from \<code>/onboard-issuer/registry\</code> — it is not in\
> &#x20;the receipt's \<code>contractAddress\</code>.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"OnboardIssuerReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/onboard-issuer</code> — build the transaction that deploys a\n brand-new eBL Token Registry.\n\n <p>This is where an eBL flow starts. <code>tokenRegistry</code> is required on <code>prepare-mint</code> and\n <code>mint</code> and core-engine keeps no server-wide default, so without a registry of your own there\n is nothing to mint into.\n\n <p>Like every other eBL write this returns an <strong>unsigned</strong> transaction: <code>admin</code>\n (or whoever you choose to pay) signs and broadcasts it, so that address needs gas first. Deployment\n is permissionless — the registry's admin comes from an encoded parameter rather than the sender —\n so the paying address and the admin need not be the same.\n\n <p><strong>The new registry's address is not in the transaction receipt's <code>contractAddress</code>\n field.</strong> The registry is deployed by the platform's shared deployer contract, not by this\n transaction directly, so that field is null. Once the transaction succeeds, read the address from\n <code>GET /tradetrust/ebl/onboard-issuer/registry?hash=...</code>.","properties":{"name":{"type":"string","description":"The registry's ERC-721 collection name, e.g. <code>&quot;MYEG Bill of Lading&quot;</code>.","minLength":1},"symbol":{"type":"string","description":"The registry's ERC-721 symbol, e.g. <code>&quot;MYEGBL&quot;</code>.","minLength":1},"admin":{"type":"string","description":"Becomes the new registry's admin, holding <code>DEFAULT_ADMIN_ROLE</code>, <code>MINTER_ROLE</code>,\n <code>RESTORER_ROLE</code> and <code>ACCEPTER_ROLE</code> — so this is the address that will be allowed\n to mint. Typically the issuer's own operational address.","minLength":1}},"required":["admin","name","symbol"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/onboard-issuer":{"post":{"tags":["TradeTrust eBL"],"summary":"Deploy a Token Registry","description":"Deploy a brand-new Token Registry — where an eBL flow starts, since <code>prepare-mint</code> and\n <code>mint</code> both require a <code>tokenRegistry</code> and there is no default.\n\n <p>Unsigned like every other write: the paying address signs and broadcasts it, and needs gas.\n Afterwards read the new registry's address from <code>/onboard-issuer/registry</code> — it is not in\n the receipt's <code>contractAddress</code>.","operationId":"onboardIssuer","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OnboardIssuerReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Get the deployed registry address

> The address of the registry an \<code>onboard-issuer\</code> transaction deployed, decoded from the\
> &#x20;receipt's \<code>Deployment\</code> event. Poll while \<code>PENDING\</code>, exactly as with\
> &#x20;\<code>/tx/status\</code>.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"ResponseWrapperRegistryAddressRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/RegistryAddressRespDto"}}},"RegistryAddressRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/onboard-issuer/registry</code> — the address of the Token Registry\n an <code>onboard-issuer</code> transaction deployed.\n\n <p>This endpoint exists because the address is not where callers look for it. The registry is\n deployed by the platform's shared deployer contract rather than by the submitted transaction\n itself, so the receipt's <code>contractAddress</code> is null and <code>GET /tx/status</code> — which returns\n no logs — cannot show it either. The address is only in the deployer's <code>Deployment</code> event, so\n this reads the receipt and decodes it.\n\n <p>Poll while <code>status</code> is <code>PENDING</code>, exactly as with <code>/tx/status</code>: a hash the node\n has not seen yet is pending rather than absent, because over JSON-RPC \"still in the mempool\" and\n \"never existed\" are indistinguishable. <code>registry</code> is populated only on <code>SUCCESS</code>.","properties":{"transactionHash":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","FAILED","PENDING"]},"registry":{"type":"string","description":"The new registry's address — the value to pass as <code>tokenRegistry</code> from here on.\n\n <p><code>null</code> while <code>PENDING</code> or on <code>FAILED</code>. Also null in one case worth\n handling: a <code>SUCCESS</code> whose logs carry no <code>Deployment</code> event, which means the hash\n belongs to some other transaction rather than an <code>onboard-issuer</code> one."}}}}},"paths":{"/tradetrust/ebl/onboard-issuer/registry":{"get":{"tags":["TradeTrust eBL"],"summary":"Get the deployed registry address","description":"The address of the registry an <code>onboard-issuer</code> transaction deployed, decoded from the\n receipt's <code>Deployment</code> event. Poll while <code>PENDING</code>, exactly as with\n <code>/tx/status</code>.","operationId":"registryAddress","parameters":[{"name":"hash","in":"query","required":true,"schema":{"type":"string","minLength":1}}],"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperRegistryAddressRespDto"}}}}}}}}}
```

## Prepare an eBL for signing

> Build the unsigned transferable record and its signing spec. The caller signs, then calls \<code>complete-mint\</code>.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblPrepareMintReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/prepare-mint</code> — build the unsigned transferable record\n and its signing spec. <code>issuerDid</code>, <code>credentialSubject</code> and <code>tokenRegistry</code> are\n required; core-engine removed its server-wide default registry (a <code>tokenId</code> is only unique\n within one registry contract).","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"tokenRegistry":{"type":"string","minLength":1},"chainId":{"type":"integer","format":"int64"},"chain":{"type":"string"},"context":{"type":"array","items":{"type":"string"}},"expirationDate":{"type":"string"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}}},"required":["credentialSubject","issuerDid","tokenRegistry"]},"ResponseWrapperPreparedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/PreparedCredentialRespDto"}}},"PreparedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/prepare</code> — the unsigned document plus its\n signing spec.\n\n <p><code>preparationId</code> is single-use and expires (~15 minutes); pass it unmodified to\n <code>complete</code> or <code>issue</code> alongside the signed document.","properties":{"preparationId":{"type":"string"},"unsignedVerifiableCredential":{"type":"object","additionalProperties":{}},"signingSpec":{"$ref":"#/components/schemas/SigningSpecRespDto"}}},"SigningSpecRespDto":{"type":"object","description":"Exactly how core-engine expects a prepared document to be signed — part of\n {@link PreparedCredentialRespDto PreparedCredentialRespDto}. Pass <code>mandatoryPointers</code> to the signer verbatim; core-engine\n derives it from what it actually built, so reconstructing it silently drops fields from the base proof.","properties":{"mandatoryPointers":{"type":"array","items":{"type":"string"}},"cryptoSuite":{"type":"string"},"expectedIssuerDid":{"type":"string"}}}}},"paths":{"/tradetrust/ebl/prepare-mint":{"post":{"tags":["TradeTrust eBL"],"summary":"Prepare an eBL for signing","description":"Build the unsigned transferable record and its signing spec. The caller signs, then calls <code>complete-mint</code>.","operationId":"prepareMint","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblPrepareMintReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperPreparedCredentialRespDto"}}}}}}}}}
```

## Verify an eBL

> Document integrity \<strong>and\</strong> on-chain state. Takes no \<code>tokenRegistry\</code> —\
> &#x20;unlike every other eBL route, it reads the registry and token id from inside the submitted\
> &#x20;credential. Read \<code>valid\</code> AND \<code>trusted\</code> — never \<code>valid\</code> alone.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"VerifyCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/verify</code> — check signature, issuer binding and\n (if declared) revocation. Open on core-engine's side, but this service still requires its own\n caller auth like every other route (no addition to <code>SecurityConfig.PUBLIC_PATHS</code>).\n\n <p><code>trustedIssuers</code> is optional; when supplied, the response's <code>trusted</code> field\n reports whether the credential's issuer is on it.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1},"trustedIssuers":{"type":"array","items":{"type":"string"}}},"required":["verifiableCredential"]},"ResponseWrapperEblVerifyRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblVerifyRespDto"}}},"EblVerifyRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/verify</code> — document integrity <strong>and</strong> on-chain\n state. Returned for both outcomes; a burned or never-minted record is a value\n (<code>valid: false</code>), never an error.\n\n <p><b>Read <code>valid</code> AND <code>trusted</code></b> — same rule as\n <code>VerifyCredentialRespDto</code>, and for the same reason.","properties":{"valid":{"type":"boolean"},"issuer":{"type":"string"},"trusted":{"type":"boolean"},"onChain":{"$ref":"#/components/schemas/EblOnChainRespDto"},"checks":{"type":"array","items":{"$ref":"#/components/schemas/VerifyCheckRespDto"}}}},"EblOnChainRespDto":{"type":"object","description":"The registry-side view of a transferable record, part of {@link EblVerifyRespDto EblVerifyRespDto}.\n\n <p><code>beneficiary</code> and <code>holder</code> are <code>null</code> unless the record is active.","properties":{"minted":{"type":"boolean","description":"True while the token exists (active or surrendered); false if burned or never minted."},"status":{"type":"string","enum":["ACTIVE","SURRENDERED","BURNED","NOT_MINTED","UNKNOWN"]},"registry":{"type":"string","description":"The registry the record points at — worth checking rather than trusting <code>valid</code> alone:\n core-engine reports {@link Status#NOT_MINTED Status#NOT_MINTED}, not an error, for a record pointing elsewhere."},"tokenId":{"type":"string"},"titleEscrow":{"type":"string","description":"The Title Escrow owning the token while active (the registry once surrendered)."},"beneficiary":{"type":"string"},"holder":{"type":"string"}}},"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}},"paths":{"/tradetrust/ebl/verify":{"post":{"tags":["TradeTrust eBL"],"summary":"Verify an eBL","description":"Document integrity <strong>and</strong> on-chain state. Takes no <code>tokenRegistry</code> —\n unlike every other eBL route, it reads the registry and token id from inside the submitted\n credential. Read <code>valid</code> AND <code>trusted</code> — never <code>valid</code> alone.","operationId":"verify","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VerifyCredentialReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperEblVerifyRespDto"}}}}}}}}}
```

## Accept a surrender

> The issuer finalizes a returned record; it is burned and retired.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/accept-surrender":{"post":{"tags":["TradeTrust eBL"],"summary":"Accept a surrender","description":"The issuer finalizes a returned record; it is burned and retired.","operationId":"acceptSurrender","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblActionReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Get the endorsement chain

> The record's full transfer history, oldest first.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"ResponseWrapperEndorsementChainRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EndorsementChainRespDto"}}},"EndorsementChainRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/{tokenId</code>/endorsement-chain} — the record's full transfer\n history, oldest first.\n\n <p>Events stay as <code>Map&lt;String, Object&gt;</code> rather than a typed class, matching the SDK's own\n choice: core-engine adds event types and fields over time. Observed fields include <code>type</code>\n (<code>INITIAL</code>, <code>TRANSFER_BENEFICIARY</code>, <code>TRANSFER_HOLDER</code>, …), <code>owner</code>,\n <code>holder</code>, <code>transactionHash</code>, <code>transactionIndex</code>, <code>blockNumber</code>,\n <code>timestamp</code> (epoch milliseconds) and <code>remark</code>.","properties":{"tokenId":{"type":"string"},"chain":{"type":"array","items":{"type":"object","additionalProperties":{}}}}}}},"paths":{"/tradetrust/ebl/{tokenId}/endorsement-chain":{"get":{"tags":["TradeTrust eBL"],"summary":"Get the endorsement chain","description":"The record's full transfer history, oldest first.","operationId":"endorsementChain","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}},{"name":"tokenRegistry","in":"query","required":true,"schema":{"type":"string","minLength":1}}],"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperEndorsementChainRespDto"}}}}}}}}}
```

## Nominate the next beneficiary

> The beneficiary nominates who may take title next — step 1 of the two-step title transfer.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblNewBeneficiaryReqDto":{"type":"object","description":"Request body shape shared by <code>POST /tradetrust/ebl/{tokenId</code>/transfer-beneficiary}\n (irreversible once broadcast) and <code>POST /tradetrust/ebl/{tokenId</code>/nominate} (step 1 of the\n two-step title transfer) — both are exactly <code>newBeneficiary</code> + the base action fields.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newBeneficiary":{"type":"string","minLength":1}},"required":["from","newBeneficiary","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/nominate":{"post":{"tags":["TradeTrust eBL"],"summary":"Nominate the next beneficiary","description":"The beneficiary nominates who may take title next — step 1 of the two-step title transfer.","operationId":"nominate","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblNewBeneficiaryReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Get the current owner

> The Title Escrow currently owning the token (or the registry, once surrendered).

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"ResponseWrapperEblOwnerRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblOwnerRespDto"}}},"EblOwnerRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/{tokenId</code>/owner}.","properties":{"tokenId":{"type":"string"},"owner":{"type":"string","description":"The Title Escrow address holding the token (or the registry, once surrendered)."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/owner":{"get":{"tags":["TradeTrust eBL"],"summary":"Get the current owner","description":"The Title Escrow currently owning the token (or the registry, once surrendered).","operationId":"owner","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}},{"name":"tokenRegistry","in":"query","required":true,"schema":{"type":"string","minLength":1}}],"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperEblOwnerRespDto"}}}}}}}}}
```

## Reject a surrender

> The issuer returns a surrendered record to the last holder, active again.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/reject-surrender":{"post":{"tags":["TradeTrust eBL"],"summary":"Reject a surrender","description":"The issuer returns a surrendered record to the last holder, active again.","operationId":"rejectSurrender","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblActionReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Reject a beneficiary transfer

> Decline an incoming beneficiary transfer.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/reject-transfer-beneficiary":{"post":{"tags":["TradeTrust eBL"],"summary":"Reject a beneficiary transfer","description":"Decline an incoming beneficiary transfer.","operationId":"rejectTransferBeneficiary","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblActionReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Reject a holder transfer

> Decline an incoming holder transfer. Not the same as {@link com.myeg.z2.tradetrust.controller.EblController#rejectSurrender #rejectSurrender} — unrelated flows.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/reject-transfer-holder":{"post":{"tags":["TradeTrust eBL"],"summary":"Reject a holder transfer","description":"Decline an incoming holder transfer. Not the same as {@link com.myeg.z2.tradetrust.controller.EblController#rejectSurrender #rejectSurrender} — unrelated flows.","operationId":"rejectTransferHolder","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblActionReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Reject a combined transfer

> Decline an incoming combined (owners) transfer.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/reject-transfer-owners":{"post":{"tags":["TradeTrust eBL"],"summary":"Reject a combined transfer","description":"Decline an incoming combined (owners) transfer.","operationId":"rejectTransferOwners","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblActionReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Surrender an eBL

> The holder returns the record to the issuer — step 1 of 3 in the end-of-life flow.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/surrender":{"post":{"tags":["TradeTrust eBL"],"summary":"Surrender an eBL","description":"The holder returns the record to the issuer — step 1 of 3 in the end-of-life flow.","operationId":"surrender","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblActionReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Transfer the beneficiary

> Transfer title to the goods. Irreversible once the returned transaction is broadcast.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblNewBeneficiaryReqDto":{"type":"object","description":"Request body shape shared by <code>POST /tradetrust/ebl/{tokenId</code>/transfer-beneficiary}\n (irreversible once broadcast) and <code>POST /tradetrust/ebl/{tokenId</code>/nominate} (step 1 of the\n two-step title transfer) — both are exactly <code>newBeneficiary</code> + the base action fields.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newBeneficiary":{"type":"string","minLength":1}},"required":["from","newBeneficiary","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/transfer-beneficiary":{"post":{"tags":["TradeTrust eBL"],"summary":"Transfer the beneficiary","description":"Transfer title to the goods. Irreversible once the returned transaction is broadcast.","operationId":"transferBeneficiary","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblNewBeneficiaryReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Transfer the holder

> Hand possession of the record to another party. Irreversible once the returned transaction is broadcast.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblTransferHolderReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/{tokenId</code>/transfer-holder} — irreversible once broadcast.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newHolder":{"type":"string","minLength":1}},"required":["from","newHolder","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/transfer-holder":{"post":{"tags":["TradeTrust eBL"],"summary":"Transfer the holder","description":"Hand possession of the record to another party. Irreversible once the returned transaction is broadcast.","operationId":"transferHolder","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblTransferHolderReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```

## Transfer beneficiary and holder

> Move beneficiary and holder together, atomically, in one transaction.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"TradeTrust eBL","description":"Mint, verify, and move a transferable record (eBL) through core-engine."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EblTransferOwnersReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/{tokenId</code>/transfer-owners} — moves beneficiary and\n holder together, atomically, in one transaction.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newBeneficiary":{"type":"string","minLength":1},"newHolder":{"type":"string","minLength":1}},"required":["from","newBeneficiary","newHolder","tokenRegistry"]},"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}},"paths":{"/tradetrust/ebl/{tokenId}/transfer-owners":{"post":{"tags":["TradeTrust eBL"],"summary":"Transfer beneficiary and holder","description":"Move beneficiary and holder together, atomically, in one transaction.","operationId":"transferOwners","parameters":[{"name":"tokenId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EblTransferOwnersReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperUnsignedTxRespDto"}}}}}}}}}
```


# Transaction

Build, sign, submit and track a raw transaction, plus fee estimation. The blob/sign/submit split lets a caller keep key custody.

## POST /tx/estimate-fee

> Estimate the transaction fee

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"Transaction","description":"Build, sign, submit and track a raw transaction, plus fee estimation. The blob/sign/submit split lets a caller keep key custody."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"EstimateFeeReqDto":{"type":"object","description":"Request for <code>POST /tx/estimate-fee</code>.\n\n <code>from</code> matters: gas depends on the sender's state (whether a storage slot is already\n set, whether the account exists), so estimating without it can give a materially different\n number than the real transaction will use.","properties":{"from":{"type":"string","minLength":1},"to":{"type":"string","minLength":1},"value":{"type":"integer"},"data":{"type":"string"}},"required":["from","to"]},"ResponseWrapperEstimateFeeRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EstimateFeeRespDto"}}},"EstimateFeeRespDto":{"type":"object","description":"Response of <code>POST /tx/estimate-fee</code>. All values in wei.\n\n <code>fee</code> is <code>gasLimit * gasPrice</code> — the ceiling the sender must be able to cover, not\n what the transaction will necessarily cost. Unused gas is not charged, so the actual spend is\n <code>gasUsed * gasPrice</code>, which is only known from the receipt.\n\n No safety margin is applied to gasPrice: it is the node's <code>eth_gasPrice</code> verbatim, per\n the 2026-08-05 decision to follow the node. (myeg-ms-ethereum doubles it below 25 gwei — a\n threshold tuned for Ethereum mainnet and meaningless on a chain quoting 7 wei.)","properties":{"gasLimit":{"type":"integer"},"gasPrice":{"type":"integer"},"fee":{"type":"string","description":"<b>A decimal String, not a JSON number</b>, unlike the two factors above.\n\n <p><code>gasLimit</code> and <code>gasPrice</code> are each safely inside a JavaScript number — a block\n gas limit is millions, and even 20 gwei is 2 × 10^10. Their <b>product</b> is not: 10^6 gas at\n 20 gwei is 2 × 10^16, past <code>Number.MAX_SAFE_INTEGER</code> (~9.007 × 10^15). Z2 quoting 7 wei\n hides this today, so the field would look fine right up until this service pointed at a chain\n with an ordinary fee market."}}}}},"paths":{"/tx/estimate-fee":{"post":{"tags":["Transaction"],"operationId":"estimateFee","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EstimateFeeReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperEstimateFeeRespDto"}}}}},"summary":"Estimate the transaction fee"}}}}
```

## POST /tx/generate-blob

> Build a signable transaction blob

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"Transaction","description":"Build, sign, submit and track a raw transaction, plus fee estimation. The blob/sign/submit split lets a caller keep key custody."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"GenerateBlobReqDto":{"type":"object","description":"Request for <code>POST /tx/generate-blob</code>.\n\n The three override fields exist so a caller can pin a transaction exactly (replacing a stuck\n nonce, for instance). Left null, each is resolved from the node: nonce from\n <code>eth_getTransactionCount(pending)</code>, gasPrice from <code>eth_gasPrice</code>, gasLimit from\n <code>eth_estimateGas</code>.","properties":{"from":{"type":"string","minLength":1},"to":{"type":"string","description":"Recipient. Required here — contract deployment (no recipient) is BT-2584.","minLength":1},"value":{"type":"integer","description":"Native value in wei. Defaults to zero."},"data":{"type":"string","description":"Hex-encoded call data. Null or empty for a plain transfer."},"nonce":{"type":"integer"},"gasPrice":{"type":"integer"},"gasLimit":{"type":"integer"},"maxFeePerGas":{"type":"integer","description":"EIP-1559 ceiling, in wei. Supplying it builds a <b>type-2</b> transaction instead of a\n legacy one; leave it null and nothing changes.\n\n <p>You are charged <code>baseFeePerGas + maxPriorityFeePerGas</code> and refunded the rest, so a\n generous ceiling does not cost more - it only has to be high enough that the transaction\n stays includable if the base fee rises.\n\n <p>Mutually exclusive with <code>gasPrice</code>: naming both a legacy bid and a 1559 ceiling is\n contradictory, and guessing which one the caller meant is worse than refusing."},"maxPriorityFeePerGas":{"type":"integer","description":"EIP-1559 validator tip, in wei. Only meaningful with <code>maxFeePerGas</code>; defaults to 0."}},"required":["from","to"]},"ResponseWrapperGenerateBlobRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/GenerateBlobRespDto"}}},"GenerateBlobRespDto":{"type":"object","description":"Response of <code>POST /tx/generate-blob</code>.\n\n The resolved nonce/gasPrice/gasLimit are echoed back deliberately: they are already encoded\n inside the blob, but a caller signing client-side needs to see what they are about to commit\n to without having to RLP-decode it first.","properties":{"blob":{"type":"string","description":"Unsigned transaction, RLP hex. Feed this to /tx/sign-blob or sign it yourself."},"nonce":{"type":"integer"},"gasPrice":{"type":"integer"},"gasLimit":{"type":"integer"},"chainId":{"type":"integer","format":"int64","description":"The chain id the blob must be signed with (EIP-155). Read from the node."},"maxFeePerGas":{"type":"integer","description":"Set only when the blob is a type-2 transaction; null for a legacy one."},"maxPriorityFeePerGas":{"type":"integer"}}}}},"paths":{"/tx/generate-blob":{"post":{"tags":["Transaction"],"operationId":"generateBlob","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateBlobReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperGenerateBlobRespDto"}}}}},"summary":"Build a signable transaction blob"}}}}
```

## POST /tx/sign-blob

> Sign a transaction blob

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"Transaction","description":"Build, sign, submit and track a raw transaction, plus fee estimation. The blob/sign/submit split lets a caller keep key custody."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"SignBlobReqDto":{"type":"object","description":"Request for <code>POST /tx/sign-blob</code>.\n\n <b>Carries a private key.</b> This is why the endpoint is POST rather than GET: a key in a\n query string ends up in access logs, proxy logs and browser history. The key is used to sign\n and then discarded — never logged, never persisted. Callers who would rather not send it at\n all should sign the blob client-side; that is the reason the blob/sign/submit split exists.","properties":{"blob":{"type":"string","description":"Unsigned transaction as RLP hex, from <code>/tx/generate-blob</code>.","minLength":1},"privateKey":{"type":"string","minLength":1}},"required":["blob","privateKey"]},"ResponseWrapperSignBlobRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/SignBlobRespDto"}}},"SignBlobRespDto":{"type":"object","description":"Response of <code>POST /tx/sign-blob</code>.\n\n Contains no echo of the submitted private key, by design — see <code>SignBlobReqDto</code>.","properties":{"signedBlob":{"type":"string","description":"Signed transaction, RLP hex. Ready for /tx/submit."},"transactionHash":{"type":"string","description":"The hash this transaction will have once submitted (keccak256 of the signed RLP).\n Computable before submission, so a caller can start watching for it immediately."},"chainId":{"type":"integer","format":"int64","description":"The chain id baked into the signature, for the caller to verify."}}}}},"paths":{"/tx/sign-blob":{"post":{"tags":["Transaction"],"operationId":"signBlob","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignBlobReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperSignBlobRespDto"}}}}},"summary":"Sign a transaction blob"}}}}
```

## Get transaction status

> What became of a submitted transaction.\
> \
> &#x20;\<p>GET with a query parameter, matching L1's \<code>GET /tx/status?hash=\</code>. Safe as a GET\
> &#x20;because a transaction hash is public information — unlike a private key, it does no harm in\
> &#x20;an access log.\
> \
> &#x20;\<p>A hash the node has not seen returns \<code>PENDING\</code>, not 404: over JSON-RPC "still in the\
> &#x20;mempool" and "never existed" are indistinguishable, so reporting not-found would be a guess.

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"Transaction","description":"Build, sign, submit and track a raw transaction, plus fee estimation. The blob/sign/submit split lets a caller keep key custody."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"ResponseWrapperTxStatusRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/TxStatusRespDto"}}},"TxStatusRespDto":{"type":"object","description":"Response of <code>GET /tx/status?hash=…</code> — the outcome of a submitted transaction.\n\n <p>This closes the gap that made <code>/tx/submit</code> a dead end: you got a hash and had no way to\n ask what became of it. A hash means only that the node accepted the transaction into its pool; a\n transaction that <b>reverts is still mined and still has that hash</b>, so the hash alone can\n never tell success from failure.\n\n <p>The four states are genuinely different and are worth distinguishing:\n <ul>\n   <li><code>SUCCESS</code> — mined, <code>status: 0x1</code>. It ran and did not revert.</li>\n   <li><code>FAILED</code> — mined, <code>status: 0x0</code>. It reverted; gas was still consumed. See\n       <code>revertReason</code>.</li>\n   <li><code>PENDING</code> — no receipt yet. Either still in the pool, or the hash never existed —\n       JSON-RPC cannot tell those apart, so neither can we, and claiming otherwise would be a\n       guess. Poll, and treat a hash that stays pending indefinitely as never having landed.</li>\n </ul>","properties":{"transactionHash":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","FAILED","PENDING"]},"blockNumber":{"type":"integer"},"gasUsed":{"type":"integer"},"from":{"type":"string"},"to":{"type":"string"},"contractAddress":{"type":"string","description":"Set only for a contract creation, and this is the <b>authoritative</b> address — unlike the\n prediction from <code>/contract/deploy/generate-blob</code>, which is conditional on the nonce\n being spent as planned. Once a deploy reaches <code>SUCCESS</code>, use this one."},"revertReason":{"type":"string","description":"Why a <code>FAILED</code> transaction reverted, when it can be recovered.\n\n <p>Revert data is not stored on chain, so this comes from replaying the call against the\n state it ran in. That needs historical state: a pruned node cannot serve it and this stays\n null. Null therefore means \"could not be recovered\", never \"no reason\"."}}}}},"paths":{"/tx/status":{"get":{"tags":["Transaction"],"summary":"Get transaction status","description":"What became of a submitted transaction.\n\n <p>GET with a query parameter, matching L1's <code>GET /tx/status?hash=</code>. Safe as a GET\n because a transaction hash is public information — unlike a private key, it does no harm in\n an access log.\n\n <p>A hash the node has not seen returns <code>PENDING</code>, not 404: over JSON-RPC \"still in the\n mempool\" and \"never existed\" are indistinguishable, so reporting not-found would be a guess.","operationId":"status","parameters":[{"name":"hash","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperTxStatusRespDto"}}}}}}}}}
```

## POST /tx/submit

> Submit a signed transaction

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"tags":[{"name":"Transaction","description":"Build, sign, submit and track a raw transaction, plus fee estimation. The blob/sign/submit split lets a caller keep key custody."}],"servers":[{"url":"https://api-sandbox.zetrix.com/z2","description":"Testnet / UAT, through AWS API Gateway. Needs X-API-Key in addition to the bearer token."}],"security":[{"bearerAuth":[],"apiKeyAuth":[]},{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","description":"OAuth2 bearer token from the shared BaaS auth server.\n\nEvery endpoint in this subset requires one. Note the security filter runs BEFORE routing, so an unauthenticated request to a path that does not exist also answers 401, not 404 - a 404 is only visible to an authenticated caller.","scheme":"bearer","bearerFormat":"JWT"},"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"AWS API Gateway key, required only on the api-sandbox and api-v2 servers. It is checked by the gateway, before the request reaches this service, so it does not substitute for the bearer token - those two headers are read by different layers. Omit it when port-forwarding to a pod."}},"schemas":{"SubmitTxReqDto":{"type":"object","description":"Request for <code>POST /tx/submit</code>: a signed transaction as RLP hex.","properties":{"signedBlob":{"type":"string","minLength":1}},"required":["signedBlob"]},"ResponseWrapperSubmitTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/SubmitTxRespDto"}}},"SubmitTxRespDto":{"type":"object","description":"Response of <code>POST /tx/submit</code>.\n\n A hash here means the node <b>accepted</b> the transaction into its pool — not that it has\n been mined, and not that it will succeed. There is currently no way to follow up on it: a\n status/receipt endpoint is a known gap with no ticket (see the BT-2583 plan doc §1).","properties":{"transactionHash":{"type":"string"}}}}},"paths":{"/tx/submit":{"post":{"tags":["Transaction"],"operationId":"submit","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmitTxReqDto"}}},"required":true},"responses":{"200":{"description":"OK","content":{"*/*":{"schema":{"$ref":"#/components/schemas/ResponseWrapperSubmitTxRespDto"}}}}},"summary":"Submit a signed transaction"}}}}
```


# Models

## The CompleteCredentialReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"CompleteCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/complete</code> — hand back the signed credential from\n the matching <code>prepare</code> call and get the finished one.\n\n <p><code>preparationId</code> is single-use and expires (core-engine's pending store has a ~15 minute\n TTL); a stale one is a 404, mapped by <code>CustomExceptionHandler</code>'s generic core-engine bucket.","properties":{"preparationId":{"type":"string","minLength":1},"signedVerifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1}},"required":["preparationId","signedVerifiableCredential"]}}}}
```

## The CompletedCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"CompletedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/complete</code> (and <code>/issue</code>, which ends at the\n same step) — the assembled, signed credential.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}}}}}}}
```

## The EblActionReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblActionReqDto":{"type":"object","description":"The two fields every eBL write that takes no extra parameter needs: <code>surrender</code>,\n <code>accept-surrender</code>, <code>reject-surrender</code>, <code>reject-transfer-holder</code>,\n <code>reject-transfer-beneficiary</code>, <code>reject-transfer-owners</code>. Extended by the writes that\n need more — see {@link EblTransferHolderReqDto EblTransferHolderReqDto}, {@link EblNewBeneficiaryReqDto EblNewBeneficiaryReqDto},\n {@link EblTransferOwnersReqDto EblTransferOwnersReqDto}.\n\n <p><code>tokenId</code> is not here — every eBL write takes it as a path variable, not a body field.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1}},"required":["from","tokenRegistry"]}}}}
```

## The EblCompleteMintReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblCompleteMintReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/complete-mint</code> — hand back the signed record and get the\n mint transaction. <code>beneficiary</code> and <code>holder</code> default to <code>from</code> server-side.","properties":{"preparationId":{"type":"string","minLength":1},"signedVerifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1},"from":{"type":"string","description":"Must hold <code>MINTER_ROLE</code> on the registry.","minLength":1},"beneficiary":{"type":"string"},"holder":{"type":"string"}},"required":["from","preparationId","signedVerifiableCredential"]}}}}
```

## The EblCompleteMintRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblCompleteMintRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/complete-mint</code> (and <code>/mint</code>, which ends at the same\n step) — the assembled record, its assigned token id, and the still-unsent mint transaction.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}},"tokenId":{"type":"string","description":"0x-prefixed 32-byte hex token id, assigned during signing rather than at prepare time."},"unsignedMintTx":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}}}
```

## The EblMintReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblMintReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/mint</code> — the same build as {@link EblPrepareMintReqDto EblPrepareMintReqDto},\n plus the issuer's key pair for delegated signing and the minting address. One call, but\n <code>from</code> must still sign and broadcast the returned <code>unsignedMintTx</code> — the token does\n not exist until that is mined.\n\n <p><b>This sends the issuer's private key to core-engine.</b> See {@link MultikeyDto MultikeyDto}.","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"tokenRegistry":{"type":"string","minLength":1},"chainId":{"type":"integer","format":"int64"},"chain":{"type":"string"},"context":{"type":"array","items":{"type":"string"}},"expirationDate":{"type":"string"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}},"from":{"type":"string","description":"Must hold <code>MINTER_ROLE</code> on the registry.","minLength":1},"beneficiary":{"type":"string","description":"Initial owner of title to the goods (Title Escrow beneficiary). Defaults to <code>from</code>."},"holder":{"type":"string","description":"Initial holder / possessor. Defaults to <code>from</code>."},"keyPair":{"$ref":"#/components/schemas/MultikeyDto"}},"required":["credentialSubject","from","issuerDid","keyPair","tokenRegistry"]},"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]}}}}
```

## The EblNewBeneficiaryReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblNewBeneficiaryReqDto":{"type":"object","description":"Request body shape shared by <code>POST /tradetrust/ebl/{tokenId</code>/transfer-beneficiary}\n (irreversible once broadcast) and <code>POST /tradetrust/ebl/{tokenId</code>/nominate} (step 1 of the\n two-step title transfer) — both are exactly <code>newBeneficiary</code> + the base action fields.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newBeneficiary":{"type":"string","minLength":1}},"required":["from","newBeneficiary","tokenRegistry"]}}}}
```

## The EblOnChainRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblOnChainRespDto":{"type":"object","description":"The registry-side view of a transferable record, part of {@link EblVerifyRespDto EblVerifyRespDto}.\n\n <p><code>beneficiary</code> and <code>holder</code> are <code>null</code> unless the record is active.","properties":{"minted":{"type":"boolean","description":"True while the token exists (active or surrendered); false if burned or never minted."},"status":{"type":"string","enum":["ACTIVE","SURRENDERED","BURNED","NOT_MINTED","UNKNOWN"]},"registry":{"type":"string","description":"The registry the record points at — worth checking rather than trusting <code>valid</code> alone:\n core-engine reports {@link Status#NOT_MINTED Status#NOT_MINTED}, not an error, for a record pointing elsewhere."},"tokenId":{"type":"string"},"titleEscrow":{"type":"string","description":"The Title Escrow owning the token while active (the registry once surrendered)."},"beneficiary":{"type":"string"},"holder":{"type":"string"}}}}}}
```

## The EblOwnerRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblOwnerRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/{tokenId</code>/owner}.","properties":{"tokenId":{"type":"string"},"owner":{"type":"string","description":"The Title Escrow address holding the token (or the registry, once surrendered)."}}}}}}
```

## The EblPrepareMintReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblPrepareMintReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/prepare-mint</code> — build the unsigned transferable record\n and its signing spec. <code>issuerDid</code>, <code>credentialSubject</code> and <code>tokenRegistry</code> are\n required; core-engine removed its server-wide default registry (a <code>tokenId</code> is only unique\n within one registry contract).","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"tokenRegistry":{"type":"string","minLength":1},"chainId":{"type":"integer","format":"int64"},"chain":{"type":"string"},"context":{"type":"array","items":{"type":"string"}},"expirationDate":{"type":"string"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}}},"required":["credentialSubject","issuerDid","tokenRegistry"]}}}}
```

## The EblTransferHolderReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblTransferHolderReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/{tokenId</code>/transfer-holder} — irreversible once broadcast.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newHolder":{"type":"string","minLength":1}},"required":["from","newHolder","tokenRegistry"]}}}}
```

## The EblTransferOwnersReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblTransferOwnersReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/{tokenId</code>/transfer-owners} — moves beneficiary and\n holder together, atomically, in one transaction.","properties":{"from":{"type":"string","minLength":1},"tokenRegistry":{"type":"string","minLength":1},"newBeneficiary":{"type":"string","minLength":1},"newHolder":{"type":"string","minLength":1}},"required":["from","newBeneficiary","newHolder","tokenRegistry"]}}}}
```

## The EblVerifyRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EblVerifyRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/verify</code> — document integrity <strong>and</strong> on-chain\n state. Returned for both outcomes; a burned or never-minted record is a value\n (<code>valid: false</code>), never an error.\n\n <p><b>Read <code>valid</code> AND <code>trusted</code></b> — same rule as\n <code>VerifyCredentialRespDto</code>, and for the same reason.","properties":{"valid":{"type":"boolean"},"issuer":{"type":"string"},"trusted":{"type":"boolean"},"onChain":{"$ref":"#/components/schemas/EblOnChainRespDto"},"checks":{"type":"array","items":{"$ref":"#/components/schemas/VerifyCheckRespDto"}}}},"EblOnChainRespDto":{"type":"object","description":"The registry-side view of a transferable record, part of {@link EblVerifyRespDto EblVerifyRespDto}.\n\n <p><code>beneficiary</code> and <code>holder</code> are <code>null</code> unless the record is active.","properties":{"minted":{"type":"boolean","description":"True while the token exists (active or surrendered); false if burned or never minted."},"status":{"type":"string","enum":["ACTIVE","SURRENDERED","BURNED","NOT_MINTED","UNKNOWN"]},"registry":{"type":"string","description":"The registry the record points at — worth checking rather than trusting <code>valid</code> alone:\n core-engine reports {@link Status#NOT_MINTED Status#NOT_MINTED}, not an error, for a record pointing elsewhere."},"tokenId":{"type":"string"},"titleEscrow":{"type":"string","description":"The Title Escrow owning the token while active (the registry once surrendered)."},"beneficiary":{"type":"string"},"holder":{"type":"string"}}},"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}}}
```

## The EndorsementChainRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EndorsementChainRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/{tokenId</code>/endorsement-chain} — the record's full transfer\n history, oldest first.\n\n <p>Events stay as <code>Map&lt;String, Object&gt;</code> rather than a typed class, matching the SDK's own\n choice: core-engine adds event types and fields over time. Observed fields include <code>type</code>\n (<code>INITIAL</code>, <code>TRANSFER_BENEFICIARY</code>, <code>TRANSFER_HOLDER</code>, …), <code>owner</code>,\n <code>holder</code>, <code>transactionHash</code>, <code>transactionIndex</code>, <code>blockNumber</code>,\n <code>timestamp</code> (epoch milliseconds) and <code>remark</code>.","properties":{"tokenId":{"type":"string"},"chain":{"type":"array","items":{"type":"object","additionalProperties":{}}}}}}}}
```

## The EstimateFeeReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EstimateFeeReqDto":{"type":"object","description":"Request for <code>POST /tx/estimate-fee</code>.\n\n <code>from</code> matters: gas depends on the sender's state (whether a storage slot is already\n set, whether the account exists), so estimating without it can give a materially different\n number than the real transaction will use.","properties":{"from":{"type":"string","minLength":1},"to":{"type":"string","minLength":1},"value":{"type":"integer"},"data":{"type":"string"}},"required":["from","to"]}}}}
```

## The EstimateFeeRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"EstimateFeeRespDto":{"type":"object","description":"Response of <code>POST /tx/estimate-fee</code>. All values in wei.\n\n <code>fee</code> is <code>gasLimit * gasPrice</code> — the ceiling the sender must be able to cover, not\n what the transaction will necessarily cost. Unused gas is not charged, so the actual spend is\n <code>gasUsed * gasPrice</code>, which is only known from the receipt.\n\n No safety margin is applied to gasPrice: it is the node's <code>eth_gasPrice</code> verbatim, per\n the 2026-08-05 decision to follow the node. (myeg-ms-ethereum doubles it below 25 gwei — a\n threshold tuned for Ethereum mainnet and meaningless on a chain quoting 7 wei.)","properties":{"gasLimit":{"type":"integer"},"gasPrice":{"type":"integer"},"fee":{"type":"string","description":"<b>A decimal String, not a JSON number</b>, unlike the two factors above.\n\n <p><code>gasLimit</code> and <code>gasPrice</code> are each safely inside a JavaScript number — a block\n gas limit is millions, and even 20 gwei is 2 × 10^10. Their <b>product</b> is not: 10^6 gas at\n 20 gwei is 2 × 10^16, past <code>Number.MAX_SAFE_INTEGER</code> (~9.007 × 10^15). Z2 quoting 7 wei\n hides this today, so the field would look fine right up until this service pointed at a chain\n with an ordinary fee market."}}}}}}
```

## The FinalityRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"FinalityRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/finality/{txHash</code>} — how final an L2 transaction is.\n\n <p><strong>On Z2, <code>final</code> adds little to <code>/tx/status</code>'s <code>SUCCESS</code>.</strong> Zetrix\n L2 runs QBFT, which is deterministic and does not reorg, so a transaction is final the moment it is\n mined: <code>final</code> is exactly <code>confirmations &gt;= 1</code>, not a threshold anyone can tune. The two\n fields worth reading are <code>confirmations</code> (which <code>/tx/status</code> cannot give you without a\n second call for the chain head) and <code>l1Settled</code>.\n\n <p>Takes any transaction hash, including one this service never submitted.","properties":{"l2Block":{"type":"integer","format":"int32","description":"<code>null</code> when the node has no receipt for this hash — still pending, or never existed."},"confirmations":{"type":"integer","format":"int32"},"l1Settled":{"type":"boolean","description":"Whether the batch containing this transaction has settled on L1. <code>null</code> means not\n checked, which is not the same as false: core-engine only answers this when an L1 settlement\n checker is configured on its side."},"final":{"type":"boolean","description":"The wire field is <code>final</code>, which cannot be a Java identifier — bound explicitly rather\n than relying on Jackson deriving it from the <code>isFinal()</code> getter."}}}}}}
```

## The GenerateBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"GenerateBlobReqDto":{"type":"object","description":"Request for <code>POST /tx/generate-blob</code>.\n\n The three override fields exist so a caller can pin a transaction exactly (replacing a stuck\n nonce, for instance). Left null, each is resolved from the node: nonce from\n <code>eth_getTransactionCount(pending)</code>, gasPrice from <code>eth_gasPrice</code>, gasLimit from\n <code>eth_estimateGas</code>.","properties":{"from":{"type":"string","minLength":1},"to":{"type":"string","description":"Recipient. Required here — contract deployment (no recipient) is BT-2584.","minLength":1},"value":{"type":"integer","description":"Native value in wei. Defaults to zero."},"data":{"type":"string","description":"Hex-encoded call data. Null or empty for a plain transfer."},"nonce":{"type":"integer"},"gasPrice":{"type":"integer"},"gasLimit":{"type":"integer"},"maxFeePerGas":{"type":"integer","description":"EIP-1559 ceiling, in wei. Supplying it builds a <b>type-2</b> transaction instead of a\n legacy one; leave it null and nothing changes.\n\n <p>You are charged <code>baseFeePerGas + maxPriorityFeePerGas</code> and refunded the rest, so a\n generous ceiling does not cost more - it only has to be high enough that the transaction\n stays includable if the base fee rises.\n\n <p>Mutually exclusive with <code>gasPrice</code>: naming both a legacy bid and a 1559 ceiling is\n contradictory, and guessing which one the caller meant is worse than refusing."},"maxPriorityFeePerGas":{"type":"integer","description":"EIP-1559 validator tip, in wei. Only meaningful with <code>maxFeePerGas</code>; defaults to 0."}},"required":["from","to"]}}}}
```

## The GenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"GenerateBlobRespDto":{"type":"object","description":"Response of <code>POST /tx/generate-blob</code>.\n\n The resolved nonce/gasPrice/gasLimit are echoed back deliberately: they are already encoded\n inside the blob, but a caller signing client-side needs to see what they are about to commit\n to without having to RLP-decode it first.","properties":{"blob":{"type":"string","description":"Unsigned transaction, RLP hex. Feed this to /tx/sign-blob or sign it yourself."},"nonce":{"type":"integer"},"gasPrice":{"type":"integer"},"gasLimit":{"type":"integer"},"chainId":{"type":"integer","format":"int64","description":"The chain id the blob must be signed with (EIP-155). Read from the node."},"maxFeePerGas":{"type":"integer","description":"Set only when the blob is a type-2 transaction; null for a legacy one."},"maxPriorityFeePerGas":{"type":"integer"}}}}}}
```

## The IssueCredentialReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"IssueCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/issue</code> — the same build as\n {@link PrepareCredentialReqDto PrepareCredentialReqDto}, plus the issuer's key pair for <b>delegated signing</b>\n (BT-2620's chosen signing model: <code>prepare</code> -&gt; core-engine's <code>/credentials/sign</code>\n -&gt; <code>complete</code>, in one call).\n\n <p><b>This sends the issuer's private key to core-engine.</b> See {@link MultikeyDto MultikeyDto} and the\n SDK's <code>signRemote</code> javadoc for the custody note.","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"type":{"type":"array","items":{"type":"string"}},"context":{"type":"array","items":{"type":"string"}},"validFrom":{"type":"string"},"expirationDate":{"type":"string"},"statusPurpose":{"type":"string","pattern":"(?i)^(revocation|suspension)$"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}},"keyPair":{"$ref":"#/components/schemas/MultikeyDto"}},"required":["credentialSubject","issuerDid","keyPair"]},"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]}}}}
```

## The MultikeyDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]}}}}
```

## The OnboardIssuerReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"OnboardIssuerReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/ebl/onboard-issuer</code> — build the transaction that deploys a\n brand-new eBL Token Registry.\n\n <p>This is where an eBL flow starts. <code>tokenRegistry</code> is required on <code>prepare-mint</code> and\n <code>mint</code> and core-engine keeps no server-wide default, so without a registry of your own there\n is nothing to mint into.\n\n <p>Like every other eBL write this returns an <strong>unsigned</strong> transaction: <code>admin</code>\n (or whoever you choose to pay) signs and broadcasts it, so that address needs gas first. Deployment\n is permissionless — the registry's admin comes from an encoded parameter rather than the sender —\n so the paying address and the admin need not be the same.\n\n <p><strong>The new registry's address is not in the transaction receipt's <code>contractAddress</code>\n field.</strong> The registry is deployed by the platform's shared deployer contract, not by this\n transaction directly, so that field is null. Once the transaction succeeds, read the address from\n <code>GET /tradetrust/ebl/onboard-issuer/registry?hash=...</code>.","properties":{"name":{"type":"string","description":"The registry's ERC-721 collection name, e.g. <code>&quot;MYEG Bill of Lading&quot;</code>.","minLength":1},"symbol":{"type":"string","description":"The registry's ERC-721 symbol, e.g. <code>&quot;MYEGBL&quot;</code>.","minLength":1},"admin":{"type":"string","description":"Becomes the new registry's admin, holding <code>DEFAULT_ADMIN_ROLE</code>, <code>MINTER_ROLE</code>,\n <code>RESTORER_ROLE</code> and <code>ACCEPTER_ROLE</code> — so this is the address that will be allowed\n to mint. Typically the issuer's own operational address.","minLength":1}},"required":["admin","name","symbol"]}}}}
```

## The PrepareCredentialReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"PrepareCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/prepare</code> — build the unsigned credential and the\n spec for signing it. <code>issuerDid</code> and <code>credentialSubject</code> are required; everything\n else defaults server-side in core-engine.\n\n <p><code>statusPurpose</code> attaches a status-list entry, which is what later makes the credential\n revocable; a plain string here (not the SDK's own enum) so this DTO — and the OpenAPI document\n generated from it — stays independent of the SDK's type, per BT-2620's design.","properties":{"issuerDid":{"type":"string","minLength":1},"credentialSubject":{"type":"object","additionalProperties":{},"minProperties":1},"type":{"type":"array","items":{"type":"string"}},"context":{"type":"array","items":{"type":"string"}},"validFrom":{"type":"string"},"expirationDate":{"type":"string"},"statusPurpose":{"type":"string","pattern":"(?i)^(revocation|suspension)$"},"renderMethod":{"type":"object","additionalProperties":{}},"qrCode":{"type":"object","additionalProperties":{}}},"required":["credentialSubject","issuerDid"]}}}}
```

## The PreparedCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"PreparedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/prepare</code> — the unsigned document plus its\n signing spec.\n\n <p><code>preparationId</code> is single-use and expires (~15 minutes); pass it unmodified to\n <code>complete</code> or <code>issue</code> alongside the signed document.","properties":{"preparationId":{"type":"string"},"unsignedVerifiableCredential":{"type":"object","additionalProperties":{}},"signingSpec":{"$ref":"#/components/schemas/SigningSpecRespDto"}}},"SigningSpecRespDto":{"type":"object","description":"Exactly how core-engine expects a prepared document to be signed — part of\n {@link PreparedCredentialRespDto PreparedCredentialRespDto}. Pass <code>mandatoryPointers</code> to the signer verbatim; core-engine\n derives it from what it actually built, so reconstructing it silently drops fields from the base proof.","properties":{"mandatoryPointers":{"type":"array","items":{"type":"string"}},"cryptoSuite":{"type":"string"},"expectedIssuerDid":{"type":"string"}}}}}}
```

## The RegistryAddressRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"RegistryAddressRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/onboard-issuer/registry</code> — the address of the Token Registry\n an <code>onboard-issuer</code> transaction deployed.\n\n <p>This endpoint exists because the address is not where callers look for it. The registry is\n deployed by the platform's shared deployer contract rather than by the submitted transaction\n itself, so the receipt's <code>contractAddress</code> is null and <code>GET /tx/status</code> — which returns\n no logs — cannot show it either. The address is only in the deployer's <code>Deployment</code> event, so\n this reads the receipt and decodes it.\n\n <p>Poll while <code>status</code> is <code>PENDING</code>, exactly as with <code>/tx/status</code>: a hash the node\n has not seen yet is pending rather than absent, because over JSON-RPC \"still in the mempool\" and\n \"never existed\" are indistinguishable. <code>registry</code> is populated only on <code>SUCCESS</code>.","properties":{"transactionHash":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","FAILED","PENDING"]},"registry":{"type":"string","description":"The new registry's address — the value to pass as <code>tokenRegistry</code> from here on.\n\n <p><code>null</code> while <code>PENDING</code> or on <code>FAILED</code>. Also null in one case worth\n handling: a <code>SUCCESS</code> whose logs carry no <code>Deployment</code> event, which means the hash\n belongs to some other transaction rather than an <code>onboard-issuer</code> one."}}}}}}
```

## The ResponseWrapperCompletedCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperCompletedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/CompletedCredentialRespDto"}}},"CompletedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/complete</code> (and <code>/issue</code>, which ends at the\n same step) — the assembled, signed credential.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}}}}}}}
```

## The ResponseWrapperEblCompleteMintRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperEblCompleteMintRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblCompleteMintRespDto"}}},"EblCompleteMintRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/complete-mint</code> (and <code>/mint</code>, which ends at the same\n step) — the assembled record, its assigned token id, and the still-unsent mint transaction.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{}},"tokenId":{"type":"string","description":"0x-prefixed 32-byte hex token id, assigned during signing rather than at prepare time."},"unsignedMintTx":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}}}
```

## The ResponseWrapperEblOwnerRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperEblOwnerRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblOwnerRespDto"}}},"EblOwnerRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/{tokenId</code>/owner}.","properties":{"tokenId":{"type":"string"},"owner":{"type":"string","description":"The Title Escrow address holding the token (or the registry, once surrendered)."}}}}}}
```

## The ResponseWrapperEblVerifyRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperEblVerifyRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EblVerifyRespDto"}}},"EblVerifyRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/ebl/verify</code> — document integrity <strong>and</strong> on-chain\n state. Returned for both outcomes; a burned or never-minted record is a value\n (<code>valid: false</code>), never an error.\n\n <p><b>Read <code>valid</code> AND <code>trusted</code></b> — same rule as\n <code>VerifyCredentialRespDto</code>, and for the same reason.","properties":{"valid":{"type":"boolean"},"issuer":{"type":"string"},"trusted":{"type":"boolean"},"onChain":{"$ref":"#/components/schemas/EblOnChainRespDto"},"checks":{"type":"array","items":{"$ref":"#/components/schemas/VerifyCheckRespDto"}}}},"EblOnChainRespDto":{"type":"object","description":"The registry-side view of a transferable record, part of {@link EblVerifyRespDto EblVerifyRespDto}.\n\n <p><code>beneficiary</code> and <code>holder</code> are <code>null</code> unless the record is active.","properties":{"minted":{"type":"boolean","description":"True while the token exists (active or surrendered); false if burned or never minted."},"status":{"type":"string","enum":["ACTIVE","SURRENDERED","BURNED","NOT_MINTED","UNKNOWN"]},"registry":{"type":"string","description":"The registry the record points at — worth checking rather than trusting <code>valid</code> alone:\n core-engine reports {@link Status#NOT_MINTED Status#NOT_MINTED}, not an error, for a record pointing elsewhere."},"tokenId":{"type":"string"},"titleEscrow":{"type":"string","description":"The Title Escrow owning the token while active (the registry once surrendered)."},"beneficiary":{"type":"string"},"holder":{"type":"string"}}},"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}}}
```

## The ResponseWrapperEndorsementChainRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperEndorsementChainRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EndorsementChainRespDto"}}},"EndorsementChainRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/{tokenId</code>/endorsement-chain} — the record's full transfer\n history, oldest first.\n\n <p>Events stay as <code>Map&lt;String, Object&gt;</code> rather than a typed class, matching the SDK's own\n choice: core-engine adds event types and fields over time. Observed fields include <code>type</code>\n (<code>INITIAL</code>, <code>TRANSFER_BENEFICIARY</code>, <code>TRANSFER_HOLDER</code>, …), <code>owner</code>,\n <code>holder</code>, <code>transactionHash</code>, <code>transactionIndex</code>, <code>blockNumber</code>,\n <code>timestamp</code> (epoch milliseconds) and <code>remark</code>.","properties":{"tokenId":{"type":"string"},"chain":{"type":"array","items":{"type":"object","additionalProperties":{}}}}}}}}
```

## The ResponseWrapperEstimateFeeRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperEstimateFeeRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/EstimateFeeRespDto"}}},"EstimateFeeRespDto":{"type":"object","description":"Response of <code>POST /tx/estimate-fee</code>. All values in wei.\n\n <code>fee</code> is <code>gasLimit * gasPrice</code> — the ceiling the sender must be able to cover, not\n what the transaction will necessarily cost. Unused gas is not charged, so the actual spend is\n <code>gasUsed * gasPrice</code>, which is only known from the receipt.\n\n No safety margin is applied to gasPrice: it is the node's <code>eth_gasPrice</code> verbatim, per\n the 2026-08-05 decision to follow the node. (myeg-ms-ethereum doubles it below 25 gwei — a\n threshold tuned for Ethereum mainnet and meaningless on a chain quoting 7 wei.)","properties":{"gasLimit":{"type":"integer"},"gasPrice":{"type":"integer"},"fee":{"type":"string","description":"<b>A decimal String, not a JSON number</b>, unlike the two factors above.\n\n <p><code>gasLimit</code> and <code>gasPrice</code> are each safely inside a JavaScript number — a block\n gas limit is millions, and even 20 gwei is 2 × 10^10. Their <b>product</b> is not: 10^6 gas at\n 20 gwei is 2 × 10^16, past <code>Number.MAX_SAFE_INTEGER</code> (~9.007 × 10^15). Z2 quoting 7 wei\n hides this today, so the field would look fine right up until this service pointed at a chain\n with an ordinary fee market."}}}}}}
```

## The ResponseWrapperFinalityRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperFinalityRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/FinalityRespDto"}}},"FinalityRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/finality/{txHash</code>} — how final an L2 transaction is.\n\n <p><strong>On Z2, <code>final</code> adds little to <code>/tx/status</code>'s <code>SUCCESS</code>.</strong> Zetrix\n L2 runs QBFT, which is deterministic and does not reorg, so a transaction is final the moment it is\n mined: <code>final</code> is exactly <code>confirmations &gt;= 1</code>, not a threshold anyone can tune. The two\n fields worth reading are <code>confirmations</code> (which <code>/tx/status</code> cannot give you without a\n second call for the chain head) and <code>l1Settled</code>.\n\n <p>Takes any transaction hash, including one this service never submitted.","properties":{"l2Block":{"type":"integer","format":"int32","description":"<code>null</code> when the node has no receipt for this hash — still pending, or never existed."},"confirmations":{"type":"integer","format":"int32"},"l1Settled":{"type":"boolean","description":"Whether the batch containing this transaction has settled on L1. <code>null</code> means not\n checked, which is not the same as false: core-engine only answers this when an L1 settlement\n checker is configured on its side."},"final":{"type":"boolean","description":"The wire field is <code>final</code>, which cannot be a Java identifier — bound explicitly rather\n than relying on Jackson deriving it from the <code>isFinal()</code> getter."}}}}}}
```

## The ResponseWrapperGenerateBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperGenerateBlobRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/GenerateBlobRespDto"}}},"GenerateBlobRespDto":{"type":"object","description":"Response of <code>POST /tx/generate-blob</code>.\n\n The resolved nonce/gasPrice/gasLimit are echoed back deliberately: they are already encoded\n inside the blob, but a caller signing client-side needs to see what they are about to commit\n to without having to RLP-decode it first.","properties":{"blob":{"type":"string","description":"Unsigned transaction, RLP hex. Feed this to /tx/sign-blob or sign it yourself."},"nonce":{"type":"integer"},"gasPrice":{"type":"integer"},"gasLimit":{"type":"integer"},"chainId":{"type":"integer","format":"int64","description":"The chain id the blob must be signed with (EIP-155). Read from the node."},"maxFeePerGas":{"type":"integer","description":"Set only when the blob is a type-2 transaction; null for a legacy one."},"maxPriorityFeePerGas":{"type":"integer"}}}}}}
```

## The ResponseWrapperPreparedCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperPreparedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/PreparedCredentialRespDto"}}},"PreparedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/prepare</code> — the unsigned document plus its\n signing spec.\n\n <p><code>preparationId</code> is single-use and expires (~15 minutes); pass it unmodified to\n <code>complete</code> or <code>issue</code> alongside the signed document.","properties":{"preparationId":{"type":"string"},"unsignedVerifiableCredential":{"type":"object","additionalProperties":{}},"signingSpec":{"$ref":"#/components/schemas/SigningSpecRespDto"}}},"SigningSpecRespDto":{"type":"object","description":"Exactly how core-engine expects a prepared document to be signed — part of\n {@link PreparedCredentialRespDto PreparedCredentialRespDto}. Pass <code>mandatoryPointers</code> to the signer verbatim; core-engine\n derives it from what it actually built, so reconstructing it silently drops fields from the base proof.","properties":{"mandatoryPointers":{"type":"array","items":{"type":"string"}},"cryptoSuite":{"type":"string"},"expectedIssuerDid":{"type":"string"}}}}}}
```

## The ResponseWrapperRegistryAddressRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperRegistryAddressRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/RegistryAddressRespDto"}}},"RegistryAddressRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/ebl/onboard-issuer/registry</code> — the address of the Token Registry\n an <code>onboard-issuer</code> transaction deployed.\n\n <p>This endpoint exists because the address is not where callers look for it. The registry is\n deployed by the platform's shared deployer contract rather than by the submitted transaction\n itself, so the receipt's <code>contractAddress</code> is null and <code>GET /tx/status</code> — which returns\n no logs — cannot show it either. The address is only in the deployer's <code>Deployment</code> event, so\n this reads the receipt and decodes it.\n\n <p>Poll while <code>status</code> is <code>PENDING</code>, exactly as with <code>/tx/status</code>: a hash the node\n has not seen yet is pending rather than absent, because over JSON-RPC \"still in the mempool\" and\n \"never existed\" are indistinguishable. <code>registry</code> is populated only on <code>SUCCESS</code>.","properties":{"transactionHash":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","FAILED","PENDING"]},"registry":{"type":"string","description":"The new registry's address — the value to pass as <code>tokenRegistry</code> from here on.\n\n <p><code>null</code> while <code>PENDING</code> or on <code>FAILED</code>. Also null in one case worth\n handling: a <code>SUCCESS</code> whose logs carry no <code>Deployment</code> event, which means the hash\n belongs to some other transaction rather than an <code>onboard-issuer</code> one."}}}}}}
```

## The ResponseWrapperSignBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperSignBlobRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/SignBlobRespDto"}}},"SignBlobRespDto":{"type":"object","description":"Response of <code>POST /tx/sign-blob</code>.\n\n Contains no echo of the submitted private key, by design — see <code>SignBlobReqDto</code>.","properties":{"signedBlob":{"type":"string","description":"Signed transaction, RLP hex. Ready for /tx/submit."},"transactionHash":{"type":"string","description":"The hash this transaction will have once submitted (keccak256 of the signed RLP).\n Computable before submission, so a caller can start watching for it immediately."},"chainId":{"type":"integer","format":"int64","description":"The chain id baked into the signature, for the caller to verify."}}}}}}
```

## The ResponseWrapperSignedCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperSignedCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/SignedCredentialRespDto"}}},"SignedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/sign</code> — the signed (and derived) credential.\n\n <p>Deliberately a separate type from {@link CompletedCredentialRespDto CompletedCredentialRespDto} despite the identical\n shape: that one is a finished credential, this one is <strong>not</strong>. Pass this document,\n unmodified, to <code>complete</code> together with the same <code>preparationId</code> to get the finished\n one. Nothing has been recorded anywhere until you do.","properties":{"signedVerifiableCredential":{"type":"object","additionalProperties":{}}}}}}}
```

## The ResponseWrapperStatusListRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperStatusListRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/StatusListRespDto"}}},"StatusListRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/credentials/status/{issuerDid</code>/{purpose}} — the signed Bitstring\n Status List credential for one issuer and purpose.\n\n <p>This is the document verifiers fetch to decide whether a credential has been revoked. It is\n signed by core-engine's own status-responder identity, deliberately separate from any issuer key:\n the issuer authorizes each individual bit flip, core-engine signs the aggregate.\n\n <p>Reading it is not how you check one credential — <code>POST /credentials/verify</code> already\n resolves revocation for you. Fetch this when you want the whole picture, e.g. to show an issuer\n everything they have revoked.","properties":{"statusListCredential":{"type":"object","additionalProperties":{}}}}}}}
```

## The ResponseWrapperStatusUpdateRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperStatusUpdateRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/StatusUpdateRespDto"}}},"StatusUpdateRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/revoke</code> — the status-list entry's state after the\n write, echoed back from core-engine.\n\n <p>Every field is an echo of what was applied, not a fresh read, so treat it as confirmation that\n the mutation was accepted rather than as the list's current contents. The bit is visible to\n verifiers on the next <code>GET</code> of the status list, which core-engine signs fresh on each\n request — there is no cache to wait out.","properties":{"issuerId":{"type":"string"},"purpose":{"type":"string"},"index":{"type":"integer","format":"int32"},"revoked":{"type":"boolean"}}}}}}
```

## The ResponseWrapperSubmitTxRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperSubmitTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/SubmitTxRespDto"}}},"SubmitTxRespDto":{"type":"object","description":"Response of <code>POST /tx/submit</code>.\n\n A hash here means the node <b>accepted</b> the transaction into its pool — not that it has\n been mined, and not that it will succeed. There is currently no way to follow up on it: a\n status/receipt endpoint is a known gap with no ticket (see the BT-2583 plan doc §1).","properties":{"transactionHash":{"type":"string"}}}}}}
```

## The ResponseWrapperTxStatusRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperTxStatusRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/TxStatusRespDto"}}},"TxStatusRespDto":{"type":"object","description":"Response of <code>GET /tx/status?hash=…</code> — the outcome of a submitted transaction.\n\n <p>This closes the gap that made <code>/tx/submit</code> a dead end: you got a hash and had no way to\n ask what became of it. A hash means only that the node accepted the transaction into its pool; a\n transaction that <b>reverts is still mined and still has that hash</b>, so the hash alone can\n never tell success from failure.\n\n <p>The four states are genuinely different and are worth distinguishing:\n <ul>\n   <li><code>SUCCESS</code> — mined, <code>status: 0x1</code>. It ran and did not revert.</li>\n   <li><code>FAILED</code> — mined, <code>status: 0x0</code>. It reverted; gas was still consumed. See\n       <code>revertReason</code>.</li>\n   <li><code>PENDING</code> — no receipt yet. Either still in the pool, or the hash never existed —\n       JSON-RPC cannot tell those apart, so neither can we, and claiming otherwise would be a\n       guess. Poll, and treat a hash that stays pending indefinitely as never having landed.</li>\n </ul>","properties":{"transactionHash":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","FAILED","PENDING"]},"blockNumber":{"type":"integer"},"gasUsed":{"type":"integer"},"from":{"type":"string"},"to":{"type":"string"},"contractAddress":{"type":"string","description":"Set only for a contract creation, and this is the <b>authoritative</b> address — unlike the\n prediction from <code>/contract/deploy/generate-blob</code>, which is conditional on the nonce\n being spent as planned. Once a deploy reaches <code>SUCCESS</code>, use this one."},"revertReason":{"type":"string","description":"Why a <code>FAILED</code> transaction reverted, when it can be recovered.\n\n <p>Revert data is not stored on chain, so this comes from replaying the call against the\n state it ran in. That needs historical state: a pruned node cannot serve it and this stays\n null. Null therefore means \"could not be recovered\", never \"no reason\"."}}}}}}
```

## The ResponseWrapperUnsignedTxRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperUnsignedTxRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/UnsignedTxRespDto"}}},"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}}}
```

## The ResponseWrapperVerifyCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"ResponseWrapperVerifyCredentialRespDto":{"type":"object","description":"Standard BaaS response envelope. Mirrors the shape used across the microservices so\n callers get a consistent contract on L2 as on L1.","properties":{"success":{"type":"boolean"},"errorCode":{"type":"string"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/VerifyCredentialRespDto"}}},"VerifyCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/verify</code> — returned for both outcomes; a failed\n verification is a value (<code>valid: false</code>), never an error.\n\n <p><b>Read <code>valid</code> AND <code>trusted</code> — never <code>valid</code> alone.</b> <code>valid</code> means\n cryptographically genuine, issuer-bound and not revoked/suspended; it says nothing about whether\n the issuer should be accepted. <code>trusted</code> answers that, and is only populated when the\n request supplied <code>trustedIssuers</code> — otherwise it stays <code>null</code>, which is not the same\n as <code>false</code>.","properties":{"valid":{"type":"boolean"},"issuer":{"type":"string"},"trusted":{"type":"boolean"},"status":{"type":"string","description":"<code>null</code> when the credential carries no <code>credentialStatus</code> entry.","enum":["ACTIVE","REVOKED","SUSPENDED","UNKNOWN"]},"checks":{"type":"array","items":{"$ref":"#/components/schemas/VerifyCheckRespDto"}}}},"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}}}
```

## The RevokeCredentialReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"RevokeCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/revoke</code> — flip one status-list bit, authorized by\n the issuer's own signature.\n\n <p><strong>This service cannot revoke on your behalf, by design.</strong> core-engine only ever\n verifies a status mutation, never signs one, so the authorization has to come from whoever holds\n the issuer key. This route is a pass-through: it carries <code>nonce</code>, <code>timestamp</code> and\n <code>signature</code> to core-engine and touches no key material at all — unlike\n <code>/credentials/issue</code>, no {@link MultikeyDto MultikeyDto} appears here and none may ever be added.\n\n <p>Sign this exact string with the issuer's P-256 key, SHA-256 prehashed, as a 64-byte compact\n <code>r‖s</code> pair, hex-encoded:\n\n <pre>STATUS-MUTATE|{issuerDid}|{purpose}|{index}|{revoked}|{nonce}|{timestamp}</pre>\n\n <p>The Java SDK's <code>CredentialsClient.statusMutationMessage(...)</code> builds it, and\n <code>Signatures.derToCompactRs</code> converts a JCA signature to the wire form — <code>SHA256withECDSA</code>\n already prehashes and emits DER, and both mistakes yield a well-formed signature that fails with\n only \"signature invalid\" to go on.\n\n <p>One route covers all four operations. <code>revoked</code> chooses the direction, <code>purpose</code>\n chooses the list: <code>revocation</code> + <code>true</code> revokes, <code>revocation</code> + <code>false</code>\n un-revokes, and <code>suspension</code> does the same to the suspension list. <code>revoked</code> is boxed\n and required so an omitted field is a 400 rather than a silent un-revoke.\n\n <p>Two server-side rules make a naive retry fail. <code>timestamp</code> must be within ~60s of\n core-engine's clock, and it must be strictly newer than the last accepted mutation for this\n <code>index</code> — so a retry has to be re-signed with a fresh timestamp, never replayed.","properties":{"issuerDid":{"type":"string","minLength":1},"purpose":{"type":"string","description":"Which list to write to. Same two values <code>prepare</code>'s <code>statusPurpose</code> accepts.","minLength":1,"pattern":"(?i)^(revocation|suspension)$"},"index":{"type":"integer","format":"int32","description":"The credential's own <code>credentialStatus.statusListIndex</code>. Read it off the credential\n rather than guessing: an unallocated index can be written, and a credential later issued into\n it would be born revoked.","minimum":0},"revoked":{"type":"boolean"},"nonce":{"type":"string","description":"Any unique value; it is signed, so it cannot be swapped after the fact.","minLength":1},"timestamp":{"type":"string","description":"ISO-8601, and part of the signed message — not a header this service adds.","minLength":1},"signature":{"type":"string","description":"Hex-encoded 64-byte compact <code>r‖s</code> P-256 signature over the canonical message above.","minLength":1}},"required":["index","issuerDid","nonce","purpose","revoked","signature","timestamp"]}}}}
```

## The SignBlobReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SignBlobReqDto":{"type":"object","description":"Request for <code>POST /tx/sign-blob</code>.\n\n <b>Carries a private key.</b> This is why the endpoint is POST rather than GET: a key in a\n query string ends up in access logs, proxy logs and browser history. The key is used to sign\n and then discarded — never logged, never persisted. Callers who would rather not send it at\n all should sign the blob client-side; that is the reason the blob/sign/submit split exists.","properties":{"blob":{"type":"string","description":"Unsigned transaction as RLP hex, from <code>/tx/generate-blob</code>.","minLength":1},"privateKey":{"type":"string","minLength":1}},"required":["blob","privateKey"]}}}}
```

## The SignBlobRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SignBlobRespDto":{"type":"object","description":"Response of <code>POST /tx/sign-blob</code>.\n\n Contains no echo of the submitted private key, by design — see <code>SignBlobReqDto</code>.","properties":{"signedBlob":{"type":"string","description":"Signed transaction, RLP hex. Ready for /tx/submit."},"transactionHash":{"type":"string","description":"The hash this transaction will have once submitted (keccak256 of the signed RLP).\n Computable before submission, so a caller can start watching for it immediately."},"chainId":{"type":"integer","format":"int64","description":"The chain id baked into the signature, for the caller to verify."}}}}}}
```

## The SignCredentialReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SignCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/sign</code> — have core-engine apply the issuer's key to\n a credential built by an earlier <code>prepare</code>, without completing it.\n\n <p>This is the middle step of <code>prepare</code> -&gt; sign -&gt; <code>complete</code>, exposed on its own.\n <code>/credentials/issue</code> already runs all three in one call; the reason to take them separately\n is to see the unsigned document (and its <code>signingSpec</code>) before anything is signed, and to\n keep the <code>complete</code> call under your own control. The result still has to go to\n <code>complete</code> — signing alone does not produce a finished credential.\n\n <p><b>This sends the issuer's private key to core-engine</b>, exactly as <code>issue</code> does — see\n {@link MultikeyDto MultikeyDto}. If that is not acceptable, do not use this route: sign the document from\n <code>prepare</code> yourself and call <code>complete</code> directly. That path exists precisely so key\n custody can stay on your side.\n\n <p>Requires <code>ALLOW_ISSUER_SIGNING=true</code> on core-engine, which defaults to off. Where it is\n off this route answers 400 no matter how well-formed the request is — the same condition that\n gates <code>issue</code> and <code>ebl/mint</code>.\n\n <p><code>preparationId</code> is single-use and expires (~15 minutes), and <code>keyPair.controller</code>\n must equal the <code>issuerDid</code> the preparation was created for; core-engine rejects a mismatch\n rather than signing with the wrong identity.","properties":{"preparationId":{"type":"string","minLength":1},"keyPair":{"$ref":"#/components/schemas/MultikeyDto"}},"required":["keyPair","preparationId"]},"MultikeyDto":{"type":"object","description":"The issuer's Multikey key pair, <b>including its secret</b> — the payload for delegated signing\n (BT-2620: <code>POST /credentials/sign</code> via the SDK's <code>signRemote</code>/<code>issueRemote</code>).\n\n <p>All six fields are required; core-engine's schema rejects a partially built key with a 400\n rather than a partial success, so this DTO enforces the same shape locally via <code>@NotBlank</code>.\n\n <p><b>Carries a private key</b>, exactly like <code>SignBlobReqDto</code>: never logged, never\n persisted, and masked in {@link com.myeg.z2.tradetrust.dto.req.MultikeyDto#toString #toString()} so it cannot leak through request logging, an\n exception message, or a debugger. Every endpoint that accepts this DTO must be POST — a key in a\n query string ends up in access logs.","properties":{"id":{"type":"string","minLength":1},"type":{"type":"string","minLength":1},"controller":{"type":"string","description":"Must equal the <code>issuerDid</code> the preparation was created for.","minLength":1},"publicKeyMultibase":{"type":"string","minLength":1},"secretKeyMultibase":{"type":"string","minLength":1},"@context":{"type":"string","minLength":1}},"required":["@context","controller","id","publicKeyMultibase","secretKeyMultibase","type"]}}}}
```

## The SignedCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SignedCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/sign</code> — the signed (and derived) credential.\n\n <p>Deliberately a separate type from {@link CompletedCredentialRespDto CompletedCredentialRespDto} despite the identical\n shape: that one is a finished credential, this one is <strong>not</strong>. Pass this document,\n unmodified, to <code>complete</code> together with the same <code>preparationId</code> to get the finished\n one. Nothing has been recorded anywhere until you do.","properties":{"signedVerifiableCredential":{"type":"object","additionalProperties":{}}}}}}}
```

## The SigningSpecRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SigningSpecRespDto":{"type":"object","description":"Exactly how core-engine expects a prepared document to be signed — part of\n {@link PreparedCredentialRespDto PreparedCredentialRespDto}. Pass <code>mandatoryPointers</code> to the signer verbatim; core-engine\n derives it from what it actually built, so reconstructing it silently drops fields from the base proof.","properties":{"mandatoryPointers":{"type":"array","items":{"type":"string"}},"cryptoSuite":{"type":"string"},"expectedIssuerDid":{"type":"string"}}}}}}
```

## The StatusListRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"StatusListRespDto":{"type":"object","description":"Response of <code>GET /tradetrust/credentials/status/{issuerDid</code>/{purpose}} — the signed Bitstring\n Status List credential for one issuer and purpose.\n\n <p>This is the document verifiers fetch to decide whether a credential has been revoked. It is\n signed by core-engine's own status-responder identity, deliberately separate from any issuer key:\n the issuer authorizes each individual bit flip, core-engine signs the aggregate.\n\n <p>Reading it is not how you check one credential — <code>POST /credentials/verify</code> already\n resolves revocation for you. Fetch this when you want the whole picture, e.g. to show an issuer\n everything they have revoked.","properties":{"statusListCredential":{"type":"object","additionalProperties":{}}}}}}}
```

## The StatusUpdateRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"StatusUpdateRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/revoke</code> — the status-list entry's state after the\n write, echoed back from core-engine.\n\n <p>Every field is an echo of what was applied, not a fresh read, so treat it as confirmation that\n the mutation was accepted rather than as the list's current contents. The bit is visible to\n verifiers on the next <code>GET</code> of the status list, which core-engine signs fresh on each\n request — there is no cache to wait out.","properties":{"issuerId":{"type":"string"},"purpose":{"type":"string"},"index":{"type":"integer","format":"int32"},"revoked":{"type":"boolean"}}}}}}
```

## The SubmitTxReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SubmitTxReqDto":{"type":"object","description":"Request for <code>POST /tx/submit</code>: a signed transaction as RLP hex.","properties":{"signedBlob":{"type":"string","minLength":1}},"required":["signedBlob"]}}}}
```

## The SubmitTxRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"SubmitTxRespDto":{"type":"object","description":"Response of <code>POST /tx/submit</code>.\n\n A hash here means the node <b>accepted</b> the transaction into its pool — not that it has\n been mined, and not that it will succeed. There is currently no way to follow up on it: a\n status/receipt endpoint is a known gap with no ticket (see the BT-2583 plan doc §1).","properties":{"transactionHash":{"type":"string"}}}}}}
```

## The TxStatusRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"TxStatusRespDto":{"type":"object","description":"Response of <code>GET /tx/status?hash=…</code> — the outcome of a submitted transaction.\n\n <p>This closes the gap that made <code>/tx/submit</code> a dead end: you got a hash and had no way to\n ask what became of it. A hash means only that the node accepted the transaction into its pool; a\n transaction that <b>reverts is still mined and still has that hash</b>, so the hash alone can\n never tell success from failure.\n\n <p>The four states are genuinely different and are worth distinguishing:\n <ul>\n   <li><code>SUCCESS</code> — mined, <code>status: 0x1</code>. It ran and did not revert.</li>\n   <li><code>FAILED</code> — mined, <code>status: 0x0</code>. It reverted; gas was still consumed. See\n       <code>revertReason</code>.</li>\n   <li><code>PENDING</code> — no receipt yet. Either still in the pool, or the hash never existed —\n       JSON-RPC cannot tell those apart, so neither can we, and claiming otherwise would be a\n       guess. Poll, and treat a hash that stays pending indefinitely as never having landed.</li>\n </ul>","properties":{"transactionHash":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","FAILED","PENDING"]},"blockNumber":{"type":"integer"},"gasUsed":{"type":"integer"},"from":{"type":"string"},"to":{"type":"string"},"contractAddress":{"type":"string","description":"Set only for a contract creation, and this is the <b>authoritative</b> address — unlike the\n prediction from <code>/contract/deploy/generate-blob</code>, which is conditional on the nonce\n being spent as planned. Once a deploy reaches <code>SUCCESS</code>, use this one."},"revertReason":{"type":"string","description":"Why a <code>FAILED</code> transaction reverted, when it can be recovered.\n\n <p>Revert data is not stored on chain, so this comes from replaying the call against the\n state it ran in. That needs historical state: a pruned node cannot serve it and this stays\n null. Null therefore means \"could not be recovered\", never \"no reason\"."}}}}}}
```

## The UnsignedTxRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"UnsignedTxRespDto":{"type":"object","description":"An <strong>unsigned</strong> EVM transaction, returned by every eBL write, by mint, and by\n <code>onboard-issuer</code>. Nothing has happened on-chain until the <code>from</code> address signs and\n broadcasts it.\n\n <p>Four calls on this same service finish the job:\n\n <ol>\n   <li><code>POST /tx/generate-blob</code> with <code>from</code> plus the <code>to</code>, <code>data</code> and\n       <code>value</code> below, which returns the RLP-encoded <code>blob</code>.\n   <li><code>POST /tx/sign-blob</code> with that <code>blob</code> — or sign it yourself and skip this call.\n   <li><code>POST /tx/submit</code> with the <code>signedBlob</code>.\n   <li><code>GET /tx/status?hash=...</code> until it reports <code>SUCCESS</code>.\n </ol>\n\n <p><b>Step 1 is not optional.</b> <code>/tx/sign-blob</code> takes a <code>blob</code> string, not the\n object below, so handing this response straight to it fails validation — an easy trap, and one\n this javadoc itself set until BT-2620's follow-up corrected it.\n\n <p><code>chainId</code> is informational: <code>/tx/sign-blob</code> signs with the chain this service is\n configured for, read live from the node. It matches when both this service and core-engine point\n at the same chain, which is the only supported arrangement — worth asserting rather than assuming\n if you run your own deployment of either.","properties":{"to":{"type":"string","description":"Contract to call — the token registry, or a Title Escrow."},"data":{"type":"string","description":"ABI-encoded calldata."},"value":{"type":"string","description":"Wei value as a decimal string; <code>&quot;0&quot;</code> for every eBL operation."},"chainId":{"type":"integer","format":"int64","description":"Chain the transaction must be signed for."}}}}}}
```

## The VerifyCheckRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}}}
```

## The VerifyCredentialReqDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"VerifyCredentialReqDto":{"type":"object","description":"Request for <code>POST /tradetrust/credentials/verify</code> — check signature, issuer binding and\n (if declared) revocation. Open on core-engine's side, but this service still requires its own\n caller auth like every other route (no addition to <code>SecurityConfig.PUBLIC_PATHS</code>).\n\n <p><code>trustedIssuers</code> is optional; when supplied, the response's <code>trusted</code> field\n reports whether the credential's issuer is on it.","properties":{"verifiableCredential":{"type":"object","additionalProperties":{},"minProperties":1},"trustedIssuers":{"type":"array","items":{"type":"string"}}},"required":["verifiableCredential"]}}}}
```

## The VerifyCredentialRespDto object

```json
{"openapi":"3.1.0","info":{"title":"myeg-z2-service - TradeTrust","version":"0.0.1"},"components":{"schemas":{"VerifyCredentialRespDto":{"type":"object","description":"Response of <code>POST /tradetrust/credentials/verify</code> — returned for both outcomes; a failed\n verification is a value (<code>valid: false</code>), never an error.\n\n <p><b>Read <code>valid</code> AND <code>trusted</code> — never <code>valid</code> alone.</b> <code>valid</code> means\n cryptographically genuine, issuer-bound and not revoked/suspended; it says nothing about whether\n the issuer should be accepted. <code>trusted</code> answers that, and is only populated when the\n request supplied <code>trustedIssuers</code> — otherwise it stays <code>null</code>, which is not the same\n as <code>false</code>.","properties":{"valid":{"type":"boolean"},"issuer":{"type":"string"},"trusted":{"type":"boolean"},"status":{"type":"string","description":"<code>null</code> when the credential carries no <code>credentialStatus</code> entry.","enum":["ACTIVE","REVOKED","SUSPENDED","UNKNOWN"]},"checks":{"type":"array","items":{"$ref":"#/components/schemas/VerifyCheckRespDto"}}}},"VerifyCheckRespDto":{"type":"object","description":"One step of a verification, e.g. <code>signature</code>, <code>status</code>, <code>trusted-issuer</code>.","properties":{"type":{"type":"string"},"status":{"type":"string","description":"<code>&quot;passed&quot;</code> or <code>&quot;failed&quot;</code>."},"reason":{"type":"string","description":"Why the check failed; <code>null</code> when it passed."}}}}}}
```


# Zetrix Faucet

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Ffymz5K0KNMLsOGnKNZf7%2Fimage.png?alt=media&amp;token=20725416-8c00-4b6c-b864-17ade99cedc0" alt=""><figcaption></figcaption></figure>

### Claiming Test ZTX Tokens

This document provides official guidance on how to claim **test ZTX tokens** using the **Zetrix Faucet**. The faucet is intended for developers and testers who require ZTX for development, testing, and integration on the Zetrix network.

URL : <https://faucet.zetrix.com/>

***

### Overview

The Zetrix Faucet allows eligible users to receive a limited amount of ZTX tokens for testing purposes.

* **Network**: Zetrix (Test environment)
* **Daily Limit**: 1 ZTX per wallet per day
* **Purpose**: Smart contract deployment, transaction testing, and API integration

***

### Accessing the Zetrix Faucet

1. Open a web browser and navigate to the **Zetrix Faucet** page.
2. The page will display the title **“Zetrix Faucet”** with a wallet input field and a claim button.

***

### Prerequisites

Before claiming tokens, ensure that you have:

* A valid **Zetrix wallet address** (format starts with `ZTX`)
* Access to the Zetrix Faucet page

***

### Claiming ZTX Tokens

#### Step 1: Enter Wallet Address

* In the **Zetrix Wallet** field, enter your wallet address (e.g., `ZTX3...`).
* Ensure the wallet address is correct. Tokens sent to an incorrect address cannot be recovered.

#### Step 2: Submit Faucet Request

* Click **Give me ZTX!** to submit the request.

#### Step 3: Transaction Processing

* Upon successful submission, the faucet will initiate a transfer of ZTX tokens to the specified wallet.
* Transaction details will be displayed under **Your Transaction**.

***

### Transaction Confirmation

* The **Your Transaction** section displays the transaction reference once the request is processed.
* Users may use the transaction hash to verify the transfer on the Zetrix blockchain explorer, if applicable.

***

### Usage Limitations

* Each wallet address is limited to **1 ZTX per day**.
* Multiple requests within the same day using the same wallet address are not permitted.
* Abuse or automated usage of the faucet may result in temporary or permanent restriction.

***

### Security and Best Practices

* Use the faucet **only for development and testing purposes**.
* Do not use production wallet addresses.
* Do not share private keys or sensitive wallet credentials.
* Store your wallet address and test tokens securely.


# ZPlatform (BaaS API)

## Introduction

This preliminary process for an organization to establish its operational presence on the Zetrix Platform. The Zetrix Platform ([https://platform.zetrix.com](https://platform.zetrix.com/)) serves as the official subscription and API management portal for all Zetrix Baas services, including the Verifiable Credential (VC) ecosystem.

Completion of the procedures described herein is a prerequisite for accessing Zetrix's blockchain-based VC issuance functionalities.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FhcoAdnEXEoMRpHPH9OUp%2Fimage.png?alt=media&amp;token=1f18962e-50a5-47e1-a25d-eb35baff5922" alt=""><figcaption></figcaption></figure>

## Process Overview

The onboarding workflow consists of three sequential stages: Registration, Subscription, and API Key Provisioning. This process formally identifies the Issuer, grants service entitlements, and provides secure access credentials.

### **Organizational Registration**

To formally register the Issuing organization on the Zetrix Platform, establishing a verified identity and granting access to the administrative dashboard.

#### **Procedure**

1. The Issuer initiates account creation on the Zetrix Platform.
2. The Issuer provides all required organizational details as stipulated by the platform.
3. The system creates a secure and authenticated profile for the Issuer.
4. Upon successful registration, the Issuer is granted access to the service management dashboard, enabling subscription and API management.

### **Service Subscription**

To enroll the Issuer in a Verifiable Credential Subscription Plan, defining the scope, limits, and privileges of their service entitlement.

#### **Subscription Plan Scope**

The selected plan governs the Issuer's operational parameters, which include but are not limited to:

* **API Usage Quotas:** The volume of API calls permitted over a defined period.
* **Rate Limits:** The frequency at which API requests can be made.
* **Access Privileges:** Specific VC issuance functions enabled for the Issuer.
* **Operational Bounds:** General service-level boundaries and capabilities.

### **API Key Provisioning**

To generate and provide a secure authentication credential, enabling the user to interface programmatically with Zetrix BaaS APIs.

### **Registration and Key Management**

#### Access Registration Page

Click **"Create an account"** or Navigate to the ZPlatform registration page:

* <https://platform.zetrix.com/#/register>

The **Sign Up Here** page will be displayed.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FIvM8n1UsxG6m23BVck01%2Fimage.png?alt=media&amp;token=38b4318a-485a-4933-b9e8-7ba1f1d3968e" alt=""><figcaption></figcaption></figure>

#### Complete Registration Form

All fields marked with (\*) are mandatory.

* **Username**\
  Unique identifier for your ZPlatform account.
* **Email**\
  Valid email address used for authentication and system notifications.
* **Phone**\
  Select the appropriate country code and enter a valid mobile number.
* **First Name**\
  Your given name.
* **Last Name**\
  Your family name.
* **Password**\
  Password must comply with the following security requirements:
  * Minimum of **8 characters**
  * At least **one uppercase letter**
  * At least **one number, symbol, or whitespace character**

#### Accept Terms and Conditions

* Select **“I agree to the privacy policy & terms”** to proceed.

#### Submit Registration

* Click **SIGN UP** to create your account.
* Upon successful registration, you may proceed to log in.

> Note: If you already have an account, select **Sign in instead** to access the login page.

***

### Account Login

#### Access Login Page

Navigate to:

* <https://platform.zetrix.com/#/login>

#### Enter Login Credentials

* **Username / Email**\
  Enter your registered username or email address.
* **Password**\
  Enter your account password.

Optional:

* Enable **Remember me** to retain login session on the device.

#### Login

* Click **LOGIN** to access the ZPlatform dashboard.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F47GfoxvfTetE3eTjCVaw%2Fimage.png?alt=media&amp;token=fb60a26c-96af-4496-b17d-48e989403a92" alt=""><figcaption></figcaption></figure>

### API Management Overview

After successful login:

1. From the left navigation menu, select **Manage API**.
2. The **Manage your API** page will be displayed.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FHOTvMMmCsavcQCYu3d3E%2Fimage.png?alt=media&amp;token=e4a6c212-6cca-428b-962d-62c0f9c0c8ee" alt=""><figcaption></figcaption></figure>

The API management table provides the following information:

* **Key Name** – User-defined identifier for the API key
* **API Key (Hashed)** – Encrypted representation of the API key
* **Expiry** – API key expiration date and time
* **Status** – Current state of the API key (Active / Revoked)
* **Actions** – Available actions (Revoke, Delete)

***

### Creating an API Key

#### Initiate API Key Creation

* On the **Manage API** page, click **CREATE**.

A dialog titled **Create your API keys** will appear.

#### Configure API Key

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F1J5IctWtEbunegFhrocW%2Fimage.png?alt=media&amp;token=bb5b3644-9e90-49ed-9080-4a75ad8ae2d0" alt=""><figcaption></figcaption></figure>

Complete the following fields:

* **Key Name**\
  A unique and descriptive name for the API key (e.g., `Billing-Service`, `Sandbox-Testing`).
* **Expiration**\
  Select the expiration date for the API key. The key will automatically become invalid after this date.

#### Generate API Key

* Click **GENERATE TOKEN** to create the API key.

> Important: The API key is a sensitive credential. Store it securely and restrict access appropriately.

***

### API Key Management

Existing API keys can be managed from the **Manage API** page.

#### Key Status

* **Active** – API key is valid and can be used for API requests.
* **Revoked** – API key access is disabled and cannot be used.

#### Available Actions

* **Revoke**\
  Temporarily disables the API key without deleting it.
* **Delete**\
  Permanently removes the API key. This action is irreversible.

***

## Account Balance

* The current **Account Balance** is displayed at the top of the dashboard (e.g., RM 0.00).
* Select **RELOAD** to top up the account if required for more API usage.

***

## Security Best Practices

To ensure secure usage of ZPlatform APIs:

* Do not embed API keys in client-side or publicly accessible code
* Store API keys using secure configuration or secret management tools
* Rotate API keys periodically
* Use separate API keys for development, testing, and production environments
* Immediately revoke compromised or unused API keys

***

## Support and Assistance

For technical assistance or account-related issues:

* Select **Contact Support** from the navigation menu, or
* Use **Forgot Password?** on the login page for credential recovery


# DID Management Platform

A DID Platform provides tools to manage decentralized identities, keys, attributes, and rights associated with an entity (person, organization, or device). Each DID contains a **DID Document**, which holds public keys, verification methods, services, and permissions.

All onboarding steps should first be performed on the **Testnet environment** for testing, and once validated, the same steps can be applied on **Mainnet** for production use:

* **Testnet:** <https://zid-identity-sandbox.zetrix.com/>
* **Mainnet:** <https://zid-identity.zetrix.com/>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FCg0jo7VZX7ulOx3sLUt2%2Fimage.png?alt=media&amp;token=e95d4f6a-6e2e-4b56-8e72-703ef38b4402" alt=""><figcaption></figcaption></figure>

The following functionalities represent the core operations in a DID Management Console:

### Change Owner

**Purpose:**\
Transfer ownership or administrative rights of a DID to another entity.

**How it works:**

* Every DID has an **owner** (often defined via controller DID).
* The owner can be changed by updating the DID Document’s **controller** field.
* After update, the new owner gains full control of:
  * key creation/removal
  * delegation management
  * attribute management
  * credential signing rights (if applicable)

**Use cases:**

* Organization transferring DID ownership to a new department.
* Rotating root level admin keys.
* Enforcing governance or recovering compromised ownership.

#### Steps:

The **Issuer** will login Zetrix Wallet and log in to website to change the owner. The steps are as follows:

1. Click on **Change Owner.**
2. Fill up the new owner DID.
3. Update.
4. Submit sign using pop up wallet.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Fh1SM0Hu73LSVwfsoEped%2FDID%20UPDATE.png?alt=media&amp;token=00058ab7-0722-46dd-b113-d6707b851f7b" alt=""><figcaption></figcaption></figure>

### Manage Attribute

**Purpose:**\
Add or remove metadata linked to a DID.

**Common DID Attributes include:**

* service entries (API endpoints, VC endpoints)
* cryptographic fingerprint

**Attribute Management includes:**

* **Add attribute** – Insert a new attribute (e.g., service endpoint).
* **Delete attribute** – Remove outdated or invalid attributes.

**Use cases:**

* Add an Issuer’s Verification endpoint (`/verify`).
* Adding a DIDComm messaging endpoint.
* Storing public profile (organization name, logo URL, contact email).

#### Steps:

The **Issuer** will login Zetrix Wallet and log in to website to manage the attribute. The steps are as follows:

1. Click on **Manage Attribute**.
2. Click on **Add Attribute**.
3. Please select Algorithms and Encoding needed.
   1. The **algorithm** specifies the cryptographic algorithm used by the public key you are adding.
      1. **Ed25519** – general signing, authentication
      2. **X25519** – encryption / key agreement
      3. **BBS+** – zero knowledge proof credentials
   2. Encoding describes **how the public key is formatted** when stored in the DID Document.
      1. **Hex** – Public key shown in raw hexadecimal bytes.\
         Example field: `publicKeyHex`
      2. **Base64** – Common web safe format used in WebCrypto.\
         Example field: `publicKeyBase64`
      3. **Base58** – Human friendly Base58 format.\
         Example field: `publicKeyBase58`
      4. **Multibase** – Base58 or Base64 but with a prefix (like `z`) telling the system which encoding is used.\
         Example field: `publicKeyMultibase`
      5. **PEM** – RSA key format with `-----BEGIN PUBLIC KEY-----`.\
         Example field: `publicKeyPem`
4. Enter Public Key Value in the input textbox.
5. Update.
6. Submit sign using pop up wallet.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FVzejEr6OrBzcFH6AG4Ue%2Fadd%20attribute.png?alt=media&amp;token=478e860f-4bd2-4325-ac28-f4c6af20cdc3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FPsqT8y4NUYBMGIQVrqJu%2Fimage.png?alt=media&amp;token=d1e74fe9-6096-4604-a9a8-5f7ec977b3c1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FrdhZJNWyiohwCboqATGN%2Fimage.png?alt=media&amp;token=477e17b4-660d-44d3-973e-4abe26fcccdb" alt=""><figcaption></figcaption></figure>

### **Update Delegation**

**Purpose:**\
Assign or modify **delegated permissions** for another DID or key.

There are two common types:

#### **Authentication Delegation**

Allows another DID or key to authenticate as the DID owner (e.g., login or signing).

#### **Authorization Delegation**

Allows a delegate to perform specific actions such as:

* issuing credentials
* managing sub-identities
* signing VC metadata
* administering services

**Operations include:**

* Add delegation (assign delegate DID)
* Revoke delegation (remove delegate rights)

**Use cases:**

* Company CEO DID delegating signing authority to HR manager DID.
* An IoT hub delegating actions to child IoT devices.
* Rotating delegated keys without changing DID ownership.

#### Steps:

The **Issuer** will login Zetrix Wallet and log in to website to update delegation. The steps are as follows:

1. Click on **Update Delegation**.
2. Click on **Add Delegation**.
3. Enter delegate DID for delegation.
4. Choose type of delegation for
   1. Signature Authentication
   2. Verification Key
5. Add validity for use case.
6. Update.
7. Submit sign using pop up wallet.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F1fgA7pU7D4YKLDcKlWsg%2Fimage.png?alt=media&amp;token=47e13ff3-ece6-4b52-9b0f-607dd23ba354" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FSI22v7AFFDf5zBWYaPXX%2Fimage.png?alt=media&amp;token=f4a79318-07f5-491c-ae0e-aed2ce6e6070" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FFAEug53Ay6DdXZwUElq1%2Fimage.png?alt=media&amp;token=c6b9616e-8ef5-433f-b210-308c9c4c902c" alt=""><figcaption></figcaption></figure>

### **Create BBS+ Key**

**Purpose:**\
Generate a **BBS+ signing key pair**, used for **Zero-Knowledge Proof (ZKP)** credentials.

**BBS+ Capabilities:**

* Multi-message signatures
* Selective disclosure
* Privacy preserving Verifiable Credentials
* Support for W3C VC ZKP formats

**Where BBS+ is used:**

* Issuers create BBS+ keys to sign credentials such as:
  * education certificates
  * IDs with ZKP support
  * medical or employment credentials
* Holders can generate proofs revealing only required fields.

**Example:**\
If a VC contains *(Name, DOB, Nationality, Address),* BBS+ allows revealing only *(Nationality)* without exposing the rest.

#### Steps:

The **Issuer** will login Zetrix Wallet and log in to website to create a **BBS+ Key**. The steps are as follows:

1. Create **BBS++ Key**.
2. Generate Key.
3. Add Validity for use case.
4. Submit/Update.
5. Submit sign using pop up wallet.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F3YDDUqtVlaE4XBXOsL1w%2Fimage.png?alt=media&amp;token=b62e980a-d512-4cd8-b0a4-e2b7710b6d6c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FQTyyPDPY7DIU6DZQk4YN%2Fcreate%20bbs.png?alt=media&amp;token=8769e22e-6842-494b-861a-3a09117e8628" alt=""><figcaption></figcaption></figure>

The **BBS+ public key** will be displayed in your ZID document after it is created.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FKj59vljm9x21HnKOonUO%2Fbbs.png?alt=media&amp;token=cd809283-ce97-4170-8c30-dd381ecf5072" alt=""><figcaption></figcaption></figure>

### **Create X25519 Key**

**Purpose:**\
Generate an **X25519 key pair** for secure encryption and key exchange.

**X25519 is used for:**

* DIDComm v2 messaging
* Encrypted communication
* Secure session key negotiation
* Holder ↔ Verifier secure data exchange

**Why X25519?**

* Lightweight and fast
* Modern elliptic curve cryptography
* Strong forward secrecy
* Recommended for DID secure messaging protocols

**Use cases:**

* Establish encrypted channels for Verifiable Presentation (VP).
* Encrypt wallet to server communication.
* DID-based encrypted chat systems.

#### Steps:

The **Issuer** will login Zetrix Wallet and log in to website to create X25519 key. The steps are as follows:

1. Click on **Create X25519 Key**.
2. Click on **Generate Key** and will auto generated below.
3. Add validity date for use case.
4. Update.
5. Submit sign using pop up wallet.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FIwZ0iIFEzXomDNGUHkjq%2Fcreatex25519.png?alt=media&amp;token=fe183784-becf-4ad7-b53e-84de446a455b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F3MOSBoi1VoVBaOQJ2cTZ%2Fcreatex255192.png?alt=media&amp;token=58b90d4c-ccfc-4aba-81b9-7717d5e64f10" alt=""><figcaption></figcaption></figure>


# ZCert Issuer Platform

The **ZCert Issuer Platform** provides a structured and secure environment for organizations to manage **Verifiable Credential (VC)** components, specifically **VC Templates** and **Design Passes**. The platform assigns clear responsibilities and approval workflows based on user roles to ensure quality, governance, and consistency across issued credentials.

### **User Roles in the ZCert Issuer Platform**

The platform supports two primary roles:

#### **Issuer Admin**

* Holds the highest authority within the Issuer’s organization.
* Manages templates, design passes, and approvals.
* Oversees makers (sub-issuers) and validates their submissions.

#### **Maker (Sub-Issuer)**

* Responsible for preparing templates and design passes.
* Requires approval from the appropriate authority before templates or designs can be used.

### Understanding Templates and Design Passes

#### VC Template (Mandatory)

A **VC Template** defines the **core data schema** and **required fields** used during VC issuance.\
It is the essential component for creating Verifiable Credentials.

* Contains the key-value structure, rules, and metadata for the credential.
* Used directly by the VC Issuance API and issuance console.
* Must exist before any credential can be issued.

Example of VC template:

```json
{
    "templateType": "MYKAD",
    "data": {
            "name": "Ali bin Abuq",
            "dob": "1990-01-01",
            "gender": "Male",
            "nationality": "Malaysian",
            "mykadNo": "901231-14-5678",
            "citizenType": "Warganegara",
            "address": "No. 123, Jalan Merdeka",
            "postcode": "43000",
            "city": "Kajang",
            "state": "Selangor",
            "photo": "base64-photo-string",
            "securityImage": "base64-security-image"
            }
} 

```

#### Design Pass (Optional)

A **Design Pass** is the **visual representation** of the credential, generated by combining:

* The VC Template (data structure), and
* A custom design layout (visual appearance)

Design passes function like **digital cards**, similar to how a digital passport, MyKad, or membership card visually displays the credential data.

* Enhances user experience by providing a branded, readable, card like UI.
* Completely optional VCs can be issued without a design pass.

### Template Creation Workflow

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FmR59mXcm09PR7VqoRJw1%2FVC%20Issuer%20Maker%20flow.drawio%20(3).png?alt=media&amp;token=0c14f064-72f1-4086-8f5d-1c671d263001" alt=""><figcaption></figcaption></figure>

#### **By Issuer Admin**

* Issuer Admin can create a template directly.
* **No approval is required.**\
  Once created, the template is immediately available for VC issuance.

#### **By Maker (Sub-Issuer)**

* Maker can create a template draft.
* The draft requires **Issuer Admin approval** before it becomes active.
* Ensures organizational governance and data schema integrity.

### Design Pass Workflow

Because design passes reflect the Issuer’s official visual identity, the platform enforces a stricter control mechanism.

#### **Approval Requirement**

* **All design passes whether created by Issuer Admin or Maker require Superadmin approval.**
* This ensures visual quality, branding consistency, and adherence to display standards.

#### **Design Pass Lifecycle**

1. **Creation**\
   Maker or Issuer Admin creates a design pass and maps it to the VC Template.
2. **Pending Approval**\
   The design pass enters the **‘Pending Approval’** state.
3. **Superadmin Review**\
   The Superadmin validates layout quality, readability, branding, and schema alignment.
4. **Approval or Rejection**\
   Only after approval can the design pass be used to generate digital card visuals during VC issuance.

### Template and Design Status Indicators

#### **Template Status: “Draft”**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F1bSUHWyIYT45OKyWeMjq%2Fimage.png?alt=media&amp;token=6768e4a7-0e27-4fbb-aeca-4bfd853feba9" alt=""><figcaption></figcaption></figure>

When a template is first created:

* The system marks the template as **“Draft”**.
* At this stage, the template has **not yet been submit**.
* The Issuer must **submit the template** before it can progress to the next stage.

This ensures that:

* The template structure is confirmed by the Issuer.
* No design or issuance activities can begin until the template is formally submitted.

#### **Template Status: “Pending Design”**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FG3mx3aVbaZ9K0sho4oE8%2Fimage.png?alt=media&amp;token=00211653-a7a4-4c5a-b405-56bf690846be" alt=""><figcaption></figcaption></figure>

After the Issuer Admin successfully creates a template:

* The system marks the template as **“Pending Design”**.
* At this stage, the template is **fully usable** for VC issuance even without a design pass.

This allows Issuers to:

* Start issuing VCs immediately using the template’s data schema.
* Optionally create a design pass later to support visual rendering.

#### **Design Pass Status: “Pending Approval”**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FTvNoAQvRaFmkzXxkP5ep%2Fimage.png?alt=media&amp;token=d8644246-22da-4b4b-99a9-d94f4ebdd837" alt=""><figcaption></figcaption></figure>

Once a design pass is created:

* Status changes to **“Pending Approval”**.
* The ZID Superadmin must validate the design before it can be used.
* Ensures the final appearance meets quality and compliance requirements.

#### **Design Pass Status: “Completed”**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FcmG1Xx2dartteG4Bvu3C%2Fcompleted.png?alt=media&amp;token=9706fde6-1963-42e9-8eb6-5d469e8716d9" alt=""><figcaption></figcaption></figure>

When the Superadmin approves the design:

* The system marks the design as **“Completed”**.
* All approved design passes are now published and ready for use.

This enables:

* VC issuance with the finalized digital card layout.
* Seamless integration of template data into the approved visual design.

#### **Design Pass Status: “Pending Publish”**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FIj9eBYEGljVqcOZKYwMU%2Fimage.png?alt=media&amp;token=1f44a9f9-f4a1-4fa3-8b06-aeeedc9e1304" alt=""><figcaption></figcaption></figure>

After a design pass is approved by the Superadmin:

* The system marks the design as **“Pending Publish”**.
* This indicates that the design is approved but **not yet published** for production use.
* The final step requires the Issuer to publish the design.

This ensures that:

* Approved designs undergo a controlled release process.
* Only intentionally published designs appear in production for VC generation.

#### **Design Pass Status: “Rejected”**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F9HVYoTksEJMBQda1Nbh9%2Frejected.png?alt=media&amp;token=f8182713-a663-4402-845e-79b262e48147" alt=""><figcaption></figcaption></figure>

If the design does not meet quality requirements:

* The system marks the design pass as **“Reject”**.
* The Maker or Issuer Admin must revise and resubmit the design.

This ensures that:

* Only compliant, high-quality visual layouts are published.
* Incorrect mapping, poor layout, or branding inconsistencies are corrected before use.

### Summary of Workflow

<table><thead><tr><th width="251.4444580078125">Component</th><th width="132.7777099609375">Created By</th><th>Approval Required</th><th>Usable for VC Issuance</th></tr></thead><tbody><tr><td><strong>VC Template</strong> (Issuer Admin)</td><td>Issuer Admin</td><td>No</td><td>Yes</td></tr><tr><td><strong>VC Template</strong> (Maker)</td><td>Maker</td><td>Yes – Issuer Admin</td><td>Yes (after approval)</td></tr><tr><td><strong>Design Pass</strong> (Issuer Admin or Maker)</td><td>Both</td><td><strong>Yes – Superadmin</strong></td><td>Yes (after approval)</td></tr></tbody></table>

### Onboarding to VC

All onboarding steps should first be performed on the **Testnet environment** for testing, and once validated, the same steps can be applied on **Mainnet** for production use:

* **Testnet**: <https://zid-issuer-sandbox.zetrix.com/#/>
* **Mainnet**: <https://zid-issuer.zetrix.com/#/>

1. Log in using the Zetrix wallet at website to register and manage VC template.\
   **Note:** Developers may also create a template directly via the API.
2. Fill in the company information and submit the application form.

   <figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FuZBAZUFu2AyieGQFVH4Q%2Fimage.png?alt=media&amp;token=47d7eb13-7eb4-4fc2-b3dc-310a8e4876ee" alt=""><figcaption></figcaption></figure>
3. Once approved, the Issuer can create and manage a VC template as shown below.

   <figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FjQNulFu9y3GVXIZVk0Tm%2Fbbs.png?alt=media&amp;token=7b8bd8fa-5127-4d48-970d-b79c64f79fc3" alt=""><figcaption></figcaption></figure>
4. After the VC template is submitted, it will shown in dashboard.


# Multisig Dapp

The Zetrix Multisig DApp is a secure blockchain application that enables **joint account ownership** with **multiple required signatures (multisig)** before any transaction can be executed. Instead of one person holding full control, the system distributes authority among several trusted participants.

This improves:

* **Security** → Prevents unauthorized movements
* **Governance** → Decisions require agreement
* **Accountability** → Transparent approvals and history
* **Reliability** → Eliminates single points of failure

Typical Use Cases

* Corporate treasury management
* Shared project funds
* DAO governance execution
* Secure long-term storage
* High-value account protection


# Introduction

### What is a Multisig Account?

A Multisig account is a **joint-controlled blockchain account** protected by multiple signers. No one can execute actions alone unless explicitly allowed by configuration.

### Key Concepts

* **Signers** → Authorized users
* **Weights** → Each signer has a security weight value
* **Threshold** → Minimum total weight required to approve an action
* **Proposals** → Pending actions waiting for signatures
* **Execution** → Only happens when approvals reach the threshold

### This design prevents:

* Single admin abuse
* Accidental transfers
* Insider theft
* Stolen private key exploitation

### Accessing the Application

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FdQO02XgechGuPR7kF0Sj%2Funknown.png?alt=media&amp;token=f3284855-3283-4617-9da9-12fcfb6e948c" alt=""><figcaption></figcaption></figure>

#### Test Environment

Use this environment for development, internal evaluation, demonstration, and testing purposes.

**Test URL:**\
<https://multisig.myegdev2.com/>

✔ Safe for experiments\
✔ Use test accounts\
✔ Features may update frequently

***

#### Production Environment

Use this environment for real usage, live operations, enterprise deployment, and actual fund management.

**Production URL:**\
<https://multisig.zetrix.com/#/>

✔ Stable and secure\
✔ Real blockchain transactions\
✔ Suitable for enterprise and organizational use

***

> ⚠️ **Important Notice**

* Always verify which environment you are using before performing transactions
* Never use real funds in the test environment
* Ensure signers are aware whether approvals are for test or production accounts


# Connect Wallet

### Function Purpose

The Connect Wallet feature is the entry point of the app. It links the DApp to your Zetrix wallet to enable:

* Account validation
* Secure transaction signing
* Identity recognition on-chain

### What Happens Technically

* DApp requests permissions to read wallet address
* Wallet confirms the user identity
* Application locks UI features until connected

### Expected Result

Once connected:

* Your wallet status becomes **Connected**
* Your address is recognized
* Multisig features become enabled

#### Common Issues

❗ Wallet not detected – ensure extension/mobile wallet installed\
❗ User cancels connection – app remains locked\
❗ Wrong network – app will notify mismatch


# Joint Account Management

**Joint Account Management** serves as the central function for handling all multisignature wallets within the Zetrix Multisig DApp. It allows users to create new multisig accounts, import existing shared wallets, convert single accounts into jointly managed accounts, and manage participants and governance policies. With structured approval mechanisms and weighted authorization, it ensures that every transaction and account update follows a secure, collective decision-making process.


# Create New Joint Account

### Purpose

Create a new multisignature account from scratch. This setup process allows you to configure signers, assign approval weights, and define the required signature threshold, resulting in a secure joint account where transactions can only be executed once enough authorized participants approve them.

### Required Inputs

* **Account Name** → For identification in dashboard
* **Signers List** → Wallet addresses allowed to sign
* **Weight Configuration** → Each signer assigned a numeric weight
* **Threshold** → Minimum total approval weight required

#### Example Setup

| Signer  | Weight |
| ------- | ------ |
| Admin A | 10     |
| Admin B | 10     |
| Admin C | 10     |

Threshold = 20\
Means → Any **two major admins** required in order to execute the operation.

## Flow

1️⃣ **Open Create Account**

Open the Create Account section to begin the process of setting up a new multisignature account. This is the first step where you will start configuring the account details, adding signers, assigning approval weights, and defining the required threshold for transaction approvals.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FdnA8Jf0FZ0QNG5ua8Ago%2Fimage.png?alt=media&amp;token=6e314e01-a6b0-44ff-ba75-e11191db1df6" alt=""><figcaption></figcaption></figure>

2️⃣**Enter Joint Account Name**

Enter the Joint Account Name. This is the display name that will be used to identify this multisignature account within the application dashboard and throughout the system. Choose a meaningful and recognizable name to help users easily distinguish this account from others.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FeNGE43kIa4hcXU6NxEKw%2Fimage.png?alt=media&amp;token=c37c4f75-10dc-40d8-9e1b-ab455a93cf4b" alt=""><figcaption></figcaption></figure>

3️⃣**Enter account configuration**

Enter the account configuration details, including the account name, list of signers, their respective approval weights, and the required approval threshold. These settings define how the multisig account will operate and how transaction approvals will be managed.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FVXcxP5lNapsFUtVj4zcr%2Fimage.png?alt=media&amp;token=11be1d98-3374-40c6-823f-67aa5ff4df53" alt=""><figcaption></figcaption></figure>

4️⃣**Confirm and submit**

Review all the account details carefully, including signers, weight distribution, and approval threshold. Once you are satisfied, confirm the configuration and deploy the multisig account to the Zetrix blockchain. This action will finalize the setup and activate the joint account.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FL0rW1u5J111IhrMUb6h8%2Fimage.png?alt=media&amp;token=6838a5ee-96a8-4e6f-ae48-db5fc4d93bfc" alt=""><figcaption></figcaption></figure>


# Import Joint Account

### Purpose

This feature enables users to access and manage a multisignature (multisig) account that was originally created by another user or organization. Instead of requiring every signer to recreate the wallet manually, authorized users can simply import the account into their own interface and immediately begin participating in approval workflows.

Once imported, the user gains the ability to:

* View account balances and configurations
* Review pending proposals and transactions
* Approve, reject, or execute actions (depending on permissions)
* Monitor completed transaction history
* Participate in governance changes

This function ensures continuity of control, allows decentralized participation, and eliminates dependency on a single account creator or administrator.

### When To Use

* Someone added you as a signer previously.

  If someone else created a multisig account and included your wallet address as one of the authorized signers, you can import that account to:

  * View the account within your dashboard
  * Participate fully in approvals
  * Take responsibility as assigned signer

  This is commonly needed in corporate teams, committees, or shared project groups.
* Organization already created the wallet.

  For enterprise environments, the multisig wallet is often created centrally by:

  * System administrators
  * Finance controllers
  * Project leads
  * DAO / governance teams

  Team members simply import the account to:

  * Share responsibility
  * Approve transactions
  * Enforce governance rules
  * Maintain accountability

  This prevents unauthorized recreation or confusion with multiple duplicate wallets.
* You are replacing a device.

  Importing is useful when:

  * Changing laptops or desktops
  * Installing a new browser
  * Resetting wallet applications
  * Moving to a new mobile device

  Instead of rebuilding or reconfiguring everything, import makes recovery seamless while maintaining all historical ownership structure and permissions.

### Requirements

* You are an authorized signer.

  Your wallet address must already exist in the account’s signer list.\
  If you are NOT a registered signer:

  * Import will fail
  * You will not gain access
  * You cannot view approvals or internal data

  This prevents unauthorized users from gaining visibility or control over secured shared accounts.
* You know the joint account details.

  To successfully import, you must know the correct:

  * Joint account identifier
  * Contract / account address
  * Any reference metadata requested by the system

  This ensures:

  * Accuracy
  * Security
  * Correct account retrieval

  Without correct information, the DApp cannot link you to the correct multisig wallet.

### Result

* Account becomes visible in dashboard.

  After successful import:

  * The account will be listed together with your other joint accounts
  * You can easily select it at any time
  * All interface features become available

  This integrates the account naturally into your daily workflow.

  * Pending tasks become accessible

    Immediately after import, you will be able to:

    * View and Participate in Governance
    * Monitor Operations
    * Maintain Security Awareness

This feature empowers signers to fulfill their roles efficiently and responsibly, ensuring that every multisig account remains securely and collaboratively managed.

### Flow

1️⃣ **Open Import Join Account and enter existing address to import.**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FEjJEHcMNDl1MqCQKxnsM%2Fimage.png?alt=media&amp;token=308e073f-d01a-4d64-a260-b245072e5b5d" alt=""><figcaption></figcaption></figure>

2️⃣**Fill up Joint Account Name**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FwFAzywZYwqOS0uyAB4cE%2Fimage.png?alt=media&amp;token=9be50feb-e13f-4434-a9ad-ee82e935c1de" alt=""><figcaption></figcaption></figure>

3️⃣**Enter new signer details.**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FDoUGA6SJzr2eujJrUOPd%2Fimage.png?alt=media&amp;token=76b6d5d7-7b29-4d69-88d3-8162be6e7af1" alt=""><figcaption></figcaption></figure>

4️⃣**Confirm and submit.**

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FV6ThmnKcmREZ3k4yJcmA%2Fimage.png?alt=media&amp;token=c854fd2b-370b-46e4-bf32-ad717bbc9a09" alt=""><figcaption></figcaption></figure>


# Convert Single Account to Joint Account

### **Purpose**

This feature allows users to upgrade an existing **single-owner Zetrix account** into a **secure multisignature (multisig) account**. Instead of being controlled by only one private key, the account is transformed into a jointly managed wallet where multiple authorized signers share responsibility and approval power.

By converting to multisig, the account adopts structured governance rules, weighted approvals, and a signature threshold mechanism. This significantly enhances security, reduces dependency on a single individual, and ensures accountability in financial and operational transactions.

### Why Use This?

#### **Secure previously single-owner wallets**

Single-controlled wallets pose several risks:

* If the private key is compromised, funds can be stolen
* If the owner loses access, control is permanently lost
* One mistake can cause irreversible loss

Converting to multisig spreads responsibility across multiple trusted parties, creating a strong security shield.

#### **Prevent unauthorized transfers**

With multisig:

* No single person can move funds alone
* Transactions require multiple approvals
* Malicious or accidental transfers can be blocked

This is critical for:

* Corporate treasuries
* Organization funds
* Shared investment accounts
* Government or institutional wallets

#### **Enable shared governance**

Multisig supports structured decision-making:

* Multiple stakeholders participate
* Approval policies can match organizational structures
* Weighted voting ensures fair control distribution

This aligns with:

* Business governance models
* DAO operations
* Joint ownership arrangements
* Compliance and audit requirements

### Flow

1️⃣ **Select “Convert Existing Account”**

Start the process by choosing the option to convert a currently single-controlled wallet into a joint account.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FMEgtNpW424oHIQV2HB5X%2Fimage.png?alt=media&amp;token=c3c1b315-25bb-43f4-8fec-7fe7016ca922" alt=""><figcaption></figcaption></figure>

2️⃣**Enter the New Joint Account Details**

You will be required to configure key governance parameters:

* **New Joint Account Name**\
  A meaningful label to identify the upgraded multisig account in the dashboard.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FRDEZkKlL25sgjmC83rI6%2Fimage.png?alt=media&amp;token=78fe0847-b592-404e-886e-e822ef237185" alt=""><figcaption></figcaption></figure>

* **Signers**\
  Add the list of authorized wallet addresses that will jointly control the account.
* **Weight Rules**\
  Assign approval weight to each signer.\
  Higher weight = greater approval influence.

You will also typically configure a **threshold**, meaning:

* How much total approval weight is required to approve transactions.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F6aKAEHUo6G3OtojsGdcj%2Fimage.png?alt=media&amp;token=e085b96c-236b-49d8-b4b1-fdc50ac11a8f" alt=""><figcaption></figcaption></figure>

3️⃣**Confirm and submit**

Review all configured details carefully:

* Signers list correctness
* Weight assignment accuracy
* Threshold logic validity

Once confirmed, submit the conversion request.

This triggers a blockchain transaction to:

* Replace single-owner design
* Activate multisig governance
* Apply new security structure

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F4FYjQJ5j7kMrS5wJq0su%2Fimage.png?alt=media&amp;token=994cf678-480a-4f00-897e-0d5ba04b69e4" alt=""><figcaption></figcaption></figure>


# Dashboard

#### **Purpose**

The Dashboard Home is the **main control center** of the Zetrix Multisig DApp. It provides a consolidated overview of every multisignature account associated with your wallet, allowing you to quickly understand your operational responsibilities and navigate between different joint accounts with ease.

It is designed to support:

* Daily operational monitoring
* Quick decision-making
* Efficient account switching
* Centralized visibility across multiple shared wallets


# Home

#### **Information Available**

From the Home dashboard, users can easily view:

* **List of Joint Accounts**\
  Displays every multisig account you are part of, whether you created it or were added as a signer.
* **Account Names**\
  Human-readable labels help users distinguish between personal, corporate, departmental, and project-based multisig accounts.
* **Status Indicators**\
  Visual indicators may display account condition, such as active state, pending approvals, or alerts requiring attention.
* **Quick Access Buttons**\
  Direct shortcuts that allow you to instantly:
  * Enter an account
  * View transactions
  * Manage governance
  * Access account-level operations

***

#### **Benefits**

The dashboard design ensures:

* **Clear Overview**\
  Everything you need to know about your multisig accounts is summarized in one place.
* **Fast Switching**\
  Move between accounts seamlessly when managing multiple projects or responsibilities.
* **Professional Management Experience**\
  Provides an enterprise-grade control surface suitable for organizational and institutional governance environments.


# Select Joint Account

#### **Purpose**

Selecting a joint account opens a **dedicated management workspace** focused specifically on that account. This transforms the interface into a targeted control panel where only relevant data, actions, and settings for the chosen multisig wallet are displayed.

This prevents confusion and ensures users always operate within the correct account context.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F6VRGKWIysjgAfqro6Kim%2Fimage.png?alt=media&amp;token=add4bf16-7cb0-4d5c-b27d-bb8a192f3e46" alt=""><figcaption></figcaption></figure>

***

#### **Data You See**

Once a joint account is selected, the system displays detailed operational and governance information, including:

* **Account Details**\
  High-level metadata such as account identity, description, and organizational context.
* **Balance**\
  Displays available Zetrix funds and relevant token balances (where applicable).
* **Signers + Weights**\
  Shows:
  * Who the authorized signers are
  * Their assigned approval weight
  * Their governance influence
* **Threshold**\
  Indicates the minimum approval weight required before a transaction can be executed.
* **Transaction Actions**\
  Provides access to functions like:
  * Send Zetrix
  * Invoke contract
  * Submit governance proposals
  * Approve/reject pending operations
* **Governance Tools**\
  Access account modification functions such as:
  * Adding/removing signers
  * Updating weights
  * Adjusting threshold
  * Upgrading contract logic

#### **Why It Matters**

This focused workspace serves as the **command center** for that specific wallet.\
It ensures clarity, eliminates operational risk, prevents accidental actions on the wrong account, and delivers a structured environment for secure and compliant multisig management.


# View Pending Proposals

#### **Purpose**

This section displays every transaction or governance action that has been proposed but has **not yet received enough approvals** to be executed. It functions as the actionable task list for signers, enabling timely decision-making.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FyUGcNkiaLWZTwJbrF9Er%2Fimage.png?alt=media&amp;token=ee6f0117-e064-4f0a-8527-fcee3e5595dc" alt=""><figcaption></figcaption></figure>

***

#### **Information Shown**

For each pending proposal, users can view:

* **Proposal Type**\
  (e.g., Send Funds, Invoke Contract, Upgrade Contract, Change Governance)
* **Creator**\
  Identifies who submitted the proposal.
* **Transaction Details**\
  Includes important execution parameters such as recipient, amount, and purpose.
* **Required Approvals**\
  Shows approval threshold requirements and remaining approval weight needed.
* **Approve / Reject Buttons**\
  Allows eligible signers to take action immediately.

***

#### **User Role Impact**

* **Signers**\
  Can:
  * Approve proposals
  * Reject proposals
  * Review decision impact
* **Non-Signers**\
  Can:
  * View proposals
  * Monitor progress
  * Maintain operational awareness

They cannot approve or reject proposals.

#### **Status Meaning**

* **Pending**\
  Proposal created and awaiting approvals.
* **Partially Approved**\
  Some approvals submitted, but threshold not yet reached.
* **Ready**\
  Required approval threshold achieved and transaction is ready for execution.
* **Expired (if applicable)**\
  Proposal is no longer valid due to time or policy rules.

This helps signers quickly assess urgency and importance.


# View Completed Proposals

#### **Purpose**

This section functions as the **historical audit ledger** for the multisig account. It provides traceability and accountability for every executed or rejected action.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F81myp7Tp5TESTIBfEkY3%2Fimage.png?alt=media&amp;token=dff57efa-b683-452b-93dc-d4264e70f80a" alt=""><figcaption></figcaption></figure>

***

#### **Shows**

* **Successfully Executed Transactions**\
  Confirmed and completed actions on-chain.
* **Failed Transactions**\
  Attempts that did not execute successfully.
* **Rejected Proposals**\
  Actions that were denied approval and were never executed.

***

#### **Value**

This section delivers:

* **Transparency**\
  Everyone can see what has been done and by whom.
* **Compliance**\
  Supports audit, governance verification, and accountability standards.
* **Accountability Evidence**\
  Provides a permanent reference to validate responsible decision-making and prevent disputes.


# Transaction Features

**Transaction Features** provide all the tools required to perform secure operations from the multisig account, including sending Zetrix tokens, interacting with smart contracts, upgrading contract logic, and managing ownership. Every transaction follows the multisignature approval process to ensure security, transparency, and collective decision-making.


# Send Zetrix

#### **Purpose**

Enables users to transfer Zetrix native tokens from the multisig account to another blockchain address while enforcing collective approval security.

***

#### **Fields Required**

* **Recipient Address**
* **Amount**

***

#### **Security Behavior**

Transactions do **not** execute instantly.\
Instead, they are submitted as **proposals**, ensuring that:

* No individual can unilaterally transfer funds
* Transactions are evaluated and approved collectively
* Governance rules are respected

***

#### **Lifecycle**

1️⃣ Proposal Created

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F0wXljhdC7wubXnhPgTJE%2Fimage.png?alt=media&amp;token=6646f33b-f422-4c8e-924f-0ed0a2a23e80" alt=""><figcaption></figcaption></figure>

\
2️⃣ Fill up details for sending token.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FTJEFQlLU64aUPsgB0cHR%2Fimage.png?alt=media&amp;token=26ea02c2-59e3-414b-a2dd-2dec36bc0959" alt=""><figcaption></figcaption></figure>

\
3️⃣ Approved and sign.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FSRwgTVXWnMWEhEd785hI%2Fimage.png?alt=media&amp;token=71e0a1fa-7d60-4c47-97bb-787ba6f0882f" alt=""><figcaption></figcaption></figure>

\
4️⃣ Funds is approved from initiator. To proceed the transaction next signer need to sign based on threshold.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2F1zYbwqA0bDJohTzuRvM4%2Fimage.png?alt=media&amp;token=a4111ccd-58c1-41be-a9cc-66645999d24a" alt=""><figcaption></figcaption></figure>

5️⃣Next signer will login and approved the transaction in pending transaction. Transaction will submitted after threshold is completed.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FSFDNhrIFtzutNlFgC0mU%2Fimage.png?alt=media&amp;token=e29b681b-5caf-48be-bbd1-383d4c535f82" alt=""><figcaption></figcaption></figure>

***

#### ❌ **Failure Conditions**

* Insufficient approvals collected
* Proposal rejected
* Proposal never executed

This prevents unauthorized or accidental fund movement.


# Invoke Contract – Send ZTP20 Tokens

#### **Purpose**

Allows the multisig account to **interact with blockchain smart contracts**, including sending ZTP20 tokens or performing contract operations.

***

#### **Use Cases**

* Token transfers
* Contract method execution
* Governance-related contract interactions

***

#### **Requires**

* Contract Address
* Required Interaction / Function Data
* Recipient Address (if token transfer)
* Token Amount

***

#### **Secure Flow**

This process follows the same multisig governance approval model as Zetrix transfers, ensuring contract actions cannot occur without proper authorization.

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FiFKKfVNhjy7dGWeWTT6h%2Fimage.png?alt=media&amp;token=3085f441-059a-420a-ac17-882aa5a1eba4" alt=""><figcaption></figcaption></figure>


# Invoke Contract - Contract Method

This section allows users to invoke a smart contract from the multisig account. It supports sending ZTP20 tokens or calling any supported contract method, while still following the multisignature approval and execution workflow.

***

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FZBsd4ugmA04bEVgFP3o0%2Fimage.png?alt=media&amp;token=f13e1b36-f9a7-4fcb-912a-22bf1bd807f8" alt=""><figcaption></figcaption></figure>

#### **1️⃣ Select Invoke Contract**

Choose the **Invoke Contract** option under Transaction Type.\
This tells the system that instead of sending native Zetrix, you are performing a smart contract interaction. This is commonly used for token transfers, contract execution functions, or system contract interactions that require multisig approval.

***

#### **2️⃣ Choose Contract Method Type**

Select the method type to specify how the contract will be invoked:

* **ZTP20 (Token Transfer)** – used when sending ZTP20 tokens
* **Others** – used for custom contract interactions beyond token transfers

This selection helps the system identify what kind of transaction structure is required.

***

#### **3️⃣ Enter Contract Method**

Provide the **method name** that will be executed in the contract.\
For example, `submitTransaction` or any valid function supported by the deployed contract.

This field defines exactly which function the contract should run once the transaction is executed after approval.

***

#### **4️⃣ Enter JSON Input**

Insert the required **JSON payload / parameters** for the contract call.\
This includes all necessary execution data such as:

* Contract parameters
* Transaction values
* Execution arguments

The JSON input ensures the blockchain understands precisely what action must be performed.

***

#### **5️⃣ Create Transaction**

Click **Create Transaction** to submit the proposal.

Important notes:

* The transaction is NOT executed immediately
* It is created as a **proposal**
* Other authorized signers must review and approve it
* Execution will occur only when the required approval threshold is met

This ensures strong security and collective decision control.

***

#### **6️⃣ Confirm Transaction Creation**

A confirmation dialog will appear to verify intent.

Select **Create Now** to finalize transaction creation.

Once confirmed:

* The proposal is recorded
* It appears in Pending Proposals
* Signers can approve or reject
* Execution happens only after reaching required approvals

This final confirmation step prevents accidental submissions and ensures user awareness.


# Upgrade Contract

The **Upgrade Contract** feature allows the multisig account to update or replace the existing smart contract with a newer or enhanced version. This is typically used for security improvements, feature upgrades, protocol enhancements, or bug fixes, and is fully protected by the multisignature approval process to ensure controlled governance.

***

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FSldOnFrUKrHHwAZ0Reos%2Fimage.png?alt=media&amp;token=fc418b5b-c808-419b-9c10-bd3ed5e0bf5e" alt=""><figcaption></figcaption></figure>

#### **1️⃣ Select Upgrade Contract**

Choose the **Upgrade Contract** option under Transaction Type.

This indicates that the action being initiated is not a normal fund transfer but a **smart contract upgrade operation**. By selecting this option, you are preparing to deploy new or updated contract code that will replace or enhance the existing contract logic.

This is commonly used for:

* Applying security patches
* Adding new functionalities
* Improving performance
* Fixing defects in the contract

***

#### **2️⃣ Enter Contract Address**

Provide the **contract address** of the smart contract that you intend to upgrade.

This identifies which specific deployed contract will receive the new version. The address must be accurate because the upgrade operation will directly affect whatever contract is referenced here.

This ensures:

* Correct target contract is upgraded
* No unintended contracts are affected
* Smooth upgrade execution process

***

#### **3️⃣ Insert Contract Code**

Paste or write the **new or updated contract code** into the Contract Code field.

This is the actual upgraded logic that will replace or enhance the existing smart contract. The code must be valid and properly formatted to execute successfully on the blockchain.

This step allows:

* Deployment of improved logic
* Introduction of new features
* Strengthened security mechanisms

Since this affects live contract behavior, it is important that only trusted administrators and organizations perform this action and that all signers carefully review the code before approving.

***

#### **4️⃣ Create Transaction**

Click **Create Transaction** to submit the upgrade request.

Important notes:

* The contract upgrade does NOT happen immediately
* A **proposal** is created for review
* Other signers must evaluate and approve
* Execution only occurs once the approval threshold is met

This ensures that such a critical action cannot be executed by a single person and maintains strong governance control.

***

#### **5️⃣ Confirm Transaction Creation**

A confirmation message will appear asking for final approval to create the upgrade transaction proposal.

Click **Create Now** to confirm.

Once confirmed:

* The proposal is officially created
* It appears under Pending Proposals
* Signers can approve or reject
* Upon reaching required approvals, the upgrade executes
* The new contract logic becomes active

This confirmation step ensures that users are fully aware of the impact and prevents accidental submission.


# Change Owner

The **Change Owner** feature allows the multisig account to transfer ownership of a smart contract to another authorized address. This is typically used during organizational restructuring, admin rotation, leadership changes, or when shifting operational responsibility to a new controlling entity. Like all critical operations, this function is fully secured by the multisignature approval mechanism to ensure trusted and collective decision-making.

***

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2Fb2u2mLyIHFNbcLmKwcME%2Fimage.png?alt=media&amp;token=43569a89-6374-4a7a-a2df-3936cc9aaff9" alt=""><figcaption></figcaption></figure>

#### **1️⃣ Select Change Owner**

Select the **Change Owner** option under Transaction Type.

By choosing this option, you are preparing a governance-level transaction that will reassign contract ownership. This is a highly sensitive action because the contract owner typically holds privileged permissions such as configuration control, upgrade authority, or administrative capabilities.

Common use scenarios include:

* Business or team restructuring
* Transferring ownership to another department or administrator
* Security rotation or access management changes

***

#### **2️⃣ Enter Contract Address**

Provide the **contract address** of the smart contract whose ownership you intend to transfer.

This ensures the system correctly identifies which contract will be affected. The address must be accurate, as the change will be applied directly to the referenced contract.

This step ensures:

* Correct ownership target
* Prevention of accidental reassignment
* Transparency and traceability

***

#### **3️⃣ Enter New Owner Address**

Input the **new owner’s wallet address** that will receive contract ownership rights.

This address will become the new contract administrator immediately after execution. It is recommended to verify the address carefully before submission to avoid misdirection of ownership.

This step:

* Assigns new administrative authority
* Ensures controlled ownership transition
* Supports governance alignment

***

#### **4️⃣ Add Remarks (Optional)**

You may include a short remark or description explaining the reason for the ownership change.

Remarks are useful for:

* Audit reference
* Governance documentation
* Organizational approval clarity

Examples:

* “Transfer to new admin team”
* “Ownership migration to security ops”

***

#### **5️⃣ Create Transaction**

Click **Create Transaction** to generate the ownership change proposal.

Important notes:

* The ownership transfer does NOT happen immediately
* A **proposal** is created first
* Other authorized signers must approve or reject
* Ownership is updated only after required approvals are collected

This ensures strong, policy-driven governance control.

***

#### **6️⃣ Confirm Transaction Creation**

A confirmation prompt will appear asking you to verify your intent.

Click **Create Now** to finalize.

Once confirmed:

* The proposal is officially recorded
* It appears in Pending Proposals
* Signers can review and approve
* After approvals meet the threshold → Ownership transfer executes
* The new owner becomes active

This final confirmation prevents accidental submissions and reinforces secure operational decisions.


# Account Update Management

Account Update Management allows authorized users to modify governance, identity, and participant structure of a multisignature (multisig) account. These updates help organizations adapt to operational changes, team restructuring, growth, or enhanced security needs. All updates are securely governed through the multisig approval process, ensuring that no single user can modify account governance unilaterally.

***

<figure><img src="https://1469461171-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXcoJUOiksWSVn1v6flsh%2Fuploads%2FA5qQk9mQYcb04MM2LTAG%2Fimage.png?alt=media&amp;token=00d7507a-a95f-4e8e-b887-acdea1b8419b" alt=""><figcaption></figcaption></figure>

### **Change Account Name**

#### **Purpose**

Allows updating the display name of the multisig account.

#### **Details**

* This change is **purely cosmetic**
* It does **not** affect security, signers, approvals, balances, or contract logic
* Helps clearly identify accounts in environments managing multiple wallets

#### **When Useful**

* Renaming for clarity or organization alignment
* Reflecting new project names or ownership changes
* Improving dashboard readability

#### **Result**

* New name appears immediately after execution
* Account identity becomes easier to recognize
* No impact on functionality or governance

***

### **Change Weightage**

#### **Purpose**

Modify the approval weight assigned to each signer within the multisig account.

#### **Details**

* This is a **critical governance function**
* Directly affects how approvals are counted
* Changes the level of authority of each signer
* Can rebalance organizational control

#### **When Useful**

* Governance restructuring
* Role promotion or responsibility changes
* Risk management adjustments
* Compliance and corporate policy evolution

#### **Security Impact**

* Requires multisig approvals
* Prevents unilateral power shifts
* Ensures controlled governance realignment

#### **Result**

* Updated weights apply immediately after execution
* New approval distribution governs future transactions

***

### **Add Signer**

#### **Purpose**

Add a new authorized participant to the multisig account.

#### **Details**

* Expands the group of individuals managing the account
* New signer may be assigned weight and incorporated into governance rules

#### **Common Use Cases**

* Team expansion
* New department or partner involvement
* Organizational scaling
* Compliance requirements demanding more oversight

#### **Security Behavior**

* Requires approvals before addition becomes valid
* Ensures existing signers consent to expansions

#### **Result**

* New signer becomes officially recognized
* Gains approval capabilities according to assigned weight

***

### **Remove Signer**

#### **Purpose**

Safely remove an existing signer from the multisig account.

#### **Details**

* Used when a signer should no longer participate in decision-making

#### **Common Scenarios**

* Signer leaves the organization
* Security risk or compromised wallet detected
* Role restructuring or reassignment

#### **Safety Enforcement**

* Requires multisig approvals before removal
* System prevents governance from being weakened to zero or invalid state
* Ensures secure and controlled member removal

#### **Result**

* Signer is removed from the authorization list
* No longer able to approve or execute transactions

***

### **Confirmation & Completion**

#### **Approval Process**

Every account update must pass through the multisig approval workflow.

#### **Execution Behavior**

Once the required approval threshold is met:

* Blockchain executes the final update
* Account configuration is securely updated
* System ensures immutability and transparency

#### **User Experience**

* Dashboard automatically refreshes
* Updated governance or account structure becomes visible
* Final confirmation is displayed to users


# Zetrix MCP Server

The **Zetrix MCP Server** enables developers to build, test, and interact with blockchain applications using natural language conversations with AI assistants such as Claude. Instead of manually navigating RPC endpoints, writing boilerplate scripts, or switching tools, developers can simply *ask* the AI to perform actions such as querying account balances, generating smart contracts, monitoring blockchain activity, or signing transactions.

This is made possible through the **Model Context Protocol (MCP)**, which acts as a bridge between AI tools and the Zetrix blockchain. With the Zetrix MCP Server, every aspect of Zetrix development becomes conversational, automated, and accessible.

This creates an **AI-assisted blockchain development environment**, enabling natural-language-driven workflows without manually referencing RPC documentation or switching between tools.


# Introduction

The Zetrix MCP Server is a comprehensive bridge between AI assistants (like Claude) and the Zetrix blockchain. It provides **44 specialized tools** that enable natural language interactions with blockchain operations, making blockchain technology accessible through conversational AI.

**Key Capabilities:**

* Query blockchain data (accounts, blocks, transactions)
* Execute real-time monitoring via WebSocket connections
* Generate and manage cryptographic keys
* Develop and deploy smart contracts
* Sign and submit transactions
* Interact with existing contracts


# What is MCP

## **Model Context Protocol(MCP)**

The **MCP** is an open communication standard created by Anthropic to allow AI assistants to interact with external systems. It defines how tools are registered, invoked, and how data flows between an AI model and an external server.

#### **Key Concepts of MCP**

| Concept             | Explanation                                                                                                                                |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **Tool**            | A callable function exposed to the AI. The AI can execute these tools on behalf of the user (e.g., query blockchain state, generate keys). |
| **Transport Layer** | Defines how messages are exchanged between the AI client and MCP server (WebSocket, stdio).                                                |
| **Schema**          | Tool definitions, input/output formats, and error structures are clearly defined using JSON schemas.                                       |
| **Streaming**       | MCP supports both static responses and streaming events (e.g., block updates).                                                             |

#### **Why MCP Matters for Zetrix**

* Allows **direct AI access** to blockchain functions
* Eliminates manual scripting for common tasks
* Enables **conversational development workflows**
* Standardizes tool interface for reliability and safety
* Allows Claude to provide explanations, context, and corrections

In short, MCP transforms Zetrix development into an intelligent, assisted process.


# Key Features

**🌐 Comprehensive Blockchain Access**

* 13 HTTP RPC Tools for standard blockchain queries
* 5 WebSocket Tools for real-time updates
* 6 Official SDK Tools with built-in signing capabilities
* 7 Cryptography Tools for key management and security

**📝 Smart Contract Development**

* 7 Development Tools with templates and documentation
* ES5 JavaScript contract support
* Built-in testing framework
* ZTP20, ZTP721, ZTP1155 token standards

**🔒 Security First**

* Ed25519 cryptographic signatures
* AES-256-CBC encryption for private keys
* Password-based key derivation (PBKDF2)
* Secure key storage and management

**⚡ Real-Time Capabilities**

* WebSocket connections for live updates
* Transaction status monitoring
* Address subscription for notifications
* Event streaming

**🎯 Developer Friendly**

* Natural language interface
* Extensive examples and documentation
* Interactive setup wizard
* Comprehensive error handling


# Complete Installation Guide

This section provides comprehensive installation instructions for all scenarios.


# System Requirements

**Minimum Requirements**

**Hardware:**

* CPU: 1 GHz or faster
* RAM: 512 MB available
* Disk: 100 MB free space
* Network: Broadband internet connection

**Software:**

* **Node.js:** v18.0.0 or higher
* **npm:** v8.0.0 or higher
* **Operating System:**
  * Windows 10 or higher
  * macOS 10.15 (Catalina) or higher
  * Ubuntu 20.04+, Debian 10+, or equivalent

**MCP Client Requirements**

**Claude Desktop (Recommended):**

* Version: Latest stable release
* Download: <https://claude.ai/download>
* Supported OS: Windows, macOS, Linux

**Claude Code (VS Code Extension):**

* VS Code: Version 1.80.0 or higher
* Extension: Claude Code from VS Code Marketplace

**Other MCP Clients:**

* Must support MCP protocol specification
* Requires stdio transport support

  It's a communication protocol that uses standard streams:

  * stdin (standard input) - receives data into the process
  * stdout (standard output) - sends data out of the process
  * stderr (standard error) - outputs error messages


# Installation Methods

**Method 1: NPM Global Installation (Recommended)**

**Best for:** Most users who want simple system-wide access.

**Installation:**

```bash
npm install -g zetrix-mcp-server
```

**What this does:**

* Downloads latest stable version from NPM
* Installs in global node\_modules directory
* Creates executable binaries accessible system-wide
* Includes all dependencies
* Size: \~15-20 MB
* Time: 30-60 seconds

**Verification:**

```bash
npx zetrix-mcp-server --version
```

**Configuration:**

For global installation, use `npx` in your Claude config:

```json
{
  "mcpServers": {
    "zetrix": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    }
  }
}
```

**Advantages:**

* ✅ Simple one-command installation
* ✅ Always uses latest published version
* ✅ Easy updates: `npm update -g zetrix-mcp-server`
* ✅ Works across multiple projects
* ✅ No local repository management

**Disadvantages:**

* ❌ Requires administrative permissions on some systems
* ❌ Cannot modify source code
* ❌ Updates require manual reinstallation

**Method 2: From Source (Development)**

**Best for:** Developers contributing to the project or needing custom modifications.

**Installation:**

```bash
# Clone repository
git clone https://github.com/Zetrix-Chain/zetrix-mcp-server.git
cd zetrix-mcp-server

# Install dependencies
npm install

# Build project
npm run build

# Run setup wizard
npm run setup
```

**What this does:**

* Downloads complete source code (\~5 MB)
* Installs development dependencies (\~30 MB)
* Compiles TypeScript to JavaScript
* Creates dist/ directory
* Sets up local development environment
* Build time: 10-20 seconds

**Configuration:**

For source installation, use absolute path in Claude config:

```json
{
  "mcpServers": {
    "zetrix": {
      "command": "node",
      "args": [
        "/absolute/path/to/zetrix-mcp-server/dist/index.js"
      ],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    }
  }
}
```

**Advantages:**

* ✅ Full access to source code
* ✅ Can create custom features and fixes
* ✅ Run tests and development builds
* ✅ Contribute changes back to project
* ✅ Use latest unreleased features from GitHub

**Disadvantages:**

* ❌ More complex setup process
* ❌ Requires Git knowledge
* ❌ Manual updates via `git pull`
* ❌ Larger disk space usage
* ❌ Need to rebuild after changes

**Method 3: NPX (No Installation)**

**Best for:** Quick testing, CI/CD pipelines, or minimal disk usage.

**Usage:**

```bash
npx -y zetrix-mcp-server
```

**What this does:**

* Downloads package to temporary NPM cache
* Executes directly without permanent installation
* Automatically uses latest version
* Cache location: `~/.npm/_npx/`

**Configuration:**

Same as Method 1 (NPM Global):

```json
{
  "mcpServers": {
    "zetrix": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    }
  }
}
```

**Advantages:**

* ✅ Zero installation required
* ✅ Always runs latest version
* ✅ Perfect for CI/CD automation
* ✅ No administrative permissions needed
* ✅ Minimal disk footprint

**Disadvantages:**

* ❌ Slightly slower startup (downloads on first run)
* ❌ Requires internet connection
* ❌ May download repeatedly
* ❌ Not suitable for offline usage
* ❌ Less control over versioning


# Claude Desktop Configuration

## **Interactive Setup Wizard (Recommended)**

**For local installations from source:**

```bash
npm run setup
```

**Wizard Steps:**

**1. Verify Installation**

* Checks Node.js version (requires v18+)
* Verifies npm installation
* Confirms project build succeeded
* Validates all dependencies installed

**2. Locate Claude Desktop Config**

* Auto-detects operating system
* Searches standard config locations
* Verifies config file exists and is readable
* Creates backup (.backup file)
* Validates JSON syntax

**3. Network Selection**

* Mainnet only
* Testnet only
* Both networks (runs two separate servers)

**4. Update Configuration**

* Generates appropriate JSON configuration
* Merges with existing MCP servers (preserves others)
* Validates final configuration syntax
* Writes updated config to Claude Desktop

**5. Optional Testing**

* Offers to run comprehensive test suite
* Tests HTTP RPC connectivity
* Validates SDK operations
* Checks cryptography functions
* Provides detailed test results

## **Manual Configuration**

**Step 1: Locate Config File**

<table><thead><tr><th width="180.3636474609375">Operating System</th><th>Config File Location</th></tr></thead><tbody><tr><td><strong>Windows</strong></td><td><code>%APPDATA%\Claude\claude_desktop_config.json</code></td></tr><tr><td><strong>macOS</strong></td><td><code>~/Library/Application Support/Claude/claude_desktop_config.json</code></td></tr><tr><td><strong>Linux</strong></td><td><code>~/.config/Claude/claude_desktop_config.json</code></td></tr></tbody></table>

**Step 2: Edit Configuration**

Open the file in a text editor and add the Zetrix MCP Server configuration.

**Mainnet Configuration:**

```json
{
  "mcpServers": {
    "zetrix": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    }
  }
}
```

**Testnet Configuration:**

```json
{
  "mcpServers": {
    "zetrix": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "testnet"
      }
    }
  }
}
```

**Both Networks (Dual Setup):**

```json
{
  "mcpServers": {
    "zetrix-mainnet": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    },
    "zetrix-testnet": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "testnet"
      }
    }
  }
}
```

**Local Development (From Source):**

```json
{
  "mcpServers": {
    "zetrix": {
      "command": "node",
      "args": [
        "/absolute/path/to/zetrix-mcp-server/dist/index.js"
      ],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    }
  }
}
```

**Step 3: Restart Claude Desktop**

Complete shutdown and restart for changes to take effect.


# Claude Code Configuration

Claude Code is a VS Code extension that integrates Claude directly into your development environment.

**Installation Steps**

**1. Install the Extension**

* Open VS Code
* Go to Extensions (`Ctrl+Shift+X` / `Cmd+Shift+X`)
* Search for "Claude Code"
* Click Install

**2. Configure MCP Server**

* Open VS Code Settings (`Ctrl+,` / `Cmd+,`)
* Search for "Claude MCP"
* Add Zetrix MCP Server configuration

**3. Configuration Format**

```json
{
  "claude.mcpServers": {
    "zetrix": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {
        "ZETRIX_NETWORK": "mainnet"
      }
    }
  }
}
```

**4. Reload VS Code**

* Press `Ctrl+Shift+P` / `Cmd+Shift+P`
* Type "Reload Window"
* Press Enter

**Advantages of Claude Code**

* **Integrated Development:** Write code and query blockchain in same window
* **Context Awareness:** Claude understands your project structure
* **Real-time Assistance:** Get blockchain data while coding
* **Debugging Support:** Test contracts and transactions inline
* **Version Control:** Easy Git integration for blockchain projects


# Network Configuration

**Environment Variables**

Configure network and endpoints via environment variables:

<table><thead><tr><th width="167">Variable</th><th>Description</th><th width="178.4544677734375">Default</th><th>Options</th></tr></thead><tbody><tr><td><code>ZETRIX_NETWORK</code></td><td>Network to connect to</td><td><code>mainnet</code></td><td><code>mainnet</code>, <code>testnet</code></td></tr><tr><td><code>ZETRIX_RPC_URL</code></td><td>Custom HTTP RPC endpoint</td><td>Auto</td><td>Any valid HTTPS URL</td></tr><tr><td><code>ZETRIX_WS_URL</code></td><td>Custom WebSocket endpoint</td><td>Auto</td><td>Any valid WS/WSS URL</td></tr></tbody></table>

**Example Configuration:**

```json
{
  "env": {
    "ZETRIX_NETWORK": "mainnet",
    "ZETRIX_RPC_URL": "https://node.zetrix.com",
    "ZETRIX_WS_URL": "wss://socket-node.zetrix.com",
  }
}
```

**Network Endpoints**

**Mainnet:**

* HTTP RPC: `https://node.zetrix.com`
* WebSocket: `wss://socket-node.zetrix.com`
* Chain ID: 0 (mainnet)
* Purpose: Production applications with real value

**Testnet:**

* HTTP RPC: `https://test-node.zetrix.com`
* WebSocket: `wss://test-socket-node.zetrix.com`
* Chain ID: 0 (testnet)
* Purpose: Development, testing, experimentation

**Switching Networks**

**Method 1: Update Configuration File**

Edit your Claude Desktop config:

```json
// Switch to Testnet
"env": {
  "ZETRIX_NETWORK": "testnet"
}

// Switch to Mainnet
"env": {
  "ZETRIX_NETWORK": "mainnet"
}
```

Then restart Claude Desktop.

**Method 2: Run Both Networks Simultaneously**

Configure two separate MCP servers:

```json
{
  "mcpServers": {
    "zetrix-mainnet": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {"ZETRIX_NETWORK": "mainnet"}
    },
    "zetrix-testnet": {
      "command": "npx",
      "args": ["-y", "zetrix-mcp-server"],
      "env": {"ZETRIX_NETWORK": "testnet"}
    }
  }
}
```

Now you can specify which network:

* "Check mainnet balance of..."
* "Get testnet latest block..."

**Method 3: Custom RPC Endpoints**

Use custom or private nodes:

```json
{
  "env": {
    "ZETRIX_NETWORK": "mainnet",
    "ZETRIX_RPC_URL": "https://your-private-node.com",
    "ZETRIX_WS_URL": "ws://your-private-websocket.com"
  }
}
```

**Use Cases for Custom Endpoints:**

* Private node infrastructure
* Load-balanced RPC endpoints
* Regional nodes for lower latency
* Testing with local nodes
* Custom network configurations

**When to Use Testnet vs Mainnet**

**Use Testnet for:**

* ✅ Development and testing
* ✅ Learning blockchain operations
* ✅ Experimenting with transactions
* ✅ Smart contract deployment testing
* ✅ No real value at risk
* ✅ Free test tokens available

**Use Mainnet for:**

* ✅ Production applications
* ✅ Real value transactions
* ✅ Live smart contract deployment
* ✅ Enterprise operations
* ⚠️ Verified and tested code only
* ⚠️ Irreversible transactions

***


# Quick Start

Get up and running with the Zetrix MCP server in Claude Desktop in just 5 minutes!


# Prerequisite

Before you begin, ensure you have:

✅ **Node.js v18 or higher** - [Download](https://nodejs.org/)

```bash
node --version  # Should show v18.0.0 or higher
```

✅ **npm v8 or higher** - (Comes with Node.js)

```bash
npm --version  # Should show v8.0.0 or higher
```

✅ **Claude Desktop** - [Download](https://claude.ai/download)

✅ **Git** - [Download](https://github.com/Zetrix-Chain/zetrix-mcp-server.git) (Optional) - Only needed for source installation




---

[Next Page](https://docs.zetrix.com/en/llms-full.txt/1)

