# getTokenAccountsByDelegate

The `getTokenAccountsByDelegate` RPC method in **CoinVera** returns all SPL token accounts where the specified public key is set as the **delegate**. Delegated accounts allow another wallet to act on behalf of the token owner, typically for transfers or burns within an approved allowance.

***

#### ✅ Common Use Cases

* **View All Delegated Token Accounts**\
  Retrieve every token account where a delegate (e.g., escrow or vault program) is authorized.
* **Monitor Allowances**\
  Track accounts where a program or external user has been granted limited spending authority.
* **Build Programmatic Access Control**\
  Use in systems that rely on delegated authority for token movement or staking operations.

***

#### 🧾 Request Parameters

```json
[
  delegateAddress: string,         // Required: base-58 public key of the delegate
  options?: {
    commitment?: string,           // Optional: "processed", "confirmed", or "finalized"
    encoding?: string,             // Optional: "jsonParsed", "json", "base64" (default: "jsonParsed")
    dataSlice?: { offset: number, length: number } // Optional: for partial account data
  }
]
```

* **delegateAddress**: Public key of the delegate to search against.
* **commitment**: Optional commitment level.
* **encoding**: Format of account data (typically `jsonParsed` for human-readable).
* **dataSlice**: If you want only part of the account data.

***

#### 📦 Response Structure

Returns a list of token accounts where the delegate matches the input address.

```json
{
  "context": { "slot": 221446650 },
  "value": [
    {
      "pubkey": "TokenAccountPubkeyHere",
      "account": {
        "data": {
          "parsed": {
            "info": {
              "delegate": "DelegatePublicKey",
              "delegatedAmount": {
                "amount": "1000000",
                "decimals": 6
              },
              ...
            }
          }
        },
        "lamports": 2039280,
        ...
      }
    }
  ]
}
```

***

#### 🧪 Example

**Get All Token Accounts Delegated to a Specific Wallet**

Request:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getTokenAccountsByDelegate",
  "params": [
    "9vZh4cYytHe7rJPVbUWziGmLZQUKvVSoL7L1uQhe9kBA",
    { "encoding": "jsonParsed" }
  ]
}
```

***

**Code Examples**

{% tabs %}
{% tab title="Nodejs" %}

```javascript
const fetch = require('node-fetch');

async function getTokenAccountsByDelegate(rpcUrl) {
  try {
    const response = await fetch(rpcUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'getTokenAccountsByDelegate',
        "params": [
            "4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T",
            {
              "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
            },
            {
              "commitment": "finalized",
              "encoding": "jsonParsed"
            }
          ]
      }),
    });

    const data = await response.json();
    
    // Print the exact full response
    console.log('Full RPC Response:');
    console.log(JSON.stringify(data, null, 2));
    
    return data;
  } catch (error) {
    console.error('Error getting health:', error.message);
    return null;
  }
}

// Example usage
const RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key';

getTokenAccountsByDelegate(RPC_URL);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def get_token_accounts_by_delegate(rpc_url):
    try:
        response = requests.post(
            rpc_url,
            headers={
                'Content-Type': 'application/json',
            },
            json={
                'jsonrpc': '2.0',
                'id': 1,
                'method': 'getTokenAccountsByDelegate',
                'params': [
                    '4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T',
                    {
                        'programId': 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'
                    },
                    {
                        'commitment': 'finalized',
                        'encoding': 'jsonParsed'
                    }
                ]
            }
        )
        
        data = response.json()
        
        # Print the exact full response
        print('Full RPC Response:')
        print(json.dumps(data, indent=2))
        
        return data
        
    except Exception as error:
        print(f'Error getting health: {error}')
        return None

# Example usage
RPC_URL = 'https://rpc.coinvera.io/?x-api-key=your-coinvera-x-api-key'
get_token_accounts_by_delegate(RPC_URL)
```

{% endtab %}
{% endtabs %}

**Example Response**

```json
{
  "jsonrpc": "2.0",
  "result": {
    "context": { "slot": 1114 },
    "value": [
      {
        "pubkey": "28YTZEwqtMHWrhWcvv34se7pjS7wctgqzCPB3gReCFKp",
        "account": {
          "data": {
            "program": "spl-token",
            "parsed": {
              "info": {
                "tokenAmount": {
                  "amount": "1",
                  "decimals": 1,
                  "uiAmount": 0.1,
                  "uiAmountString": "0.1"
                },
                "delegate": "4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T",
                "delegatedAmount": {
                  "amount": "1",
                  "decimals": 1,
                  "uiAmount": 0.1,
                  "uiAmountString": "0.1"
                },
                "state": "initialized",
                "isNative": false,
                "mint": "3wyAj7Rt1TWVPZVteFJPLa26JmLvdb1CAKEFZm3NY75E",
                "owner": "CnPoSPKXu7wJqxe59Fs72tkBeALovhsCxYeFwPCQH9TD"
              },
              "type": "account"
            },
            "space": 165
          },
          "executable": false,
          "lamports": 1726080,
          "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
          "rentEpoch": 4,
          "space": 165
        }
      }
    ]
  },
  "id": 1
}
```

***

#### 💡 Developer Tips

* **Use `jsonParsed` for Easy Parsing**\
  You'll get structured info like mint, owner, delegate, and balance without decoding manually.
* **Delegated Amounts Are Limited**\
  The `delegatedAmount` field shows how much the delegate is allowed to transfer.
* **Matches Token Accounts, Not Wallets**\
  The method returns token accounts, which are tied to specific SPL tokens, not SOL.
* **Use with Caution in Critical Systems**\
  If you're automating logic based on delegated authority, ensure up-to-date commitment levels (e.g., `finalized`).

***

The `getTokenAccountsByDelegate` method is essential for inspecting delegated token authority, enabling permissioned workflows and token allowances across Solana-powered apps using **CoinVera**.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.coinvera.io/integration/solana/rpc/gettokenaccountsbydelegate.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
