> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hotstuff.trade/llms.txt
> Use this file to discover all available pages before exploring further.

# Signing Actions

### How Signing Works

The SDK uses EIP-712 typed data signing for all exchange actions. Here's what happens under the hood:

1. **Action Encoding**: The action payload is encoded using MessagePack
2. **Hashing**: The encoded bytes are hashed with keccak256
3. **EIP-712 Signing**: The hash is signed using EIP-712 typed data with the following structure:

```typescript theme={null}
const domain = {
  name: "HotstuffCore",
  version: "1",
  chainId: 1,
  verifyingContract: "0x1234567890123456789012345678901234567890",
};

const types = {
  Action: [
    { name: "source", type: "string" }, // "Testnet" or "Mainnet"
    { name: "hash", type: "bytes32" }, // keccak256 of msgpack-encoded action
    { name: "txType", type: "uint16" }, // Tx Op Code
  ],
};
```

### Action types & Opcodes

| **Action** | **Tx Type** | \*\*Tx Op Codes \*\* |
| - | - | :-: |
| **Account Actions** | | |
| Add Agent | `addAgent` | 1201 |
| Revoke Agent | `revokeAgent` | 1211 |
| Update Perp Instrument Leverage | `updatePerpLeverage` | 1203 |
| Approve Broker Fee | `approveBrokerFee` | 1207 |
| Create Referral Code | `createReferralCode` | 1208 |
| Set Referrer | `setReferrer` | 1209 |
| Claim Referral Rewards | `claimReferralRewards` | 1210 |
| **Trading Actions** | | |
| Place Order | `placeOrder` | 1301 |
| Cancel Order by OID | `cancelByOid` | 1302 |
| Cancel All | `cancelAll` | 1311 |
| Cancel by Cloid | `cancelByCloid` | 1312 |
| Cancel by Instrument | `cancelByInstrument` | 1313 |
| **Collateral Actions** | | |
| Spot Withdraw Request | `spotWithdrawRequest` | 1002 |
| Derivative Withdraw Request | `derivativeWithdrawRequest` | 1003 |
| Spot Balance Transfer Request | `spotBalanceTransferRequest` | 1051 |
| Derivative Balance Transfer Request | `derivativeBalanceTransferRequest` | 1052 |
| Internal Balance Transfer Request | `internalBalanceTransferRequest` | 1053 |

### SDK Implementation

```typescript TypeScript theme={null}
import { encode } from "@msgpack/msgpack";
import { keccak256 } from "viem";

export async function signAction(
  args: {
    wallet: any;
    action: unknown;
    txType: number;
  },
  options?: {
    isTestnet: boolean;
  },
) {
  const isTestnet = options?.isTestnet ?? false;

  const actionBytes = encode(args.action);

  const payloadHash = keccak256(actionBytes);

  const domain = {
    name: "HotstuffCore",
    version: "1",
    chainId: 1,
    verifyingContract:
      "0x1234567890123456789012345678901234567890" as `0x${string}`,
  };

  const types = {
    Action: [
      { name: "source", type: "string" },
      { name: "hash", type: "bytes32" },
      { name: "txType", type: "uint16" },
    ],
  };

  const eip712Message = {
    source: isTestnet ? "Testnet" : "Mainnet",
    hash: payloadHash,
    txType: args.txType,
  };

  const signature = await args.wallet.signTypedData({
    domain,
    types,
    primaryType: "Action",
    message: eip712Message,
  });

  return signature;
}
```

```python Python theme={null}
"""Signing utilities for EIP-712 typed data."""
import msgpack
from eth_account import Account
from eth_account.messages import encode_structured_data
from eth_utils import keccak
from hotstuff.methods.exchange.op_codes import EXCHANGE_OP_CODES


async def sign_action(
    wallet: Account,
    action: dict,
    tx_type: int,
    is_testnet: bool = False
) -> str:
    """
    Sign an action using EIP-712.

    Args:
        wallet: The account to sign with
        action: The action data
        tx_type: The transaction type code
        is_testnet: Whether this is for testnet

    Returns:
        str: The signature
    """
    # Encode action to msgpack
    action_bytes = msgpack.packb(action)

    # Hash the payload
    payload_hash = keccak(action_bytes)

    # EIP-712 domain
    domain = {
        "name": "HotstuffCore",
        "version": "1",
        "chainId": 1,
        "verifyingContract": "0x1234567890123456789012345678901234567890",
    }

    # EIP-712 types
    types = {
        "EIP712Domain": [
            {"name": "name", "type": "string"},
            {"name": "version", "type": "string"},
            {"name": "chainId", "type": "uint256"},
            {"name": "verifyingContract", "type": "address"},
        ],
        "Action": [
            {"name": "source", "type": "string"},
            {"name": "hash", "type": "bytes32"},
            {"name": "txType", "type": "uint16"},
        ],
    }

    # Message
    message = {
        "source": "Testnet" if is_testnet else "Mainnet",
        "hash": payload_hash,
        "txType": tx_type,
    }

    # Create structured data
    structured_data = {
        "types": types,
        "primaryType": "Action",
        "domain": domain,
        "message": message,
    }

    # Encode and sign
    encoded_data = encode_structured_data(structured_data)
    signed_message = wallet.sign_message(encoded_data)

    return signed_message.signature.hex()
```

### Debugging Signature Issues

It is recommended to use an existing SDK instead of manually generating signatures. There are many potential ways in which signatures can be wrong. An incorrect signature results in recovering a different signer based on the signature and payload and results in one of the following errors:

```
"Error: account does not exist."
```

```
"invalid order signer"
```

where the returned address does not match the public address of the wallet you are signing with. The returned address also changes for different inputs.

An incorrect signature does not indicate why it is incorrect which makes debugging more challenging. To debug this it is recommended to read through the SDK carefully and make sure the implementation matches exactly. If that doesn't work, add logging to find where the output diverges.

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.