# Manage user delegates

This guide shows how to interact with the Safe Transaction Service API to manage user delegates.

The different steps are implemented using [Curl](https://github.com/curl/curl) requests, the [Safe\{Core\} SDK](https://github.com/safe-global/safe-core-sdk) TypeScript library and the [safe-eth-py](https://github.com/safe-global/safe-eth-py) Python library.

The [Safe Queue Service](../safe-queue-service-overview.mdx) serves the delegate endpoints for every chain, so the Curl requests in this guide call it and pass the chain ID in the request. If your integration still calls the Safe Transaction Service for these endpoints, see the [migration guide](../safe-queue-service-migration.mdx).

## Prerequisites

1. [Node.js and npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm#using-a-node-version-manager-to-install-nodejs-and-npm) when using the Safe\{Core\} SDK.
2. [Python](https://www.python.org/downloads/) >= 3.9 when using `safe-eth-py`.
3. Have a Safe account.

## Steps

<Steps>
  ### Install dependencies


  <Tabs items={['TypeScript', 'Python']}>
    <Tabs.Tab>
      ```bash
      yarn add ethers @safe-global/api-kit @safe-global/protocol-kit @safe-global/types-kit
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      ```bash
      pip install safe-eth-py web3 hexbytes
      ```
    </Tabs.Tab>
  </Tabs>


  ### Imports


  <Tabs items={['TypeScript', 'Python']}>
    <Tabs.Tab>
      ```typescript
      import { ethers } from 'ethers'
      import SafeApiKit, { AddSafeDelegateProps } from '@safe-global/api-kit'
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      ```python
      from safe_eth.eth import EthereumClient, EthereumNetwork
      from safe_eth.safe.api.transaction_service_api import TransactionServiceApi
      from eth_account import Account
      from eth_typing import ChecksumAddress
      ```
    </Tabs.Tab>
  </Tabs>


  ### Get the delegates from a Safe


  <Tabs items={['TypeScript', 'Python', 'Curl']}>
    <Tabs.Tab>
      ```typescript
      // Initialize the API Kit
      // How to get an Api key => http://docs.safe.global/core-api/how-to-use-api-keys
      const apiKit = new SafeApiKit({
        chainId: 11155111n,
        apiKey: 'YOUR_API_KEY'
      })

      // Get the Safe delegates
      const delegates = await apiKit.getSafeDelegates({
        delegatorAddress: config.SAFE_ADDRESS
      })
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      ```python
      # Instantiate the Transaction Service API
      ethereum_client = EthereumClient(config.get("RPC_URL"))
      transaction_service_api = TransactionServiceApi(
          network=EthereumNetwork.SEPOLIA,
          ethereum_client=ethereum_client,
          api_key="YOUR_API_KEY",  # You can also use an environment variable: SAFE_TRANSACTION_SERVICE_API_KEY
      )

      # Get delegates from a Safe
      delegates_for_safe = transaction_service_api.get_delegates(
          config.get("SAFE_ADDRESS"))
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      The `chainId` filter is an exact match: it doesn't return delegates that are valid on all chains, so this request leaves it out and returns the delegates of every chain. Check the `chainId` of each result, which is `null` for a delegate that's valid on all chains.

      ```bash
      curl -X 'GET' \
      'https://api.safe.global/queue/api/v1/delegates?delegator=0xAA86E576c084aFFFFFFFFFFFF7967F10C467d318' \
      -H 'accept: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY'
      ```
    </Tabs.Tab>
  </Tabs>


  ### Add a delegate to a delegator


  <Tabs items={['TypeScript', 'Python', 'Curl']}>
    <Tabs.Tab>
      ```typescript
      const provider = new ethers.JsonRpcProvider(config.RPC_URL)

      const ownerA = new ethers.Wallet(config.OWNER_A_PRIVATE_KEY, provider)
      const ownerAAddress = await ownerA.getAddress()

      const ownerB = new ethers.Wallet(config.OWNER_B_PRIVATE_KEY, provider)
      const ownerBAddress = await ownerB.getAddress()

      const delegateConfig: AddSafeDelegateProps = {
        delegateAddress: ownerBAddress || '0x',
        delegatorAddress: ownerAAddress || '0x',
        signer: ownerA,
        label: 'Label'
      }

      // Add Owner B as a delegate of Owner A for all Safes accounts (safeAddress = null)
      const safeDelegateAddResponse = await apiKit.addSafeDelegate(delegateConfig)
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      ```python
      # Add Owner B as a delegate of Owner A for all Safes accounts (safe_address = null)
      account_owner_a = Account.from_key(config.get("OWNER_A_PRIVATE_KEY"))
      account_owner_b = Account.from_key(config.get("OWNER_B_PRIVATE_KEY"))
      
      hash_to_sign = transaction_service_api.create_delegate_message_hash(delegate_address=account_owner_b.address)
      signature = account_owner_a.signHash(hash_to_sign)
      
      transaction_service_api.add_delegate(
          delegate_address=ChecksumAddress(account_owner_b.address),
          delegator_address=ChecksumAddress(account_owner_a.address),
          label="Label",
          signature=signature.signature)
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      The delegator signs the EIP-712 typed data described in the "Create Delegate" endpoint of the [Safe Queue Service reference](../safe-queue-service-reference.mdx): a `Delegate` message with the `delegateAddress`, the hourly `totp` value and `action` set to `add`, in a domain with name `Safe Queue Service`, version `1.0`, and the `chainId` and `safe` of the delegation (`0` and the zero address for all chains and all Safes). Signatures made for the Safe Transaction Service delegate endpoints aren't valid.

      ```bash
      curl -X 'POST' \
      'https://api.safe.global/queue/api/v1/delegates' \
      -H 'accept: application/json' \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
          "chainId": 11155111,
          "safe": "0xc62C5cbB964459F3C984682f78A4d3ffffffffff",
          "delegate": "0x634Ce7818a1Ca34d3D69FFFFFFFFFFFFFFFF0AC6",
          "delegator": "0xAA86E576c084aFFFFFFFFFFFF7967F10C467d318",
          "signature": "0xe026c189805d7d5026e8b33e03dfe1847a488a9c6846afefffffffffffff0a566af485b7b4a68189c69c2245fcb9321d718d829d6180245cfe56dc51a0c15b031b",
          "label": "User delegator label"
      }'
      ```
    </Tabs.Tab>
  </Tabs>


  ### Delete a delegate of a delegator


  <Tabs items={['TypeScript', 'Python', 'Curl']}>
    <Tabs.Tab>
      ```typescript
      const delegateConfig: DeleteSafeDelegateProps = {
        delegateAddress: ownerBAddress || '0x',
        delegatorAddress: ownerAAddress || '0x',
        signer: ownerA
      }

      // Remove Owner B as delegate of Owner A
      await apiKit.removeSafeDelegate(delegateConfig)
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      ```python
      hash_to_sign = transaction_service_api.create_delegate_message_hash(delegate_address=account_owner_b.address)
      signature = account_owner_a.signHash(hash_to_sign)

      transaction_service_api.remove_delegate(
          delegate_address=ChecksumAddress(account_owner_b.address),
          delegator_address=ChecksumAddress(account_owner_a.address),
          signature=signature.signature)
      ```
    </Tabs.Tab>
    <Tabs.Tab>
      The delegator signs the same EIP-712 typed data as in the previous step, with `action` set to `delete`, as described in the "Delete Delegates" endpoint of the [Safe Queue Service reference](../safe-queue-service-reference.mdx). On `DELETE`, `chainId` and `safe` work as filters: a `null` or missing value matches the delegations of every chain or of every Safe.

      ```bash
      curl -X 'DELETE' \
      'https://api.safe.global/queue/api/v1/delegates' \
      -H 'accept: application/json' \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
          "chainId": 11155111,
          "safe": "0xc62C5cbB964459F3C984682f78A4d3ffffffffff",
          "delegate": "0x634Ce7818a1Ca34d3D69FFFFFFFFFFFFFFFF0AC6",
          "delegator": "0xAA86E576c084aFFFFFFFFFFFF7967F10C467d318",
          "signature": "0xe026c189805d7d5026e8b33e03dfe1847a488a9c6846afefffffffffffff0a566af485b7b4a68189c69c2245fcb9321d718d829d6180245cfe56dc51a0c15b031b"
      }'
      ```
    </Tabs.Tab>
  </Tabs>

</Steps>
