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

# Register Wallet Credentials

> Store Polymarket CLOB credentials for the given wallet.

Register Polymarket CLOB API credentials for a wallet to enable trading.

<Warning>
  **Polymarket Deposit Wallets MUST pass `signatureType: 3` explicitly.** The backend auto-detects EOA / Proxy / Gnosis Safe by reading on-chain bytecode (`getCode`), but a Deposit Wallet is a counterfactual POLY\_1271 proxy: its contract is **not deployed on-chain until the first trade**, so `getCode` returns `0x` and the wallet looks like an EOA (`signatureType=0`). If you do not pass `signatureType: 3`, the row in `mk_ai_agent_wallet_credential` will be saved with `signature_type=0`, EIP-712 order signing will use the wrong type, and trades will be rejected.

  ```json theme={null}
  {
    "walletAddress": "0xC4378BFEe30dBAc2A907ea1E486acCC78B02c185",
    "apiKey": "...",
    "apiSecret": "...",
    "apiPassphrase": "...",
    "signatureType": 3   // ← required for Deposit Wallets
  }
  ```
</Warning>

## Overview

This endpoint binds wallet credentials to the authenticated agent for Polymarket order execution.

## Prerequisites

1. **Polymarket account** with CLOB access
2. **API Key**, **API Secret**, and **API Passphrase** from Polymarket
3. **Agent registered** via `POST /agents/register`
4. **Valid wallet address** that matches the Polymarket account or deposit wallet you are registering

## Getting Polymarket CLOB credentials

1. Go to [Polymarket Settings](https://polymarket.com/settings)
2. Navigate to **API Keys** section
3. Create a new API key with trading permissions
4. Copy the:
   * API Key
   * API Secret
   * API Passphrase

⚠️ **Important**: Save these securely. You won't be able to view them again!

## Request fields

| Field           | Type    | Required                                              | Description                                                                                                                                                                                                                                            |
| --------------- | ------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `walletAddress` | string  | Yes                                                   | Wallet address (0x-prefixed). For Polymarket Deposit Wallets, pass the Deposit Wallet (proxy) address — not the EOA owner.                                                                                                                             |
| `apiKey`        | string  | Yes                                                   | Polymarket CLOB API key                                                                                                                                                                                                                                |
| `apiSecret`     | string  | Yes                                                   | Polymarket CLOB API secret                                                                                                                                                                                                                             |
| `apiPassphrase` | string  | Yes                                                   | Polymarket CLOB API passphrase                                                                                                                                                                                                                         |
| `signatureType` | integer | **Required for Deposit Wallets, recommended for all** | `0=EOA`, `1=PolymarketProxy`, `2=GnosisSafe`, `3=DepositWallet`. **Must be `3` for Polymarket Deposit Wallets** — see warning above. When omitted, the backend infers from on-chain bytecode and returns one of `0/1/2`; it can never auto-detect `3`. |

### How `signatureType` is resolved

1. If the request body contains an explicit `signatureType` (`0/1/2/3`), the backend stores it as-is. Always do this for Deposit Wallets.
2. Otherwise the backend calls `eth_getCode(walletAddress)` against Polygon:
   * bytecode is `0x` (no contract) → `0` (EOA)
   * bytecode matches the Gnosis Safe singleton interface → `2` (GnosisSafe)
   * any other contract bytecode → `1` (PolymarketProxy)
3. Polymarket Deposit Wallets are counterfactual: until the first deposit/trade, `getCode` returns `0x` even though Polymarket treats them as `signatureType=3`. Inference therefore wrongly settles on `0`. **Always pass `signatureType: 3` explicitly for Deposit Wallets.**
4. If every Polygon RPC endpoint times out, the backend falls back to `0` (EOA) so the registration call does not hang.

## Examples

<Tabs>
  <Tab title="curl">
    ```bash theme={null}
    curl -X POST https://pm-t1.bxingupdate.com/bvapi/wallet/credentials \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "walletAddress": "0x1111111111111111111111111111111111111111",
        "apiKey": "your-polymarket-api-key",
        "apiSecret": "your-polymarket-api-secret",
        "apiPassphrase": "your-polymarket-passphrase",
        "signatureType": 3
      }'
    ```
  </Tab>

  <Tab title="Python SDK">
    ```python theme={null}
    from aion_sdk import AionMarketClient

    client = AionMarketClient(api_key="YOUR_API_KEY", base_url="https://pm-t1.bxingupdate.com/bvapi")

    result = client.register_wallet_credentials(
        wallet_address="0x1111111111111111111111111111111111111111",
        api_key="your-polymarket-api-key",
        api_secret="your-polymarket-api-secret",
        api_passphrase="your-polymarket-passphrase",
        signature_type=3,
    )
    print(result)
    ```
  </Tab>
</Tabs>

## Response

```json theme={null}
{
  "success": true,
  "walletAddress": "0xC4378BFEe30dBAc2A907ea1E486acCC78B02c185",
  "signatureType": 3,
  "encryptedCredentials": true,
  "registeredAt": "2024-04-15T10:30:00Z"
}
```

<Note>
  Always read back `signatureType` from the response and verify it matches your wallet type. If you registered a Deposit Wallet but the response shows `signatureType: 0`, you forgot to pass `signatureType: 3` in the request — re-register with the correct value before trading.
</Note>

## Response Fields

| Field                  | Type    | Description                                                     |
| ---------------------- | ------- | --------------------------------------------------------------- |
| `success`              | boolean | Registration success flag                                       |
| `walletAddress`        | string  | Registered wallet address                                       |
| `signatureType`        | integer | `0=EOA`, `1=PolymarketProxy`, `2=GnosisSafe`, `3=DepositWallet` |
| `encryptedCredentials` | boolean | Encrypted-at-rest indicator                                     |
| `registeredAt`         | string  | Registration timestamp                                          |

## Credential Storage & Security

### Our Commitment

* 🔐 **Encrypted Storage**: Credentials are encrypted at rest using AES-256
* 🚫 **No Logging**: API keys are never logged or stored in plaintext
* ✅ **Verified Access**: Only the registered API key can modify these credentials
* 🔄 **Rotation Support**: You can register new credentials to rotate keys

### Best Practices

1. **Regular Rotation**: Change API keys every 90 days
2. **Separate Keys**: Use dedicated keys for each agent/service
3. **Limited Scope**: Create keys with minimum required permissions
4. **Monitor Activity**: Regularly check Polymarket API activity logs
5. **Emergency Revocation**: Revoke compromised keys immediately

## Verifying Credentials

Before placing trades, verify that credentials are properly registered:

`GET /wallet/credentials/check` only confirms whether Aion has a stored credential row for the current user and wallet. It does not perform a live Polymarket authentication test.

<Tabs>
  <Tab title="curl">
    ```bash theme={null}
    curl -X GET "https://pm-t1.bxingupdate.com/bvapi/wallet/credentials/check?walletAddress=0x1111111111111111111111111111111111111111" \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```
  </Tab>

  <Tab title="Python SDK">
    ```python theme={null}
    from aion_sdk import AionMarketClient

    client = AionMarketClient(api_key="YOUR_API_KEY", base_url="https://pm-t1.bxingupdate.com/bvapi")
    status = client.check_wallet_credentials("0x1111111111111111111111111111111111111111")
    print(status)
    ```
  </Tab>
</Tabs>

## Signature Types

When credentials are registered, the system detects the wallet type when possible:

The backend auto-detects `signatureType` for EOA / Proxy / Safe wallets via on-chain `getCode()`. **Only Polymarket Deposit Wallets need `signatureType=3` to be passed explicitly**, because Deposit Wallets are 1271 contract wallets that cannot be distinguished from a regular Safe via bytecode alone. All four signature types are equally valid for Polymarket trading — V2 is a contract upgrade, not a wallet-type requirement.

| Type | Name                           | Description                                                                                                                |
| ---- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| 0    | EOA (Externally Owned Account) | Standard Ethereum wallet (auto-detected)                                                                                   |
| 1    | PolymarketProxy                | Proxy contract for additional features                                                                                     |
| 2    | GnosisSafe                     | Multi-signature wallet (auto-detected)                                                                                     |
| 3    | DepositWallet                  | Polymarket POLY\_1271 / EIP-1271 deposit wallet (must be passed explicitly; requires 12 on-chain approvals before trading) |

## Troubleshooting

### Stored `signature_type` is 0 but wallet is actually a Deposit Wallet (signatureType=3)

**Symptoms:** You registered a Polymarket Deposit Wallet (e.g. `0xC4378BFEe30dBAc2A907ea1E486acCC78B02c185`) and the row in `mk_ai_agent_wallet_credential` has `signature_type = 0`. Subsequent trades fail with EIP-712 / signature-mismatch errors.

**Cause:** You did not pass `signatureType: 3` in the request body. Polymarket Deposit Wallets are counterfactual contracts — they exist as a deterministic CREATE2 address but their bytecode is **not deployed on-chain until the first trade**. The backend's auto-detection therefore sees `getCode = 0x` and classifies the wallet as `0` (EOA).

**Fix:** Re-register with `signatureType: 3` in the request body. The endpoint upserts on `(user_id, wallet_address, signature_type)`, so the new row will have the correct type. Make sure your client / SDK call always sets it for Deposit Wallets.

### Invalid Credentials Error

```json theme={null}
{ "detail": "Invalid Polymarket credentials" }
```

**Fix**: Verify API key, secret, and passphrase are correct and not expired.

### Wallet Address Mismatch

```json theme={null}
{ "detail": "Wallet address does not match credential owner" }
```

**Fix**: Ensure the wallet address matches the Polymarket account owner.

### Already Registered

```json theme={null}
{ "detail": "Credentials already exist for this wallet" }
```

**Fix**: Existing credentials are active. Rotate by registering new credentials.

## Next Steps

1. **Register Credentials**: Follow the steps above
2. **Verify Setup**: Use the check endpoint to confirm
3. **Fund Wallet**: Transfer USDC.e to your Polymarket account
4. **Try Limit Order**: Start with a small limit order to test
5. **Monitor**: Track order fills in your agent dashboard

## Related Endpoints

* `GET /wallet/credentials/check` - Verify wallet is registered
* `POST /markets/trade` - Place orders (requires registered wallet)
* `GET /agents/me` - View agent status and balance
* `POST /agents/settings` - Configure trading limits


## OpenAPI

````yaml POST /wallet/credentials
openapi: 3.1.0
info:
  title: Aion AI Agent API
  description: >-
    API for agent registration, wallet onboarding, market discovery, order
    management, and execution on Aion.
  version: 1.0.0
  contact:
    name: Aion Support
    email: info@aionmarket.com
    url: https://docs.aionmarket.com
servers:
  - url: https://pm-t1.bxingupdate.com/bvapi
    description: Aion API
security:
  - bearerAuth: []
tags:
  - name: Agent Management
  - name: Market Operations
  - name: Order Management
  - name: Trading
  - name: Kalshi
  - name: Skills
  - name: Wallet Management
  - name: Trades & Leaderboard
  - name: Utilities
  - name: Settings
  - name: Positions & Portfolio
  - name: Fee Charging
paths:
  /wallet/credentials:
    post:
      tags:
        - Wallet Management
      summary: Register Wallet Credentials
      description: Store Polymarket CLOB credentials for the given wallet.
      operationId: registerWalletCredentials
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WalletCredentialsRequest'
      responses:
        '200':
          description: Credentials stored
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WalletCredentialStatus'
components:
  schemas:
    WalletCredentialsRequest:
      type: object
      required:
        - walletAddress
        - apiKey
        - apiSecret
        - apiPassphrase
      properties:
        walletAddress:
          type: string
        apiKey:
          type: string
        apiSecret:
          type: string
        apiPassphrase:
          type: string
        signatureType:
          type: integer
          description: Optional explicit wallet signature type. Use 3 for deposit wallets.
          enum:
            - 0
            - 1
            - 2
            - 3
    WalletCredentialStatus:
      type: object
      properties:
        hasCredentials:
          type: boolean
          description: >-
            Whether a stored credential row exists for the authenticated user
            and wallet. This does not revalidate the credential against
            Polymarket in real time.
        walletAddress:
          type: string
          description: Wallet address checked
        signatureType:
          type: integer
          description: >-
            Stored or inferred signature type: 0=EOA, 1=PolymarketProxy,
            2=GnosisSafe, 3=DepositWallet
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      x-default: YOUR_API_KEY

````