All files / src bee.ts

85.22% Statements 346/406
58.16% Branches 57/98
88.39% Functions 99/112
85.11% Lines 343/403

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 196433x   33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x                                                                                                         33x                   33x 33x 33x 33x 33x   33x 33x 33x   33x 33x 33x                                 33x                           33x               33x                                                     36x         36x   36x       36x   36x                                                     53x 53x   53x 4x     53x                                                               71x       71x                                   2x       2x                                       16x   16x       16x       16x       16x                                   12x   12x       12x                                   1x 3x   1x                           2x   2x                                       1x 1x 1x   1x 1x 2x     1x                                                         18x 18x   18x 11x     18x       18x 1x 1x 1x 1x   1x               17x                                           5x 1x     5x                                         1x   1x       1x                                                 3x   3x 2x     3x   3x       1x                   1x   1x                                                                                         2x 2x   2x 1x     2x                                                 1x   1x       1x   1x                     2x                               824x 823x     824x                             2x   2x                             1x   1x                                                                       1x   1x                         2x   2x                   4x                           1x   1x                                     1x 1x   1x                                 1x   1x                                                 11x 11x   11x       11x 2x 2x   2x                       9x                                                                               1x 1x   1x         1x                                     1x   1x   1x 1x 1x 1x         1x 1x             1x         1x 1x   1x 1x     1x             1x                                                       1x       1x   1x             1x 1x 1x       1x 1x                         1x 1x 1x 1x 470x 470x 470x   470x 1x                           1x 1x 1x   1x 1x   1x               2x 2x 2x   2x   2x   2x 2x 2x 2x   2x 2x             2x         2x 1x   1x 1x     2x 1x         2x                                             2x 2x 2x   2x       2x                                 3x 3x   3x                                 7x 7x   7x       7x               1x 1x   1x                     2x   2x                           1x   1x       1x                     1x 1x   1x                   1x                   1x 1x         1x           4x                     1x                   1x                                 1x                 1x   1x             1x                       1x   1x                           1x             1x             1x                       1x   1x                       1x   1x                                                                           1x       1x       1x                                 1x       1x       1x                         1x   1x             1x             1x             1x             1x             1x                 1x                       1x                                 1x             12x                 1x                                                   7x   7x 2x     7x 2x     5x 5x   5x 2x           3x             3x 2x     3x                 2x 2x 2x   2x 1x     2x       1x 1x 1x   1x       3x 3x 3x   3x 1x     2x   2x               1x 1x 1x   1x                 1x 1x 1x 1x   1x 1x   1x               2x 2x 2x   2x 1x     1x 1x   1x               1x 1x 1x   1x                                         4x 4x   4x                                           3x 3x   3x                             78x   78x                             1x   1x                   1x             1x             24x                     1x   1x                                                                                         4x                                 2x   2x       2x                 1x       2x 2x 32x 32x   2x 2x           30x             1220x 36x     1220x      
import { Binary, Objects, System, Types } from 'cafe-utility'
import { Readable } from 'stream'
import { Chunk, makeContentAddressedChunk } from './chunk/cac'
import { downloadSingleOwnerChunk, makeSOCAddress, makeSingleOwnerChunk, uploadSingleOwnerChunkData } from './chunk/soc'
import { makeFeedReader, makeFeedWriter } from './feed'
import { areAllSequentialFeedsUpdateRetrievable } from './feed/retrievable'
import * as bytes from './modules/bytes'
import * as bzz from './modules/bzz'
import * as chunk from './modules/chunk'
import * as balance from './modules/debug/balance'
import * as chequebook from './modules/debug/chequebook'
import * as connectivity from './modules/debug/connectivity'
import * as settlements from './modules/debug/settlements'
import * as stake from './modules/debug/stake'
import * as stamps from './modules/debug/stamps'
import * as states from './modules/debug/states'
import * as debugStatus from './modules/debug/status'
import * as transactions from './modules/debug/transactions'
import { postEnvelope } from './modules/envelope'
import { FeedPayloadResult, createFeedManifest, fetchLatestFeedUpdate } from './modules/feed'
import * as grantee from './modules/grantee'
import * as gsoc from './modules/gsoc'
import * as pinning from './modules/pinning'
import * as pss from './modules/pss'
import * as status from './modules/status'
import * as stewardship from './modules/stewardship'
import * as tag from './modules/tag'
import type {
  AllSettlements,
  BalanceResponse,
  BeeOptions,
  BeeRequestOptions,
  BeeVersions,
  ChainState,
  ChequebookAddressResponse,
  ChequebookBalanceResponse,
  CollectionUploadOptions,
  DebugStatus,
  DownloadOptions,
  EnvelopeWithBatchId,
  FeedReader,
  FeedWriter,
  FileData,
  FileUploadOptions,
  GetGranteesResult,
  GlobalPostageBatch,
  GranteesResult,
  GsocMessageHandler,
  GsocSubscription,
  Health,
  LastCashoutActionResponse,
  LastChequesForPeerResponse,
  LastChequesResponse,
  NodeAddresses,
  NodeInfo,
  NumberString,
  Peer,
  PeerBalance,
  Pin,
  PingResponse,
  PostageBatch,
  PostageBatchBuckets,
  PssMessageHandler,
  PssSubscription,
  Readiness,
  RedistributionState,
  RedundantUploadOptions,
  ReferenceInformation,
  RemovePeerResponse,
  ReserveState,
  SOCReader,
  SOCWriter,
  Settlements,
  Tag,
  Topology,
  TransactionInfo,
  UploadOptions,
  WalletBalance,
} from './types'
import {
  AllTagsOptions,
  CHUNK_SIZE,
  Collection,
  PostageBatchOptions,
  STAMPS_DEPTH_MAX,
  STAMPS_DEPTH_MIN,
  TransactionOptions,
  UploadResult,
} from './types'
import { Bytes } from './utils/bytes'
import { hashDirectory, streamDirectory, streamFiles } from './utils/chunk-stream'
import { assertCollection, makeCollectionFromFileList } from './utils/collection'
import { makeCollectionFromFS } from './utils/collection.node'
import { prepareWebsocketData } from './utils/data'
import { Duration } from './utils/duration'
import { BeeArgumentError, BeeError } from './utils/error'
import { fileArrayBuffer, isFile } from './utils/file'
import { ResourceLocator } from './utils/resource-locator'
import { Size } from './utils/size'
import { getAmountForDuration, getDepthForSize, getStampCost } from './utils/stamps'
import { BZZ } from './utils/tokens'
import {
  asNumberString,
  assertData,
  assertFileData,
  makeTagUid,
  prepareAllTagsOptions,
  prepareBeeRequestOptions,
  prepareCollectionUploadOptions,
  prepareDownloadOptions,
  prepareFileUploadOptions,
  prepareGsocMessageHandler,
  preparePostageBatchOptions,
  preparePssMessageHandler,
  prepareRedundantUploadOptions,
  prepareTransactionOptions,
  prepareUploadOptions,
} from './utils/type'
import {
  BatchId,
  EthAddress,
  FeedIndex,
  Identifier,
  PeerAddress,
  PrivateKey,
  PublicKey,
  Reference,
  Span,
  Topic,
  TransactionId,
} from './utils/typed-bytes'
import { UploadProgress } from './utils/upload-progress'
import { assertBeeUrl, stripLastSlash } from './utils/url'
 
/**
 * The main component that abstracts operations available on the main Bee API.
 *
 * Not all methods are always available as it depends in what mode is Bee node launched in.
 * For example gateway mode and light node mode has only limited set of endpoints enabled.
 */
export class Bee {
  /**
   * URL on which is the main API of Bee node exposed
   */
  public readonly url: string
 
  /**
   * Default Signer object used for signing operations, mainly Feeds.
   */
  public readonly signer?: PrivateKey
 
  /**
   * Network on which the Bee node is running
   */
  public readonly network: 'gnosis' | 'sepolia'
 
  /**
   * Options for making requests
   * @private
   */
  private readonly requestOptions: BeeRequestOptions
 
  /**
   * @param url URL on which is the main API of Bee node exposed
   * @param options
   */
  constructor(url: string, options?: BeeOptions) {
    assertBeeUrl(url)
 
    // Remove last slash if present, as our endpoint strings starts with `/...`
    // which could lead to double slash in URL to which Bee responds with
    // unnecessary redirects.
    this.url = stripLastSlash(url)
 
    Iif (options?.signer) {
      this.signer = new PrivateKey(options.signer)
    }
 
    this.network = options?.network ?? 'gnosis'
 
    this.requestOptions = {
      baseURL: this.url,
      timeout: options?.timeout ?? 0,
      headers: options?.headers,
      onRequest: options?.onRequest,
      httpAgent: options?.httpAgent,
      httpsAgent: options?.httpsAgent,
    }
  }
 
  /**
   * Upload data to a Bee node
   *
   * @param postageBatchId Postage BatchId to be used to upload the data with
   * @param data    Data to be uploaded
   * @param options Additional options like tag, encryption, pinning, content-type and request options
   *
   * @returns reference is a content hash of the data
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `POST /bytes`](https://docs.ethswarm.org/api/#tag/Bytes/paths/~1bytes/post)
   */
  async uploadData(
    postageBatchId: BatchId | Uint8Array | string,
    data: string | Uint8Array,
    options?: RedundantUploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<UploadResult> {
    postageBatchId = new BatchId(postageBatchId)
    assertData(data)
 
    if (options) {
      options = prepareRedundantUploadOptions(options)
    }
 
    return bytes.upload(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options)
  }
 
  /**
   * Requests content length for a `/bytes` reference
   *
   * @see [Bee API reference - `HEAD /bytes/`](https://docs.ethswarm.org/api/#tag/Bytes/paths/~1bytes~1%7Breference%7D/head)
   */
  async probeData(
    reference: Reference | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<ReferenceInformation> {
    reference = new Reference(reference)
 
    return bytes.head(this.getRequestOptionsForCall(options), reference)
  }
 
  /**
   * Download data as a byte array
   *
   * @param resource Swarm reference, Swarm CID, or ENS domain
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `GET /bytes`](https://docs.ethswarm.org/api/#tag/Bytes/paths/~1bytes~1{reference}/get)
   */
  async downloadData(
    resource: Reference | string | Uint8Array,
    options?: DownloadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<Bytes> {
    Iif (options) {
      options = prepareDownloadOptions(options)
    }
 
    return bytes.download(this.getRequestOptionsForCall(requestOptions), new ResourceLocator(resource), options)
  }
 
  /**
   * Download data as a Readable stream
   *
   * @param resource Swarm reference, Swarm CID, or ENS domain
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `GET /bytes`](https://docs.ethswarm.org/api/#tag/Bytes/paths/~1bytes~1{reference}/get)
   */
  async downloadReadableData(
    resource: Reference | Uint8Array | string,
    options?: DownloadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<ReadableStream<Uint8Array>> {
    Iif (options) {
      options = prepareDownloadOptions(options)
    }
 
    return bytes.downloadReadable(this.getRequestOptionsForCall(requestOptions), new ResourceLocator(resource), options)
  }
 
  /**
   * Upload chunk to a Bee node
   *
   * @param postageBatchId Postage BatchId to be used to upload the chunk with
   * @param data    Raw chunk to be uploaded
   * @param options Additional options like tag, encryption, pinning, content-type and request options
   *
   * @returns reference is a content hash of the data
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `POST /chunks`](https://docs.ethswarm.org/api/#tag/Chunk/paths/~1chunks/post)
   */
  async uploadChunk(
    stamp: EnvelopeWithBatchId | BatchId | Uint8Array | string,
    data: Uint8Array | Chunk,
    options?: UploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<UploadResult> {
    data = data instanceof Uint8Array ? data : data.data
 
    Iif (options) {
      options = prepareUploadOptions(options)
    }
 
    Iif (data.length < Span.LENGTH) {
      throw new BeeArgumentError(`Chunk has to have size of at least ${Span.LENGTH}.`, data)
    }
 
    Iif (data.length > CHUNK_SIZE + Span.LENGTH) {
      throw new BeeArgumentError(`Chunk has to have size of at most ${CHUNK_SIZE + Span.LENGTH}.`, data)
    }
 
    return chunk.upload(this.getRequestOptionsForCall(requestOptions), data, stamp, options)
  }
 
  /**
   * Download chunk as a byte array
   *
   * @param reference Bee chunk reference in hex string (either 64 or 128 chars long) or ENS domain.
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `GET /chunks`](https://docs.ethswarm.org/api/#tag/Chunk/paths/~1chunks~1{address}/get)
   */
  async downloadChunk(
    reference: Reference | Uint8Array | string,
    options?: DownloadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<Uint8Array> {
    reference = new Reference(reference)
 
    Iif (options) {
      options = prepareDownloadOptions(options)
    }
 
    return chunk.download(this.getRequestOptionsForCall(requestOptions), reference, options)
  }
 
  /**
   * Create a grantees list from the given array of public keys.
   *
   * The grantees list can be obtained with the `getGrantees` method.
   *
   * @param postageBatchId - The ID of the postage batch.
   * @param grantees - An array of public keys representing the grantees.
   * @param requestOptions - Optional request options.
   * @returns A promise that resolves to a `GranteesResult` object.
   */
  async createGrantees(
    postageBatchId: BatchId | Uint8Array | string,
    grantees: PublicKey[] | Uint8Array[] | string[],
    requestOptions?: BeeRequestOptions,
  ): Promise<GranteesResult> {
    postageBatchId = new BatchId(postageBatchId)
    grantees = grantees.map(x => new PublicKey(x))
 
    return grantee.createGrantees(this.getRequestOptionsForCall(requestOptions), postageBatchId, grantees)
  }
 
  /**
   * Retrieves the grantees for a given reference.
   *
   * @param reference - The reference.
   * @param requestOptions - Optional request options.
   * @returns A promise that resolves to a `GetGranteesResult` object.
   */
  async getGrantees(
    reference: Reference | Uint8Array | string,
    requestOptions?: BeeRequestOptions,
  ): Promise<GetGranteesResult> {
    reference = new Reference(reference)
 
    return grantee.getGrantees(reference, this.getRequestOptionsForCall(requestOptions))
  }
 
  /**
   * Updates the grantees of a specific reference and history.
   *
   * @param reference - The reference.
   * @param history - The history.
   * @param postageBatchId - The ID of the postage batch.
   * @param grantees - The grantees.
   * @param requestOptions - Optional request options.
   * @returns A Promise that resolves to to a `GranteesResult` object.
   */
  async patchGrantees(
    postageBatchId: BatchId | Uint8Array | string,
    reference: Reference | Uint8Array | string,
    history: Reference | Uint8Array | string,
    grantees: { add?: PublicKey[] | Uint8Array[] | string[]; revoke?: PublicKey[] | Uint8Array[] | string[] },
    requestOptions?: BeeRequestOptions,
  ): Promise<GranteesResult> {
    postageBatchId = new BatchId(postageBatchId)
    reference = new Reference(reference)
    history = new Reference(history)
 
    const publicKeys = {
      add: grantees.add?.map(x => new PublicKey(x)) ?? [],
      revoke: grantees.revoke?.map(x => new PublicKey(x)) ?? [],
    }
 
    return grantee.patchGrantees(
      postageBatchId,
      reference,
      history,
      publicKeys,
      this.getRequestOptionsForCall(requestOptions),
    )
  }
 
  /**
   * Upload single file to a Bee node.
   *
   * @param postageBatchId Postage BatchId to be used to upload the data with
   * @param data    Data or file to be uploaded
   * @param name    Optional name of the uploaded file
   * @param options Additional options like tag, encryption, pinning, content-type and request options
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `POST /bzz`](https://docs.ethswarm.org/api/#tag/BZZ/paths/~1bzz/post)
   * @returns reference is a content hash of the file
   */
  async uploadFile(
    postageBatchId: BatchId | Uint8Array | string,
    data: string | Uint8Array | Readable | File,
    name?: string,
    options?: FileUploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<UploadResult> {
    postageBatchId = new BatchId(postageBatchId)
    assertFileData(data)
 
    if (options) {
      options = prepareFileUploadOptions(options)
    }
 
    Iif (name && typeof name !== 'string') {
      throw new TypeError('name has to be string or undefined!')
    }
 
    if (isFile(data)) {
      const fileData = await fileArrayBuffer(data)
      const fileName = name ?? data.name
      const contentType = data.type
      const fileOptions = { contentType, ...options }
 
      return bzz.uploadFile(
        this.getRequestOptionsForCall(requestOptions),
        fileData,
        postageBatchId,
        fileName,
        fileOptions,
      )
    } else {
      return bzz.uploadFile(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, name, options)
    }
  }
 
  /**
   * Download single file.
   *
   * @param resource Swarm reference, Swarm CID, or ENS domain
   * @param path If reference points to manifest, then this parameter defines path to the file
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   * @see Data
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `GET /bzz`](https://docs.ethswarm.org/api/#tag/BZZ/paths/~1bzz~1%7Breference%7D~1%7Bpath%7D/get)
   */
  async downloadFile(
    resource: Reference | Uint8Array | string,
    path = '',
    options?: DownloadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<FileData<Bytes>> {
    if (options) {
      options = prepareDownloadOptions(options)
    }
 
    return bzz.downloadFile(this.getRequestOptionsForCall(requestOptions), new ResourceLocator(resource), path, options)
  }
 
  /**
   * Download single file as a readable stream
   *
   * @param reference Bee file reference in hex string (either 64 or 128 chars long), ENS domain or Swarm CID.
   * @param path If reference points to manifest / collections, then this parameter defines path to the file
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   *
   * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download)
   * @see [Bee API reference - `GET /bzz`](https://docs.ethswarm.org/api/#tag/BZZ/paths/~1bzz~1%7Breference%7D~1%7Bpath%7D/get)
   */
  async downloadReadableFile(
    reference: Reference | Uint8Array | string,
    path = '',
    options?: DownloadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<FileData<ReadableStream<Uint8Array>>> {
    reference = new Reference(reference)
 
    Iif (options) {
      options = prepareDownloadOptions(options)
    }
 
    return bzz.downloadFileReadable(this.getRequestOptionsForCall(requestOptions), reference, path, options)
  }
 
  /**
   * Upload collection of files to a Bee node
   *
   * Uses the FileList API from the browser.
   *
   * The returned `UploadResult.tag` might be undefined if called in CORS-enabled environment.
   * This will be fixed upon next Bee release. https://github.com/ethersphere/bee-js/issues/406
   *
   * @param postageBatchId Postage BatchId to be used to upload the data with
   * @param fileList list of files to be uploaded
   * @param options Additional options like tag, encryption, pinning and request options
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee docs - Upload directory](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download#upload-a-directory)
   * @see [Bee API reference - `POST /bzz`](https://docs.ethswarm.org/api/#tag/BZZ/paths/~1bzz/post)
   */
  async uploadFiles(
    postageBatchId: BatchId | Uint8Array | string,
    fileList: FileList | File[],
    options?: CollectionUploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<UploadResult> {
    postageBatchId = new BatchId(postageBatchId)
 
    if (options) {
      options = prepareCollectionUploadOptions(options)
    }
 
    const data = makeCollectionFromFileList(fileList)
 
    return bzz.uploadCollection(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options)
  }
 
  async hashDirectory(dir: string) {
    return hashDirectory(dir)
  }
 
  async streamDirectory(
    postageBatchId: BatchId | Uint8Array | string,
    dir: string,
    onUploadProgress?: (progress: UploadProgress) => void,
    options?: UploadOptions,
    requestOptions?: BeeRequestOptions,
  ) {
    postageBatchId = new BatchId(postageBatchId)
 
    return streamDirectory(
      this,
      dir,
      postageBatchId,
      onUploadProgress,
      options,
      this.getRequestOptionsForCall(requestOptions),
    )
  }
 
  async streamFiles(
    postageBatchId: BatchId | Uint8Array | string,
    files: File[] | FileList,
    onUploadProgress?: (progress: UploadProgress) => void,
    options?: UploadOptions,
    requestOptions?: BeeRequestOptions,
  ) {
    postageBatchId = new BatchId(postageBatchId)
 
    return streamFiles(
      this,
      files,
      postageBatchId,
      onUploadProgress,
      options,
      this.getRequestOptionsForCall(requestOptions),
    )
  }
 
  /**
   * Upload Collection that you can assembly yourself.
   *
   * The returned `UploadResult.tag` might be undefined if called in CORS-enabled environment.
   * This will be fixed upon next Bee release. https://github.com/ethersphere/bee-js/issues/406
   *
   * @param postageBatchId
   * @param collection
   * @param options Collections and request options
   */
  async uploadCollection(
    postageBatchId: BatchId | Uint8Array | string,
    collection: Collection,
    options?: CollectionUploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<UploadResult> {
    postageBatchId = new BatchId(postageBatchId)
    assertCollection(collection)
 
    if (options) {
      options = prepareCollectionUploadOptions(options)
    }
 
    return bzz.uploadCollection(this.getRequestOptionsForCall(requestOptions), collection, postageBatchId, options)
  }
 
  /**
   * Upload collection of files.
   *
   * Available only in Node.js as it uses the `fs` module.
   *
   * The returned `UploadResult.tag` might be undefined if called in CORS-enabled environment.
   * This will be fixed upon next Bee release. https://github.com/ethersphere/bee-js/issues/406
   *
   * @param postageBatchId Postage BatchId to be used to upload the data with
   * @param dir the path of the files to be uploaded
   * @param options Additional options like tag, encryption, pinning and request options
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee docs - Upload directory](https://docs.ethswarm.org/docs/develop/access-the-swarm/upload-and-download#upload-a-directory)
   * @see [Bee API reference - `POST /bzz`](https://docs.ethswarm.org/api/#tag/BZZ/paths/~1bzz/post)
   */
  async uploadFilesFromDirectory(
    postageBatchId: BatchId | Uint8Array | string,
    dir: string,
    options?: CollectionUploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<UploadResult> {
    postageBatchId = new BatchId(postageBatchId)
 
    Iif (options) {
      options = prepareCollectionUploadOptions(options)
    }
 
    const data = await makeCollectionFromFS(dir)
 
    return bzz.uploadCollection(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options)
  }
 
  /**
   * Create a new Tag which is meant for tracking progres of syncing data across network.
   *
   * @param options Options that affects the request behavior
   * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing)
   * @see [Bee API reference - `POST /tags`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags/post)
   */
  async createTag(options?: BeeRequestOptions): Promise<Tag> {
    return tag.createTag(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Fetches all tags.
   *
   * The listing is limited by options.limit. So you have to iterate using options.offset to get all tags.
   *
   * @param options Options that affects the request behavior
   * @throws TypeError if limit or offset are not numbers or undefined
   * @throws BeeArgumentError if limit or offset have invalid options
   *
   * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing)
   * @see [Bee API reference - `GET /tags`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags/get)
   */
  async getAllTags(options?: AllTagsOptions, requestOptions?: BeeRequestOptions): Promise<Tag[]> {
    if (options) {
      options = prepareAllTagsOptions(options)
    }
 
    return tag.getAllTags(this.getRequestOptionsForCall(requestOptions), options?.offset, options?.limit)
  }
 
  /**
   * Retrieve tag information from Bee node
   *
   * @param tagUid UID or tag object to be retrieved
   * @param options Options that affects the request behavior
   * @throws TypeError if tagUid is in not correct format
   *
   * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing)
   * @see [Bee API reference - `GET /tags/{uid}`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags~1{uid}/get)
   *
   */
  async retrieveTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise<Tag> {
    tagUid = makeTagUid(tagUid)
 
    return tag.retrieveTag(this.getRequestOptionsForCall(options), tagUid)
  }
 
  /**
   * Delete Tag
   *
   * @param tagUid UID or tag object to be retrieved
   * @param options Options that affects the request behavior
   * @throws TypeError if tagUid is in not correct format
   * @throws BeeResponse error if something went wrong on the Bee node side while deleting the tag.
   *
   * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing)
   * @see [Bee API reference - `DELETE /tags/{uid}`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags~1{uid}/delete)
   */
  async deleteTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise<void> {
    tagUid = makeTagUid(tagUid)
 
    return tag.deleteTag(this.getRequestOptionsForCall(options), tagUid)
  }
 
  /**
   * Update tag's total chunks count.
   *
   * This is important if you are uploading individual chunks with a tag. Then upon finishing the final root chunk,
   * you can use this method to update the total chunks count for the tag.
   *
   * @param tagUid UID or tag object to be retrieved
   * @param reference The root reference that contains all the chunks to be counted
   * @param options Options that affects the request behavior
   * @throws TypeError if tagUid is in not correct format
   * @throws BeeResponse error if something went wrong on the Bee node side while deleting the tag.
   *
   * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/develop/access-the-swarm/syncing)
   * @see [Bee API reference - `PATCH /tags/{uid}`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags~1{uid}/patch)
   */
  async updateTag(tagUid: number | Tag, reference: Reference | string, options?: BeeRequestOptions): Promise<void> {
    reference = new Reference(reference)
 
    tagUid = makeTagUid(tagUid)
 
    return tag.updateTag(this.getRequestOptionsForCall(options), tagUid, reference)
  }
 
  /**
   * Pin local data with given reference
   *
   * @param reference Data reference
   * @param options Options that affects the request behavior
   * @throws TypeError if reference is in not correct format
   *
   * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/develop/access-the-swarm/pinning)
   */
  async pin(reference: Reference | Uint8Array | string, options?: BeeRequestOptions): Promise<void> {
    reference = new Reference(reference)
 
    return pinning.pin(this.getRequestOptionsForCall(options), reference)
  }
 
  /**
   * Unpin local data with given reference
   *
   * @param reference Data reference
   * @param options Options that affects the request behavior
   * @throws TypeError if reference is in not correct format
   *
   * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/develop/access-the-swarm/pinning)
   */
  async unpin(reference: Reference | Uint8Array | string, options?: BeeRequestOptions): Promise<void> {
    reference = new Reference(reference)
 
    return pinning.unpin(this.getRequestOptionsForCall(options), reference)
  }
 
  /**
   * Get list of all locally pinned references
   *
   * @param options Options that affects the request behavior
   * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/develop/access-the-swarm/pinning)
   */
  async getAllPins(options?: BeeRequestOptions): Promise<Reference[]> {
    return pinning.getAllPins(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get pinning status of chunk with given reference
   *
   * @param reference Bee data reference in hex string (either 64 or 128 chars long) or ENS domain.
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   *
   * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/develop/access-the-swarm/pinning)
   */
  async getPin(reference: Reference | Uint8Array | string, options?: BeeRequestOptions): Promise<Pin> {
    reference = new Reference(reference)
 
    return pinning.getPin(this.getRequestOptionsForCall(options), reference)
  }
 
  /**
   * Instructs the Bee node to reupload a locally pinned data into the network.
   *
   * @param reference Bee data reference to be re-uploaded in hex string (either 64 or 128 chars long) or ENS domain.
   * @param options Options that affects the request behavior
   * @throws BeeArgumentError if the reference is not locally pinned
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   *
   * @see [Bee API reference - `PUT /stewardship`](https://docs.ethswarm.org/api/#tag/Stewardship/paths/~1stewardship~1{reference}/put)
   */
  async reuploadPinnedData(
    postageBatchId: BatchId | Uint8Array | string,
    reference: Reference | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<void> {
    postageBatchId = new BatchId(postageBatchId)
    reference = new Reference(reference)
 
    await stewardship.reupload(this.getRequestOptionsForCall(options), postageBatchId, reference)
  }
 
  /**
   * Checks if content specified by reference is retrievable from the network.
   *
   * @param reference Bee data reference to be checked in hex string (either 64 or 128 chars long) or ENS domain.
   * @param options Options that affects the request behavior
   * @throws TypeError if some of the input parameters is not expected type
   * @throws BeeArgumentError if there is passed ENS domain with invalid unicode characters
   *
   * @see [Bee API reference - `GET /stewardship`](https://docs.ethswarm.org/api/#tag/Stewardship/paths/~1stewardship~1{reference}/get)
   */
  async isReferenceRetrievable(
    reference: Reference | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<boolean> {
    reference = new Reference(reference)
 
    return stewardship.isRetrievable(this.getRequestOptionsForCall(options), reference)
  }
 
  /**
   * Functions that validates if feed is retrievable in the network.
   *
   * If no index is passed then it check for "latest" update, which is a weaker guarantee as nobody can be really
   * sure what is the "latest" update.
   *
   * If index is passed then it validates all previous sequence index chunks if they are available as they are required
   * to correctly resolve the feed upto the given index update.
   *
   * @param type
   * @param owner
   * @param topic
   * @param index
   * @param options
   */
  async isFeedRetrievable(
    owner: EthAddress | Uint8Array | string,
    topic: Topic | Uint8Array | string,
    index?: FeedIndex,
    options?: DownloadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<boolean> {
    owner = new EthAddress(owner)
    topic = new Topic(topic)
 
    Iif (options) {
      options = prepareDownloadOptions(options)
    }
 
    if (!index) {
      try {
        await this.makeFeedReader(topic, owner, requestOptions).download()
 
        return true
      } catch (e: unknown) {
        const status = Objects.getDeep(e, 'status')
 
        Iif (status === 404 || status === 500) {
          return false
        }
 
        throw e
      }
    }
 
    return areAllSequentialFeedsUpdateRetrievable(
      this,
      owner,
      topic,
      index,
      options,
      this.getRequestOptionsForCall(requestOptions),
    )
  }
 
  /**
   * Send data to recipient or target with Postal Service for Swarm.
   *
   * Because sending a PSS message is slow and CPU intensive,
   * it is not supposed to be used for general messaging but
   * most likely for setting up an encrypted communication
   * channel by sending an one-off message.
   *
   * **Warning! If the recipient Bee node is a light node, then he will never receive the message!**
   * This is because light nodes does not fully participate in the data exchange in Swarm network and hence the message won't arrive to them.
   *
   * @param postageBatchId Postage BatchId that will be assigned to sent message
   * @param topic Topic name
   * @param target Target message address prefix. Has a limit on length. Recommend to use `Utils.Pss.makeMaxTarget()` to get the most specific target that Bee node will accept.
   * @param data Message to be sent
   * @param recipient Recipient public key
   * @param options Options that affects the request behavior
   * @throws TypeError if `data`, `batchId`, `target` or `recipient` are in invalid format
   *
   * @see [Bee docs - PSS](https://docs.ethswarm.org/docs/develop/tools-and-features/pss)
   * @see [Bee API reference - `POST /pss`](https://docs.ethswarm.org/api/#tag/Postal-Service-for-Swarm/paths/~1pss~1send~1{topic}~1{targets}/post)
   */
  async pssSend(
    postageBatchId: BatchId | Uint8Array | string,
    topic: Topic,
    target: string,
    data: string | Uint8Array,
    recipient?: string | PublicKey,
    options?: BeeRequestOptions,
  ): Promise<void> {
    postageBatchId = new BatchId(postageBatchId)
    assertData(data)
 
    Iif (recipient) {
      recipient = new PublicKey(recipient)
 
      return pss.send(this.getRequestOptionsForCall(options), topic, target, data, postageBatchId, recipient)
    } else {
      return pss.send(this.getRequestOptionsForCall(options), topic, target, data, postageBatchId)
    }
  }
 
  /**
   * Subscribe to messages for given topic with Postal Service for Swarm
   *
   * **Warning! If connected Bee node is a light node, then he will never receive any message!**
   * This is because light nodes does not fully participate in the data exchange in Swarm network and hence the message won't arrive to them.
   *
   * @param topic Topic name
   * @param handler Message handler interface
   *
   * @returns Subscription to a given topic
   *
   * @see [Bee docs - PSS](https://docs.ethswarm.org/docs/develop/tools-and-features/pss)
   * @see [Bee API reference - `GET /pss`](https://docs.ethswarm.org/api/#tag/Postal-Service-for-Swarm/paths/~1pss~1subscribe~1{topic}/get)
   */
  pssSubscribe(topic: Topic, handler: PssMessageHandler): PssSubscription {
    handler = preparePssMessageHandler(handler)
 
    const ws = pss.subscribe(this.url, topic, this.requestOptions.headers)
 
    let cancelled = false
    const cancel = () => {
      if (cancelled === false) {
        cancelled = true
 
        // although the WebSocket API offers a `close` function, it seems that
        // with the library that we are using (isomorphic-ws) it doesn't close
        // the websocket properly, whereas `terminate` does
        if (ws.terminate) {
          ws.terminate()
        } else E{
          ws.close()
        } // standard Websocket in browser does not have terminate function
      }
    }
 
    const subscription = {
      topic,
      cancel,
    }
 
    ws.onmessage = async event => {
      const data = await prepareWebsocketData(event.data)
 
      if (data.length) {
        handler.onMessage(new Bytes(data), subscription)
      }
    }
    ws.onerror = event => {
      // ignore errors after subscription was cancelled
      Iif (!cancelled) {
        handler.onError(new BeeError(event.message), subscription)
      }
    }
 
    return subscription
  }
 
  /**
   * Receive message with Postal Service for Swarm
   *
   * Because sending a PSS message is slow and CPU intensive,
   * it is not supposed to be used for general messaging but
   * most likely for setting up an encrypted communication
   * channel by sending an one-off message.
   *
   * This is a helper function to wait for exactly one message to
   * arrive and then cancel the subscription. Additionally a
   * timeout can be provided for the message to arrive or else
   * an error will be thrown.
   *
   * **Warning! If connected Bee node is a light node, then he will never receive any message!**
   * This is because light nodes does not fully participate in the data exchange in Swarm network and hence the message won't arrive to them.
   *
   * @param topic Topic name
   * @param timeoutMsec Timeout in milliseconds
   *
   * @returns Message in byte array
   *
   * @see [Bee docs - PSS](https://docs.ethswarm.org/docs/develop/tools-and-features/pss)
   * @see [Bee API reference - `GET /pss`](https://docs.ethswarm.org/api/#tag/Postal-Service-for-Swarm/paths/~1pss~1subscribe~1{topic}/get)
   */
  async pssReceive(topic: Topic, timeoutMsec = 0): Promise<Bytes> {
    Iif (typeof timeoutMsec !== 'number') {
      throw new TypeError('timeoutMsc parameter has to be a number!')
    }
 
    return new Promise((resolve, reject) => {
      let timeout: ReturnType<typeof setTimeout> | undefined
      const subscription = this.pssSubscribe(topic, {
        onError: error => {
          clearTimeout(timeout)
          subscription.cancel()
          reject(error.message)
        },
        onMessage: message => {
          clearTimeout(timeout)
          subscription.cancel()
          resolve(message)
        },
      })
 
      if (timeoutMsec > 0) {
        timeout = setTimeout(() => {
          subscription.cancel()
          reject(new BeeError('pssReceive timeout'))
        }, timeoutMsec)
      }
    })
  }
 
  gsocMine(
    targetOverlay: PeerAddress | Uint8Array | string,
    identifier: Identifier | Uint8Array | string,
    proximity = 12,
  ): PrivateKey {
    targetOverlay = new PeerAddress(targetOverlay)
    identifier = new Identifier(identifier)
    const start = 0xb33n
    for (let i = 0n; i < 0xffffn; i++) {
      const signer = new PrivateKey(Binary.numberToUint256(start + i, 'BE'))
      const socAddress = makeSOCAddress(identifier, signer.publicKey().address())
      const actualProximity = 256 - Binary.proximity(socAddress.toUint8Array(), targetOverlay.toUint8Array(), 256)
 
      if (actualProximity <= 256 - proximity) {
        return signer
      }
    }
    throw Error('Could not mine a valid signer')
  }
 
  async gsocSend(
    postageBatchId: BatchId | Uint8Array | string,
    signer: PrivateKey | Uint8Array | string,
    identifier: Identifier | Uint8Array | string,
    data: string | Uint8Array,
    options?: UploadOptions,
    requestOptions?: BeeRequestOptions,
  ) {
    postageBatchId = new BatchId(postageBatchId)
    signer = new PrivateKey(signer)
    identifier = new Identifier(identifier)
 
    const cac = makeContentAddressedChunk(data)
    const soc = makeSingleOwnerChunk(cac, identifier, signer)
 
    return gsoc.send(this.getRequestOptionsForCall(requestOptions), soc, postageBatchId, options)
  }
 
  gsocSubscribe(
    address: EthAddress | Uint8Array | string,
    identifier: Identifier | Uint8Array | string,
    handler: GsocMessageHandler,
  ): GsocSubscription {
    address = new EthAddress(address)
    identifier = new Identifier(identifier)
    handler = prepareGsocMessageHandler(handler)
 
    const socAddress = makeSOCAddress(identifier, address)
 
    const ws = gsoc.subscribe(this.url, socAddress, this.requestOptions.headers)
 
    let cancelled = false
    const cancel = () => {
      if (cancelled === false) {
        cancelled = true
 
        if (ws.terminate) {
          ws.terminate()
        } else E{
          ws.close()
        }
      }
    }
 
    const subscription = {
      address,
      cancel,
    }
 
    ws.onmessage = async event => {
      const data = await prepareWebsocketData(event.data)
 
      if (data.length) {
        handler.onMessage(new Bytes(data), subscription)
      }
    }
    ws.onerror = event => {
      Iif (!cancelled) {
        handler.onError(new BeeError(event.message), subscription)
      }
    }
 
    return subscription
  }
 
  /**
   * Create feed manifest chunk and return the reference to it.
   *
   * Feed manifest chunk allows for a feed to be able to be resolved through `/bzz` endpoint.
   *
   * @param postageBatchId  Postage BatchId to be used to create the Feed Manifest
   * @param topic           Topic in hex or bytes
   * @param owner           Owner's ethereum address in hex or bytes
   * @param options Options that affects the request behavior
   *
   * @see [Bee docs - Feeds](https://docs.ethswarm.org/docs/develop/tools-and-features/feeds)
   * @see [Bee API reference - `POST /feeds`](https://docs.ethswarm.org/api/#tag/Feed/paths/~1feeds~1{owner}~1{topic}/post)
   */
  async createFeedManifest(
    postageBatchId: BatchId | Uint8Array | string,
    topic: Topic | Uint8Array | string,
    owner: EthAddress | Uint8Array | string,
    options?: UploadOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<Reference> {
    postageBatchId = new BatchId(postageBatchId)
    topic = new Topic(topic)
    owner = new EthAddress(owner)
 
    Iif (options) {
      options = prepareUploadOptions(options)
    }
 
    return createFeedManifest(this.getRequestOptionsForCall(requestOptions), owner, topic, postageBatchId, options)
  }
 
  /**
   * Make a new feed reader for downloading feed updates.
   *
   * @param topic   Topic in hex or bytes
   * @param owner   Owner's ethereum address in hex or bytes
   * @param options Options that affects the request behavior
   *
   * @see [Bee docs - Feeds](https://docs.ethswarm.org/docs/develop/tools-and-features/feeds)
   */
  makeFeedReader(
    topic: Topic | Uint8Array | string,
    owner: EthAddress | Uint8Array | string,
    options?: BeeRequestOptions,
  ): FeedReader {
    topic = new Topic(topic)
    owner = new EthAddress(owner)
 
    return makeFeedReader(this.getRequestOptionsForCall(options), topic, owner)
  }
 
  /**
   * Make a new feed writer for updating feeds
   *
   * @param topic   Topic in hex or bytes
   * @param signer  The signer's private key or a Signer instance that can sign data
   * @param options Options that affects the request behavior
   *
   * @see [Bee docs - Feeds](https://docs.ethswarm.org/docs/develop/tools-and-features/feeds)
   */
  makeFeedWriter(
    topic: Topic | Uint8Array | string,
    signer?: PrivateKey | Uint8Array | string,
    options?: BeeRequestOptions,
  ): FeedWriter {
    topic = new Topic(topic)
    signer = signer ? new PrivateKey(signer) : this.signer
 
    Iif (!signer) {
      throw Error('No signer provided')
    }
 
    return makeFeedWriter(this.getRequestOptionsForCall(options), topic, signer)
  }
 
  async fetchLatestFeedUpdate(
    topic: Topic | Uint8Array | string,
    owner: EthAddress | Uint8Array | string,
    requestOptions?: BeeRequestOptions,
  ): Promise<FeedPayloadResult> {
    topic = new Topic(topic)
    owner = new EthAddress(owner)
 
    return fetchLatestFeedUpdate(this.getRequestOptionsForCall(requestOptions), owner, topic)
  }
 
  /**
   * Returns an object for reading single owner chunks
   *
   * @param ownerAddress The ethereum address of the owner
   * @param options Options that affects the request behavior
   * @see [Bee docs - Chunk Types](https://docs.ethswarm.org/docs/develop/tools-and-features/chunk-types#single-owner-chunks)
   */
  makeSOCReader(ownerAddress: EthAddress | Uint8Array | string, options?: BeeRequestOptions): SOCReader {
    ownerAddress = new EthAddress(ownerAddress)
 
    return {
      owner: ownerAddress,
      download: downloadSingleOwnerChunk.bind(null, this.getRequestOptionsForCall(options), ownerAddress),
    }
  }
 
  /**
   * Returns an object for reading and writing single owner chunks
   *
   * @param signer The signer's private key or a Signer instance that can sign data
   * @param options Options that affects the request behavior
   * @see [Bee docs - Chunk Types](https://docs.ethswarm.org/docs/develop/tools-and-features/chunk-types#single-owner-chunks)
   */
  makeSOCWriter(signer?: PrivateKey | Uint8Array | string, options?: BeeRequestOptions): SOCWriter {
    signer = signer ? new PrivateKey(signer) : this.signer
 
    Iif (!signer) {
      throw Error('No signer provided')
    }
 
    return {
      ...this.makeSOCReader((signer as PrivateKey).publicKey().address(), options),
      upload: uploadSingleOwnerChunkData.bind(null, this.getRequestOptionsForCall(options), signer),
    }
  }
 
  async createEnvelope(
    postageBatchId: BatchId | Uint8Array | string,
    reference: Reference | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<EnvelopeWithBatchId> {
    postageBatchId = new BatchId(postageBatchId)
    reference = new Reference(reference)
 
    return postEnvelope(this.getRequestOptionsForCall(options), postageBatchId, reference)
  }
 
  /**
   * Ping the Bee node to see if there is a live Bee node on the given URL.
   *
   * @param options Options that affects the request behavior
   * @throws If connection was not successful throw error
   */
  async checkConnection(options?: BeeRequestOptions): Promise<void> | never {
    return status.checkConnection(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Ping the Bee node to see if there is a live Bee node on the given URL.
   *
   * @param options Options that affects the request behavior
   * @returns true if successful, false on error
   */
  async isConnected(options?: BeeRequestOptions): Promise<boolean> {
    try {
      await status.checkConnection(this.getRequestOptionsForCall(options))
    } catch (e) {
      return false
    }
 
    return true
  }
 
  // Legacy debug API
 
  async getNodeAddresses(options?: BeeRequestOptions): Promise<NodeAddresses> {
    return connectivity.getNodeAddresses(this.getRequestOptionsForCall(options))
  }
 
  async getBlocklist(options?: BeeRequestOptions): Promise<Peer[]> {
    return connectivity.getBlocklist(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get list of peers for this node
   */
  async getPeers(options?: BeeRequestOptions): Promise<Peer[]> {
    return connectivity.getPeers(this.getRequestOptionsForCall(options))
  }
 
  async removePeer(peer: PeerAddress | string, options?: BeeRequestOptions): Promise<RemovePeerResponse> {
    peer = new PeerAddress(peer)
 
    return connectivity.removePeer(this.getRequestOptionsForCall(options), peer)
  }
 
  async getTopology(options?: BeeRequestOptions): Promise<Topology> {
    return connectivity.getTopology(this.getRequestOptionsForCall(options))
  }
 
  async pingPeer(peer: PeerAddress | string, options?: BeeRequestOptions): Promise<PingResponse> {
    peer = new PeerAddress(peer)
 
    return connectivity.pingPeer(this.getRequestOptionsForCall(options), peer)
  }
 
  /*
   * Balance endpoints
   */
 
  /**
   * Get the balances with all known peers including prepaid services
   */
  async getAllBalances(options?: BeeRequestOptions): Promise<BalanceResponse> {
    return balance.getAllBalances(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get the balances with a specific peer including prepaid services
   *
   * @param address Swarm address of peer
   */
  async getPeerBalance(address: PeerAddress | string, options?: BeeRequestOptions): Promise<PeerBalance> {
    address = new PeerAddress(address)
 
    return balance.getPeerBalance(this.getRequestOptionsForCall(options), address)
  }
 
  /**
   * Get the past due consumption balances with all known peers
   */
  async getPastDueConsumptionBalances(options?: BeeRequestOptions): Promise<BalanceResponse> {
    return balance.getPastDueConsumptionBalances(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get the past due consumption balance with a specific peer
   *
   * @param address Swarm address of peer
   */
  async getPastDueConsumptionPeerBalance(
    address: PeerAddress | string,
    options?: BeeRequestOptions,
  ): Promise<PeerBalance> {
    address = new PeerAddress(address)
 
    return balance.getPastDueConsumptionPeerBalance(this.getRequestOptionsForCall(options), address)
  }
 
  /*
   * Chequebook endpoints
   */
 
  /**
   * Get the address of the chequebook contract used.
   *
   * **Warning:** The address is returned with 0x prefix unlike all other calls.
   * https://github.com/ethersphere/bee/issues/1443
   */
  async getChequebookAddress(options?: BeeRequestOptions): Promise<ChequebookAddressResponse> {
    return chequebook.getChequebookAddress(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get the balance of the chequebook
   */
  async getChequebookBalance(options?: BeeRequestOptions): Promise<ChequebookBalanceResponse> {
    return chequebook.getChequebookBalance(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get last cheques for all peers
   */
  async getLastCheques(options?: BeeRequestOptions): Promise<LastChequesResponse> {
    return chequebook.getLastCheques(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get last cheques for the peer
   *
   * @param address  Swarm address of peer
   */
  async getLastChequesForPeer(
    address: PeerAddress | string,
    options?: BeeRequestOptions,
  ): Promise<LastChequesForPeerResponse> {
    address = new PeerAddress(address)
 
    return chequebook.getLastChequesForPeer(this.getRequestOptionsForCall(options), address)
  }
 
  /**
   * Get last cashout action for the peer
   *
   * @param address  Swarm address of peer
   */
  async getLastCashoutAction(
    address: PeerAddress | string,
    options?: BeeRequestOptions,
  ): Promise<LastCashoutActionResponse> {
    address = new PeerAddress(address)
 
    return chequebook.getLastCashoutAction(this.getRequestOptionsForCall(options), address)
  }
 
  /**
   * Cashout the last cheque for the peer
   *
   * @param address  Swarm address of peer
   * @param options
   * @param options.gasPrice Gas price for the cashout transaction in WEI
   * @param options.gasLimit Gas limit for the cashout transaction in WEI
   */
  async cashoutLastCheque(
    address: PeerAddress | string,
    options?: TransactionOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<TransactionId> {
    address = new PeerAddress(address)
 
    Iif (options) {
      prepareTransactionOptions(options)
    }
 
    return chequebook.cashoutLastCheque(this.getRequestOptionsForCall(requestOptions), address, options)
  }
 
  /**
   * Deposit tokens from overlay address into chequebook
   *
   * @param amount  Amount of tokens to deposit (must be positive integer)
   * @param gasPrice Gas Price in WEI for the transaction call
   * @return string  Hash of the transaction
   */
  async depositTokens(
    amount: BZZ | NumberString | string | bigint,
    gasPrice?: NumberString | string | bigint,
    options?: BeeRequestOptions,
  ): Promise<TransactionId> {
    const amountString =
      amount instanceof BZZ ? amount.toPLURString() : asNumberString(amount, { min: 1n, name: 'amount' })
 
    let gasPriceString
 
    Iif (gasPrice) {
      gasPriceString = asNumberString(amount, { min: 0n, name: 'gasPrice' })
    }
 
    return chequebook.depositTokens(this.getRequestOptionsForCall(options), amountString, gasPriceString)
  }
 
  /**
   * Withdraw tokens from the chequebook to the overlay address
   *
   * @param amount  Amount of tokens to withdraw (must be positive integer)
   * @param gasPrice Gas Price in WEI for the transaction call
   * @return string  Hash of the transaction
   */
  async withdrawTokens(
    amount: BZZ | NumberString | string | bigint,
    gasPrice?: NumberString | string | bigint,
    options?: BeeRequestOptions,
  ): Promise<TransactionId> {
    // TODO: check BZZ in tests
    const amountString =
      amount instanceof BZZ ? amount.toPLURString() : asNumberString(amount, { min: 1n, name: 'amount' })
 
    let gasPriceString
 
    Iif (gasPrice) {
      gasPriceString = asNumberString(amount, { min: 0n, name: 'gasPrice' })
    }
 
    return chequebook.withdrawTokens(this.getRequestOptionsForCall(options), amountString, gasPriceString)
  }
 
  /*
   * Settlements endpoint
   */
 
  /**
   * Get amount of sent and received from settlements with a peer
   *
   * @param address  Swarm address of peer
   */
  async getSettlements(address: PeerAddress | string, options?: BeeRequestOptions): Promise<Settlements> {
    address = new PeerAddress(address)
 
    return settlements.getSettlements(this.getRequestOptionsForCall(options), address)
  }
 
  /**
   * Get settlements with all known peers and total amount sent or received
   */
  async getAllSettlements(options?: BeeRequestOptions): Promise<AllSettlements> {
    return settlements.getAllSettlements(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get status of node
   */
  async getStatus(options?: BeeRequestOptions): Promise<DebugStatus> {
    return debugStatus.getDebugStatus(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get health of node
   */
  async getHealth(options?: BeeRequestOptions): Promise<Health> {
    return debugStatus.getHealth(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get readiness of node
   */
  async getReadiness(options?: BeeRequestOptions): Promise<Readiness> {
    return debugStatus.getReadiness(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get mode information of node
   */
  async getNodeInfo(options?: BeeRequestOptions): Promise<NodeInfo> {
    return debugStatus.getNodeInfo(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Connects to a node and checks if its version matches with the one that bee-js supports.
   *
   * @param options
   */
  async isSupportedExactVersion(options?: BeeRequestOptions): Promise<boolean> | never {
    return debugStatus.isSupportedExactVersion(this.getRequestOptionsForCall(options))
  }
 
  /**
   *
   * Connects to a node and checks if its Main API version matches with the one that bee-js supports.
   *
   * This should be the main way how to check compatibility for your app and Bee node.
   *
   * @param options
   */
  async isSupportedApiVersion(options?: BeeRequestOptions): Promise<boolean> | never {
    return debugStatus.isSupportedApiVersion(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Returns object with all versions specified by the connected Bee node (properties prefixed with `bee*`)
   * and versions that bee-js supports (properties prefixed with `supported*`).
   *
   * @param options
   */
  async getVersions(options?: BeeRequestOptions): Promise<BeeVersions> | never {
    return debugStatus.getVersions(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get reserve state
   */
  async getReserveState(options?: BeeRequestOptions): Promise<ReserveState> {
    return states.getReserveState(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get chain state
   */
  async getChainState(options?: BeeRequestOptions): Promise<ChainState> {
    return states.getChainState(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Get wallet balances for xDai and BZZ of the Bee node
   *
   * @param options
   */
  async getWalletBalance(options?: BeeRequestOptions): Promise<WalletBalance> {
    return states.getWalletBalance(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Creates new postage batch from the funds that the node has available in its Ethereum account.
   *
   * For better understanding what each parameter means and what are the optimal values please see
   * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction#keep-your-data-alive).
   *
   * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY**
   *
   * @param amount Amount that represents the value per chunk, has to be greater or equal zero.
   * @param depth Logarithm of the number of chunks that can be stamped with the batch.
   * @param options Options for creation of postage batch
   * @throws BeeArgumentError when negative amount or depth is specified
   * @throws TypeError if non-integer value is passed to amount or depth
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee Debug API reference - `POST /stamps`](https://docs.ethswarm.org/api/#tag/Postage-Stamps/paths/~1stamps~1{amount}~1{depth}/post)
   */
  async createPostageBatch(
    amount: NumberString | string | bigint,
    depth: number,
    options?: PostageBatchOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<BatchId> {
    const amountString = asNumberString(amount, { min: 0n, name: 'amount' })
 
    if (options) {
      options = preparePostageBatchOptions(options)
    }
 
    if (depth < STAMPS_DEPTH_MIN || depth > STAMPS_DEPTH_MAX) {
      throw new BeeArgumentError(`Depth has to be between ${STAMPS_DEPTH_MIN}..${STAMPS_DEPTH_MAX}`, depth)
    }
 
    const chainState = await this.getChainState()
    const minimumAmount = BigInt(chainState.currentPrice) * 17280n + 1n
 
    if (BigInt(amountString) < minimumAmount) {
      throw new BeeArgumentError(
        `Amount has to be at least ${minimumAmount} (1 day at current price ${chainState.currentPrice})`,
        amountString,
      )
    }
 
    const stamp = await stamps.createPostageBatch(
      this.getRequestOptionsForCall(requestOptions),
      amountString,
      depth,
      options,
    )
 
    if (options?.waitForUsable !== false) {
      await this.waitForUsablePostageStamp(stamp, options?.waitForUsableTimeout)
    }
 
    return stamp
  }
 
  async buyStorage(
    size: Size,
    duration: Duration,
    options?: PostageBatchOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<BatchId> {
    const chainState = await this.getChainState(requestOptions)
    const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
    const depth = getDepthForSize(size)
 
    if (options) {
      options = preparePostageBatchOptions(options)
    }
 
    return this.createPostageBatch(amount, depth, options, requestOptions)
  }
 
  async getStorageCost(size: Size, duration: Duration, options?: BeeRequestOptions): Promise<BZZ> {
    const chainState = await this.getChainState(options)
    const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
    const depth = getDepthForSize(size)
 
    return getStampCost(depth, amount)
  }
 
  async extendStorageSize(postageBatchId: BatchId | Uint8Array | string, size: Size, options?: BeeRequestOptions) {
    const batch = await this.getPostageBatch(postageBatchId, options)
    const depth = getDepthForSize(size)
    const delta = depth - batch.depth
 
    if (delta <= 0) {
      throw new BeeArgumentError('New depth has to be greater than the original depth', depth)
    }
 
    await this.topUpBatch(batch.batchID, BigInt(batch.amount) * 2n ** BigInt(delta - 1) + 1n, options)
 
    return this.diluteBatch(batch.batchID, depth, options)
  }
 
  async extendStorageDuration(
    postageBatchId: BatchId | Uint8Array | string,
    duration: Duration,
    options?: BeeRequestOptions,
  ) {
    const batch = await this.getPostageBatch(postageBatchId, options)
    const chainState = await this.getChainState(options)
    const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
 
    return this.topUpBatch(batch.batchID, amount, options)
  }
 
  async getExtensionCost(
    postageBatchId: BatchId | Uint8Array | string,
    size: Size,
    duration: Duration,
    options?: BeeRequestOptions,
  ): Promise<BZZ> {
    const batch = await this.getPostageBatch(postageBatchId, options)
    const chainState = await this.getChainState(options)
    const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
    const depth = getDepthForSize(size)
 
    const currentValue = getStampCost(batch.depth, batch.amount)
    const newValue = getStampCost(depth, amount)
 
    return newValue.minus(currentValue)
  }
 
  async getSizeExtensionCost(
    postageBatchId: BatchId | Uint8Array | string,
    size: Size,
    options?: BeeRequestOptions,
  ): Promise<BZZ> {
    const batch = await this.getPostageBatch(postageBatchId, options)
    const depth = getDepthForSize(size)
    const delta = depth - batch.depth
 
    if (delta <= 0) {
      throw new BeeArgumentError('New depth has to be greater than the original depth', depth)
    }
 
    const currentPaid = getStampCost(batch.depth, batch.amount)
    const newPaid = getStampCost(depth, batch.amount)
 
    return newPaid.minus(currentPaid)
  }
 
  async getDurationExtensionCost(
    postageBatchId: BatchId | Uint8Array | string,
    duration: Duration,
    options?: BeeRequestOptions,
  ): Promise<BZZ> {
    const batch = await this.getPostageBatch(postageBatchId, options)
    const chainState = await this.getChainState(options)
    const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
 
    return getStampCost(batch.depth, amount)
  }
 
  /**
   * Topup a fresh amount of BZZ to given Postage Batch.
   *
   * For better understanding what each parameter means and what are the optimal values please see
   * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive).
   *
   * @param postageBatchId Batch ID
   * @param amount Amount to be added to the batch
   * @param options Request options
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{batch_id}~1{amount}/patch)
   */
  async topUpBatch(
    postageBatchId: BatchId | Uint8Array | string,
    amount: NumberString | string | bigint,
    options?: BeeRequestOptions,
  ): Promise<BatchId> {
    postageBatchId = new BatchId(postageBatchId)
    const amountString = asNumberString(amount, { min: 1n, name: 'amount' })
 
    return stamps.topUpBatch(this.getRequestOptionsForCall(options), postageBatchId, amountString)
  }
 
  /**
   * Dilute given Postage Batch with new depth (that has to be bigger then the original depth), which allows
   * the Postage Batch to be used for more chunks.
   *
   * For better understanding what each parameter means and what are the optimal values please see
   * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive).
   *
   * @param postageBatchId Batch ID
   * @param depth Amount to be added to the batch
   * @param options Request options
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/api/#tag/Postage-Stamps/paths/~1stamps~1dilute~1%7Bbatch_id%7D~1%7Bdepth%7D/patch)
   */
  async diluteBatch(
    postageBatchId: BatchId | Uint8Array | string,
    depth: number,
    options?: BeeRequestOptions,
  ): Promise<BatchId> {
    postageBatchId = new BatchId(postageBatchId)
    depth = Types.asNumber(depth, { name: 'depth', min: 18, max: 255 })
 
    return stamps.diluteBatch(this.getRequestOptionsForCall(options), postageBatchId, depth)
  }
 
  /**
   * Return details for specific postage batch.
   *
   * @param postageBatchId Batch ID
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee Debug API reference - `GET /stamps/${id}`](https://docs.ethswarm.org/api/#tag/Postage-Stamps/paths/~1stamps~1%7Bbatch_id%7D/get)
   */
  async getPostageBatch(
    postageBatchId: BatchId | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<PostageBatch> {
    postageBatchId = new BatchId(postageBatchId)
 
    return stamps.getPostageBatch(this.getRequestOptionsForCall(options), postageBatchId)
  }
 
  /**
   * Return detailed information related to buckets for specific postage batch.
   *
   * @param postageBatchId Batch ID
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee Debug API reference - `GET /stamps/${id}/buckets`](https://docs.ethswarm.org/api/#tag/Postage-Stamps/paths/~1stamps~1%7Bbatch_id%7D~1buckets/get)
   */
  async getPostageBatchBuckets(
    postageBatchId: BatchId | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<PostageBatchBuckets> {
    postageBatchId = new BatchId(postageBatchId)
 
    return stamps.getPostageBatchBuckets(this.getRequestOptionsForCall(options), postageBatchId)
  }
 
  /**
   * Return all postage batches that has the node available.
   *
   * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/develop/access-the-swarm/introduction/#keep-your-data-alive)
   * @see [Bee Debug API reference - `GET /stamps`](https://docs.ethswarm.org/api/#tag/Postage-Stamps/paths/~1stamps/get)
   */
  async getAllPostageBatch(options?: BeeRequestOptions): Promise<PostageBatch[]> {
    return stamps.getAllPostageBatches(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Return all globally available postage batches.
   */
  async getAllGlobalPostageBatch(options?: BeeRequestOptions): Promise<GlobalPostageBatch[]> {
    return stamps.getGlobalPostageBatches(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Return lists of all current pending transactions that the Bee made
   */
  async getAllPendingTransactions(options?: BeeRequestOptions): Promise<TransactionInfo[]> {
    return transactions.getAllTransactions(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Return transaction information for specific transaction
   * @param transactionHash
   */
  async getPendingTransaction(
    transactionHash: TransactionId | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<TransactionInfo> {
    transactionHash = new TransactionId(transactionHash)
 
    return transactions.getTransaction(this.getRequestOptionsForCall(options), transactionHash)
  }
 
  /**
   * Rebroadcast already created transaction.
   * This is mainly needed when your transaction fall off mempool from other reason is not incorporated into block.
   *
   * @param transactionHash
   */
  async rebroadcastPendingTransaction(
    transactionHash: TransactionId | Uint8Array | string,
    options?: BeeRequestOptions,
  ): Promise<TransactionId> {
    transactionHash = new TransactionId(transactionHash)
 
    return transactions.rebroadcastTransaction(this.getRequestOptionsForCall(options), transactionHash)
  }
 
  /**
   * Cancel currently pending transaction
   * @param transactionHash
   * @param gasPrice
   */
  async cancelPendingTransaction(
    transactionHash: TransactionId | Uint8Array | string,
    gasPrice?: NumberString | string | bigint,
    options?: BeeRequestOptions,
  ): Promise<TransactionId> {
    transactionHash = new TransactionId(transactionHash)
 
    let gasPriceString
 
    Iif (gasPrice) {
      gasPriceString = asNumberString(gasPrice, { min: 0n, name: 'gasPrice' })
    }
 
    return transactions.cancelTransaction(this.getRequestOptionsForCall(options), transactionHash, gasPriceString)
  }
 
  /**
   * Gets the staked amount of BZZ (in PLUR unit) as number string.
   *
   * @param options
   */
  async getStake(options?: BeeRequestOptions): Promise<BZZ> {
    return stake.getStake(this.getRequestOptionsForCall(options))
  }
 
  /**
   * Deposits given amount of BZZ token (in PLUR unit).
   *
   * Be aware that staked BZZ tokens can **not** be withdrawn.
   *
   * @param amount Amount of BZZ token (in PLUR unit) to be staked. Minimum is 100_000_000_000_000_000 PLUR (10 BZZ).
   * @param options
   */
  async depositStake(
    amount: BZZ | NumberString | string | bigint,
    options?: TransactionOptions,
    requestOptions?: BeeRequestOptions,
  ): Promise<TransactionId> {
    const amountString =
      amount instanceof BZZ ? amount.toPLURString() : asNumberString(amount, { min: 1n, name: 'amount' })
 
    Iif (options) {
      options = prepareTransactionOptions(options)
    }
 
    return stake.stake(this.getRequestOptionsForCall(requestOptions), amountString, options)
  }
 
  /**
   * Get current status of node in redistribution game
   *
   * @param options
   */
  async getRedistributionState(options?: BeeRequestOptions): Promise<RedistributionState> {
    return stake.getRedistributionState(this.getRequestOptionsForCall(options))
  }
 
  private async waitForUsablePostageStamp(id: BatchId, timeout = 240_000): Promise<void> {
    const TIME_STEP = 3_000
    for (let time = 0; time < timeout; time += TIME_STEP) {
      try {
        const stamp = await this.getPostageBatch(id)
 
        if (stamp.usable) {
          return
        }
      } catch (error) {
        // ignore error
      }
 
      await System.sleepMillis(TIME_STEP)
    }
 
    throw new BeeError('Timeout on waiting for postage stamp to become usable')
  }
 
  protected getRequestOptionsForCall(options?: BeeRequestOptions): BeeRequestOptions {
    if (options) {
      options = prepareBeeRequestOptions(options)
    }
 
    return options ? Objects.deepMerge2(this.requestOptions, options) : this.requestOptions
  }
}