import { __assign, __spreadArray, __read, __awaiter, __generator, __values } from 'tslib';
import { PublicKey, Transaction, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
import bs58 from 'bs58';
import { sample } from 'lodash';
import BN from 'bn.js';
import keccak256 from 'keccak256';
import secp256k1 from 'secp256k1';

var AUDIO_DECIMALS = 18;
var WAUDIO_DECIMALS = 8;
var USDC_DECIMALS = 6;
var CURRENT_USER_EXISTS_LOCAL_STORAGE_KEY = '@audius/libs:found-user';
var AuthHeaders;
(function (AuthHeaders) {
  AuthHeaders["MESSAGE"] = "Encoded-Data-Message";
  AuthHeaders["SIGNATURE"] = "Encoded-Data-Signature";
})(AuthHeaders || (AuthHeaders = {}));

var getTrackListens = function getTrackListens(timeFrame, idsArray, startTime, endTime, limit, offset) {
  if (timeFrame === void 0) {
    timeFrame = null;
  }
  if (idsArray === void 0) {
    idsArray = null;
  }
  if (startTime === void 0) {
    startTime = null;
  }
  if (endTime === void 0) {
    endTime = null;
  }
  if (limit === void 0) {
    limit = null;
  }
  if (offset === void 0) {
    offset = null;
  }
  var queryUrl = 'tracks/listens/';
  if (timeFrame != null) {
    switch (timeFrame) {
      case 'day':
      case 'week':
      case 'month':
      case 'year':
      case 'millennium':
        break;
      default:
        throw new Error('Invalid timeFrame value provided');
    }
    queryUrl += timeFrame;
  }
  var queryParams = {};
  if (idsArray !== null) {
    queryParams.id = idsArray;
  }
  if (limit !== null) {
    queryParams.limit = limit;
  }
  if (offset !== null) {
    queryParams.offset = offset;
  }
  if (startTime != null) {
    queryParams.start = startTime;
  }
  if (endTime != null) {
    queryParams.end = endTime;
  }
  var req = {
    url: queryUrl,
    method: 'get',
    params: queryParams
  };
  return req;
};

var requests$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getTrackListens: getTrackListens
});

/* eslint-disable @typescript-eslint/restrict-plus-operands */
var getUsers = function getUsers(limit, offset, idsArray, walletAddress, handle, minBlockNumber, includeIncomplete) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  var queryParams = {
    limit: limit,
    offset: offset
  };
  if (handle) {
    queryParams.handle = handle;
  }
  if (walletAddress) {
    queryParams.wallet = walletAddress;
  }
  if (minBlockNumber) {
    queryParams.min_block_number = minBlockNumber;
  }
  if (idsArray != null) {
    if (!Array.isArray(idsArray)) {
      throw new Error('Expected integer array of user ids');
    }
    queryParams.id = idsArray;
  }
  if (includeIncomplete != null) {
    queryParams.include_incomplete = includeIncomplete;
  }
  var req = {
    endpoint: 'users',
    queryParams: queryParams
  };
  return req;
};
var getTracks = function getTracks(limit, offset, idsArray, targetUserId, sort, minBlockNumber, filterDeleted, withUsers) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  var queryParams = {
    limit: limit,
    offset: offset
  };
  if (idsArray) {
    if (!Array.isArray(idsArray)) {
      throw new Error('Expected array of track ids');
    }
    queryParams.id = idsArray;
  }
  if (minBlockNumber) {
    queryParams.min_block_number = minBlockNumber;
  }
  if (targetUserId) {
    queryParams.user_id = targetUserId;
  }
  if (sort) {
    queryParams.sort = sort;
  }
  if (typeof filterDeleted === 'boolean') {
    queryParams.filter_deleted = filterDeleted;
  }
  if (withUsers) {
    queryParams.with_users = true;
  }
  var req = {
    endpoint: 'tracks',
    queryParams: queryParams
  };
  return req;
};
var getTracksByHandleAndSlug = function getTracksByHandleAndSlug(handle, slug) {
  return {
    endpoint: 'v1/tracks',
    method: 'get',
    queryParams: {
      handle: handle,
      slug: slug
    }
  };
};
var getTracksIncludingUnlisted = function getTracksIncludingUnlisted(identifiers, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  var queryParams = {};
  if (withUsers) {
    queryParams.with_users = true;
  }
  var req = {
    endpoint: 'tracks_including_unlisted',
    method: 'post',
    data: {
      tracks: identifiers
    },
    queryParams: queryParams
  };
  return req;
};
var getRandomTracks = function getRandomTracks(genre, limit, exclusionList, time) {
  var req = {
    endpoint: 'tracks/random',
    queryParams: {
      genre: genre,
      limit: limit,
      exclusionList: exclusionList,
      time: time
    }
  };
  return req;
};
var getStemsForTrack = function getStemsForTrack(trackId) {
  var req = {
    endpoint: "stems/".concat(trackId),
    queryParams: {
      with_users: true
    }
  };
  return req;
};
var getRemixesOfTrack = function getRemixesOfTrack(trackId, limit, offset) {
  if (limit === void 0) {
    limit = null;
  }
  if (offset === void 0) {
    offset = null;
  }
  var req = {
    endpoint: "remixes/".concat(trackId, "/children"),
    queryParams: {
      with_users: true,
      limit: limit,
      offset: offset
    }
  };
  return req;
};
var getRemixTrackParents = function getRemixTrackParents(trackId, limit, offset) {
  if (limit === void 0) {
    limit = null;
  }
  if (offset === void 0) {
    offset = null;
  }
  var req = {
    endpoint: "remixes/".concat(trackId, "/parents"),
    queryParams: {
      with_users: true,
      limit: limit,
      offset: offset
    }
  };
  return req;
};
var getTrendingTracks = function getTrendingTracks(genre, timeFrame, idsArray, limit, offset, withUsers) {
  if (genre === void 0) {
    genre = null;
  }
  if (timeFrame === void 0) {
    timeFrame = null;
  }
  if (idsArray === void 0) {
    idsArray = null;
  }
  if (limit === void 0) {
    limit = null;
  }
  if (offset === void 0) {
    offset = null;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  var endpoint = '/trending/';
  if (timeFrame != null) {
    switch (timeFrame) {
      case 'day':
      case 'week':
      case 'month':
      case 'year':
        break;
      default:
        throw new Error('Invalid timeFrame value provided');
    }
    endpoint += "".concat(endpoint).concat(timeFrame);
  }
  var req = {
    endpoint: endpoint,
    method: 'get',
    queryParams: __assign(__assign(__assign(__assign(__assign({}, idsArray !== null ? {
      id: idsArray
    } : {}), limit !== null ? {
      limit: limit
    } : {}), offset !== null ? {
      offset: offset
    } : {}), genre !== null ? {
      genre: genre
    } : {}), withUsers ? {
      with_users: withUsers
    } : {})
  };
  return req;
};
var getPlaylists = function getPlaylists(limit, offset, idsArray, targetUserId, withUsers) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (idsArray === void 0) {
    idsArray = null;
  }
  if (targetUserId === void 0) {
    targetUserId = null;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  if (idsArray != null) {
    if (!Array.isArray(idsArray)) {
      throw new Error('Expected integer array of user ids');
    }
  }
  return {
    endpoint: 'playlists',
    queryParams: __assign(__assign(__assign({
      limit: limit,
      offset: offset
    }, idsArray != null ? {
      playlist_id: idsArray
    } : {}), targetUserId ? {
      user_id: targetUserId
    } : {}), withUsers ? {
      with_users: true
    } : {})
  };
};
var getFullPlaylist = function getFullPlaylist(encodedPlaylistId, encodedUserId) {
  return {
    endpoint: 'v1/full/playlists',
    urlParams: '/' + encodedPlaylistId,
    queryParams: {
      user_id: encodedUserId
    }
  };
};
var getSocialFeed = function getSocialFeed(filter, limit, offset, withUsers, tracksOnly) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  if (tracksOnly === void 0) {
    tracksOnly = false;
  }
  return {
    endpoint: 'feed',
    queryParams: {
      filter: filter,
      limit: limit,
      offset: offset,
      with_users: withUsers,
      tracks_only: tracksOnly
    }
  };
};
var getUserRepostFeed = function getUserRepostFeed(userId, limit, offset, withUsers) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: 'feed',
    urlParams: '/reposts/' + userId,
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getFollowIntersectionUsers = function getFollowIntersectionUsers(limit, offset, followeeUserId, followerUserId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/intersection/follow/' + followeeUserId + '/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getTrackRepostIntersectionUsers = function getTrackRepostIntersectionUsers(limit, offset, repostTrackId, followerUserId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/intersection/repost/track/' + repostTrackId + '/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getPlaylistRepostIntersectionUsers = function getPlaylistRepostIntersectionUsers(limit, offset, repostPlaylistId, followerUserId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/intersection/repost/playlist/' + repostPlaylistId + '/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getFollowersForUser = function getFollowersForUser(limit, offset, followeeUserId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/followers/' + followeeUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getFolloweesForUser = function getFolloweesForUser(limit, offset, followerUserId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/followees/' + followerUserId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getRepostersForTrack = function getRepostersForTrack(limit, offset, repostTrackId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/reposts/track/' + repostTrackId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getRepostersForPlaylist = function getRepostersForPlaylist(limit, offset, repostPlaylistId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/reposts/playlist/' + repostPlaylistId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getSaversForTrack = function getSaversForTrack(limit, offset, saveTrackId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/saves/track/' + saveTrackId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getSaversForPlaylist = function getSaversForPlaylist(limit, offset, savePlaylistId) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'users',
    urlParams: '/saves/playlist/' + savePlaylistId,
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var searchFull = function searchFull(text, kind, limit, offset) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'search/full',
    queryParams: {
      query: text,
      kind: kind,
      limit: limit,
      offset: offset
    }
  };
};
var searchAutocomplete = function searchAutocomplete(text, limit, offset) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'search/autocomplete',
    queryParams: {
      query: text,
      limit: limit,
      offset: offset
    }
  };
};
var searchTags = function searchTags(text, userTagCount, kind, limit, offset) {
  if (userTagCount === void 0) {
    userTagCount = 2;
  }
  if (kind === void 0) {
    kind = 'all';
  }
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: 'search/tags',
    queryParams: {
      query: text,
      user_tag_count: userTagCount,
      kind: kind,
      limit: limit,
      offset: offset
    }
  };
};
var getSavedPlaylists = function getSavedPlaylists(limit, offset, withUsers) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: 'saves/playlists',
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getSavedAlbums = function getSavedAlbums(limit, offset, withUsers) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: 'saves/albums',
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getSavedTracks = function getSavedTracks(limit, offset, withUsers) {
  if (limit === void 0) {
    limit = 100;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: 'saves/tracks',
    queryParams: {
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
/**
 * Return user collections (saved & uploaded) along w/ users for those collections
 */
var getUserAccount = function getUserAccount(wallet) {
  if (wallet === undefined) {
    throw new Error('Expected wallet to get user account');
  }
  return {
    endpoint: 'users/account',
    queryParams: {
      wallet: wallet
    }
  };
};
/**
 * @deprecated Migrate to using getTopFullPlaylists
 */
var getTopPlaylists = function getTopPlaylists(type, limit, mood, filter, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: "/top/".concat(type),
    queryParams: {
      limit: limit,
      mood: mood,
      filter: filter,
      with_users: withUsers
    }
  };
};
var getTopFullPlaylists = function getTopFullPlaylists(_a) {
  var type = _a.type,
    limit = _a.limit,
    mood = _a.mood,
    filter = _a.filter,
    encodedUserId = _a.encodedUserId,
    _b = _a.withUsers,
    withUsers = _b === void 0 ? false : _b;
  return {
    endpoint: "/v1/full/playlists/top",
    queryParams: {
      type: type,
      limit: limit,
      mood: mood,
      filter: filter,
      with_users: withUsers,
      user_id: encodedUserId
    }
  };
};
/**
 * @deprecated Migrate to using getBestNewReleases
 */
var getTopFolloweeWindowed = function getTopFolloweeWindowed(type, window, limit, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: "/top_followee_windowed/".concat(type, "/").concat(window),
    queryParams: {
      limit: limit,
      with_users: withUsers
    }
  };
};
var getBestNewReleases = function getBestNewReleases(window, limit, encodedUserId, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: "/v1/full/tracks/best_new_releases",
    queryParams: {
      window: window,
      limit: limit,
      user_id: encodedUserId,
      with_users: withUsers
    }
  };
};
var getMostLovedTracks = function getMostLovedTracks(encodedUserId, limit, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: "/v1/full/tracks/most_loved",
    queryParams: {
      limit: limit,
      user_id: encodedUserId,
      with_users: withUsers
    }
  };
};
var getFeelingLuckyTracks = function getFeelingLuckyTracks(encodedUserId, limit, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: "/v1/full/tracks/feeling_lucky",
    queryParams: {
      limit: limit,
      user_id: encodedUserId,
      with_users: withUsers
    }
  };
};
var getTopFolloweeSaves = function getTopFolloweeSaves(type, limit, withUsers) {
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: "/top_followee_saves/".concat(type),
    queryParams: {
      limit: limit,
      with_users: withUsers
    }
  };
};
var getLatest = function getLatest(type, limit, offset) {
  if (limit === void 0) {
    limit = 1;
  }
  if (offset === void 0) {
    offset = 0;
  }
  return {
    endpoint: "/latest/".concat(type),
    queryParams: {
      limit: limit,
      offset: offset
    }
  };
};
var getTopCreatorsByGenres = function getTopCreatorsByGenres(genres, limit, offset, withUsers) {
  if (limit === void 0) {
    limit = 30;
  }
  if (offset === void 0) {
    offset = 0;
  }
  if (withUsers === void 0) {
    withUsers = false;
  }
  return {
    endpoint: 'users/genre/top',
    queryParams: {
      genre: genres,
      limit: limit,
      offset: offset,
      with_users: withUsers
    }
  };
};
var getURSMContentNodes = function getURSMContentNodes(ownerWallet) {
  return {
    endpoint: 'ursm_content_nodes',
    queryParams: {
      owner_wallet: ownerWallet
    }
  };
};
var getNotifications = function getNotifications(minBlockNumber, trackIds, timeout) {
  return {
    endpoint: 'notifications',
    queryParams: {
      min_block_number: minBlockNumber,
      track_id: trackIds
    },
    timeout: timeout
  };
};
var getUserNotifications = function getUserNotifications(_a) {
  var encodedUserId = _a.encodedUserId,
    timestamp = _a.timestamp,
    groupId = _a.groupId,
    limit = _a.limit,
    validTypes = _a.validTypes;
  return {
    endpoint: "v1/full/notifications/".concat(encodedUserId),
    queryParams: {
      timestamp: timestamp,
      group_id: groupId,
      limit: limit,
      valid_types: validTypes
    }
  };
};
var getUserSubscribers = function getUserSubscribers(encodedUserId, timeout) {
  return {
    endpoint: "v1/full/users/".concat(encodedUserId, "/subscribers"),
    method: 'get',
    timeout: timeout
  };
};
var bulkGetUserSubscribers = function bulkGetUserSubscribers(encodedUserIds, timeout) {
  return {
    endpoint: 'v1/full/users/subscribers',
    method: 'post',
    headers: {
      'Content-Type': 'application/json'
    },
    data: {
      ids: encodedUserIds
    },
    timeout: timeout
  };
};
var getCIDData = function getCIDData(cid, responseType, timeout) {
  if (responseType === void 0) {
    responseType = 'json';
  }
  return {
    endpoint: "v1/full/cid_data/".concat(cid),
    method: 'get',
    responseType: responseType,
    timeout: timeout
  };
};
var getSolanaNotifications = function getSolanaNotifications(minSlotNumber, timeout) {
  return {
    endpoint: 'solana_notifications',
    queryParams: {
      min_slot_number: minSlotNumber
    },
    timeout: timeout
  };
};
var getTrackListenMilestones = function getTrackListenMilestones(timeout) {
  return {
    endpoint: 'track_listen_milestones',
    timeout: timeout
  };
};
var getChallengeAttestation = function getChallengeAttestation(challengeId, encodedUserId, specifier, oracleAddress) {
  return {
    endpoint: "/v1/challenges/".concat(challengeId, "/attest"),
    queryParams: {
      user_id: encodedUserId,
      specifier: specifier,
      oracle: oracleAddress
    }
  };
};
var getCreateSenderAttestation = function getCreateSenderAttestation(senderEthAddress) {
  return {
    endpoint: '/v1/challenges/attest_sender',
    queryParams: {
      sender_eth_address: senderEthAddress
    }
  };
};
var getUndisbursedChallenges = function getUndisbursedChallenges(limit, offset, completedBlockNumber, encodedUserId) {
  return {
    endpoint: '/v1/challenges/undisbursed',
    queryParams: {
      limit: limit,
      offset: offset,
      completed_blocknumber: completedBlockNumber,
      user_id: encodedUserId
    }
  };
};
var verifyToken = function verifyToken(token) {
  return {
    endpoint: '/v1/users/verify_token',
    queryParams: {
      token: token
    }
  };
};
var getUserReplicaSet = function getUserReplicaSet(encodedUserId) {
  return {
    endpoint: "/v1/full/users/".concat(encodedUserId, "/replica_set"),
    timeout: 5000
  };
};
var getUnclaimedId = function getUnclaimedId(type) {
  return {
    endpoint: "/v1/".concat(type, "/unclaimed_id"),
    timeout: 5000,
    queryParams: {
      noCache: Math.floor(Math.random() * 1000).toString()
    }
  };
};
var getUserListenCountsMonthly = function getUserListenCountsMonthly(encodedUserId, startTime, endTime) {
  return {
    endpoint: "/v1/users/".concat(encodedUserId, "/listen_counts_monthly"),
    timeout: 10000,
    queryParams: {
      start_time: startTime,
      end_time: endTime
    }
  };
};

var requests = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getUsers: getUsers,
    getTracks: getTracks,
    getTracksByHandleAndSlug: getTracksByHandleAndSlug,
    getTracksIncludingUnlisted: getTracksIncludingUnlisted,
    getRandomTracks: getRandomTracks,
    getStemsForTrack: getStemsForTrack,
    getRemixesOfTrack: getRemixesOfTrack,
    getRemixTrackParents: getRemixTrackParents,
    getTrendingTracks: getTrendingTracks,
    getPlaylists: getPlaylists,
    getFullPlaylist: getFullPlaylist,
    getSocialFeed: getSocialFeed,
    getUserRepostFeed: getUserRepostFeed,
    getFollowIntersectionUsers: getFollowIntersectionUsers,
    getTrackRepostIntersectionUsers: getTrackRepostIntersectionUsers,
    getPlaylistRepostIntersectionUsers: getPlaylistRepostIntersectionUsers,
    getFollowersForUser: getFollowersForUser,
    getFolloweesForUser: getFolloweesForUser,
    getRepostersForTrack: getRepostersForTrack,
    getRepostersForPlaylist: getRepostersForPlaylist,
    getSaversForTrack: getSaversForTrack,
    getSaversForPlaylist: getSaversForPlaylist,
    searchFull: searchFull,
    searchAutocomplete: searchAutocomplete,
    searchTags: searchTags,
    getSavedPlaylists: getSavedPlaylists,
    getSavedAlbums: getSavedAlbums,
    getSavedTracks: getSavedTracks,
    getUserAccount: getUserAccount,
    getTopPlaylists: getTopPlaylists,
    getTopFullPlaylists: getTopFullPlaylists,
    getTopFolloweeWindowed: getTopFolloweeWindowed,
    getBestNewReleases: getBestNewReleases,
    getMostLovedTracks: getMostLovedTracks,
    getFeelingLuckyTracks: getFeelingLuckyTracks,
    getTopFolloweeSaves: getTopFolloweeSaves,
    getLatest: getLatest,
    getTopCreatorsByGenres: getTopCreatorsByGenres,
    getURSMContentNodes: getURSMContentNodes,
    getNotifications: getNotifications,
    getUserNotifications: getUserNotifications,
    getUserSubscribers: getUserSubscribers,
    bulkGetUserSubscribers: bulkGetUserSubscribers,
    getCIDData: getCIDData,
    getSolanaNotifications: getSolanaNotifications,
    getTrackListenMilestones: getTrackListenMilestones,
    getChallengeAttestation: getChallengeAttestation,
    getCreateSenderAttestation: getCreateSenderAttestation,
    getUndisbursedChallenges: getUndisbursedChallenges,
    verifyToken: verifyToken,
    getUserReplicaSet: getUserReplicaSet,
    getUnclaimedId: getUnclaimedId,
    getUserListenCountsMonthly: getUserListenCountsMonthly
});

function _typeof(o) {
  "@babel/helpers - typeof";

  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, _typeof(o);
}

/**
 * Converts a BN to a Uint8Array of length 8, in little endian notation.
 * Useful for when Rust wants a u64 (8 * 8) represented as a byte array.
 * Ex: https://github.com/AudiusProject/audius-protocol/blob/main/solana-programs/reward-manager/program/src/processor.rs#L389
 */
var padBNToUint8Array = function padBNToUint8Array(bn) {
  return bn.toArray('le', 8);
};

var SolanaUtils = /** @class */function () {
  function SolanaUtils() {}
  /**
   * Signs arbitrary bytes
   */
  SolanaUtils.signBytes = function (bytes, ethPrivateKey) {
    var msgHash = keccak256(bytes);
    var ethPrivateKeyArr = Buffer.from(ethPrivateKey, 'hex');
    var signatureObj = secp256k1.ecdsaSign(Uint8Array.from(msgHash), ethPrivateKeyArr);
    var signature = Buffer.from(signatureObj.signature);
    return {
      signature: signature,
      recoveryId: signatureObj.recid
    };
  };
  /**
   * Puts an instruction in a serializable form that our relay can understand.
   * Note we are faking the return type for callers to work with it easier
   */
  SolanaUtils.prepareInstructionForRelay = function (instruction) {
    return {
      programId: instruction.programId.toString(),
      data: instruction.data,
      keys: instruction.keys.map(function (_a) {
        var isSigner = _a.isSigner,
          pubkey = _a.pubkey,
          isWritable = _a.isWritable;
        return {
          pubkey: pubkey.toString(),
          isSigner: isSigner,
          isWritable: isWritable
        };
      })
    };
  };
  /**
   * Constructs a transfer ID
   */
  SolanaUtils.constructTransferId = function (challengeId, specifier) {
    return "".concat(challengeId, ":").concat(specifier);
  };
  /**
   * Constructs an attestation from inputs.
   */
  SolanaUtils.constructAttestation = function (recipientEthAddress, tokenAmount, transferId, oracleAddress) {
    var encoder = new TextEncoder();
    var userBytes = SolanaUtils.ethAddressToArray(recipientEthAddress);
    var transferIdBytes = encoder.encode(transferId);
    var amountBytes = padBNToUint8Array(tokenAmount);
    var items = oracleAddress ? [userBytes, amountBytes, transferIdBytes, SolanaUtils.ethAddressToArray(oracleAddress)] : [userBytes, amountBytes, transferIdBytes];
    var sep = encoder.encode('_');
    var res = items.slice(1).reduce(function (prev, cur) {
      return Uint8Array.of.apply(Uint8Array, __spreadArray(__spreadArray(__spreadArray([], __read(prev), false), __read(sep), false), __read(cur), false));
    }, Uint8Array.from(items[0]));
    return res;
  };
  /**
   * Converts "UI" wAudio (i.e. 5) into properly denominated BN representation - (i.e. 5 * 10 ^ 8)
   */
  SolanaUtils.uiAudioToBNWaudio = function (amount) {
    return new BN(amount * Math.pow(10, WAUDIO_DECIMALS));
  };
  /**
   * Derives a program address from a program ID and pubkey as seed.
   * Optionally takes in seeds.
   * Returns the new pubkey and bump seeds.
   */
  SolanaUtils.findProgramAddressFromPubkey = function (programId, pubkey, seed) {
    return __awaiter(this, void 0, void 0, function () {
      var seedsArr;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            seedsArr = [pubkey.toBytes().slice(0, 32)];
            if (seed) {
              seedsArr.push(seed);
            }
            return [4 /*yield*/, PublicKey.findProgramAddress(seedsArr, programId)];
          case 1:
            return [2 /*return*/, _a.sent()];
        }
      });
    });
  };
  /**
   * Finds a program address, using both seeds, pubkey, and the derived authority.
   * Return [authority, derivedAddress, and bumpSeeds]
   *
   */
  SolanaUtils.findProgramAddressWithAuthority = function (programId, address, seed) {
    return __awaiter(this, void 0, void 0, function () {
      var _a, authority, _b, derivedAddress, bumpSeed;
      return __generator(this, function (_c) {
        switch (_c.label) {
          case 0:
            return [4 /*yield*/, SolanaUtils.findProgramAddressFromPubkey(programId, address)];
          case 1:
            _a = __read.apply(void 0, [_c.sent(), 1]), authority = _a[0];
            return [4 /*yield*/, SolanaUtils.findProgramAddressFromPubkey(programId, authority, seed)];
          case 2:
            _b = __read.apply(void 0, [_c.sent(), 2]), derivedAddress = _b[0], bumpSeed = _b[1];
            return [2 /*return*/, [authority, derivedAddress, bumpSeed]];
        }
      });
    });
  };
  /**
   * Converts an eth address hex represenatation to an array of Uint8s in big endian notation
   * @param ethAddress
   */
  SolanaUtils.ethAddressToArray = function (ethAddress) {
    var strippedEthAddress = ethAddress.replace('0x', '');
    // Need to pad the array to length 20 - otherwise, hex eth keys starting with '0' would
    // result in truncated arrays, while eth spec is always 20 bytes
    return Uint8Array.of.apply(Uint8Array, __spreadArray([], __read(new BN(strippedEthAddress, 'hex').toArray('be', 20)), false));
  };
  // Safely create pubkey from nullable val
  SolanaUtils.newPublicKeyNullable = function (val) {
    return val ? new PublicKey(val) : null;
  };
  return SolanaUtils;
}();

/**
 * Handles sending Solana transactions, either directly via `sendAndConfirmTransaction`,
 * or via IdentityService's relay.
 */
var TransactionHandler = /** @class */function () {
  /**
   * Creates an instance of TransactionHandler.
   */
  function TransactionHandler(_a) {
    var connection = _a.connection,
      useRelay = _a.useRelay,
      _b = _a.identityService,
      identityService = _b === void 0 ? null : _b,
      _c = _a.feePayerKeypairs,
      feePayerKeypairs = _c === void 0 ? null : _c,
      _d = _a.skipPreflight,
      skipPreflight = _d === void 0 ? true : _d,
      _e = _a.retryTimeoutMs,
      retryTimeoutMs = _e === void 0 ? 60000 : _e,
      _f = _a.pollingFrequencyMs,
      pollingFrequencyMs = _f === void 0 ? 2000 : _f,
      _g = _a.sendingFrequencyMs,
      sendingFrequencyMs = _g === void 0 ? 2000 : _g,
      _h = _a.fallbackConnections,
      fallbackConnections = _h === void 0 ? null : _h;
    this.connection = connection;
    this.useRelay = useRelay;
    this.identityService = identityService;
    this.feePayerKeypairs = feePayerKeypairs;
    this.skipPreflight = skipPreflight;
    this.retryTimeoutMs = retryTimeoutMs;
    this.pollingFrequencyMs = pollingFrequencyMs;
    this.sendingFrequencyMs = sendingFrequencyMs;
    this.fallbackConnections = fallbackConnections;
  }
  /**
   * Primary method to send a Solana transaction.
   */
  TransactionHandler.prototype.handleTransaction = function (_a) {
    var instructions = _a.instructions,
      _b = _a.errorMapping,
      errorMapping = _b === void 0 ? null : _b,
      _c = _a.recentBlockhash,
      recentBlockhash = _c === void 0 ? null : _c,
      _d = _a.logger,
      logger = _d === void 0 ? console : _d,
      _e = _a.skipPreflight,
      skipPreflight = _e === void 0 ? false : _e,
      _f = _a.feePayerOverride,
      feePayerOverride = _f === void 0 ? null : _f,
      _g = _a.sendBlockhash,
      sendBlockhash = _g === void 0 ? false : _g,
      _h = _a.signatures,
      signatures = _h === void 0 ? null : _h,
      _j = _a.lookupTableAddresses,
      lookupTableAddresses = _j === void 0 ? [] : _j,
      _k = _a.retry,
      retry = _k === void 0 ? true : _k;
    return __awaiter(this, void 0, void 0, function () {
      var result;
      return __generator(this, function (_l) {
        switch (_l.label) {
          case 0:
            result = null;
            if (!this.useRelay) return [3 /*break*/, 2];
            return [4 /*yield*/, this._relayTransaction(instructions, recentBlockhash, skipPreflight, feePayerOverride, sendBlockhash, signatures, lookupTableAddresses, retry)];
          case 1:
            result = _l.sent();
            return [3 /*break*/, 4];
          case 2:
            return [4 /*yield*/, this._locallyConfirmTransaction(instructions, recentBlockhash, logger, feePayerOverride, signatures, lookupTableAddresses, retry)];
          case 3:
            result = _l.sent();
            _l.label = 4;
          case 4:
            if (result.error && result.errorCode !== null && errorMapping) {
              result.errorCode = errorMapping.fromErrorCode(result.errorCode);
            }
            return [2 /*return*/, result];
        }
      });
    });
  };
  TransactionHandler.prototype._relayTransaction = function (instructions, recentBlockhash, skipPreflight, feePayerOverride, sendBlockhash, signatures, lookupTableAddresses, retry) {
    var _a, _b, _c, _d;
    if (feePayerOverride === void 0) {
      feePayerOverride = null;
    }
    return __awaiter(this, void 0, void 0, function () {
      var relayable, transactionData, _e, _f, response, e_1, error, errorCode;
      return __generator(this, function (_g) {
        switch (_g.label) {
          case 0:
            relayable = instructions.map(SolanaUtils.prepareInstructionForRelay);
            transactionData = {
              signatures: signatures,
              instructions: relayable,
              skipPreflight: skipPreflight === null ? this.skipPreflight : skipPreflight,
              feePayerOverride: feePayerOverride ? feePayerOverride.toString() : null,
              lookupTableAddresses: lookupTableAddresses,
              retry: retry
            };
            if (!(sendBlockhash || Array.isArray(signatures))) return [3 /*break*/, 4];
            _e = transactionData;
            if (!(recentBlockhash !== null && recentBlockhash !== void 0)) return [3 /*break*/, 1];
            _f = recentBlockhash;
            return [3 /*break*/, 3];
          case 1:
            return [4 /*yield*/, this.connection.getLatestBlockhash('confirmed')];
          case 2:
            _f = _g.sent().blockhash;
            _g.label = 3;
          case 3:
            _e.recentBlockhash = _f;
            _g.label = 4;
          case 4:
            _g.trys.push([4, 6,, 7]);
            return [4 /*yield*/, (_a = this.identityService) === null || _a === void 0 ? void 0 : _a.solanaRelay(transactionData)];
          case 5:
            response = _g.sent();
            return [2 /*return*/, {
              res: (_b = response === null || response === void 0 ? void 0 : response.transactionSignature) !== null && _b !== void 0 ? _b : null,
              error: null,
              errorCode: null
            }];
          case 6:
            e_1 = _g.sent();
            error = null;
            if (_typeof(e_1) === 'object' && e_1 !== null) {
              error = ((_d = (_c = e_1.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.error) || e_1.message;
            }
            errorCode = error ? this._parseSolanaErrorCode(error) : null;
            return [2 /*return*/, {
              res: null,
              error: error,
              errorCode: errorCode
            }];
          case 7:
            return [2 /*return*/];
        }
      });
    });
  };
  TransactionHandler.prototype._locallyConfirmTransaction = function (instructions, recentBlockhash, logger, feePayerOverride, signatures, lookupTableAddresses, retry) {
    var _a, _b, _c, _d;
    if (feePayerOverride === void 0) {
      feePayerOverride = null;
    }
    if (signatures === void 0) {
      signatures = null;
    }
    if (retry === void 0) {
      retry = true;
    }
    return __awaiter(this, void 0, void 0, function () {
      var txStartTime, feePayerKeypairOverride, feePayerAccount, feePayerPubKey, alreadySigned, _e, rawTransaction, txid, lookupTableAccounts, lookupTableAddresses_1, lookupTableAddresses_1_1, address, lookupTableAccount, e_2_1, message, tx_1, tx_2, sendRawTransaction, e_3, done, sendCount, startTime, e_4, fallbackConnection, errorCode, error;
      var e_2, _f;
      var _this = this;
      return __generator(this, function (_g) {
        switch (_g.label) {
          case 0:
            txStartTime = Date.now();
            feePayerKeypairOverride = function () {
              if (feePayerOverride && _this.feePayerKeypairs) {
                var stringFeePayer_1 = feePayerOverride.toString();
                return _this.feePayerKeypairs.find(function (keypair) {
                  return keypair.publicKey.toString() === stringFeePayer_1;
                });
              }
              return null;
            }();
            feePayerAccount = feePayerKeypairOverride !== null && feePayerKeypairOverride !== void 0 ? feePayerKeypairOverride : (_a = this.feePayerKeypairs) === null || _a === void 0 ? void 0 : _a[0];
            feePayerPubKey = (_b = feePayerAccount === null || feePayerAccount === void 0 ? void 0 : feePayerAccount.publicKey) !== null && _b !== void 0 ? _b : feePayerOverride ? new PublicKey(feePayerOverride) : null;
            alreadySigned = signatures === null || signatures === void 0 ? void 0 : signatures.some(function (s) {
              return s.publicKey === (feePayerOverride === null || feePayerOverride === void 0 ? void 0 : feePayerOverride.toString()) && !s.signature.every(function (b) {
                return b === 0;
              });
            });
            if (!feePayerPubKey || !feePayerAccount && !alreadySigned) {
              logger.error('transactionHandler: Local feepayer keys missing for direct confirmation!');
              return [2 /*return*/, {
                res: null,
                error: 'Missing keys',
                errorCode: null
              }];
            }
            if (!(recentBlockhash !== null && recentBlockhash !== void 0)) return [3 /*break*/, 1];
            _e = recentBlockhash;
            return [3 /*break*/, 3];
          case 1:
            return [4 /*yield*/, this.connection.getLatestBlockhash('confirmed')];
          case 2:
            _e = _g.sent().blockhash;
            _g.label = 3;
          case 3:
            // Get blockhash
            recentBlockhash = _e;
            if (!(lookupTableAddresses.length > 0)) return [3 /*break*/, 12];
            lookupTableAccounts = [];
            _g.label = 4;
          case 4:
            _g.trys.push([4, 9, 10, 11]);
            lookupTableAddresses_1 = __values(lookupTableAddresses), lookupTableAddresses_1_1 = lookupTableAddresses_1.next();
            _g.label = 5;
          case 5:
            if (!!lookupTableAddresses_1_1.done) return [3 /*break*/, 8];
            address = lookupTableAddresses_1_1.value;
            if (address === undefined) return [3 /*break*/, 7];
            return [4 /*yield*/, this.connection.getAddressLookupTable(new PublicKey(address))];
          case 6:
            lookupTableAccount = _g.sent();
            if (lookupTableAccount.value !== null) {
              lookupTableAccounts.push(lookupTableAccount.value);
            } else {
              // Abort if a lookup table account is missing because the resulting transaction
              // might be too large
              return [2 /*return*/, {
                res: null,
                error: "Missing lookup table account for address ".concat(address),
                errorCode: null
              }];
            }
            _g.label = 7;
          case 7:
            lookupTableAddresses_1_1 = lookupTableAddresses_1.next();
            return [3 /*break*/, 5];
          case 8:
            return [3 /*break*/, 11];
          case 9:
            e_2_1 = _g.sent();
            e_2 = {
              error: e_2_1
            };
            return [3 /*break*/, 11];
          case 10:
            try {
              if (lookupTableAddresses_1_1 && !lookupTableAddresses_1_1.done && (_f = lookupTableAddresses_1["return"])) _f.call(lookupTableAddresses_1);
            } finally {
              if (e_2) throw e_2.error;
            }
            return [7 /*endfinally*/];
          case 11:
            message = new TransactionMessage({
              payerKey: feePayerPubKey,
              recentBlockhash: recentBlockhash,
              instructions: instructions
            }).compileToV0Message(lookupTableAccounts);
            tx_1 = new VersionedTransaction(message);
            if (feePayerAccount) {
              tx_1.sign([feePayerAccount]);
            }
            if (Array.isArray(signatures)) {
              signatures.forEach(function (_a) {
                var publicKey = _a.publicKey,
                  signature = _a.signature;
                tx_1.addSignature(new PublicKey(publicKey), signature);
              });
            }
            txid = bs58.encode(tx_1.signatures[0]);
            rawTransaction = tx_1.serialize();
            return [3 /*break*/, 13];
          case 12:
            tx_2 = new Transaction();
            tx_2.recentBlockhash = recentBlockhash;
            instructions.forEach(function (i) {
              return tx_2.add(i);
            });
            tx_2.feePayer = feePayerPubKey;
            if (feePayerAccount) {
              tx_2.sign(feePayerAccount);
            }
            if (Array.isArray(signatures)) {
              signatures.forEach(function (_a) {
                var publicKey = _a.publicKey,
                  signature = _a.signature;
                tx_2.addSignature(new PublicKey(publicKey), signature);
              });
            }
            txid = bs58.encode(tx_2.signatures[0].signature);
            rawTransaction = tx_2.serialize();
            _g.label = 13;
          case 13:
            sendRawTransaction = function sendRawTransaction() {
              return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                  switch (_a.label) {
                    case 0:
                      return [4 /*yield*/, this.connection.sendRawTransaction(rawTransaction, {
                        skipPreflight: true,
                        preflightCommitment: 'processed',
                        maxRetries: 0
                      })];
                    case 1:
                      return [2 /*return*/, _a.sent()];
                  }
                });
              });
            };
            _g.label = 14;
          case 14:
            _g.trys.push([14, 16,, 17]);
            return [4 /*yield*/, sendRawTransaction()];
          case 15:
            _g.sent();
            return [3 /*break*/, 17];
          case 16:
            e_3 = _g.sent();
            // Rarely, this intiial send will fail
            logger.warn("transactionHandler: Initial send failed for txId ".concat(txid, ": ").concat(e_3));
            return [3 /*break*/, 17];
          case 17:
            done = false;
            sendCount = 0;
            startTime = Date.now();
            if (retry) {
              (function () {
                return __awaiter(_this, void 0, void 0, function () {
                  var elapsed;
                  return __generator(this, function (_a) {
                    switch (_a.label) {
                      case 0:
                        elapsed = Date.now() - startTime;
                        _a.label = 1;
                      case 1:
                        if (!(!done && elapsed < this.retryTimeoutMs)) return [3 /*break*/, 3];
                        try {
                          sendRawTransaction();
                        } catch (e) {
                          logger.warn("transactionHandler: error in send loop: ".concat(e, " for txId ").concat(txid));
                        }
                        sendCount++;
                        return [4 /*yield*/, delay(this.sendingFrequencyMs)];
                      case 2:
                        _a.sent();
                        elapsed = Date.now() - startTime;
                        return [3 /*break*/, 1];
                      case 3:
                        return [2 /*return*/];
                    }
                  });
                });
              })();
            }
            _g.label = 18;
          case 18:
            _g.trys.push([18, 20,, 21]);
            return [4 /*yield*/, this._awaitTransactionSignatureConfirmation(txid, logger)];
          case 19:
            _g.sent();
            done = true;
            logger.info("transactionHandler: finished sending txid ".concat(txid, " with ").concat(sendCount, " retries to ").concat(this.connection.rpcEndpoint, " in ").concat(Date.now() - txStartTime, " ms"));
            return [2 /*return*/, {
              res: txid,
              error: null,
              errorCode: null
            }];
          case 20:
            e_4 = _g.sent();
            fallbackConnection = (_d = sample((_c = this.fallbackConnections) === null || _c === void 0 ? void 0 : _c.filter(function (conn) {
              return conn.rpcEndpoint !== _this.connection.rpcEndpoint;
            }))) !== null && _d !== void 0 ? _d : this.connection;
            logger.warn("transactionHandler: error in awaitTransactionSignature: ".concat(JSON.stringify(e_4), ", ").concat(txid, ", with ").concat(sendCount, " retries to ").concat(this.connection.rpcEndpoint, " falling back to ").concat(fallbackConnection.rpcEndpoint));
            this.connection = fallbackConnection;
            done = true;
            errorCode = null;
            error = null;
            if (e_4 instanceof Error) {
              error = e_4.message;
              errorCode = this._parseSolanaErrorCode(error);
            }
            return [2 /*return*/, {
              res: null,
              error: error,
              errorCode: errorCode
            }];
          case 21:
            return [2 /*return*/];
        }
      });
    });
  };
  TransactionHandler.prototype._awaitTransactionSignatureConfirmation = function (txid, logger) {
    return __awaiter(this, void 0, void 0, function () {
      var done, result;
      var _this = this;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            done = false;
            return [4 /*yield*/, new Promise(function (resolve, reject) {
              (function () {
                return __awaiter(_this, void 0, void 0, function () {
                  var _this = this;
                  return __generator(this, function (_a) {
                    switch (_a.label) {
                      case 0:
                        // Setup timeout if nothing else finishes
                        setTimeout(function () {
                          if (done) {
                            return;
                          }
                          done = true;
                          var message = "transactionHandler: Timed out in await, ".concat(txid);
                          logger.warn(message);
                          reject(new Error(message));
                        }, this.retryTimeoutMs);
                        // Setup WS listener
                        try {
                          this.connection.onSignature(txid, function (result) {
                            if (done) return;
                            done = true;
                            if (result.err) {
                              var err = JSON.stringify(result.err);
                              logger.warn("transactionHandler: Error in onSignature ".concat(txid, ", ").concat(err));
                              reject(new Error(err));
                            } else {
                              resolve(txid);
                            }
                          }, 'processed');
                        } catch (e) {
                          done = true;
                          logger.error("transactionHandler: WS error in setup ".concat(txid, ", ").concat(e));
                        }
                        _a.label = 1;
                      case 1:
                        if (!!done) return [3 /*break*/, 3];
                        (function () {
                          return __awaiter(_this, void 0, void 0, function () {
                            var signatureStatuses, result_1, err, e_5;
                            return __generator(this, function (_a) {
                              switch (_a.label) {
                                case 0:
                                  _a.trys.push([0, 2,, 3]);
                                  return [4 /*yield*/, this.connection.getSignatureStatuses([txid])];
                                case 1:
                                  signatureStatuses = _a.sent();
                                  result_1 = signatureStatuses === null || signatureStatuses === void 0 ? void 0 : signatureStatuses.value[0];
                                  // Early return this iteration if already done, or no result
                                  if (done || !result_1) return [2 /*return*/];
                                  // End loop if error
                                  if (result_1.err) {
                                    err = JSON.stringify(result_1.err);
                                    logger.error("transactionHandler: polling saw result error: ".concat(err, ", tx: ").concat(txid));
                                    done = true;
                                    reject(new Error(err));
                                    return [2 /*return*/];
                                  }
                                  // Early return if response without confirmation
                                  if (!(result_1.confirmations !== null && result_1.confirmations !== 0 || result_1.confirmationStatus === 'confirmed' || result_1.confirmationStatus === 'finalized')) {
                                    return [2 /*return*/];
                                  }
                                  // Otherwise, we made it
                                  done = true;
                                  resolve(txid);
                                  return [3 /*break*/, 3];
                                case 2:
                                  e_5 = _a.sent();
                                  if (!done) {
                                    logger.error("transactionHandler: REST polling connection error: ".concat(e_5, ", tx: ").concat(txid));
                                  }
                                  return [3 /*break*/, 3];
                                case 3:
                                  return [2 /*return*/];
                              }
                            });
                          });
                        })();
                        return [4 /*yield*/, delay(this.pollingFrequencyMs)];
                      case 2:
                        _a.sent();
                        return [3 /*break*/, 1];
                      case 3:
                        return [2 /*return*/];
                    }
                  });
                });
              })();
            })];
          case 1:
            result = _a.sent();
            done = true;
            return [2 /*return*/, result];
        }
      });
    });
  };
  /**
   * Attempts to parse an error code out of a message of the form:
   * "... custom program error: 0x1", where the return in this case would be the number 1.
   * Returns null for unparsable strings.
   */
  TransactionHandler.prototype._parseSolanaErrorCode = function (errorMessage) {
    if (!errorMessage) return null;
    // Match on custom solana program errors
    var matcher = /(?:custom program error: 0x)(.*)$/;
    var res = errorMessage.match(matcher);
    if (res && res.length === 2) return res[1] ? parseInt(res[1], 16) || null : null;
    // Match on custom anchor errors
    var matcher2 = /(?:"Custom":)(\d+)/;
    var res2 = errorMessage.match(matcher2);
    if (res2 && res2.length === 2) return res2[1] ? parseInt(res2[1], 10) || null : null;
    return null;
  };
  return TransactionHandler;
}();
function delay(ms) {
  return __awaiter(this, void 0, void 0, function () {
    return __generator(this, function (_a) {
      switch (_a.label) {
        case 0:
          return [4 /*yield*/, new Promise(function (resolve) {
            return setTimeout(resolve, ms);
          })];
        case 1:
          return [2 /*return*/, _a.sent()];
      }
    });
  });
}

export { AUDIO_DECIMALS, AuthHeaders, CURRENT_USER_EXISTS_LOCAL_STORAGE_KEY, requests as DiscoveryAPI, requests$1 as IdentityAPI, TransactionHandler, USDC_DECIMALS, WAUDIO_DECIMALS };
//# sourceMappingURL=core.js.map
