> For the complete documentation index, see [llms.txt](https://docs.kasware.xyz/wallet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kasware.xyz/wallet/developer-documentation/kaspa/kaspa-krc20.md).

# KRC20 API

## buildScript

[Demo Code For buildScript()](https://github.com/kasware-wallet/dapp-demo/blob/a5e209592a01e298a71909151be6d9ca6db08f7b/src/App.tsx#L1101)

```javascript
kasware.buildScript({ type, data });
```

Build an inscription script for KRC20, KNS, or KSPR\_KRC721 protocols. This method generates the script and corresponding P2SH (Pay-to-Script-Hash) address required for the commit-reveal inscription process.

This is a **safe** operation that does not require user approval, as it only constructs the script locally without broadcasting any transaction.

### How It Works

The function constructs a script with the following structure:

```
<public_key> OP_CHECKSIG OP_FALSE OP_IF <protocol_id> <0> <data> OP_ENDIF
```

The script embeds your inscription data within a conditional branch that can be revealed in a subsequent transaction. Different protocols use different identifiers:

* **KRC20**: Uses `kasplex` as protocol identifier
* **KNS**: Uses `kns` as protocol identifier
* **KSPR\_KRC721**: Uses `kspr` as protocol identifier

### Parameters

| Parameter | Type   | Required | Description                                                                 |
| --------- | ------ | -------- | --------------------------------------------------------------------------- |
| type      | string | Yes      | Script type. Supported values: `"KRC20"`, `"KNS"`, `"KSPR_KRC721"`          |
| data      | string | Yes      | JSON string of the data to inscribe. Must be pre-stringified before passing |

### Returns

`Promise<{ script: string, p2shAddress: string }>`

| Field       | Type   | Description                                                                                    |
| ----------- | ------ | ---------------------------------------------------------------------------------------------- |
| script      | string | The constructed inscription script                                                             |
| p2shAddress | string | The P2SH address derived from the script, used as commit address in commit-reveal transactions |

### Example

```javascript
try {
  enum BuildScriptType {
    KRC20 = "KRC20",
    KNS = "KNS",
    KSPR_KRC721 = "KSPR_KRC721",
  }

  // Prepare the KRC20 inscription data
  const jsonData = {
    p: "krc-20",
    op: "mint",
    tick: "test",
  };

  // Convert to JSON string without extra whitespace
  const data = JSON.stringify(jsonData, null, 0);

  // Build the script
  const { script, p2shAddress } = await window.kasware.buildScript({
    type: BuildScriptType.KRC20,
    data: data,
  });

  console.log("Inscription script:", script);
  console.log("P2SH address for commit:", p2shAddress);

  // Next step: Use submitCommitReveal() to commit and reveal the inscription
} catch (e) {
  console.log(e);
}
```

### Typical Workflow

1. **buildScript()** - Construct the inscription script and get P2SH address
2. **submitCommitReveal()** or **submitCommit() + submitReveal()** - Execute the commit-reveal transaction to inscribe the data on-chain

### Notes

* The function uses the current account's public key to construct the script
* For hardware wallets (e.g., Tangem), the script uses ECDSA signature verification instead of Schnorr
* The returned `p2shAddress` is used as the commit address in the commit-reveal process

***

## submitCommitReveal

```javascript
kasware.submitCommitReveal(commit, reveal, script, networkId);
```

Execute a complete commit-reveal transaction in a single call. This method combines the commit and reveal phases into one atomic operation, automatically handling the wait for commit confirmation before broadcasting the reveal transaction.

This method requires **user approval** - a popup window will appear asking the user to confirm the transaction details.

### How It Works

The commit-reveal mechanism is a two-phase transaction process used for inscribing data on the Kaspa blockchain:

1. **Commit Phase**: Creates and broadcasts a transaction that sends funds to a P2SH (Pay-to-Script-Hash) address. The script containing the inscription data is committed but not yet revealed.
2. **Reveal Phase**: Once the commit transaction is confirmed and UTXOs are available at the P2SH address, broadcasts a reveal transaction that spends from the P2SH address, effectively revealing the inscription data on-chain.

This method automatically waits for the commit transaction to be confirmed before proceeding with the reveal phase, ensuring reliable inscription.

### Parameters

| Parameter | Type   | Required | Description                                                           |
| --------- | ------ | -------- | --------------------------------------------------------------------- |
| commit    | object | Yes      | Commit transaction configuration                                      |
| reveal    | object | Yes      | Reveal transaction configuration                                      |
| script    | string | Yes      | The inscription script (obtained from `buildScript()`)                |
| networkId | string | No       | Network identifier. If not specified, uses the current wallet network |

#### commit object

| Field           | Type                                   | Required | Description                                                                 |
| --------------- | -------------------------------------- | -------- | --------------------------------------------------------------------------- |
| priorityEntries | IUtxoEntryJson\[]                      | No       | Priority UTXOs to use first for the transaction                             |
| entries         | IUtxoEntryJson\[]                      | Yes      | UTXO entries to fund the commit transaction                                 |
| outputs         | { address: string; amount: number }\[] | Yes      | Output destinations for the commit transaction (typically the P2SH address) |
| changeAddress   | string                                 | Yes      | Address to receive any change from the commit transaction                   |
| priorityFee     | number                                 | No       | Additional network priority fee in KAS to speed up confirmation             |

#### reveal object

| Field         | Type                                   | Required | Description                                                            |
| ------------- | -------------------------------------- | -------- | ---------------------------------------------------------------------- |
| outputs       | { address: string; amount: number }\[] | No       | Output destinations for the reveal transaction (e.g., revenue address) |
| changeAddress | string                                 | Yes      | Address to receive any change from the reveal transaction              |
| priorityFee   | number                                 | No       | Additional network priority fee in KAS for the reveal transaction      |

### Returns

`Promise<{ commitIds: string[]; revealIds: string[] }>`

| Field     | Type      | Description                                                         |
| --------- | --------- | ------------------------------------------------------------------- |
| commitIds | string\[] | Array of commit transaction IDs                                     |
| revealIds | string\[] | Array of reveal transaction IDs (primary txids for the inscription) |

### Example

```javascript
try {
  // Step 1: Get UTXO entries and current address
  const entries = await window.kasware.getUtxoEntries();
  const [address] = await window.kasware.getAccounts();
  const network = await window.kasware.getNetwork();

  // Step 2: Build the inscription script
  const data = {
    p: "krc-20",
    op: "mint",
    tick: "WARE",
  };
  const jsonStr = JSON.stringify(data, null, 0);
  const { script, p2shAddress } = await window.kasware.buildScript({
    type: "KRC20",
    data: jsonStr,
  });

  // Step 3: Determine network ID
  let networkId = "mainnet";
  switch (network) {
    case "kaspa_mainnet":
      networkId = "mainnet";
      break;
    case "kaspa_testnet_11":
      networkId = "testnet-11";
      break;
    case "kaspa_testnet_10":
      networkId = "testnet-10";
      break;
    case "kaspa_devnet":
      networkId = "devnet";
      break;
  }

  // Step 4: Configure commit and reveal parameters
  const revenueAddress = "kaspatest:qrpygfgeq45h68wz5pk4rtay02w7fwlhax09x4rsqceqq6s3mz6uctlh3a695";

  const commit = {
    priorityEntries: [],
    entries: entries,
    outputs: [{ address: p2shAddress, amount: 2.5 }], // Send to P2SH address
    changeAddress: address,
    priorityFee: 0.01,
  };

  const reveal = {
    outputs: [{ address: revenueAddress, amount: 0.5 }], // Optional revenue output
    changeAddress: address,
    priorityFee: 0.02,
  };

  // Step 5: Execute commit-reveal transaction
  const results = await window.kasware.submitCommitReveal(
    commit,
    reveal,
    script,
    networkId
  );

  console.log("Commit Transaction IDs:", results.commitIds);
  console.log("Reveal Transaction IDs:", results.revealIds);
  // The revealIds are the primary transaction IDs for the inscription

} catch (e) {
  if (e.message.includes("user rejected")) {
    console.log("User cancelled the transaction");
  } else {
    console.error("Transaction failed:", e);
  }
}
```

### Typical Workflow

1. **getUtxoEntries()** - Get available UTXOs for funding
2. **getAccounts()** - Get current wallet address
3. **buildScript()** - Generate inscription script and P2SH address
4. **submitCommitReveal()** - Execute the complete commit-reveal process

### Alternative Methods

For more granular control, you can use the separate methods:

* **submitCommit()** - Execute only the commit phase
* **submitReveal()** - Execute only the reveal phase (requires prior commit)

This is useful when you need to:

* Add custom delays between phases
* Monitor the commit transaction status manually
* Handle multiple reveals from a single commit

### Notes

* The method automatically waits for commit confirmation before revealing
* Ensure sufficient KAS balance for both commit and reveal transaction fees
* The `outputs` in commit should include the P2SH address from `buildScript()`
* The `amount` sent to P2SH address determines the value locked during commit
* For KRC20 operations, consider using `signKRC20Transaction()` as a simpler alternative
* Hardware wallets may require additional confirmation steps

***

## signKRC20Transaction

[Demo Code For signKRC20Transaction()](https://github.com/kasware-wallet/dapp-demo/blob/a5e209592a01e298a71909151be6d9ca6db08f7b/src/App.tsx#L476)

```javascript
kasware.signKRC20Transaction(inscribeJsonString, type, destAddr, priorityFee);
```

Sign and broadcast a KRC20 transaction using the commit-reveal mechanism. This method handles the complete inscription process for KRC20 tokens, including deployment, minting, and transfer operations.

This method requires **user approval** - a popup window will appear asking the user to confirm the transaction details.

### How It Works

The function implements a two-phase commit-reveal transaction process:

1. **Commit Phase**: Creates and broadcasts a commit transaction that sends funds to a P2SH (Pay-to-Script-Hash) address containing the inscription data embedded in the script.
2. **Reveal Phase**: Once the commit transaction is confirmed, creates and broadcasts a reveal transaction that spends from the P2SH address, effectively revealing the inscription data on-chain.

This approach ensures that the inscription data is permanently recorded on the Kaspa blockchain in a secure and verifiable manner.

### Parameters

| Parameter          | Type   | Required | Description                                                                                    |
| ------------------ | ------ | -------- | ---------------------------------------------------------------------------------------------- |
| inscribeJsonString | string | Yes      | JSON stringified KRC20 operation object. Must follow KRC20 specification format                |
| type               | number | Yes      | Transaction type: `2` for deploy, `3` for mint, `4` for transfer                               |
| destAddr           | string | No       | Destination address for transfer operations. Only used when `type` is `4`                      |
| priorityFee        | number | No       | Network priority fee in KAS. Default is `0`. Higher fees can speed up transaction confirmation |

### Transaction Types

| Type Value | Operation | Description                                        |
| ---------- | --------- | -------------------------------------------------- |
| 2          | Deploy    | Deploy a new KRC20 token with specified parameters |
| 3          | Mint      | Mint tokens from an existing KRC20 deployment      |
| 4          | Transfer  | Transfer KRC20 tokens to a destination address     |

### Returns

`Promise<string>` - JSON string containing transaction identifiers. Parse the result to access:

| Field       | Type   | Description                                                                                     |
| ----------- | ------ | ----------------------------------------------------------------------------------------------- |
| commitId    | string | The transaction ID of the commit transaction                                                    |
| revealId    | string | The transaction ID of the reveal transaction (this is the primary txid for the KRC20 operation) |
| commitTxStr | string | The raw commit transaction hex string                                                           |
| revealTxStr | string | The raw reveal transaction hex string                                                           |

### KRC20 JSON Format

The `inscribeJsonString` parameter must be a valid JSON string following the KRC20 specification:

**Deploy Operation:**

```json
{
  "p": "KRC-20",
  "op": "deploy",
  "tick": "TOKEN_NAME",
  "max": "maximum_supply",
  "lim": "mint_limit_per_tx",
  "pre": "pre_mint_amount"
}
```

**Mint Operation:**

```json
{
  "p": "KRC-20",
  "op": "mint",
  "tick": "TOKEN_NAME"
}
```

**Transfer Operation:**

```json
{
  "p": "KRC-20",
  "op": "transfer",
  "tick": "TOKEN_NAME",
  "amt": "amount_to_transfer",
  "to": "destination_address"
}
```

### Example-1: Deploy a KRC20 Token

```javascript
try {
  const deployData = {
    p: "KRC-20",
    op: "deploy",
    tick: "BBBB",
    max: "21000000000000000000000000000000",
    lim: "100000000000000000000",
    pre: "100000000000000000000"
  };
  const inscribeJsonString = JSON.stringify(deployData);
  const type = 2; // Deploy

  const result = await window.kasware.signKRC20Transaction(inscribeJsonString, type);
  const { commitId, revealId } = JSON.parse(result);
  console.log("Deploy transaction ID:", revealId);
} catch (e) {
  console.log(e);
}
```

### Example-2: Mint a KRC20 Token

```javascript
try {
  const mintData = {
    p: "KRC-20",
    op: "mint",
    tick: "XXXX"
  };
  const inscribeJsonString = JSON.stringify(mintData);
  const type = 3; // Mint

  const result = await window.kasware.signKRC20Transaction(inscribeJsonString, type);
  const { commitId, revealId } = JSON.parse(result);
  console.log("Mint transaction ID:", revealId);
} catch (e) {
  console.log(e);
}
```

### Example-3: Transfer KRC20 Tokens

```javascript
try {
  const transferData = {
    p: "KRC-20",
    op: "transfer",
    tick: "RBMV",
    amt: "10000000000",
    to: "kaspa:qzhkxxaully72gk23lyn7z3d9tdzdpw48ujsavrwlulekyk7"
  };
  const inscribeJsonString = JSON.stringify(transferData);
  const type = 4; // Transfer
  const destAddr = "kaspa:qzhkxxaully72gk23lyn7z3d9tdzdpw48ujsavrwlulekyk7";
  const priorityFee = 0.1; // Optional priority fee in KAS

  const result = await window.kasware.signKRC20Transaction(
    inscribeJsonString,
    type,
    destAddr,
    priorityFee
  );
  const { commitId, revealId } = JSON.parse(result);
  console.log("Transfer transaction ID:", revealId);
} catch (e) {
  console.log(e);
}
```

### Example-4: Handle Transaction Result

```javascript
try {
  const result = await window.kasware.signKRC20Transaction(inscribeJsonString, type);
  const txInfo = JSON.parse(result);

  console.log("Commit Transaction:", txInfo.commitId);
  console.log("Reveal Transaction:", txInfo.revealId);
  console.log("Raw Commit TX:", txInfo.commitTxStr);
  console.log("Raw Reveal TX:", txInfo.revealTxStr);

  // You can track the transaction status using the revealId
  // The KRC20 operation is considered complete once the reveal transaction is confirmed
} catch (e) {
  if (e.message.includes("insufficient balance")) {
    console.error("Not enough KAS to pay for transaction fees");
  } else if (e.message.includes("user rejected")) {
    console.log("User cancelled the transaction");
  } else {
    console.error("Transaction failed:", e);
  }
}
```

### Fees and Costs

The transaction requires sufficient KAS balance to cover:

* **Protocol Fee**: Required by the KRC20 protocol for each operation type
* **Commit Transaction Fee**: Network fee for the commit transaction
* **Reveal Transaction Fee**: Network fee for the reveal transaction (includes any priority fee)
* **Minimum Commit Amount**: A small amount locked in the P2SH address during the commit phase

The `priorityFee` parameter allows you to add additional fees to speed up transaction confirmation, especially useful during network congestion.

### Notes

* Ensure the user has sufficient KAS balance before calling this method
* For transfer operations, verify the destination address is valid
* The `revealId` is the primary transaction ID to track for KRC20 operation status
* This method automatically handles the commit-reveal process, waiting for commit confirmation before revealing
* For batch transfers, consider using `krc20BatchTransferTransaction()` instead
