# STAS Documentation

STAS tokens utilize BSV smart-contracts to provide a secure and transparent way to generate digital assets that can represent various forms of value.

<figure><img src="https://807638184-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJsRw0G7i90QeoFv3yiXF%2Fuploads%2FYVa91ljvnP4UEiousPFw%2FRectangle%204179.png?alt=media&amp;token=9af4804a-f908-4f14-9d42-e9b6f42f112f" alt=""><figcaption></figcaption></figure>

STAS tokens are a unique type of digital asset that can be used for a variety of purposes within the STAS ecosystem. STAS stands for "Substantiated Tokens from Actualized Satoshis" and it is designed to provide a secure, decentralized platform for token issuance and management.

At its core, STAS is built on top of blockchain technology, which ensures that all transactions are secure and transparent. This means that every STAS token is recorded on a public ledger, which can be verified by anyone with access to the blockchain.

One of the primary use cases for STAS tokens is in the world of digital identity. By using STAS tokens, individuals and organizations can establish their identities on the blockchain, which can then be used to authenticate their actions and transactions. This is particularly useful in contexts where trust is critical, such as in financial transactions or in sensitive data sharing.

Another use case for STAS tokens is in the world of digital asset management. By tokenizing assets such as real estate, artwork, or other valuable items, owners can use STAS tokens to represent their ownership in a secure, transparent way. This can make it easier to buy, sell, or trade these assets, as ownership can be easily verified on the blockchain.

Overall, STAS tokens represent a powerful new tool for establishing trust and security in a variety of contexts. Whether you are looking to authenticate your digital identity or tokenize your assets, STAS tokens provide a secure, decentralized solution that can help you achieve your goals.


# Setup

Setup your STAS SDK

**For this setup example, we will use Node.js along with the Visual Studio Code IDE or your preferred IDE.**&#x20;

1. Create a new project directory: Open your terminal and navigate to the directory where you want to create your project. Create a new folder for your project.<br>

   <pre><code><strong>mkdir mintTest
   </strong></code></pre>
2. Initialize a new Node.js project: Navigate into the new directory you just created and run initiation.<br>

   ```
   cd mintTest
   npm init -y
   ```
3. Install required packages: In your project directory we will now install the `stas` and `bsv` libraries:<br>

   ```
   npm install bsv
   npm install stas-sdk
   ```
4. Create an entry point file: In your project directory, create a new file called `index.js`. This will serve as the entry point for your application, where you can import the libraries and write your code.<br>
5. Import required libraries: In your `index.js` file, import the required libraries using the `require` function. Here's an example:

   ```
   const stas = require('stas-sdk');
   const bsv = require('bsv');
   ```

{% hint style="info" %}
Alternatively, you can retrieve the open source code for the STAS SDK from GitHub <https://github.com/stas-token/stas-sdk>
{% endhint %}

{% hint style="success" %}
That concludes the setup! you are now ready to start writing code to mint your first STAS tokens!
{% endhint %}


# 2 Minute Mint

Mint a STAS token using the relysia SDK

{% embed url="<https://vimeo.com/822805296>" %}

Minting a STAS token can be a quick and simple routine on the <https://stastoken.com> platform or any of our partner wallets.


# The Ecosystem

Explore the STAS token variations

### STAS Templates <a href="#stas-templates" id="stas-templates"></a>

STAS tokens can be customized using a variety of templates, which allow users to input any relevant data that may be necessary for their specific use case. This customization feature enables users to tailor their STAS tokens to their precise requirements, making them versatile tools within the ecosystem. By allowing for precise tailoring of STAS tokens, users can ensure that the tokens meet their specific needs, whether that be for data management, atomic swaps, or other use cases within the ecosystem.

* **STAS-20** - A token template specifically designed for stable coins, this token possesses all the features of the original divisible token with some added unique features. Optionally an OP\_RETURN output can be added to the transaction, which can support up to 63337 bytes, is useful for transaction notes, etc. Additionally, redemption is only possible by the issuer.
* **STAS-789** - This innovative design offers a non-divisible version of the STAS token that enables the addition of more data after each transfer. This token prohibits the deletion of previously added data, allowing only for the appendage of new information. This feature is also optional on this STAS token and use cases that may suit this token include but are not limited to data logging and supply chain management.
* **STAS-50** - The original STAS template has been expanded to accommodate more outputs in a single transaction. With a larger script size, the new token provides the same capabilities as the original but can now handle up to 50 outputs per transaction.
* **STAS-0 (legacy)** - The original template of the library offers the option to make tokens either splittable or non-splittable during the contract and issuance stage. Non-splittable tokens are best suited for NFTs as they allow for custom data to represent unique digital assets. On the other hand, splittable tokens, commonly used for stablecoins, can be merged or split into multiple UTXOs. The redemption function for both types of tokens will return native BSV to the original contract address, as defined in the smart contract.

### STAS Wallets

* [relysia.com](https://relysia.com/) wallet
* [centi.ch](https://centi.ch/) app
* [dxs.app](https://dxs.app/) (Fidorin) wallet
* [my2cents.io](https://www.my2cents.io/) wallet (limited to NFTs)
* [musicart.io](https://musicart.io/) wallet
* [soundoshi.com](https://www.soundoshi.com/) wallet
*


# Presentations

Selected STAS technology based presentations

Centi presents 1M STAS stable coin micropayments within 24 hours at FinovateEurope

{% embed url="<https://www.youtube.com/watch?v=AE0-1YPK4Zo>" %}
Centi Presentation
{% endembed %}

A detailed analysis of STAS tokens and technology by Cain Nussdorfer.

{% embed url="<https://youtu.be/dO5T4_70Qho>" %}
What is STAS ? by Cain Nussdorfer
{% endembed %}


# STAS-20

The STAS-20 token protocol is a highly adaptable token template that supports the creation of diverse token types, such as stable coins, utility tokens, and security tokens.

{% embed url="<https://player.vimeo.com/video/813881305&portrait=0&byline=0>" %}

The STAS-20 token protocol is a game-changing solution designed for the creation of various token types, including stable coins, utility tokens, and security tokens. Its unique features and seamless integration with a multitude of blockchain platforms make it the go-to choice for businesses and individuals alike.

### Redemption Functionality

A distinctive feature of the STAS-20 token protocol is its redemption function. This enables the destruction of tokens and the release of the native satoshis locked within the token. The redemption function can only be executed by the redemption address, which is derived from the contract private key and acts as the token issuer.

### STAS-20 Use Cases

The STAS-20 token protocol's diverse range of features and adaptability make it suitable for various use cases, including:

* **Stable Coins**: Create tokens pegged to fiat currencies or other stable assets.
* **Utility Tokens**: Develop tokens that grant access to specific services or products.
* **Security Tokens**: Establish tokens representing ownership in an asset or investment opportunity.
* **Micropayments**: Leverage the low transaction fees associated with the BSV blockchain for small-value transactions.

The STAS-20 token protocol is an exceptional choice for those looking to create custom tokens on the blockchain. Its unique redemption function and notes output feature, combined with its adaptability, make it an invaluable tool for a wide array of applications. Embrace the power and potential of the STAS-20 token protocol for your next project.<br>


# STAS-50

The STAS-50 token is a digital token that allows users to create transactions with up to 50 outputs, which is significantly more than what is allowed by standard tokens. This feature makes it particularly useful in situations where large numbers of recipients are required per transaction.

One of the primary use cases for the STAS-50 token is in data management, where it can be used to send data to multiple recipients in a single transaction. This can be particularly useful for companies that need to share large amounts of data with a large number of stakeholders, such as suppliers, partners, and customers. By using the STAS-50 token, companies can reduce the number of transactions required to share data, which can help to save time and money.

Another key feature of the STAS-50 token is its versatility. It can be used for diverse distribution of royalties among multiple parties in a single atomic swap transaction. This makes it a valuable tool for businesses who need to quickly and easily exchange multiple assets with multiple parties, while maintaining transparency and security.

Overall, the STAS-50 token provides users with a wide range of benefits for data management and atomic swaps. With its ability to enable extra outputs in a transaction and its versatility, this token is well-suited for a variety of business use cases.


# STAS-789

The STAS-789 is a next generation blockchain utility token bringing real world use cases with its unique data handling features.

{% embed url="<https://player.vimeo.com/video/813964418&portrait=0&byline=0>" %}

STAS-789 is designed to revolutionize the way businesses manage their supply chains, logistics, and more. With the STAS-789 token, you can create a secure and trustworthy database on the blockchain, where all data is transparent and tamper-proof.

It is the perfect solution for businesses of all sizes and industries, as it provides a powerful tool for creating a verifiable record of transactions. With STAS-789, you can easily track your goods, vehicles, and medical records, ensuring that every transfer is accurately documented and can be traced back to its origin. This level of transparency and accountability is crucial in today's fast-paced business environment, where trust is a key factor in maintaining successful partnerships.

One of the key features of this token is its ability to create a variety of different token types that can be utilized for a wide range of applications. This flexibility allows businesses to customize the token protocol to fit their specific needs. By leveraging the power of STAS-789, businesses can create a blockchain database that is uniquely tailored to their industry and use case.

The STAS-789 token protocol is inherently unique and cannot be replicated, providing businesses with a secure and reliable solution for managing their data. During the issuance process, a collection of interrelated tokens is created, which can be utilized individually for transfers while providing a comprehensive record of all processes that have taken place on each token within the set. This approach provides a robust and secure system that allows for the traceability of transactions carried out using each token within the set, ensuring that each token retains its individual identity and history.


# Token Properties

Details on different token templates

A comprehensive table has been prepared to display all the characteristics and attributes of each token template script. This tool will be incredibly helpful in determining the most suitable token template to use for your particular needs. By referring to the table, you will be able to compare and contrast the various token templates, and ultimately make an informed decision on which one to select. This will ensure that you choose the token template that is best suited for your project and will help you achieve your desired outcome.

* **Splittable** - determines if a token can be split or merged with other UTXOs. If it's splittable, it can be merged with other STAS token UTXOs that have matching script values, regardless of whether their owner addresses match.
* **MaxInputsPerTx** - the maximum number of utxo input elements allowed per transaction, excluding the fee UTXO. This applies to transaction types such as merge, mergeSplit, or atomic swap functions where more than one STAS input is required.
* **MaxOutputsPerTx** - the maximum number of outputs allowed per transaction, excluding the fee UTXO. This applies to transaction types such as split, mergeSplit, redeemSplit, or acceptSwap functions.
* **DataOutput** - determines if the STAS template supports an additional OP\_RETURN output in the transaction.
* **Flags** - determines if the STAS template supports both splittable and non-splittable types. When flags are permitted during issuance, the STAS token will be issued as either splittable or not.
* **DataAppend** - an additional data array that can be added to an existing STAS token script during a transfer transaction.
* **RedeemAny** - determines if the STAS token can be redeemed by any token owner address.
* **SendToIssuerAddress** - for some STAS token templates, sending the token to the issuer address is not allowed. This applies only to output index #0 in the transaction and is part of the redemption functionality when RedemptionAny is true, reserving that address only for redemption purposes.
* **RoyaltyPayment** - a conditional output in the transaction that pays a certain address upon any transaction.

<table><thead><tr><th width="201.33333333333331">Props</th><th width="135">STAS-20</th><th width="130">STAS-789</th><th width="137">STAS-50</th><th>STAS (legacy)</th></tr></thead><tbody><tr><td>Splittable</td><td>true</td><td>false</td><td>true|false</td><td>true|false</td></tr><tr><td>MaxInputsPerTx</td><td>2</td><td>2</td><td>2</td><td>2</td></tr><tr><td>MaxOutputsPerTx</td><td>4</td><td>4</td><td>50</td><td>4</td></tr><tr><td>DataOutputs</td><td>true</td><td>false</td><td>false</td><td>false</td></tr><tr><td>Flags</td><td>false</td><td>false</td><td>true</td><td>true</td></tr><tr><td>DataAppend</td><td>false</td><td>true</td><td>false</td><td>false</td></tr><tr><td>RedeemAny</td><td>false</td><td>true</td><td>true</td><td>true</td></tr><tr><td>SendToIssuerAddr</td><td>true</td><td>false</td><td>false</td><td>false</td></tr><tr><td>RoyaltyPayment</td><td>false</td><td>false</td><td>false</td><td>false</td></tr></tbody></table>

{% hint style="info" %}
For minting Tokens the STAS-20 template is a recommended choice.\
For minting NFTs with added utility it is recommended to use the STAS-789 that allows for additional data added after each transfer transaction.
{% endhint %}


# Instant Mint

Lets mint!

Here is a straightforward example that illustrates how you can mint your very first token. To begin, you will need to add your private key to the testUtility.js file. To obtain a new random private key simply run this command in the terminal while in the /tests directory

```javascript
node getPrivateKey.js
```

{% hint style="info" %}
The  corresponding address will appear in the terminal console.
{% endhint %}

```javascript
Address to send funds to:  "some address "
Funding Private Key: "some private key"
```

In order to utilize this address for minting purposes, you will need to first send funds to it. Please note that a minimum of 5000 satoshis will be required in order to run the test, although only a fraction of this amount will actually be used in the mint example. Please be sure to keep a copy of this private key if you still have funds that you would like to recover in the future. At any time you would like to withdraw the funds from the test address please refer to the /tests/getFundsFromAddress.js file and follow the instructions.

To proceed, take the private key string and replace the two values in the testUtility.js file. In this example, you can use the same private key for both variables on lines 11 and 16

```javascript
this.privateKey = bsv.PrivateKey.fromString('Enter Funding Private Key Here');
this.issuerPrivateKey = bsv.PrivateKey.fromString('Enter Funding Private Key Here');
```

{% hint style="warning" %}
Make sure to retain a copy of this private key if you have any remaining funds that you may wish to retrieve later. If you want to withdraw the funds from the test address at any point in time, consult the /tests/getFundsFromAddress.js file and adhere to the guidelines provided.
{% endhint %}

&#x20;We're now set to conduct the test! Just go to the /test directory and execute this command in the terminal.

```javascript
node instantMint.js
```

{% hint style="success" %}
The process will start and the token will be minted onchain with all Txids provided.
{% endhint %}

```javascript
Starting Instant Mint Example...
Fetching UTXO from the blockchain...
Building transactions...
Prepare Utxos Txid:  31fa389bec5677c048e6a5539467dda02da576427f8bbccb22fcb2250cd601ec
Contract Txid:  81bbdce661ea6b0133e8073a48b8334658bf6151d08cb8061d4a106175a095fb
Issue Txid:  7b678504f67fc87e93ddd6816800d73915cd43a09ad2a53d177cc539b3f8c233
Redeem Txid:  c7951ceb0bb8fd712e2e993a022d7d37c23a65a779477e5e80694640e6d9cb45
Instant Mint Example Completed
```

{% hint style="info" %}
As this is for testing purposes, we will also redeem the token back to native satoshis as part of this test.
{% endhint %}


# Mint in Detail

Developers guide to minting

To mint tokens, two transaction building functions - Contract and Issuance - are needed. The Contract transaction generates a JSON output that defines the token properties and metadata, and includes all the satoshis necessary for the token issuance transaction. The Issuance transaction spends the Contract UTXO as input and adds token scripts as outputs, effectively linking the contract metadata to the issuance transaction, resulting in the creation of the tokens.

### Contract <a href="#contract" id="contract"></a>

To generate a Contract transaction, a JSON object containing token information is necessary. You can find a template of this JSON object in tokenSchemaTemplate.js. <br>

| Parameter    | Description                                                                                      | Property                                            |
| ------------ | ------------------------------------------------------------------------------------------------ | --------------------------------------------------- |
| name         | The token name                                                                                   | string                                              |
| protocolId   | The token template protocol identifier                                                           | string format of available token protocol templates |
| symbol       | The token symbol                                                                                 | alphanumeric characters 1-64 length                 |
| description  | The token description                                                                            | up to 512 characters                                |
| image        | The image URL                                                                                    | 250x250 pixels (recomended)                         |
| tokenSupply  | The amount of tokens to mint in the issuance                                                     | Any integer                                         |
| decimals     | Decimals indicate the formatting, e.g. decimals 2 for a dollar token with cents.  Reference only | Integer not bigger than 8                           |
| satsPerToken | Satoshis to be used for each token. (value of 1 recommended)                                     | Integer                                             |
| legal        | STAS legal terms                                                                                 | RFC 3986 JSON formatted                             |
| issuer       | Issuer information                                                                               | RFC 3986 JSON formatted                             |
| meta         | Any extra data to indicate legals and terms.                                                     | RFC 3986 JSON formatted                             |

<br>

{% hint style="info" %}
The "protocolId" field should match the token template wanting to use in the issuance. This is to allow correct referencing from the contract JSON to the token script itself. See [Issuance ](#issuance)section on "protocol" for more information on how to choose the different token templates.
{% endhint %}

```javascript
const tokenSchemaTemplate = {
    name: "Test Token",
    protocolId: "STAS-20", // SHOULD MATCH THE ISSUANCE PROTOCOL VALUE 
    symbol: "TESTTOKEN001", // REQUIRED
    description: "This is a test token",
    image: "Some Image URL",
    totalSupply: 10, // REQUIRED
    decimals: 0,
    satsPerToken: 1, // REQUIRED
    properties: {
      legal: {
        terms: "STAS, Inc. retains all rights to the token script. Use is subject to terms at https://stastoken.com/license.",
        licenceId: "stastoken.com"
      },
      issuer: {
        organisation: "string",
        legalForm: "string",
        governingLaw: "string",
        issuerCountry: "string",
        jurisdiction: "string",
        email: "string"
      },
      meta: {
        schemaId: "STAS1.0",
        website: "string",
        legal: {
          terms: "string"
        },
        media: [
          {
            URI: "string",
            type: "string",
            altURI: "string"
          }
        ]
      }
    },
  }
```

The contractUtxo holds the satoshis that will fund the token supply. The satoshi amount in the contractUtxo must meet a minimum requirement for the token(s) being minted, and any extra satoshis will be returned to the issuer address in the form of a change output. The paymentUtxo is used to cover the transaction fees for the transaction. You can pass in the tokenSchema as a JSON object, which will be added to the transaction output. The tokenSatoshis refers to the total amount of satoshis utilized in the tokenSupply that is multiplied against the satsPerToken

```javascript
const contractHex =  await stasContract.signed(
    issuerPrivateKey,
    contractUtxo,
    paymentUtxo,
    paymentPrivateKey,
    tokenSchema,
    tokenSatoshis
)
```

{% hint style="info" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}

You need to use the contract output #0 UTXO in the issuance function. The utility.js file includes a helper function that retrieves a UTXO object from a transaction hex. This function takes the transaction hex and output index value as arguments.

```javascript
const {utility} = require(stas)

const contractUtxo = utility.getUtxoFromTx(contractHex, 0)
```

{% hint style="success" %}
The contract function is completed and now can move onto issuing the tokens!
{% endhint %}

### Issuance <a href="#issuance" id="issuance"></a>

The issuance function is responsible for generating the transaction that issues the tokens. You can set any amount of satoshis per token during issuance. However, the library will verify that the total token supply and the satoshis per token correspond to the value in the contract UTXO.

Tokens can be issued as single or multiple outputs, in the case of splittable tokens. However, for non-splittable tokens, each token will be issued as a separate output since they cannot be divided or combined with other scripts of the same data value.

Here is an example of the issue data array.

```javascript
const issueInfo = [{
		addr: "Some address string",
		satoshis: 100,
		data: ['STAS CUSTOM DATA', 'STAS CUSTOM DATA 2', 'STAS CUSTOM DATA 3']
}]
```

In this example, we are issuing 100 tokens to a single address and incorporating three custom data elements into the token script. The data field can accept an array consisting of string values. Each element of the array will be transformed into a hexadecimal data chunk and appended to the token script in ASM format. This method facilitates the separation of each data element with a space while in ASM format.

We can also distribute tokens to multiple addresses, as illustrated in the following example:

```javascript
const issueInfo = [{
       addr: "Some address string ONE ",
       satoshis: 50,
       data: ['STAS CUSTOM DATA', 'STAS CUSTOM DATA 2', 'STAS CUSTOM DATA 3']
    },
    {
	addr: "Some address string TWO",
	satoshis: 50,
	data: ['STAS CUSTOM DATA', 'STAS CUSTOM DATA 2', 'STAS CUSTOM DATA 3']
}]
```

{% hint style="warning" %}
IMPORTANT : It's crucial to note that when issuing splittable tokens and intending to merge them later using the merge and mergeSplit functions, the custom data must be identical across all token outputs in the issueInfo array. The UTXO scripts of tokens can only be merged if their data matches precisely. If the tokens will not be combined in the future, you may issue them with varying custom data. To restrict the merging capability of tokens for future use cases, consider issuing non-splittable token types since these cannot be merged on a script level. To learn more about splittable and non-splittable tokens, as well as additional information about available token templates, please refer to the Token Properties in Detail section.
{% endhint %}

{% hint style="info" %}
When using non-splittable tokens, it is essential to ensure that the token supply and the satoshis per token match the number of outputs in the issuance transaction. The amounts need to evenly divisible from the contract Utxo satoshi amount.
{% endhint %}

```javascript
const issueInfo = [
    {
		addr: "Some address string ONE ",
		satoshis: 1,
		data: ['STAS CUSTOM DATA FOR NFT1', 'STAS CUSTOM DATA 2 FOR NFT1', 'STAS CUSTOM DATA 3 FOR NFT1']
	},
    {
		addr: "Some address string TWO",
		satoshis: 1,
		data: ['STAS CUSTOM DATA FOR NFT2', 'STAS CUSTOM DATA 2 FOR NFT2', 'STAS CUSTOM DATA 3 FOR NFT2']
	},
    {
		addr: "Some address string THREE",
		satoshis: 1,
		data: ['STAS CUSTOM DATA FOR NFT3', 'STAS CUSTOM DATA 2 FOR NFT3', 'STAS CUSTOM DATA 3 FOR NFT3']
	},
    {
        ...
    },
    ...
]

```

{% hint style="info" %}
In this example we are creating multiple tokens with unique custom data added for each output.
{% endhint %}

The issuerPrivateKey will sign for the contractUtxo, and a paymentUtxo is added to pay the transaction fees along with the corresponding private key. The final function arguments are as follows:

**isSplittable** : is a boolean value that is only necessary for token templates that have flags indicating whether the token can be splittable or non-splittable. This is applicable to protocol types such as "STAS" or "STAS-50". However, for token templates that do not have such flags, this argument is not relevant and can be ignored by passing "undefined" in its place.

**symbol** : is a string value representing the token symbol. For it to be considered valid, it must match the tokenId field specified in the contract JSON.

**protocol** : represents the token template used to issue the token and must be a string value, such as "STAS-20" or "STAS-789". It should match the token schema field value for "protocolId" to maintain correct referencing back to the contract JSON.

```javascript
const issuanceHex = await stasIssuace.signed(
    issuerPrivateKey, 
    issueData, 
    contractUtxo, 
    paymentUtxo, 
    paymentPrivateKey, 
    isSplittable, 
    symbol, // SHOULD MATCH THE CONTRACT JSON SYMBOL VALUE
    protocol
)
```

{% hint style="success" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}


# Transfer

Create a transfer transaction

The transfer function is used to generate a transaction hexadecimal that will allow you to send STAS tokens to another designated address. Once you have successfully completed the installation process, you will be able to access the SDK functions.

To utilize the transfer function, it is necessary to first prepare some UTXOs. Specifically, you will need a stasUtxo, which will be the STAS token utilized in the transfer, as well as a paymentUtxo, which will provide funding for the transaction fees.

Both UTXOs will require private keys to be supplied, although it is possible to use the same private keys for both, if applicable. Finally, you will need to input the destination address string to complete the process.

```javascript
const transferHex = await stasTransfer.signed(
    ownerPrivatekey, 
    stasUtxo, 
    destinationAddress, 
    paymentUtxo, 
    paymentPrivateKey
)
```

{% hint style="success" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}


# Split

Create a split transaction

Similar to the transfer function, this particular function generates a hexadecimal representation of a transaction that can distribute tokens to multiple addresses at once. It should be noted that this function is only applicable to tokens that have the splittable property set to true. For more details on which token templates possess this attribute, please refer to the STAS features table.

To create a split transaction, we need a STAS UTXO, a fee UTXO, and the private keys linked with these UTXOs. Instead of the destination address required in the transfer function, we need an array that contains all the destination addresses and their corresponding amounts.

The splitDestinations array is made up of objects that contain two fields. Please keep in mind that the sum of the outputs' amounts must match the amount in the STAS UTXO input to ensure a valid transaction is created.

```javascript
const splitDestinations = [
    {
        satoshis : 10,
        address : "someAddressString"
    },
    {
        satoshis : 10,
        address : "someOtherAddressString"
    }
]
```

{% hint style="info" %}
If the token owner needs to receive change from the STAS UTXO input, it must be included in the splitDestination array. The total amount in the outputs of the array should match the input satoshis amount.
{% endhint %}

```javascript
const splitHex = await stasSplit.signed(
    ownerPrivatekey, 
    stasUtxo, 
    splitDestinations, 
    paymentUtxo, 
    paymentPrivateKey
)
```

{% hint style="success" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}


# Merge

Create a merge transaction

With the merge function, it is possible to combine two STAS UTXO inputs into one output. However, please keep in mind that this function can only be used by tokens that have the splittable property set to true. For more information on which token templates have this property, please see [Token Properties](/library/token-properties).

{% hint style="warning" %}
Merging can only occur for STAS UTXOs that contain identical script values with exception of the owner address in the script.
{% endhint %}

The merge function has different parameters compared to the split or transfer functions. It necessitates the previous transaction hex value of the UTXOs being merged, and the required format is as follows:

```javascript
const stasInput1 = {
    txHex : 'previous transaction hex string',
    vout : 'output index of the UTXO being spent'
}

const stasInput2 = {
    txHex : 'previous transaction hex string',
    vout : 'output index of the UTXO being spent'
}
```

The previous transaction hex is required as part of the unlocking script to complete the merge functionality. To create a merge transaction, the following additional parameters are necessary: private keys for both UTXO inputs, a destination address, and the payment UTXO and its corresponding private key.

```javascript
const mergeHex = await stasMerge.signed(
    ownerPrivateKey1,
    stasInput1,
    ownerPrivateKey2,
    stasInput2,
    destinationAddr,
    paymentPrivateKey,
    paymentUtxo
)

```

{% hint style="success" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}

{% hint style="warning" %}
NOTE: It is important to keep in mind that the size of the merge transaction will increase after each subsequent merge transaction due to its design nature. To optimize the transaction size, it is recommended to consider ways to mitigate the compounding effects of the merge transactions. One possible solution is to use interval transfer functions for each UTXO being merged, which resets the previous transaction hexadecimal to the size of a transfer transaction. It is recommended to transfer the UTXO after every two merge transactions as a means of resetting the transaction size before continuing with additional merge transactions.
{% endhint %}

{% hint style="info" %}
The MergeSplit function works in a similar way to merge, with the exception that instead of a single destination address, it accepts an array of splitDestinations, just like in the split function.
{% endhint %}


# Redeem

Create a redemption transaction

Token redemption refers to the process of converting the STAS token satoshis back into native BSV satoshis, which essentially destroys the STAS token. To perform this operation, a single STAS UTXO input is required, and the resulting output is in the form of a regular pay-to-public-key-hash output. By default, the unlocked satoshis are always sent to the issuer address of the token, which is known as the redemption address and can be found in the token script as the first element after the OP\_RETURN.\
\
This function will take the typical arguments as follows:

```javascript
const redeemHex = await stasRedeem.signed(
    ownerPrivateKey,
    stasUtxo,
    paymentUtxo,
    paymentPrivateKey
)
```

{% hint style="success" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}

{% hint style="info" %}
The RedeemSplit function is designed to operate similarly to the redeem function, with an added parameter called "splitDestinations". This parameter specifies where the additional outputs of the transaction will be directed, much like the split function. It's worth noting that the total amount designated for split destinations will determine the number of satoshis redeemed from the STAS UTXO input. For example, if the STAS UTXO input contains 10 satoshis and the total output amount in the split destination array is 8, only 2 satoshis will be redeemed. The remaining satoshis will remain locked in STAS tokens and be sent to the new destination address(es).
{% endhint %}


# Atomic Swaps

How to create atomic swap transactions

The process of atomic swaps entails the utilization of partially signed components from both parties, and completion occurs only after both parties have signed all the necessary pieces. With this SDK, there are two methods available to accomplish an atomic swap transaction: a two-step and a three-step approach.

To begin with, let's examine the two-step method provided by the SDK, which involves utilizing two functions, namely "stasCreateSwap" and "stasAcceptSwap."

### Two step swap <a href="#two-step-swap" id="two-step-swap"></a>

The stasCreateSwap function requires the user to input a UTXO that they are willing to swap for something else, which can either be a STAS token or native BSV. The user must also specify the output they desire to receive as a result of the atomic swap transaction, which can also be either a STAS token or native BSV output.

To define the output, the SDK utilizes an object known as wantedData, which comprises the following fields:

```javascript
const wantedData = {
    satoshis :  number
    script :  scriptHex // optional if STAS script
}
```

{% hint style="info" %}
In the event that only the value of the satoshis field is provided, stasCreateSwap will create a native BSV output to the address from input #0. However, if the user desires a specific STAS token for the atomic swap, the script field must be supplied with the hexadecimal representation of the token script.
{% endhint %}

```javascript
const offerHex = await stasCreateSwap.signed(
    ownerPrivateKey, 
    utxo, 
    wantedData
)
```

The subsequent step involves finalizing the atomic swap transaction by adding the remaining inputs and information required to generate the unlocking scripts. In the stasAcceptSwap function, the following core arguments are required, and we will examine each one in this example:

* offerTxHex: This represents the hexadecimal form of the transaction from the stasCreateSwap function.
* ownerPrivateKey: This refers to the private key of the UTXO's owner who is participating in the atomic swap transaction.
* makerInputTxHex: This denotes the complete transaction hexadecimal of the input #0 in the offerTxHex.&#x20;
* takerInputTxHex: This represents the complete transaction hexadecimal of the UTXO that is being utilized to complete the atomic swap transaction.
* &#x20;takerVout: This refers to the output index of the UTXO being used to complete the atomic swap transaction.
* paymentPrivateKey: This denotes the private key of the UTXO's owner who is paying the transaction fee.
* paymentUtxo: This represents the UTXO that is being used to pay the transaction fee.

```javascript
const swapHex = stasAcceptSwap.signed(
    offerTxHex, 
    ownerPrivateKey, 
    makerInputTxHex, 
    takerInputTxHex, 
    takerVout, 
    paymentPrivateKey, 
    paymentUtxo,
    additionalOutputs // optional
)
```

more on additionalOutputs soon... After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner. The final outcome of the transaction will be that input #0 will transfer ownership to output #1, while input #1 will transfer ownership to output #0, in accordance with the terms of the atomic swap transaction.

### Three step swap <a href="#three-step-swap" id="three-step-swap"></a>

To make this a three step swap we can simply create the offer hex with the unsigned function call as follows:

```javascript
const unsignedOfferHex = await stasCreateSwap.unSigned(
    ownerPublicKey, 
    utxo, 
    wantedData
)
```

When the unsigned function call is made, the returned object will contain the transaction in the "tx" field, which can be converted to a string to obtain the hexadecimal format. In this scenario, input #0 will not be signed. After the stasAcceptOffer function has returned the "swapHex" value, it can then be used to sign the transaction and send it back to the offer hex creator.

{% hint style="info" %}
An additional argument must be included, which is the complete transaction hexadecimal representation of the taker, which corresponds to input #1 in the unsigned swap hexadecimal.
{% endhint %}

```javascript
const signedSwapHex = await stasSignSwap.signed(
    unSignedSwapHex, 
    ownerPrivateKey, 
    takerInputTx
)
```

{% hint style="success" %}
After executing the function, you will receive a transaction hexadecimal representation that is now ready to be broadcasted to the miner.
{% endhint %}

### Additional outputs for atomic swaps <a href="#additional-outputs-for-atomic-swaps" id="additional-outputs-for-atomic-swaps"></a>

During the second step of the atomic swap transaction, it is possible to include additional outputs. This can be accomplished by adding an array as an additional function argument to specify the amounts and addresses to which the extra funds will be sent. It is important to note that for additional outputs, the funds must originate from input #1 UTXO in the atomic swap. Consider the following example:

Output #0 requests 1000 Native satoshis

```javascript
const wantedData = {
    satoshis: 1000
}
```

Additional outputs are added as follows:

```javascript
const additionalOutputs = [ 
    {
        address : "some address string",
        satoshis : 1000
    },
    {
        address : "some address string",
        satoshis : 1000
    }
]
```

{% hint style="info" %}
In this case the input #1 needs to contain exactly 3000 in native satoshis to complete this transaction. This can also be done using STAS tokens where the property of the token is splittable and the total input #1 amount in satoshis is equal to the output #0 amount plus any additional output amounts if applicable.
{% endhint %}


# Advanced Features

Get more out of the library

In this section we will go over some of the advanced transaction building features that are available in the library.


# Data Transactions

Adding Data to your transaction

Certain token templates allow for data to be incorporated into transactions in varying ways. In order to maintain a universal format, the data format will always employ an array format. Each element within the array will be regarded as a single script chunk, and all data will be provided as plain text strings. Let us explore some examples of how we can leverage this feature in some of the token templates.

### STAS-20 data output

The STAS-20 token template permits an optional extra output in each transaction, which is always positioned as the last output even after the payment change output. All transactional functions in the STAS library contain the "data" argument. To incorporate this additional output, we can easily provide this value as an argument in the function, as shown below:

```javascript
const data = [
    "Some plain text string",
    "Some other plain text string"
]

const transferHex = await stasTransfer.signed(
    ownerPrivatekey, 
    stasUtxo, 
    destinationAddress, 
    paymentUtxo, 
    paymentPrivateKey,
    data
)
```

{% hint style="info" %}
the data array can contain&#x20;
{% endhint %}

In this instance, the stasTransfer function is being utilized. An additional parameter can be included in the function if an extra output is needed in the transaction. If no data output is necessary, this parameter can be disregarded. The array can contain numerous elements, but it's important to note that the data's maximum size must not surpass 63337 bytes.<br>

### STAS-789 data append

The STAS-789 template possesses a distinctive capability to append additional data to the token script when executing a transfer transaction. The data that previously resided in the script cannot be altered and is immutable. This is an optional feature and not necessary for token transfers. To include additional data, the stasTransfer function must be supplied with the data in array format.

```javascript
const data = [
    "Some plain text string",
    "Some other plain text string"
]

const transferHex = await stasTransfer.signed(
    ownerPrivatekey, 
    stasUtxo, 
    destinationAddress, 
    paymentUtxo, 
    paymentPrivateKey,
    data
)
```

Subsequently, the transaction output will contain the supplementary data in the script. Each element in the data array will be converted into data script chunks in ASM format. By including the data in chunks, we can introduce new OP CODES or other data that may be supported in applications that adhere to the data format.


# Fee Estimates

Get a fee cost of your transaction

As the name suggests, fee estimation functions offer a means of computing the expense of a STAS transaction before officially constructing it. This is accomplished using the minimum necessary arguments, which creates a transaction template that can then be used to determine the cost in satoshis based on the fee rate. The fee rate settings can be located in the utility.js file as follows:

```javascript
this.SATS = 50 // Don't change this setting unless you know what you're doing
this.PERBYTE = 1000 // Don't change this setting unless you know what you're doing
```

Here is an example of using the fee estimate functions for the stasTransfer Function :&#x20;

```javascript
const feeEstimate = await stasTransfer.feeEstimate(stasUtxo)
```

The function will return a number in satoshi value that can then be used for pre processing conditions where UTXOs for fees are required to be prepared beforehand. All transaction functions in the library contain a feeEstimate function with varying required arguments.


# Zero Change

No change output transactions

Zero change transaction building is an excellent resource for developers who wish to construct STAS transactions without any change outputs. An instance of this model is when the payment UTXOs for the transactions are prearranged. By incorporating this model in conjunction with fee estimation functions, developers can minimize chained UTXO transactions by determining the exact fee amount requirement ahead of time, allowing them to create the appropriate size UTXO for the fee payment without the need to handle UTXOs afterwards as part of further fee UTXOs. This is especially handy for instances where multiple fee UTXOs are required for multiple transactions at once.

{% hint style="info" %}
To use the zero change model in the functions it requires an arguement boolean set to true. Here is an example in the stasTransfer function:
{% endhint %}

```javascript
const transferHex = await stasTransfer.signed(
    ownerPrivatekey, 
    stasUtxo, 
    destinationAddress, 
    paymentUtxo, 
    paymentPrivateKey,
    undefined|data,
    true
)
```

We can observe that the final argument in the stasTransfer function is set to "true". This allows for the transfer to be conducted utilizing the zero change model. It's important to note that the second-to-last argument in the function must be set to either "undefined" or, if data is required, added in as demonstrated in the preceding examples regarding data additions.

Utilizing the zero change model also involves a fallback to ensure that no significant excess in satoshis goes unaccounted for in the change output. The parameters for the zero change model can be located in the utility.js file as depicted below:

```javascript
this.ZEROCHANGETHRESHOLD = 10 // Don't change this setting unless you know what you're doing
```

In this instance, if the change amount surpasses 10 satoshis, an error will be thrown, and the transaction build will not be completed. The zero change model is intended to be utilized alongside fee estimation functions to yield optimal results with minimal satoshi wastage, and to decrease the handling of excess change UTXOs when they are not required.&#x20;

{% hint style="info" %}
Each transaction function in the library has zero change option in the function arguments. By default, this value is set to false when not supplied.
{% endhint %}


# Zero Fee

No fee input transactions

Zero fee will create the transaction hex without any payment input UTXO or change output UTXO. To enable zero fee model simply do not include the paymentUtxo or paymentPrivateKey values in the function argument by passing in "null".

```javascript
const transferHex = await stasTransfer.signed(
    ownerPrivatekey, 
    stasUtxo, 
    destinationAddress, 
    null, 
    null
)
```

The result will be a transaction that does not include any funds to cover the transaction cost and instead the transaction fee will be managed from the miner side through a zero fee authentication model.

{% hint style="warning" %}
Please note that this model is currently not supported by any existing miners on the network.
{% endhint %}


# Unsigned Transactions

Sign a transaction externally

The unsigned features for the functions are the most advanced feature available in the library. It will create unsigned versions of the transactions and return an array of unsigned data for each input in the transaction that is not yet signed. This feature is designed to be used for wallets that may require external signatures such as web browser wallets. The current format of data returned by this function is as follows :

```javascript
const unsignedData = {
    unsignedData : [] // array of objects for each input in the transaction
    tx : tx // whole transaction object
}

unsignedData = [{
            inputIndex : number // index of the input being signed
            satoshis : number // satoshi converted to BN
            script : string // script buffer of the input
            sighash  : number // sighash flags for the input,
            publicKeyString : string // public key string of the input
            stas : boolean // indicating whether the input is stas type or not
})
```

{% hint style="info" %}
The unsigned data can be used in conjunction with the BSV library to construct a valid signature for the input(s).
{% endhint %}


# DXS Library

Advanced STAS Usage

## Consigliere API and DXS STAS SDK

Welcome to the documentation overview for the **Consigliere API** and the **DXS STAS SDK**. These tools are designed to streamline your development experience and provide robust access to the DXS ecosystem. Below, you'll find details and links to get started with both the API and the SDK.

***

### Consigliere API

The **Consigliere API** is a powerful interface for interacting with the DXS platform. It provides endpoints to manage data, execute actions, and integrate seamlessly with your applications.

#### Key Features

* RESTful architecture for easy integration
* Comprehensive endpoint documentation
* Staging environment for testing and development

#### API Documentation

Explore the full API specification and try out endpoints directly in the interactive documentation:

👉 [**Consigliere API Reference**](https://consigliere.staging.dxs.app/api/index.html)

***

### DXS STAS SDK

The **DXS STAS SDK** is a software development kit that simplifies working with the DXS platform in your projects. Available on GitHub, this SDK provides pre-built tools and utilities to accelerate development.

#### Key Features

* Easy-to-use library for integrating DXS functionality
* Open-source and community-driven
* Well-documented codebase for customization

#### SDK Repository

Check out the source code, installation instructions, and examples on GitHub:

👉 [**DXS STAS SDK on GitHub**](https://github.com/dxsapp/dxs-stas-sdk)

***

### Getting Started

1. **Explore the API**: Visit the [Consigliere API Reference](https://consigliere.staging.dxs.app/api/index.html) to understand available endpoints and test them in the staging environment.
2. **Install the SDK**: Clone or fork the [DXS STAS SDK](https://github.com/dxsapp/dxs-stas-sdk) repository and follow the setup instructions in the README.
3. **Build Something Amazing**: Combine the API and SDK to create powerful applications tailored to your needs.

***

### Need Help?

* For API-related questions, refer to the interactive documentation or reach out to the DXS support team.
* For SDK assistance, open an issue on the GitHub repository or contribute directly to the project.

Happy coding!


