getAccounts function

Future<List<Account>> getAccounts({
  1. int? limit = 250,
  2. String? cursor,
  3. Client? client,
  4. required Credential credential,
  5. bool isSandbox = false,
})

Gets a list of accounts for the current user.

GET /api/v3/brokerage/accounts https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/accounts/list-accounts

This function makes a GET request to the /accounts endpoint of the Coinbase Advanced Trade API. It supports pagination using a cursor.

limit - A limit on the number of accounts to be returned. cursor - A cursor for pagination. credential - The user's API credentials. isSandbox - Whether to use the sandbox environment.

Returns a list of Account objects.

Implementation

Future<List<Account>> getAccounts(
    {int? limit = 250,
    String? cursor,
    http.Client? client,
    required Credential credential,
    bool isSandbox = false}) async {
  List<Account> accounts = [];
  Map<String, dynamic>? queryParameters = {'limit': '$limit'};
  (cursor != null) ? queryParameters.addAll({'cursor': cursor}) : null;

  http.Response response = await getAuthorized('/accounts',
      queryParameters: queryParameters,
      client: client,
      credential: credential,
      isSandbox: isSandbox);

  if (response.statusCode == 200) {
    String data = response.body;
    var jsonResponse = jsonDecode(data);
    var jsonAccounts = jsonResponse['accounts'];
    String? jsonCursor = jsonResponse['cursor'];

    for (var jsonObject in jsonAccounts) {
      accounts.add(Account.fromCBJson(jsonObject));
    }
    // Recursive Break
    if (jsonCursor != null && jsonCursor != '') {
      // Recursive Call
      List<Account> paginatedAccounts = await getAccounts(
          limit: limit,
          cursor: jsonCursor,
          client: client,
          credential: credential,
          isSandbox: isSandbox);
      accounts.addAll(paginatedAccounts);
    }
  } else {
    throw CoinbaseException(
        'Failed to get accounts', response.statusCode, response.body);
  }

  return accounts;
}