@lightprotocol/compressed-token 0.14.1 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1062,8 +1062,7 @@ const IDL = {
1062
1062
  name: 'inputCompressedAccountsWithMerkleContext',
1063
1063
  type: {
1064
1064
  vec: {
1065
- defined:
1066
- 'PackedCompressedAccountWithMerkleContext',
1065
+ defined: 'PackedCompressedAccountWithMerkleContext',
1067
1066
  },
1068
1067
  },
1069
1068
  },
@@ -1071,8 +1070,7 @@ const IDL = {
1071
1070
  name: 'outputCompressedAccounts',
1072
1071
  type: {
1073
1072
  vec: {
1074
- defined:
1075
- 'OutputCompressedAccountWithPackedContext',
1073
+ defined: 'OutputCompressedAccountWithPackedContext',
1076
1074
  },
1077
1075
  },
1078
1076
  },
@@ -1128,8 +1126,7 @@ const IDL = {
1128
1126
  name: 'inputCompressedAccountsWithMerkleContext',
1129
1127
  type: {
1130
1128
  vec: {
1131
- defined:
1132
- 'PackedCompressedAccountWithMerkleContext',
1129
+ defined: 'PackedCompressedAccountWithMerkleContext',
1133
1130
  },
1134
1131
  },
1135
1132
  },
@@ -1137,8 +1134,7 @@ const IDL = {
1137
1134
  name: 'outputCompressedAccounts',
1138
1135
  type: {
1139
1136
  vec: {
1140
- defined:
1141
- 'OutputCompressedAccountWithPackedContext',
1137
+ defined: 'OutputCompressedAccountWithPackedContext',
1142
1138
  },
1143
1139
  },
1144
1140
  },
@@ -1383,8 +1379,7 @@ const IDL = {
1383
1379
  name: 'outputCompressedAccounts',
1384
1380
  type: {
1385
1381
  vec: {
1386
- defined:
1387
- 'OutputCompressedAccountWithPackedContext',
1382
+ defined: 'OutputCompressedAccountWithPackedContext',
1388
1383
  },
1389
1384
  },
1390
1385
  },
@@ -1692,37 +1687,20 @@ const IDL = {
1692
1687
  * Packs Compressed Token Accounts.
1693
1688
  */
1694
1689
  function packCompressedTokenAccounts(params) {
1695
- const {
1696
- inputCompressedTokenAccounts,
1697
- outputStateTrees,
1698
- remainingAccounts = [],
1699
- rootIndices,
1700
- tokenTransferOutputs,
1701
- } = params;
1690
+ const { inputCompressedTokenAccounts, outputStateTrees, remainingAccounts = [], rootIndices, tokenTransferOutputs, } = params;
1702
1691
  const _remainingAccounts = remainingAccounts.slice();
1703
1692
  let delegateIndex = null;
1704
- if (
1705
- inputCompressedTokenAccounts.length > 0 &&
1706
- inputCompressedTokenAccounts[0].parsed.delegate
1707
- ) {
1708
- delegateIndex = stateless_js.getIndexOrAdd(
1709
- _remainingAccounts,
1710
- inputCompressedTokenAccounts[0].parsed.delegate,
1711
- );
1693
+ if (inputCompressedTokenAccounts.length > 0 &&
1694
+ inputCompressedTokenAccounts[0].parsed.delegate) {
1695
+ delegateIndex = stateless_js.getIndexOrAdd(_remainingAccounts, inputCompressedTokenAccounts[0].parsed.delegate);
1712
1696
  }
1713
1697
  /// TODO: move pubkeyArray to remainingAccounts
1714
1698
  /// Currently just packs 'delegate' to pubkeyArray
1715
1699
  const packedInputTokenData = [];
1716
1700
  /// pack inputs
1717
1701
  inputCompressedTokenAccounts.forEach((account, index) => {
1718
- const merkleTreePubkeyIndex = stateless_js.getIndexOrAdd(
1719
- _remainingAccounts,
1720
- account.compressedAccount.merkleTree,
1721
- );
1722
- const nullifierQueuePubkeyIndex = stateless_js.getIndexOrAdd(
1723
- _remainingAccounts,
1724
- account.compressedAccount.nullifierQueue,
1725
- );
1702
+ const merkleTreePubkeyIndex = stateless_js.getIndexOrAdd(_remainingAccounts, account.compressedAccount.merkleTree);
1703
+ const nullifierQueuePubkeyIndex = stateless_js.getIndexOrAdd(_remainingAccounts, account.compressedAccount.nullifierQueue);
1726
1704
  packedInputTokenData.push({
1727
1705
  amount: account.parsed.amount,
1728
1706
  delegateIndex,
@@ -1740,27 +1718,15 @@ function packCompressedTokenAccounts(params) {
1740
1718
  });
1741
1719
  });
1742
1720
  /// pack output state trees
1743
- const paddedOutputStateMerkleTrees = stateless_js.padOutputStateMerkleTrees(
1744
- outputStateTrees,
1745
- tokenTransferOutputs.length,
1746
- inputCompressedTokenAccounts.map(acc => acc.compressedAccount),
1747
- );
1721
+ const paddedOutputStateMerkleTrees = stateless_js.padOutputStateMerkleTrees(outputStateTrees, tokenTransferOutputs.length, inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
1748
1722
  const packedOutputTokenData = [];
1749
1723
  paddedOutputStateMerkleTrees.forEach((account, index) => {
1750
1724
  var _a;
1751
- const merkleTreeIndex = stateless_js.getIndexOrAdd(
1752
- _remainingAccounts,
1753
- account,
1754
- );
1725
+ const merkleTreeIndex = stateless_js.getIndexOrAdd(_remainingAccounts, account);
1755
1726
  packedOutputTokenData.push({
1756
1727
  owner: tokenTransferOutputs[index].owner,
1757
1728
  amount: tokenTransferOutputs[index].amount,
1758
- lamports: (
1759
- (_a = tokenTransferOutputs[index].lamports) === null ||
1760
- _a === void 0
1761
- ? void 0
1762
- : _a.eq(stateless_js.bn(0))
1763
- )
1729
+ lamports: ((_a = tokenTransferOutputs[index].lamports) === null || _a === void 0 ? void 0 : _a.eq(stateless_js.bn(0)))
1764
1730
  ? null
1765
1731
  : tokenTransferOutputs[index].lamports,
1766
1732
  merkleTreeIndex,
@@ -1768,7 +1734,7 @@ function packCompressedTokenAccounts(params) {
1768
1734
  });
1769
1735
  });
1770
1736
  // to meta
1771
- const remainingAccountMetas = _remainingAccounts.map(account => ({
1737
+ const remainingAccountMetas = _remainingAccounts.map((account) => ({
1772
1738
  pubkey: account,
1773
1739
  isWritable: true,
1774
1740
  isSigner: false,
@@ -1785,15 +1751,11 @@ const CPI_AUTHORITY_SEED = Buffer.from('cpi_authority');
1785
1751
  const SPL_TOKEN_MINT_RENT_EXEMPT_BALANCE = 1461600;
1786
1752
 
1787
1753
  /** Address of the SPL Token program */
1788
- const TOKEN_PROGRAM_ID = new web3_js.PublicKey(
1789
- 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
1790
- );
1754
+ const TOKEN_PROGRAM_ID = new web3_js.PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
1791
1755
  /** Address of the SPL Token 2022 program */
1792
1756
  new web3_js.PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
1793
1757
  /** Address of the SPL Associated Token Account program */
1794
- const ASSOCIATED_TOKEN_PROGRAM_ID = new web3_js.PublicKey(
1795
- 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',
1796
- );
1758
+ const ASSOCIATED_TOKEN_PROGRAM_ID = new web3_js.PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
1797
1759
  /** Address of the special mint for wrapped native SOL in spl-token */
1798
1760
  new web3_js.PublicKey('So11111111111111111111111111111111111111112');
1799
1761
  /** Address of the special mint for wrapped native SOL in spl-token-2022 */
@@ -1823,88 +1785,9 @@ var Layout$1 = {};
1823
1785
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1824
1786
  * THE SOFTWARE.
1825
1787
  */
1826
- Object.defineProperty(Layout$1, '__esModule', { value: true });
1827
- Layout$1.s16 =
1828
- Layout$1.s8 =
1829
- Layout$1.nu64be =
1830
- Layout$1.u48be =
1831
- Layout$1.u40be =
1832
- Layout$1.u32be =
1833
- Layout$1.u24be =
1834
- Layout$1.u16be =
1835
- Layout$1.nu64 =
1836
- Layout$1.u48 =
1837
- Layout$1.u40 =
1838
- u32 =
1839
- Layout$1.u32 =
1840
- Layout$1.u24 =
1841
- Layout$1.u16 =
1842
- u8 =
1843
- Layout$1.u8 =
1844
- Layout$1.offset =
1845
- Layout$1.greedy =
1846
- Layout$1.Constant =
1847
- Layout$1.UTF8 =
1848
- Layout$1.CString =
1849
- Layout$1.Blob =
1850
- Layout$1.Boolean =
1851
- Layout$1.BitField =
1852
- Layout$1.BitStructure =
1853
- Layout$1.VariantLayout =
1854
- Layout$1.Union =
1855
- Layout$1.UnionLayoutDiscriminator =
1856
- Layout$1.UnionDiscriminator =
1857
- Layout$1.Structure =
1858
- Layout$1.Sequence =
1859
- Layout$1.DoubleBE =
1860
- Layout$1.Double =
1861
- Layout$1.FloatBE =
1862
- Layout$1.Float =
1863
- Layout$1.NearInt64BE =
1864
- Layout$1.NearInt64 =
1865
- Layout$1.NearUInt64BE =
1866
- Layout$1.NearUInt64 =
1867
- Layout$1.IntBE =
1868
- Layout$1.Int =
1869
- Layout$1.UIntBE =
1870
- Layout$1.UInt =
1871
- Layout$1.OffsetLayout =
1872
- Layout$1.GreedyCount =
1873
- Layout$1.ExternalLayout =
1874
- Layout$1.bindConstructorLayout =
1875
- Layout$1.nameWithProperty =
1876
- Layout_2 =
1877
- Layout$1.Layout =
1878
- Layout$1.uint8ArrayToBuffer =
1879
- Layout$1.checkUint8Array =
1880
- void 0;
1881
- Layout$1.constant =
1882
- Layout$1.utf8 =
1883
- Layout$1.cstr =
1884
- blob =
1885
- Layout$1.blob =
1886
- Layout$1.unionLayoutDiscriminator =
1887
- Layout$1.union =
1888
- Layout$1.seq =
1889
- Layout$1.bits =
1890
- struct =
1891
- Layout$1.struct =
1892
- Layout$1.f64be =
1893
- Layout$1.f64 =
1894
- Layout$1.f32be =
1895
- Layout$1.f32 =
1896
- Layout$1.ns64be =
1897
- Layout$1.s48be =
1898
- Layout$1.s40be =
1899
- Layout$1.s32be =
1900
- Layout$1.s24be =
1901
- Layout$1.s16be =
1902
- Layout$1.ns64 =
1903
- Layout$1.s48 =
1904
- Layout$1.s40 =
1905
- Layout$1.s32 =
1906
- Layout$1.s24 =
1907
- void 0;
1788
+ Object.defineProperty(Layout$1, "__esModule", { value: true });
1789
+ Layout$1.s16 = Layout$1.s8 = Layout$1.nu64be = Layout$1.u48be = Layout$1.u40be = Layout$1.u32be = Layout$1.u24be = Layout$1.u16be = Layout$1.nu64 = Layout$1.u48 = Layout$1.u40 = u32 = Layout$1.u32 = Layout$1.u24 = Layout$1.u16 = u8 = Layout$1.u8 = Layout$1.offset = Layout$1.greedy = Layout$1.Constant = Layout$1.UTF8 = Layout$1.CString = Layout$1.Blob = Layout$1.Boolean = Layout$1.BitField = Layout$1.BitStructure = Layout$1.VariantLayout = Layout$1.Union = Layout$1.UnionLayoutDiscriminator = Layout$1.UnionDiscriminator = Layout$1.Structure = Layout$1.Sequence = Layout$1.DoubleBE = Layout$1.Double = Layout$1.FloatBE = Layout$1.Float = Layout$1.NearInt64BE = Layout$1.NearInt64 = Layout$1.NearUInt64BE = Layout$1.NearUInt64 = Layout$1.IntBE = Layout$1.Int = Layout$1.UIntBE = Layout$1.UInt = Layout$1.OffsetLayout = Layout$1.GreedyCount = Layout$1.ExternalLayout = Layout$1.bindConstructorLayout = Layout$1.nameWithProperty = Layout_2 = Layout$1.Layout = Layout$1.uint8ArrayToBuffer = Layout$1.checkUint8Array = void 0;
1790
+ Layout$1.constant = Layout$1.utf8 = Layout$1.cstr = blob = Layout$1.blob = Layout$1.unionLayoutDiscriminator = Layout$1.union = Layout$1.seq = Layout$1.bits = struct = Layout$1.struct = Layout$1.f64be = Layout$1.f64 = Layout$1.f32be = Layout$1.f32 = Layout$1.ns64be = Layout$1.s48be = Layout$1.s40be = Layout$1.s32be = Layout$1.s24be = Layout$1.s16be = Layout$1.ns64 = Layout$1.s48 = Layout$1.s40 = Layout$1.s32 = Layout$1.s24 = void 0;
1908
1791
  const buffer_1 = require$$0;
1909
1792
  /* Check if a value is a Uint8Array.
1910
1793
  *
@@ -2050,7 +1933,7 @@ class Layout {
2050
1933
  return undefined;
2051
1934
  }
2052
1935
  }
2053
- var Layout_2 = (Layout$1.Layout = Layout);
1936
+ var Layout_2 = Layout$1.Layout = Layout;
2054
1937
  /* Provide text that carries a name (such as for a function that will
2055
1938
  * be throwing an error) annotated with the property of a given layout
2056
1939
  * (such as one for which the value was unacceptable).
@@ -2099,7 +1982,7 @@ function bindConstructorLayout(Class, layout) {
2099
1982
  if (Object.prototype.hasOwnProperty.call(Class, 'layout_')) {
2100
1983
  throw new Error('Class is already bound to a layout');
2101
1984
  }
2102
- if (!(layout && layout instanceof Layout)) {
1985
+ if (!(layout && (layout instanceof Layout))) {
2103
1986
  throw new TypeError('layout must be a Layout');
2104
1987
  }
2105
1988
  if (Object.prototype.hasOwnProperty.call(layout, 'boundConstructor_')) {
@@ -2107,7 +1990,7 @@ function bindConstructorLayout(Class, layout) {
2107
1990
  }
2108
1991
  Class.layout_ = layout;
2109
1992
  layout.boundConstructor_ = Class;
2110
- layout.makeDestinationObject = () => new Class();
1993
+ layout.makeDestinationObject = (() => new Class());
2111
1994
  Object.defineProperty(Class.prototype, 'encode', {
2112
1995
  value(b, offset) {
2113
1996
  return layout.encode(this, b, offset);
@@ -2177,7 +2060,7 @@ Layout$1.ExternalLayout = ExternalLayout;
2177
2060
  */
2178
2061
  class GreedyCount extends ExternalLayout {
2179
2062
  constructor(elementSpan = 1, property) {
2180
- if (!Number.isInteger(elementSpan) || 0 >= elementSpan) {
2063
+ if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {
2181
2064
  throw new TypeError('elementSpan must be a (positive) integer');
2182
2065
  }
2183
2066
  super(-1, property);
@@ -2243,7 +2126,8 @@ class OffsetLayout extends ExternalLayout {
2243
2126
  }
2244
2127
  /** @override */
2245
2128
  isCount() {
2246
- return this.layout instanceof UInt || this.layout instanceof UIntBE;
2129
+ return ((this.layout instanceof UInt)
2130
+ || (this.layout instanceof UIntBE));
2247
2131
  }
2248
2132
  /** @override */
2249
2133
  decode(b, offset = 0) {
@@ -2396,7 +2280,7 @@ const V2E32 = Math.pow(2, 32);
2396
2280
  * non-negative. */
2397
2281
  function divmodInt64(src) {
2398
2282
  const hi32 = Math.floor(src / V2E32);
2399
- const lo32 = src - hi32 * V2E32;
2283
+ const lo32 = src - (hi32 * V2E32);
2400
2284
  return { hi32, lo32 };
2401
2285
  }
2402
2286
  /* Reconstruct Number from quotient and non-negative remainder */
@@ -2653,19 +2537,14 @@ class Sequence extends Layout {
2653
2537
  if (!(elementLayout instanceof Layout)) {
2654
2538
  throw new TypeError('elementLayout must be a Layout');
2655
2539
  }
2656
- if (
2657
- !(
2658
- (count instanceof ExternalLayout && count.isCount()) ||
2659
- (Number.isInteger(count) && 0 <= count)
2660
- )
2661
- ) {
2662
- throw new TypeError(
2663
- 'count must be non-negative integer ' +
2664
- 'or an unsigned integer ExternalLayout',
2665
- );
2540
+ if (!(((count instanceof ExternalLayout) && count.isCount())
2541
+ || (Number.isInteger(count) && (0 <= count)))) {
2542
+ throw new TypeError('count must be non-negative integer '
2543
+ + 'or an unsigned integer ExternalLayout');
2666
2544
  }
2667
2545
  let span = -1;
2668
- if (!(count instanceof ExternalLayout) && 0 < elementLayout.span) {
2546
+ if ((!(count instanceof ExternalLayout))
2547
+ && (0 < elementLayout.span)) {
2669
2548
  span = count * elementLayout.span;
2670
2549
  }
2671
2550
  super(span, property);
@@ -2690,7 +2569,8 @@ class Sequence extends Layout {
2690
2569
  }
2691
2570
  if (0 < this.elementLayout.span) {
2692
2571
  span = count * this.elementLayout.span;
2693
- } else {
2572
+ }
2573
+ else {
2694
2574
  let idx = 0;
2695
2575
  while (idx < count) {
2696
2576
  span += this.elementLayout.getSpan(b, offset + span);
@@ -2770,30 +2650,27 @@ Layout$1.Sequence = Sequence;
2770
2650
  */
2771
2651
  class Structure extends Layout {
2772
2652
  constructor(fields, property, decodePrefixes) {
2773
- if (
2774
- !(
2775
- Array.isArray(fields) &&
2776
- fields.reduce((acc, v) => acc && v instanceof Layout, true)
2777
- )
2778
- ) {
2653
+ if (!(Array.isArray(fields)
2654
+ && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {
2779
2655
  throw new TypeError('fields must be array of Layout instances');
2780
2656
  }
2781
- if ('boolean' === typeof property && undefined === decodePrefixes) {
2657
+ if (('boolean' === typeof property)
2658
+ && (undefined === decodePrefixes)) {
2782
2659
  decodePrefixes = property;
2783
2660
  property = undefined;
2784
2661
  }
2785
2662
  /* Verify absence of unnamed variable-length fields. */
2786
2663
  for (const fd of fields) {
2787
- if (0 > fd.span && undefined === fd.property) {
2788
- throw new Error(
2789
- 'fields cannot contain unnamed variable-length layout',
2790
- );
2664
+ if ((0 > fd.span)
2665
+ && (undefined === fd.property)) {
2666
+ throw new Error('fields cannot contain unnamed variable-length layout');
2791
2667
  }
2792
2668
  }
2793
2669
  let span = -1;
2794
2670
  try {
2795
2671
  span = fields.reduce((span, fd) => span + fd.getSpan(), 0);
2796
- } catch (e) {
2672
+ }
2673
+ catch (e) {
2797
2674
  // ignore error
2798
2675
  }
2799
2676
  super(span, property);
@@ -2831,7 +2708,8 @@ class Structure extends Layout {
2831
2708
  offset += fsp;
2832
2709
  return span + fsp;
2833
2710
  }, 0);
2834
- } catch (e) {
2711
+ }
2712
+ catch (e) {
2835
2713
  throw new RangeError('indeterminate span');
2836
2714
  }
2837
2715
  return span;
@@ -2845,7 +2723,8 @@ class Structure extends Layout {
2845
2723
  dest[fd.property] = fd.decode(b, offset);
2846
2724
  }
2847
2725
  offset += fd.getSpan(b, offset);
2848
- if (this.decodePrefixes && b.length === offset) {
2726
+ if (this.decodePrefixes
2727
+ && (b.length === offset)) {
2849
2728
  break;
2850
2729
  }
2851
2730
  }
@@ -2862,7 +2741,7 @@ class Structure extends Layout {
2862
2741
  let lastWrote = 0;
2863
2742
  for (const fd of this.fields) {
2864
2743
  let span = fd.span;
2865
- lastWrote = 0 < span ? span : 0;
2744
+ lastWrote = (0 < span) ? span : 0;
2866
2745
  if (undefined !== fd.property) {
2867
2746
  const fv = src[fd.property];
2868
2747
  if (undefined !== fv) {
@@ -2881,13 +2760,14 @@ class Structure extends Layout {
2881
2760
  * item may have had a dynamic length and we don't want to include
2882
2761
  * the padding between it and the end of the space reserved for
2883
2762
  * it. */
2884
- return lastOffset + lastWrote - firstOffset;
2763
+ return (lastOffset + lastWrote) - firstOffset;
2885
2764
  }
2886
2765
  /** @override */
2887
2766
  fromArray(values) {
2888
2767
  const dest = this.makeDestinationObject();
2889
2768
  for (const fd of this.fields) {
2890
- if (undefined !== fd.property && 0 < values.length) {
2769
+ if ((undefined !== fd.property)
2770
+ && (0 < values.length)) {
2891
2771
  dest[fd.property] = values.shift();
2892
2772
  }
2893
2773
  }
@@ -2934,7 +2814,8 @@ class Structure extends Layout {
2934
2814
  }
2935
2815
  if (0 > fd.span) {
2936
2816
  offset = -1;
2937
- } else if (0 <= offset) {
2817
+ }
2818
+ else if (0 <= offset) {
2938
2819
  offset += fd.span;
2939
2820
  }
2940
2821
  }
@@ -2999,10 +2880,9 @@ Layout$1.UnionDiscriminator = UnionDiscriminator;
2999
2880
  */
3000
2881
  class UnionLayoutDiscriminator extends UnionDiscriminator {
3001
2882
  constructor(layout, property) {
3002
- if (!(layout instanceof ExternalLayout && layout.isCount())) {
3003
- throw new TypeError(
3004
- 'layout must be an unsigned integer ExternalLayout',
3005
- );
2883
+ if (!((layout instanceof ExternalLayout)
2884
+ && layout.isCount())) {
2885
+ throw new TypeError('layout must be an unsigned integer ExternalLayout');
3006
2886
  }
3007
2887
  super(property || layout.property || 'variant');
3008
2888
  /** The {@link ExternalLayout} used to access the discriminator
@@ -3081,24 +2961,26 @@ Layout$1.UnionLayoutDiscriminator = UnionLayoutDiscriminator;
3081
2961
  class Union extends Layout {
3082
2962
  constructor(discr, defaultLayout, property) {
3083
2963
  let discriminator;
3084
- if (discr instanceof UInt || discr instanceof UIntBE) {
3085
- discriminator = new UnionLayoutDiscriminator(
3086
- new OffsetLayout(discr),
3087
- );
3088
- } else if (discr instanceof ExternalLayout && discr.isCount()) {
2964
+ if ((discr instanceof UInt)
2965
+ || (discr instanceof UIntBE)) {
2966
+ discriminator = new UnionLayoutDiscriminator(new OffsetLayout(discr));
2967
+ }
2968
+ else if ((discr instanceof ExternalLayout)
2969
+ && discr.isCount()) {
3089
2970
  discriminator = new UnionLayoutDiscriminator(discr);
3090
- } else if (!(discr instanceof UnionDiscriminator)) {
3091
- throw new TypeError(
3092
- 'discr must be a UnionDiscriminator ' +
3093
- 'or an unsigned integer layout',
3094
- );
3095
- } else {
2971
+ }
2972
+ else if (!(discr instanceof UnionDiscriminator)) {
2973
+ throw new TypeError('discr must be a UnionDiscriminator '
2974
+ + 'or an unsigned integer layout');
2975
+ }
2976
+ else {
3096
2977
  discriminator = discr;
3097
2978
  }
3098
2979
  if (undefined === defaultLayout) {
3099
2980
  defaultLayout = null;
3100
2981
  }
3101
- if (!(null === defaultLayout || defaultLayout instanceof Layout)) {
2982
+ if (!((null === defaultLayout)
2983
+ || (defaultLayout instanceof Layout))) {
3102
2984
  throw new TypeError('defaultLayout must be null or a Layout');
3103
2985
  }
3104
2986
  if (null !== defaultLayout) {
@@ -3116,10 +2998,8 @@ class Union extends Layout {
3116
2998
  let span = -1;
3117
2999
  if (defaultLayout) {
3118
3000
  span = defaultLayout.span;
3119
- if (
3120
- 0 <= span &&
3121
- (discr instanceof UInt || discr instanceof UIntBE)
3122
- ) {
3001
+ if ((0 <= span) && ((discr instanceof UInt)
3002
+ || (discr instanceof UIntBE))) {
3123
3003
  span += discriminator.layout.span;
3124
3004
  }
3125
3005
  }
@@ -3138,8 +3018,8 @@ class Union extends Layout {
3138
3018
  *
3139
3019
  * If `false` the discriminator is obtained from somewhere
3140
3020
  * else. */
3141
- this.usesPrefixDiscriminator =
3142
- discr instanceof UInt || discr instanceof UIntBE;
3021
+ this.usesPrefixDiscriminator = (discr instanceof UInt)
3022
+ || (discr instanceof UIntBE);
3143
3023
  /** The layout for non-discriminator content when the value of the
3144
3024
  * discriminator is not recognized.
3145
3025
  *
@@ -3204,9 +3084,7 @@ class Union extends Layout {
3204
3084
  * determine the span. */
3205
3085
  const vlo = this.getVariant(b, offset);
3206
3086
  if (!vlo) {
3207
- throw new Error(
3208
- 'unable to determine span for unrecognized variant',
3209
- );
3087
+ throw new Error('unable to determine span for unrecognized variant');
3210
3088
  }
3211
3089
  return vlo.getSpan(b, offset);
3212
3090
  }
@@ -3240,41 +3118,22 @@ class Union extends Layout {
3240
3118
  * registered variant.
3241
3119
  */
3242
3120
  defaultGetSourceVariant(src) {
3243
- if (
3244
- Object.prototype.hasOwnProperty.call(
3245
- src,
3246
- this.discriminator.property,
3247
- )
3248
- ) {
3249
- if (
3250
- this.defaultLayout &&
3251
- this.defaultLayout.property &&
3252
- Object.prototype.hasOwnProperty.call(
3253
- src,
3254
- this.defaultLayout.property,
3255
- )
3256
- ) {
3121
+ if (Object.prototype.hasOwnProperty.call(src, this.discriminator.property)) {
3122
+ if (this.defaultLayout && this.defaultLayout.property
3123
+ && Object.prototype.hasOwnProperty.call(src, this.defaultLayout.property)) {
3257
3124
  return undefined;
3258
3125
  }
3259
3126
  const vlo = this.registry[src[this.discriminator.property]];
3260
- if (
3261
- vlo &&
3262
- (!vlo.layout ||
3263
- (vlo.property &&
3264
- Object.prototype.hasOwnProperty.call(
3265
- src,
3266
- vlo.property,
3267
- )))
3268
- ) {
3127
+ if (vlo
3128
+ && ((!vlo.layout)
3129
+ || (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)))) {
3269
3130
  return vlo;
3270
3131
  }
3271
- } else {
3132
+ }
3133
+ else {
3272
3134
  for (const tag in this.registry) {
3273
3135
  const vlo = this.registry[tag];
3274
- if (
3275
- vlo.property &&
3276
- Object.prototype.hasOwnProperty.call(src, vlo.property)
3277
- ) {
3136
+ if (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)) {
3278
3137
  return vlo;
3279
3138
  }
3280
3139
  }
@@ -3302,11 +3161,9 @@ class Union extends Layout {
3302
3161
  dest[dlo.property] = discr;
3303
3162
  // defaultLayout.property can be undefined, but this is allowed by buffer-layout
3304
3163
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
3305
- dest[defaultLayout.property] = defaultLayout.decode(
3306
- b,
3307
- offset + contentOffset,
3308
- );
3309
- } else {
3164
+ dest[defaultLayout.property] = defaultLayout.decode(b, offset + contentOffset);
3165
+ }
3166
+ else {
3310
3167
  dest = clo.decode(b, offset);
3311
3168
  }
3312
3169
  return dest;
@@ -3331,10 +3188,7 @@ class Union extends Layout {
3331
3188
  dlo.encode(src[dlo.property], b, offset);
3332
3189
  // clo.property is not undefined when vlo is undefined
3333
3190
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
3334
- return (
3335
- contentOffset +
3336
- clo.encode(src[clo.property], b, offset + contentOffset)
3337
- );
3191
+ return contentOffset + clo.encode(src[clo.property], b, offset + contentOffset);
3338
3192
  }
3339
3193
  return vlo.encode(src, b, offset);
3340
3194
  }
@@ -3374,7 +3228,8 @@ class Union extends Layout {
3374
3228
  let variant;
3375
3229
  if (vb instanceof Uint8Array) {
3376
3230
  variant = this.discriminator.decode(vb, offset);
3377
- } else {
3231
+ }
3232
+ else {
3378
3233
  variant = vb;
3379
3234
  }
3380
3235
  return this.registry[variant];
@@ -3415,10 +3270,11 @@ class VariantLayout extends Layout {
3415
3270
  if (!(union instanceof Union)) {
3416
3271
  throw new TypeError('union must be a Union');
3417
3272
  }
3418
- if (!Number.isInteger(variant) || 0 > variant) {
3273
+ if ((!Number.isInteger(variant)) || (0 > variant)) {
3419
3274
  throw new TypeError('variant must be a (non-negative) integer');
3420
3275
  }
3421
- if ('string' === typeof layout && undefined === property) {
3276
+ if (('string' === typeof layout)
3277
+ && (undefined === property)) {
3422
3278
  property = layout;
3423
3279
  layout = null;
3424
3280
  }
@@ -3426,14 +3282,10 @@ class VariantLayout extends Layout {
3426
3282
  if (!(layout instanceof Layout)) {
3427
3283
  throw new TypeError('layout must be a Layout');
3428
3284
  }
3429
- if (
3430
- null !== union.defaultLayout &&
3431
- 0 <= layout.span &&
3432
- layout.span > union.defaultLayout.span
3433
- ) {
3434
- throw new Error(
3435
- 'variant span exceeds span of containing union',
3436
- );
3285
+ if ((null !== union.defaultLayout)
3286
+ && (0 <= layout.span)
3287
+ && (layout.span > union.defaultLayout.span)) {
3288
+ throw new Error('variant span exceeds span of containing union');
3437
3289
  }
3438
3290
  if ('string' !== typeof property) {
3439
3291
  throw new TypeError('variant must have a String property');
@@ -3442,7 +3294,7 @@ class VariantLayout extends Layout {
3442
3294
  let span = union.span;
3443
3295
  if (0 > union.span) {
3444
3296
  span = layout ? layout.span : 0;
3445
- if (0 <= span && union.usesPrefixDiscriminator) {
3297
+ if ((0 <= span) && union.usesPrefixDiscriminator) {
3446
3298
  span += union.discriminator.layout.span;
3447
3299
  }
3448
3300
  }
@@ -3489,9 +3341,11 @@ class VariantLayout extends Layout {
3489
3341
  }
3490
3342
  if (this.layout) {
3491
3343
  dest[this.property] = this.layout.decode(b, offset + contentOffset);
3492
- } else if (this.property) {
3344
+ }
3345
+ else if (this.property) {
3493
3346
  dest[this.property] = true;
3494
- } else if (this.union.usesPrefixDiscriminator) {
3347
+ }
3348
+ else if (this.union.usesPrefixDiscriminator) {
3495
3349
  dest[this.union.discriminator.property] = this.variant;
3496
3350
  }
3497
3351
  return dest;
@@ -3502,10 +3356,8 @@ class VariantLayout extends Layout {
3502
3356
  if (this.union.usesPrefixDiscriminator) {
3503
3357
  contentOffset = this.union.discriminator.layout.span;
3504
3358
  }
3505
- if (
3506
- this.layout &&
3507
- !Object.prototype.hasOwnProperty.call(src, this.property)
3508
- ) {
3359
+ if (this.layout
3360
+ && (!Object.prototype.hasOwnProperty.call(src, this.property))) {
3509
3361
  throw new TypeError('variant lacks property ' + this.property);
3510
3362
  }
3511
3363
  this.union.discriminator.encode(this.variant, b, offset);
@@ -3513,7 +3365,8 @@ class VariantLayout extends Layout {
3513
3365
  if (this.layout) {
3514
3366
  this.layout.encode(src[this.property], b, offset + contentOffset);
3515
3367
  span += this.layout.getSpan(b, offset + contentOffset);
3516
- if (0 <= this.union.span && span > this.union.span) {
3368
+ if ((0 <= this.union.span)
3369
+ && (span > this.union.span)) {
3517
3370
  throw new Error('encoded variant overruns containing union');
3518
3371
  }
3519
3372
  }
@@ -3574,10 +3427,12 @@ function fixBitwiseResult(v) {
3574
3427
  */
3575
3428
  class BitStructure extends Layout {
3576
3429
  constructor(word, msb, property) {
3577
- if (!(word instanceof UInt || word instanceof UIntBE)) {
3430
+ if (!((word instanceof UInt)
3431
+ || (word instanceof UIntBE))) {
3578
3432
  throw new TypeError('word must be a UInt or UIntBE layout');
3579
3433
  }
3580
- if ('string' === typeof msb && undefined === property) {
3434
+ if (('string' === typeof msb)
3435
+ && (undefined === property)) {
3581
3436
  property = msb;
3582
3437
  msb = false;
3583
3438
  }
@@ -3721,19 +3576,15 @@ class BitField {
3721
3576
  if (!(container instanceof BitStructure)) {
3722
3577
  throw new TypeError('container must be a BitStructure');
3723
3578
  }
3724
- if (!Number.isInteger(bits) || 0 >= bits) {
3579
+ if ((!Number.isInteger(bits)) || (0 >= bits)) {
3725
3580
  throw new TypeError('bits must be positive integer');
3726
3581
  }
3727
3582
  const totalBits = 8 * container.span;
3728
3583
  const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);
3729
- if (bits + usedBits > totalBits) {
3730
- throw new Error(
3731
- 'bits too long for span remainder (' +
3732
- (totalBits - usedBits) +
3733
- ' of ' +
3734
- totalBits +
3735
- ' remain)',
3736
- );
3584
+ if ((bits + usedBits) > totalBits) {
3585
+ throw new Error('bits too long for span remainder ('
3586
+ + (totalBits - usedBits) + ' of '
3587
+ + totalBits + ' remain)');
3737
3588
  }
3738
3589
  /** The {@link BitStructure} instance to which this bit field
3739
3590
  * belongs. */
@@ -3746,9 +3597,8 @@ class BitField {
3746
3597
  * That is, it masks a value that has not yet been shifted into
3747
3598
  * position within its containing packed integer. */
3748
3599
  this.valueMask = (1 << bits) - 1;
3749
- if (32 === bits) {
3750
- // shifted value out of range
3751
- this.valueMask = 0xffffffff;
3600
+ if (32 === bits) { // shifted value out of range
3601
+ this.valueMask = 0xFFFFFFFF;
3752
3602
  }
3753
3603
  /** The offset of the value within the containing packed unsigned
3754
3604
  * integer. The least significant bit of the packed value is at
@@ -3786,22 +3636,16 @@ class BitField {
3786
3636
  * **NOTE** This is not a specialization of {@link
3787
3637
  * Layout#encode|Layout.encode} and there is no return value. */
3788
3638
  encode(value) {
3789
- if (
3790
- 'number' !== typeof value ||
3791
- !Number.isInteger(value) ||
3792
- value !== fixBitwiseResult(value & this.valueMask)
3793
- ) {
3794
- throw new TypeError(
3795
- nameWithProperty('BitField.encode', this) +
3796
- ' value must be integer not exceeding ' +
3797
- this.valueMask,
3798
- );
3639
+ if ('number' !== typeof value
3640
+ || !Number.isInteger(value)
3641
+ || (value !== fixBitwiseResult(value & this.valueMask))) {
3642
+ throw new TypeError(nameWithProperty('BitField.encode', this)
3643
+ + ' value must be integer not exceeding ' + this.valueMask);
3799
3644
  }
3800
3645
  const word = this.container._packedGetValue();
3801
3646
  const wordValue = fixBitwiseResult(value << this.start);
3802
- this.container._packedSetValue(
3803
- fixBitwiseResult(word & ~this.wordMask) | wordValue,
3804
- );
3647
+ this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)
3648
+ | wordValue);
3805
3649
  }
3806
3650
  }
3807
3651
  Layout$1.BitField = BitField;
@@ -3859,16 +3703,10 @@ Layout$1.Boolean = Boolean;
3859
3703
  */
3860
3704
  class Blob extends Layout {
3861
3705
  constructor(length, property) {
3862
- if (
3863
- !(
3864
- (length instanceof ExternalLayout && length.isCount()) ||
3865
- (Number.isInteger(length) && 0 <= length)
3866
- )
3867
- ) {
3868
- throw new TypeError(
3869
- 'length must be positive integer ' +
3870
- 'or an unsigned integer ExternalLayout',
3871
- );
3706
+ if (!(((length instanceof ExternalLayout) && length.isCount())
3707
+ || (Number.isInteger(length) && (0 <= length)))) {
3708
+ throw new TypeError('length must be positive integer '
3709
+ + 'or an unsigned integer ExternalLayout');
3872
3710
  }
3873
3711
  let span = -1;
3874
3712
  if (!(length instanceof ExternalLayout)) {
@@ -3909,23 +3747,14 @@ class Blob extends Layout {
3909
3747
  span = src.length;
3910
3748
  }
3911
3749
  if (!(src instanceof Uint8Array && span === src.length)) {
3912
- throw new TypeError(
3913
- nameWithProperty('Blob.encode', this) +
3914
- ' requires (length ' +
3915
- span +
3916
- ') Uint8Array as src',
3917
- );
3750
+ throw new TypeError(nameWithProperty('Blob.encode', this)
3751
+ + ' requires (length ' + span + ') Uint8Array as src');
3918
3752
  }
3919
- if (offset + span > b.length) {
3753
+ if ((offset + span) > b.length) {
3920
3754
  throw new RangeError('encoding overruns Uint8Array');
3921
3755
  }
3922
3756
  const srcBuffer = uint8ArrayToBuffer(src);
3923
- uint8ArrayToBuffer(b).write(
3924
- srcBuffer.toString('hex'),
3925
- offset,
3926
- span,
3927
- 'hex',
3928
- );
3757
+ uint8ArrayToBuffer(b).write(srcBuffer.toString('hex'), offset, span, 'hex');
3929
3758
  if (this.length instanceof ExternalLayout) {
3930
3759
  this.length.encode(span, b, offset);
3931
3760
  }
@@ -3954,7 +3783,7 @@ class CString extends Layout {
3954
3783
  getSpan(b, offset = 0) {
3955
3784
  checkUint8Array(b);
3956
3785
  let idx = offset;
3957
- while (idx < b.length && 0 !== b[idx]) {
3786
+ while ((idx < b.length) && (0 !== b[idx])) {
3958
3787
  idx += 1;
3959
3788
  }
3960
3789
  return 1 + idx - offset;
@@ -3962,9 +3791,7 @@ class CString extends Layout {
3962
3791
  /** @override */
3963
3792
  decode(b, offset = 0) {
3964
3793
  const span = this.getSpan(b, offset);
3965
- return uint8ArrayToBuffer(b)
3966
- .slice(offset, offset + span - 1)
3967
- .toString('utf-8');
3794
+ return uint8ArrayToBuffer(b).slice(offset, offset + span - 1).toString('utf-8');
3968
3795
  }
3969
3796
  /** @override */
3970
3797
  encode(src, b, offset = 0) {
@@ -3976,7 +3803,7 @@ class CString extends Layout {
3976
3803
  }
3977
3804
  const srcb = buffer_1.Buffer.from(src, 'utf8');
3978
3805
  const span = srcb.length;
3979
- if (offset + span > b.length) {
3806
+ if ((offset + span) > b.length) {
3980
3807
  throw new RangeError('encoding overruns Buffer');
3981
3808
  }
3982
3809
  const buffer = uint8ArrayToBuffer(b);
@@ -4007,13 +3834,14 @@ Layout$1.CString = CString;
4007
3834
  */
4008
3835
  class UTF8 extends Layout {
4009
3836
  constructor(maxSpan, property) {
4010
- if ('string' === typeof maxSpan && undefined === property) {
3837
+ if (('string' === typeof maxSpan) && (undefined === property)) {
4011
3838
  property = maxSpan;
4012
3839
  maxSpan = undefined;
4013
3840
  }
4014
3841
  if (undefined === maxSpan) {
4015
3842
  maxSpan = -1;
4016
- } else if (!Number.isInteger(maxSpan)) {
3843
+ }
3844
+ else if (!Number.isInteger(maxSpan)) {
4017
3845
  throw new TypeError('maxSpan must be an integer');
4018
3846
  }
4019
3847
  super(-1, property);
@@ -4035,12 +3863,11 @@ class UTF8 extends Layout {
4035
3863
  /** @override */
4036
3864
  decode(b, offset = 0) {
4037
3865
  const span = this.getSpan(b, offset);
4038
- if (0 <= this.maxSpan && this.maxSpan < span) {
3866
+ if ((0 <= this.maxSpan)
3867
+ && (this.maxSpan < span)) {
4039
3868
  throw new RangeError('text length exceeds maxSpan');
4040
3869
  }
4041
- return uint8ArrayToBuffer(b)
4042
- .slice(offset, offset + span)
4043
- .toString('utf-8');
3870
+ return uint8ArrayToBuffer(b).slice(offset, offset + span).toString('utf-8');
4044
3871
  }
4045
3872
  /** @override */
4046
3873
  encode(src, b, offset = 0) {
@@ -4052,10 +3879,11 @@ class UTF8 extends Layout {
4052
3879
  }
4053
3880
  const srcb = buffer_1.Buffer.from(src, 'utf8');
4054
3881
  const span = srcb.length;
4055
- if (0 <= this.maxSpan && this.maxSpan < span) {
3882
+ if ((0 <= this.maxSpan)
3883
+ && (this.maxSpan < span)) {
4056
3884
  throw new RangeError('text length exceeds maxSpan');
4057
3885
  }
4058
- if (offset + span > b.length) {
3886
+ if ((offset + span) > b.length) {
4059
3887
  throw new RangeError('encoding overruns Buffer');
4060
3888
  }
4061
3889
  srcb.copy(uint8ArrayToBuffer(b), offset);
@@ -4108,121 +3936,115 @@ class Constant extends Layout {
4108
3936
  }
4109
3937
  Layout$1.Constant = Constant;
4110
3938
  /** Factory for {@link GreedyCount}. */
4111
- Layout$1.greedy = (elementSpan, property) =>
4112
- new GreedyCount(elementSpan, property);
3939
+ Layout$1.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));
4113
3940
  /** Factory for {@link OffsetLayout}. */
4114
- Layout$1.offset = (layout, offset, property) =>
4115
- new OffsetLayout(layout, offset, property);
3941
+ Layout$1.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));
4116
3942
  /** Factory for {@link UInt|unsigned int layouts} spanning one
4117
3943
  * byte. */
4118
- var u8 = (Layout$1.u8 = property => new UInt(1, property));
3944
+ var u8 = Layout$1.u8 = ((property) => new UInt(1, property));
4119
3945
  /** Factory for {@link UInt|little-endian unsigned int layouts}
4120
3946
  * spanning two bytes. */
4121
- Layout$1.u16 = property => new UInt(2, property);
3947
+ Layout$1.u16 = ((property) => new UInt(2, property));
4122
3948
  /** Factory for {@link UInt|little-endian unsigned int layouts}
4123
3949
  * spanning three bytes. */
4124
- Layout$1.u24 = property => new UInt(3, property);
3950
+ Layout$1.u24 = ((property) => new UInt(3, property));
4125
3951
  /** Factory for {@link UInt|little-endian unsigned int layouts}
4126
3952
  * spanning four bytes. */
4127
- var u32 = (Layout$1.u32 = property => new UInt(4, property));
3953
+ var u32 = Layout$1.u32 = ((property) => new UInt(4, property));
4128
3954
  /** Factory for {@link UInt|little-endian unsigned int layouts}
4129
3955
  * spanning five bytes. */
4130
- Layout$1.u40 = property => new UInt(5, property);
3956
+ Layout$1.u40 = ((property) => new UInt(5, property));
4131
3957
  /** Factory for {@link UInt|little-endian unsigned int layouts}
4132
3958
  * spanning six bytes. */
4133
- Layout$1.u48 = property => new UInt(6, property);
3959
+ Layout$1.u48 = ((property) => new UInt(6, property));
4134
3960
  /** Factory for {@link NearUInt64|little-endian unsigned int
4135
3961
  * layouts} interpreted as Numbers. */
4136
- Layout$1.nu64 = property => new NearUInt64(property);
3962
+ Layout$1.nu64 = ((property) => new NearUInt64(property));
4137
3963
  /** Factory for {@link UInt|big-endian unsigned int layouts}
4138
3964
  * spanning two bytes. */
4139
- Layout$1.u16be = property => new UIntBE(2, property);
3965
+ Layout$1.u16be = ((property) => new UIntBE(2, property));
4140
3966
  /** Factory for {@link UInt|big-endian unsigned int layouts}
4141
3967
  * spanning three bytes. */
4142
- Layout$1.u24be = property => new UIntBE(3, property);
3968
+ Layout$1.u24be = ((property) => new UIntBE(3, property));
4143
3969
  /** Factory for {@link UInt|big-endian unsigned int layouts}
4144
3970
  * spanning four bytes. */
4145
- Layout$1.u32be = property => new UIntBE(4, property);
3971
+ Layout$1.u32be = ((property) => new UIntBE(4, property));
4146
3972
  /** Factory for {@link UInt|big-endian unsigned int layouts}
4147
3973
  * spanning five bytes. */
4148
- Layout$1.u40be = property => new UIntBE(5, property);
3974
+ Layout$1.u40be = ((property) => new UIntBE(5, property));
4149
3975
  /** Factory for {@link UInt|big-endian unsigned int layouts}
4150
3976
  * spanning six bytes. */
4151
- Layout$1.u48be = property => new UIntBE(6, property);
3977
+ Layout$1.u48be = ((property) => new UIntBE(6, property));
4152
3978
  /** Factory for {@link NearUInt64BE|big-endian unsigned int
4153
3979
  * layouts} interpreted as Numbers. */
4154
- Layout$1.nu64be = property => new NearUInt64BE(property);
3980
+ Layout$1.nu64be = ((property) => new NearUInt64BE(property));
4155
3981
  /** Factory for {@link Int|signed int layouts} spanning one
4156
3982
  * byte. */
4157
- Layout$1.s8 = property => new Int(1, property);
3983
+ Layout$1.s8 = ((property) => new Int(1, property));
4158
3984
  /** Factory for {@link Int|little-endian signed int layouts}
4159
3985
  * spanning two bytes. */
4160
- Layout$1.s16 = property => new Int(2, property);
3986
+ Layout$1.s16 = ((property) => new Int(2, property));
4161
3987
  /** Factory for {@link Int|little-endian signed int layouts}
4162
3988
  * spanning three bytes. */
4163
- Layout$1.s24 = property => new Int(3, property);
3989
+ Layout$1.s24 = ((property) => new Int(3, property));
4164
3990
  /** Factory for {@link Int|little-endian signed int layouts}
4165
3991
  * spanning four bytes. */
4166
- Layout$1.s32 = property => new Int(4, property);
3992
+ Layout$1.s32 = ((property) => new Int(4, property));
4167
3993
  /** Factory for {@link Int|little-endian signed int layouts}
4168
3994
  * spanning five bytes. */
4169
- Layout$1.s40 = property => new Int(5, property);
3995
+ Layout$1.s40 = ((property) => new Int(5, property));
4170
3996
  /** Factory for {@link Int|little-endian signed int layouts}
4171
3997
  * spanning six bytes. */
4172
- Layout$1.s48 = property => new Int(6, property);
3998
+ Layout$1.s48 = ((property) => new Int(6, property));
4173
3999
  /** Factory for {@link NearInt64|little-endian signed int layouts}
4174
4000
  * interpreted as Numbers. */
4175
- Layout$1.ns64 = property => new NearInt64(property);
4001
+ Layout$1.ns64 = ((property) => new NearInt64(property));
4176
4002
  /** Factory for {@link Int|big-endian signed int layouts}
4177
4003
  * spanning two bytes. */
4178
- Layout$1.s16be = property => new IntBE(2, property);
4004
+ Layout$1.s16be = ((property) => new IntBE(2, property));
4179
4005
  /** Factory for {@link Int|big-endian signed int layouts}
4180
4006
  * spanning three bytes. */
4181
- Layout$1.s24be = property => new IntBE(3, property);
4007
+ Layout$1.s24be = ((property) => new IntBE(3, property));
4182
4008
  /** Factory for {@link Int|big-endian signed int layouts}
4183
4009
  * spanning four bytes. */
4184
- Layout$1.s32be = property => new IntBE(4, property);
4010
+ Layout$1.s32be = ((property) => new IntBE(4, property));
4185
4011
  /** Factory for {@link Int|big-endian signed int layouts}
4186
4012
  * spanning five bytes. */
4187
- Layout$1.s40be = property => new IntBE(5, property);
4013
+ Layout$1.s40be = ((property) => new IntBE(5, property));
4188
4014
  /** Factory for {@link Int|big-endian signed int layouts}
4189
4015
  * spanning six bytes. */
4190
- Layout$1.s48be = property => new IntBE(6, property);
4016
+ Layout$1.s48be = ((property) => new IntBE(6, property));
4191
4017
  /** Factory for {@link NearInt64BE|big-endian signed int layouts}
4192
4018
  * interpreted as Numbers. */
4193
- Layout$1.ns64be = property => new NearInt64BE(property);
4019
+ Layout$1.ns64be = ((property) => new NearInt64BE(property));
4194
4020
  /** Factory for {@link Float|little-endian 32-bit floating point} values. */
4195
- Layout$1.f32 = property => new Float(property);
4021
+ Layout$1.f32 = ((property) => new Float(property));
4196
4022
  /** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */
4197
- Layout$1.f32be = property => new FloatBE(property);
4023
+ Layout$1.f32be = ((property) => new FloatBE(property));
4198
4024
  /** Factory for {@link Double|little-endian 64-bit floating point} values. */
4199
- Layout$1.f64 = property => new Double(property);
4025
+ Layout$1.f64 = ((property) => new Double(property));
4200
4026
  /** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */
4201
- Layout$1.f64be = property => new DoubleBE(property);
4027
+ Layout$1.f64be = ((property) => new DoubleBE(property));
4202
4028
  /** Factory for {@link Structure} values. */
4203
- var struct = (Layout$1.struct = (fields, property, decodePrefixes) =>
4204
- new Structure(fields, property, decodePrefixes));
4029
+ var struct = Layout$1.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));
4205
4030
  /** Factory for {@link BitStructure} values. */
4206
- Layout$1.bits = (word, msb, property) => new BitStructure(word, msb, property);
4031
+ Layout$1.bits = ((word, msb, property) => new BitStructure(word, msb, property));
4207
4032
  /** Factory for {@link Sequence} values. */
4208
- Layout$1.seq = (elementLayout, count, property) =>
4209
- new Sequence(elementLayout, count, property);
4033
+ Layout$1.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));
4210
4034
  /** Factory for {@link Union} values. */
4211
- Layout$1.union = (discr, defaultLayout, property) =>
4212
- new Union(discr, defaultLayout, property);
4035
+ Layout$1.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));
4213
4036
  /** Factory for {@link UnionLayoutDiscriminator} values. */
4214
- Layout$1.unionLayoutDiscriminator = (layout, property) =>
4215
- new UnionLayoutDiscriminator(layout, property);
4037
+ Layout$1.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));
4216
4038
  /** Factory for {@link Blob} values. */
4217
- var blob = (Layout$1.blob = (length, property) => new Blob(length, property));
4039
+ var blob = Layout$1.blob = ((length, property) => new Blob(length, property));
4218
4040
  /** Factory for {@link CString} values. */
4219
- Layout$1.cstr = property => new CString(property);
4041
+ Layout$1.cstr = ((property) => new CString(property));
4220
4042
  /** Factory for {@link UTF8} values. */
4221
- Layout$1.utf8 = (maxSpan, property) => new UTF8(maxSpan, property);
4043
+ Layout$1.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));
4222
4044
  /** Factory for {@link Constant} values. */
4223
- Layout$1.constant = (value, property) => new Constant(value, property);
4045
+ Layout$1.constant = ((value, property) => new Constant(value, property));
4224
4046
 
4225
- const encodeDecode = layout => {
4047
+ const encodeDecode = (layout) => {
4226
4048
  const decode = layout.decode.bind(layout);
4227
4049
  const encode = layout.encode.bind(layout);
4228
4050
  return { decode, encode };
@@ -4230,7 +4052,7 @@ const encodeDecode = layout => {
4230
4052
 
4231
4053
  var browser = {};
4232
4054
 
4233
- Object.defineProperty(browser, '__esModule', { value: true });
4055
+ Object.defineProperty(browser, "__esModule", { value: true });
4234
4056
  /**
4235
4057
  * Convert a little-endian buffer into a BigInt.
4236
4058
  * @param buf The little-endian buffer to convert
@@ -4247,7 +4069,7 @@ function toBigIntLE(buf) {
4247
4069
  return BigInt(`0x${hex}`);
4248
4070
  }
4249
4071
  }
4250
- var toBigIntLE_1 = (browser.toBigIntLE = toBigIntLE);
4072
+ var toBigIntLE_1 = browser.toBigIntLE = toBigIntLE;
4251
4073
  /**
4252
4074
  * Convert a big-endian buffer into a BigInt
4253
4075
  * @param buf The big-endian buffer to convert.
@@ -4272,15 +4094,12 @@ browser.toBigIntBE = toBigIntBE;
4272
4094
  function toBufferLE(num, width) {
4273
4095
  {
4274
4096
  const hex = num.toString(16);
4275
- const buffer = Buffer.from(
4276
- hex.padStart(width * 2, '0').slice(0, width * 2),
4277
- 'hex',
4278
- );
4097
+ const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
4279
4098
  buffer.reverse();
4280
4099
  return buffer;
4281
4100
  }
4282
4101
  }
4283
- var toBufferLE_1 = (browser.toBufferLE = toBufferLE);
4102
+ var toBufferLE_1 = browser.toBufferLE = toBufferLE;
4284
4103
  /**
4285
4104
  * Convert a BigInt to a big-endian buffer.
4286
4105
  * @param num The BigInt to convert.
@@ -4290,15 +4109,12 @@ var toBufferLE_1 = (browser.toBufferLE = toBufferLE);
4290
4109
  function toBufferBE(num, width) {
4291
4110
  {
4292
4111
  const hex = num.toString(16);
4293
- return Buffer.from(
4294
- hex.padStart(width * 2, '0').slice(0, width * 2),
4295
- 'hex',
4296
- );
4112
+ return Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
4297
4113
  }
4298
4114
  }
4299
4115
  browser.toBufferBE = toBufferBE;
4300
4116
 
4301
- const bigInt = length => property => {
4117
+ const bigInt = (length) => (property) => {
4302
4118
  const layout = blob(length, property);
4303
4119
  const { encode, decode } = encodeDecode(layout);
4304
4120
  const bigIntLayout = layout;
@@ -4314,7 +4130,7 @@ const bigInt = length => property => {
4314
4130
  };
4315
4131
  const u64 = bigInt(8);
4316
4132
 
4317
- const bool = property => {
4133
+ const bool = (property) => {
4318
4134
  const layout = u8(property);
4319
4135
  const { encode, decode } = encodeDecode(layout);
4320
4136
  const boolLayout = layout;
@@ -4329,7 +4145,7 @@ const bool = property => {
4329
4145
  return boolLayout;
4330
4146
  };
4331
4147
 
4332
- const publicKey = property => {
4148
+ const publicKey = (property) => {
4333
4149
  const layout = blob(32, property);
4334
4150
  const { encode, decode } = encodeDecode(layout);
4335
4151
  const publicKeyLayout = layout;
@@ -4403,112 +4219,73 @@ class TokenOwnerOffCurveError extends TokenError {
4403
4219
  /** Instructions defined by the program */
4404
4220
  var TokenInstruction;
4405
4221
  (function (TokenInstruction) {
4406
- TokenInstruction[(TokenInstruction['InitializeMint'] = 0)] =
4407
- 'InitializeMint';
4408
- TokenInstruction[(TokenInstruction['InitializeAccount'] = 1)] =
4409
- 'InitializeAccount';
4410
- TokenInstruction[(TokenInstruction['InitializeMultisig'] = 2)] =
4411
- 'InitializeMultisig';
4412
- TokenInstruction[(TokenInstruction['Transfer'] = 3)] = 'Transfer';
4413
- TokenInstruction[(TokenInstruction['Approve'] = 4)] = 'Approve';
4414
- TokenInstruction[(TokenInstruction['Revoke'] = 5)] = 'Revoke';
4415
- TokenInstruction[(TokenInstruction['SetAuthority'] = 6)] = 'SetAuthority';
4416
- TokenInstruction[(TokenInstruction['MintTo'] = 7)] = 'MintTo';
4417
- TokenInstruction[(TokenInstruction['Burn'] = 8)] = 'Burn';
4418
- TokenInstruction[(TokenInstruction['CloseAccount'] = 9)] = 'CloseAccount';
4419
- TokenInstruction[(TokenInstruction['FreezeAccount'] = 10)] =
4420
- 'FreezeAccount';
4421
- TokenInstruction[(TokenInstruction['ThawAccount'] = 11)] = 'ThawAccount';
4422
- TokenInstruction[(TokenInstruction['TransferChecked'] = 12)] =
4423
- 'TransferChecked';
4424
- TokenInstruction[(TokenInstruction['ApproveChecked'] = 13)] =
4425
- 'ApproveChecked';
4426
- TokenInstruction[(TokenInstruction['MintToChecked'] = 14)] =
4427
- 'MintToChecked';
4428
- TokenInstruction[(TokenInstruction['BurnChecked'] = 15)] = 'BurnChecked';
4429
- TokenInstruction[(TokenInstruction['InitializeAccount2'] = 16)] =
4430
- 'InitializeAccount2';
4431
- TokenInstruction[(TokenInstruction['SyncNative'] = 17)] = 'SyncNative';
4432
- TokenInstruction[(TokenInstruction['InitializeAccount3'] = 18)] =
4433
- 'InitializeAccount3';
4434
- TokenInstruction[(TokenInstruction['InitializeMultisig2'] = 19)] =
4435
- 'InitializeMultisig2';
4436
- TokenInstruction[(TokenInstruction['InitializeMint2'] = 20)] =
4437
- 'InitializeMint2';
4438
- TokenInstruction[(TokenInstruction['GetAccountDataSize'] = 21)] =
4439
- 'GetAccountDataSize';
4440
- TokenInstruction[(TokenInstruction['InitializeImmutableOwner'] = 22)] =
4441
- 'InitializeImmutableOwner';
4442
- TokenInstruction[(TokenInstruction['AmountToUiAmount'] = 23)] =
4443
- 'AmountToUiAmount';
4444
- TokenInstruction[(TokenInstruction['UiAmountToAmount'] = 24)] =
4445
- 'UiAmountToAmount';
4446
- TokenInstruction[(TokenInstruction['InitializeMintCloseAuthority'] = 25)] =
4447
- 'InitializeMintCloseAuthority';
4448
- TokenInstruction[(TokenInstruction['TransferFeeExtension'] = 26)] =
4449
- 'TransferFeeExtension';
4450
- TokenInstruction[(TokenInstruction['ConfidentialTransferExtension'] = 27)] =
4451
- 'ConfidentialTransferExtension';
4452
- TokenInstruction[(TokenInstruction['DefaultAccountStateExtension'] = 28)] =
4453
- 'DefaultAccountStateExtension';
4454
- TokenInstruction[(TokenInstruction['Reallocate'] = 29)] = 'Reallocate';
4455
- TokenInstruction[(TokenInstruction['MemoTransferExtension'] = 30)] =
4456
- 'MemoTransferExtension';
4457
- TokenInstruction[(TokenInstruction['CreateNativeMint'] = 31)] =
4458
- 'CreateNativeMint';
4459
- TokenInstruction[(TokenInstruction['InitializeNonTransferableMint'] = 32)] =
4460
- 'InitializeNonTransferableMint';
4461
- TokenInstruction[(TokenInstruction['InterestBearingMintExtension'] = 33)] =
4462
- 'InterestBearingMintExtension';
4463
- TokenInstruction[(TokenInstruction['CpiGuardExtension'] = 34)] =
4464
- 'CpiGuardExtension';
4465
- TokenInstruction[(TokenInstruction['InitializePermanentDelegate'] = 35)] =
4466
- 'InitializePermanentDelegate';
4467
- TokenInstruction[(TokenInstruction['TransferHookExtension'] = 36)] =
4468
- 'TransferHookExtension';
4222
+ TokenInstruction[TokenInstruction["InitializeMint"] = 0] = "InitializeMint";
4223
+ TokenInstruction[TokenInstruction["InitializeAccount"] = 1] = "InitializeAccount";
4224
+ TokenInstruction[TokenInstruction["InitializeMultisig"] = 2] = "InitializeMultisig";
4225
+ TokenInstruction[TokenInstruction["Transfer"] = 3] = "Transfer";
4226
+ TokenInstruction[TokenInstruction["Approve"] = 4] = "Approve";
4227
+ TokenInstruction[TokenInstruction["Revoke"] = 5] = "Revoke";
4228
+ TokenInstruction[TokenInstruction["SetAuthority"] = 6] = "SetAuthority";
4229
+ TokenInstruction[TokenInstruction["MintTo"] = 7] = "MintTo";
4230
+ TokenInstruction[TokenInstruction["Burn"] = 8] = "Burn";
4231
+ TokenInstruction[TokenInstruction["CloseAccount"] = 9] = "CloseAccount";
4232
+ TokenInstruction[TokenInstruction["FreezeAccount"] = 10] = "FreezeAccount";
4233
+ TokenInstruction[TokenInstruction["ThawAccount"] = 11] = "ThawAccount";
4234
+ TokenInstruction[TokenInstruction["TransferChecked"] = 12] = "TransferChecked";
4235
+ TokenInstruction[TokenInstruction["ApproveChecked"] = 13] = "ApproveChecked";
4236
+ TokenInstruction[TokenInstruction["MintToChecked"] = 14] = "MintToChecked";
4237
+ TokenInstruction[TokenInstruction["BurnChecked"] = 15] = "BurnChecked";
4238
+ TokenInstruction[TokenInstruction["InitializeAccount2"] = 16] = "InitializeAccount2";
4239
+ TokenInstruction[TokenInstruction["SyncNative"] = 17] = "SyncNative";
4240
+ TokenInstruction[TokenInstruction["InitializeAccount3"] = 18] = "InitializeAccount3";
4241
+ TokenInstruction[TokenInstruction["InitializeMultisig2"] = 19] = "InitializeMultisig2";
4242
+ TokenInstruction[TokenInstruction["InitializeMint2"] = 20] = "InitializeMint2";
4243
+ TokenInstruction[TokenInstruction["GetAccountDataSize"] = 21] = "GetAccountDataSize";
4244
+ TokenInstruction[TokenInstruction["InitializeImmutableOwner"] = 22] = "InitializeImmutableOwner";
4245
+ TokenInstruction[TokenInstruction["AmountToUiAmount"] = 23] = "AmountToUiAmount";
4246
+ TokenInstruction[TokenInstruction["UiAmountToAmount"] = 24] = "UiAmountToAmount";
4247
+ TokenInstruction[TokenInstruction["InitializeMintCloseAuthority"] = 25] = "InitializeMintCloseAuthority";
4248
+ TokenInstruction[TokenInstruction["TransferFeeExtension"] = 26] = "TransferFeeExtension";
4249
+ TokenInstruction[TokenInstruction["ConfidentialTransferExtension"] = 27] = "ConfidentialTransferExtension";
4250
+ TokenInstruction[TokenInstruction["DefaultAccountStateExtension"] = 28] = "DefaultAccountStateExtension";
4251
+ TokenInstruction[TokenInstruction["Reallocate"] = 29] = "Reallocate";
4252
+ TokenInstruction[TokenInstruction["MemoTransferExtension"] = 30] = "MemoTransferExtension";
4253
+ TokenInstruction[TokenInstruction["CreateNativeMint"] = 31] = "CreateNativeMint";
4254
+ TokenInstruction[TokenInstruction["InitializeNonTransferableMint"] = 32] = "InitializeNonTransferableMint";
4255
+ TokenInstruction[TokenInstruction["InterestBearingMintExtension"] = 33] = "InterestBearingMintExtension";
4256
+ TokenInstruction[TokenInstruction["CpiGuardExtension"] = 34] = "CpiGuardExtension";
4257
+ TokenInstruction[TokenInstruction["InitializePermanentDelegate"] = 35] = "InitializePermanentDelegate";
4258
+ TokenInstruction[TokenInstruction["TransferHookExtension"] = 36] = "TransferHookExtension";
4469
4259
  // ConfidentialTransferFeeExtension = 37,
4470
4260
  // WithdrawalExcessLamports = 38,
4471
- TokenInstruction[(TokenInstruction['MetadataPointerExtension'] = 39)] =
4472
- 'MetadataPointerExtension';
4473
- TokenInstruction[(TokenInstruction['GroupPointerExtension'] = 40)] =
4474
- 'GroupPointerExtension';
4475
- TokenInstruction[(TokenInstruction['GroupMemberPointerExtension'] = 41)] =
4476
- 'GroupMemberPointerExtension';
4261
+ TokenInstruction[TokenInstruction["MetadataPointerExtension"] = 39] = "MetadataPointerExtension";
4262
+ TokenInstruction[TokenInstruction["GroupPointerExtension"] = 40] = "GroupPointerExtension";
4263
+ TokenInstruction[TokenInstruction["GroupMemberPointerExtension"] = 41] = "GroupMemberPointerExtension";
4477
4264
  })(TokenInstruction || (TokenInstruction = {}));
4478
4265
 
4479
4266
  /** @internal */
4480
4267
  function addSigners(keys, ownerOrAuthority, multiSigners) {
4481
4268
  if (multiSigners.length) {
4482
- keys.push({
4483
- pubkey: ownerOrAuthority,
4484
- isSigner: false,
4485
- isWritable: false,
4486
- });
4269
+ keys.push({ pubkey: ownerOrAuthority, isSigner: false, isWritable: false });
4487
4270
  for (const signer of multiSigners) {
4488
4271
  keys.push({
4489
- pubkey:
4490
- signer instanceof web3_js.PublicKey
4491
- ? signer
4492
- : signer.publicKey,
4272
+ pubkey: signer instanceof web3_js.PublicKey ? signer : signer.publicKey,
4493
4273
  isSigner: true,
4494
4274
  isWritable: false,
4495
4275
  });
4496
4276
  }
4497
- } else {
4498
- keys.push({
4499
- pubkey: ownerOrAuthority,
4500
- isSigner: true,
4501
- isWritable: false,
4502
- });
4277
+ }
4278
+ else {
4279
+ keys.push({ pubkey: ownerOrAuthority, isSigner: true, isWritable: false });
4503
4280
  }
4504
4281
  return keys;
4505
4282
  }
4506
4283
 
4507
4284
  var AccountType;
4508
4285
  (function (AccountType) {
4509
- AccountType[(AccountType['Uninitialized'] = 0)] = 'Uninitialized';
4510
- AccountType[(AccountType['Mint'] = 1)] = 'Mint';
4511
- AccountType[(AccountType['Account'] = 2)] = 'Account';
4286
+ AccountType[AccountType["Uninitialized"] = 0] = "Uninitialized";
4287
+ AccountType[AccountType["Mint"] = 1] = "Mint";
4288
+ AccountType[AccountType["Account"] = 2] = "Account";
4512
4289
  })(AccountType || (AccountType = {}));
4513
4290
  const ACCOUNT_TYPE_SIZE = 1;
4514
4291
 
@@ -4535,9 +4312,9 @@ const MULTISIG_SIZE = MultisigLayout.span;
4535
4312
  /** Token account state as stored by the program */
4536
4313
  var AccountState;
4537
4314
  (function (AccountState) {
4538
- AccountState[(AccountState['Uninitialized'] = 0)] = 'Uninitialized';
4539
- AccountState[(AccountState['Initialized'] = 1)] = 'Initialized';
4540
- AccountState[(AccountState['Frozen'] = 2)] = 'Frozen';
4315
+ AccountState[AccountState["Uninitialized"] = 0] = "Uninitialized";
4316
+ AccountState[AccountState["Initialized"] = 1] = "Initialized";
4317
+ AccountState[AccountState["Frozen"] = 2] = "Frozen";
4541
4318
  })(AccountState || (AccountState = {}));
4542
4319
  /** Buffer layout for de/serializing a token account */
4543
4320
  const AccountLayout = struct([
@@ -4565,12 +4342,7 @@ const ACCOUNT_SIZE = AccountLayout.span;
4565
4342
  *
4566
4343
  * @return Token account information
4567
4344
  */
4568
- async function getAccount(
4569
- connection,
4570
- address,
4571
- commitment,
4572
- programId = TOKEN_PROGRAM_ID,
4573
- ) {
4345
+ async function getAccount(connection, address, commitment, programId = TOKEN_PROGRAM_ID) {
4574
4346
  const info = await connection.getAccountInfo(address, commitment);
4575
4347
  return unpackAccount(address, info, programId);
4576
4348
  }
@@ -4584,7 +4356,8 @@ async function getAccount(
4584
4356
  * @return Unpacked token account
4585
4357
  */
4586
4358
  function unpackAccount(address, info, programId = TOKEN_PROGRAM_ID) {
4587
- if (!info) throw new TokenAccountNotFoundError();
4359
+ if (!info)
4360
+ throw new TokenAccountNotFoundError();
4588
4361
  if (!info.owner.equals(programId))
4589
4362
  throw new TokenInvalidAccountOwnerError();
4590
4363
  if (info.data.length < ACCOUNT_SIZE)
@@ -4608,12 +4381,8 @@ function unpackAccount(address, info, programId = TOKEN_PROGRAM_ID) {
4608
4381
  isInitialized: rawAccount.state !== AccountState.Uninitialized,
4609
4382
  isFrozen: rawAccount.state === AccountState.Frozen,
4610
4383
  isNative: !!rawAccount.isNativeOption,
4611
- rentExemptReserve: rawAccount.isNativeOption
4612
- ? rawAccount.isNative
4613
- : null,
4614
- closeAuthority: rawAccount.closeAuthorityOption
4615
- ? rawAccount.closeAuthority
4616
- : null,
4384
+ rentExemptReserve: rawAccount.isNativeOption ? rawAccount.isNative : null,
4385
+ closeAuthority: rawAccount.closeAuthorityOption ? rawAccount.closeAuthority : null,
4617
4386
  tlvData,
4618
4387
  };
4619
4388
  }
@@ -4641,19 +4410,10 @@ const MINT_SIZE = MintLayout.span;
4641
4410
  *
4642
4411
  * @return Address of the associated token account
4643
4412
  */
4644
- function getAssociatedTokenAddressSync(
4645
- mint,
4646
- owner,
4647
- allowOwnerOffCurve = false,
4648
- programId = TOKEN_PROGRAM_ID,
4649
- associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID,
4650
- ) {
4413
+ function getAssociatedTokenAddressSync(mint, owner, allowOwnerOffCurve = false, programId = TOKEN_PROGRAM_ID, associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
4651
4414
  if (!allowOwnerOffCurve && !web3_js.PublicKey.isOnCurve(owner.toBuffer()))
4652
4415
  throw new TokenOwnerOffCurveError();
4653
- const [address] = web3_js.PublicKey.findProgramAddressSync(
4654
- [owner.toBuffer(), programId.toBuffer(), mint.toBuffer()],
4655
- associatedTokenProgramId,
4656
- );
4416
+ const [address] = web3_js.PublicKey.findProgramAddressSync([owner.toBuffer(), programId.toBuffer(), mint.toBuffer()], associatedTokenProgramId);
4657
4417
  return address;
4658
4418
  }
4659
4419
 
@@ -4673,7 +4433,8 @@ class COptionPublicKeyLayout extends Layout_2 {
4673
4433
  if (src === null) {
4674
4434
  buffer[offset] = 0;
4675
4435
  return 1;
4676
- } else {
4436
+ }
4437
+ else {
4677
4438
  buffer[offset] = 1;
4678
4439
  this.publicKeyLayout.encode(src, buffer, offset + 1);
4679
4440
  return 33;
@@ -4700,43 +4461,16 @@ class COptionPublicKeyLayout extends Layout_2 {
4700
4461
  *
4701
4462
  * @return Instruction to add to a transaction
4702
4463
  */
4703
- function createAssociatedTokenAccountInstruction(
4704
- payer,
4705
- associatedToken,
4706
- owner,
4707
- mint,
4708
- programId = TOKEN_PROGRAM_ID,
4709
- associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID,
4710
- ) {
4711
- return buildAssociatedTokenAccountInstruction(
4712
- payer,
4713
- associatedToken,
4714
- owner,
4715
- mint,
4716
- Buffer.alloc(0),
4717
- programId,
4718
- associatedTokenProgramId,
4719
- );
4464
+ function createAssociatedTokenAccountInstruction(payer, associatedToken, owner, mint, programId = TOKEN_PROGRAM_ID, associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
4465
+ return buildAssociatedTokenAccountInstruction(payer, associatedToken, owner, mint, Buffer.alloc(0), programId, associatedTokenProgramId);
4720
4466
  }
4721
- function buildAssociatedTokenAccountInstruction(
4722
- payer,
4723
- associatedToken,
4724
- owner,
4725
- mint,
4726
- instructionData,
4727
- programId = TOKEN_PROGRAM_ID,
4728
- associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID,
4729
- ) {
4467
+ function buildAssociatedTokenAccountInstruction(payer, associatedToken, owner, mint, instructionData, programId = TOKEN_PROGRAM_ID, associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
4730
4468
  const keys = [
4731
4469
  { pubkey: payer, isSigner: true, isWritable: true },
4732
4470
  { pubkey: associatedToken, isSigner: false, isWritable: true },
4733
4471
  { pubkey: owner, isSigner: false, isWritable: false },
4734
4472
  { pubkey: mint, isSigner: false, isWritable: false },
4735
- {
4736
- pubkey: web3_js.SystemProgram.programId,
4737
- isSigner: false,
4738
- isWritable: false,
4739
- },
4473
+ { pubkey: web3_js.SystemProgram.programId, isSigner: false, isWritable: false },
4740
4474
  { pubkey: programId, isSigner: false, isWritable: false },
4741
4475
  ];
4742
4476
  return new web3_js.TransactionInstruction({
@@ -4764,24 +4498,15 @@ const initializeMint2InstructionData = struct([
4764
4498
  *
4765
4499
  * @return Instruction to add to a transaction
4766
4500
  */
4767
- function createInitializeMint2Instruction(
4768
- mint,
4769
- decimals,
4770
- mintAuthority,
4771
- freezeAuthority,
4772
- programId = TOKEN_PROGRAM_ID,
4773
- ) {
4501
+ function createInitializeMint2Instruction(mint, decimals, mintAuthority, freezeAuthority, programId = TOKEN_PROGRAM_ID) {
4774
4502
  const keys = [{ pubkey: mint, isSigner: false, isWritable: true }];
4775
4503
  const data = Buffer.alloc(initializeMint2InstructionData.span);
4776
- initializeMint2InstructionData.encode(
4777
- {
4778
- instruction: TokenInstruction.InitializeMint2,
4779
- decimals,
4780
- mintAuthority,
4781
- freezeAuthority,
4782
- },
4783
- data,
4784
- );
4504
+ initializeMint2InstructionData.encode({
4505
+ instruction: TokenInstruction.InitializeMint2,
4506
+ decimals,
4507
+ mintAuthority,
4508
+ freezeAuthority,
4509
+ }, data);
4785
4510
  return new web3_js.TransactionInstruction({ keys, programId, data });
4786
4511
  }
4787
4512
 
@@ -4800,77 +4525,39 @@ function createInitializeMint2Instruction(
4800
4525
  *
4801
4526
  * @return Address of the new associated token account
4802
4527
  */
4803
- async function getOrCreateAssociatedTokenAccount(
4804
- connection,
4805
- payer,
4806
- mint,
4807
- owner,
4808
- allowOwnerOffCurve = false,
4809
- commitment,
4810
- confirmOptions,
4811
- programId = TOKEN_PROGRAM_ID,
4812
- associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID,
4813
- ) {
4814
- const associatedToken = getAssociatedTokenAddressSync(
4815
- mint,
4816
- owner,
4817
- allowOwnerOffCurve,
4818
- programId,
4819
- associatedTokenProgramId,
4820
- );
4528
+ async function getOrCreateAssociatedTokenAccount(connection, payer, mint, owner, allowOwnerOffCurve = false, commitment, confirmOptions, programId = TOKEN_PROGRAM_ID, associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
4529
+ const associatedToken = getAssociatedTokenAddressSync(mint, owner, allowOwnerOffCurve, programId, associatedTokenProgramId);
4821
4530
  // This is the optimal logic, considering TX fee, client-side computation, RPC roundtrips and guaranteed idempotent.
4822
4531
  // Sadly we can't do this atomically.
4823
4532
  let account;
4824
4533
  try {
4825
- account = await getAccount(
4826
- connection,
4827
- associatedToken,
4828
- commitment,
4829
- programId,
4830
- );
4831
- } catch (error) {
4534
+ account = await getAccount(connection, associatedToken, commitment, programId);
4535
+ }
4536
+ catch (error) {
4832
4537
  // TokenAccountNotFoundError can be possible if the associated address has already received some lamports,
4833
4538
  // becoming a system account. Assuming program derived addressing is safe, this is the only case for the
4834
4539
  // TokenInvalidAccountOwnerError in this code path.
4835
- if (
4836
- error instanceof TokenAccountNotFoundError ||
4837
- error instanceof TokenInvalidAccountOwnerError
4838
- ) {
4540
+ if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {
4839
4541
  // As this isn't atomic, it's possible others can create associated accounts meanwhile.
4840
4542
  try {
4841
- const transaction = new web3_js.Transaction().add(
4842
- createAssociatedTokenAccountInstruction(
4843
- payer.publicKey,
4844
- associatedToken,
4845
- owner,
4846
- mint,
4847
- programId,
4848
- associatedTokenProgramId,
4849
- ),
4850
- );
4851
- await web3_js.sendAndConfirmTransaction(
4852
- connection,
4853
- transaction,
4854
- [payer],
4855
- confirmOptions,
4856
- );
4857
- } catch (error) {
4543
+ const transaction = new web3_js.Transaction().add(createAssociatedTokenAccountInstruction(payer.publicKey, associatedToken, owner, mint, programId, associatedTokenProgramId));
4544
+ await web3_js.sendAndConfirmTransaction(connection, transaction, [payer], confirmOptions);
4545
+ }
4546
+ catch (error) {
4858
4547
  // Ignore all errors; for now there is no API-compatible way to selectively ignore the expected
4859
4548
  // instruction error if the associated account exists already.
4860
4549
  }
4861
4550
  // Now this should always succeed
4862
- account = await getAccount(
4863
- connection,
4864
- associatedToken,
4865
- commitment,
4866
- programId,
4867
- );
4868
- } else {
4551
+ account = await getAccount(connection, associatedToken, commitment, programId);
4552
+ }
4553
+ else {
4869
4554
  throw error;
4870
4555
  }
4871
4556
  }
4872
- if (!account.mint.equals(mint)) throw new TokenInvalidMintError();
4873
- if (!account.owner.equals(owner)) throw new TokenInvalidOwnerError();
4557
+ if (!account.mint.equals(mint))
4558
+ throw new TokenInvalidMintError();
4559
+ if (!account.owner.equals(owner))
4560
+ throw new TokenInvalidOwnerError();
4874
4561
  return account;
4875
4562
  }
4876
4563
 
@@ -4888,46 +4575,29 @@ const mintToInstructionData = struct([u8('instruction'), u64('amount')]);
4888
4575
  *
4889
4576
  * @return Instruction to add to a transaction
4890
4577
  */
4891
- function createMintToInstruction(
4892
- mint,
4893
- destination,
4894
- authority,
4895
- amount,
4896
- multiSigners = [],
4897
- programId = TOKEN_PROGRAM_ID,
4898
- ) {
4899
- const keys = addSigners(
4900
- [
4901
- { pubkey: mint, isSigner: false, isWritable: true },
4902
- { pubkey: destination, isSigner: false, isWritable: true },
4903
- ],
4904
- authority,
4905
- multiSigners,
4906
- );
4578
+ function createMintToInstruction(mint, destination, authority, amount, multiSigners = [], programId = TOKEN_PROGRAM_ID) {
4579
+ const keys = addSigners([
4580
+ { pubkey: mint, isSigner: false, isWritable: true },
4581
+ { pubkey: destination, isSigner: false, isWritable: true },
4582
+ ], authority, multiSigners);
4907
4583
  const data = Buffer.alloc(mintToInstructionData.span);
4908
- mintToInstructionData.encode(
4909
- {
4910
- instruction: TokenInstruction.MintTo,
4911
- amount: BigInt(amount),
4912
- },
4913
- data,
4914
- );
4584
+ mintToInstructionData.encode({
4585
+ instruction: TokenInstruction.MintTo,
4586
+ amount: BigInt(amount),
4587
+ }, data);
4915
4588
  return new web3_js.TransactionInstruction({ keys, programId, data });
4916
4589
  }
4917
4590
 
4918
4591
  /**
4919
4592
  * Sum up the token amounts of the compressed token accounts
4920
4593
  */
4921
- const sumUpTokenAmount = accounts => {
4922
- return accounts.reduce(
4923
- (acc, account) => acc.add(account.parsed.amount),
4924
- stateless_js.bn(0),
4925
- );
4594
+ const sumUpTokenAmount = (accounts) => {
4595
+ return accounts.reduce((acc, account) => acc.add(account.parsed.amount), stateless_js.bn(0));
4926
4596
  };
4927
4597
  /**
4928
4598
  * Validate that all the compressed token accounts are owned by the same owner.
4929
4599
  */
4930
- const validateSameTokenOwner = accounts => {
4600
+ const validateSameTokenOwner = (accounts) => {
4931
4601
  const owner = accounts[0].parsed.owner;
4932
4602
  accounts.forEach(acc => {
4933
4603
  if (!acc.parsed.owner.equals(owner)) {
@@ -4938,7 +4608,7 @@ const validateSameTokenOwner = accounts => {
4938
4608
  /**
4939
4609
  * Parse compressed token accounts to get the mint, current owner and delegate.
4940
4610
  */
4941
- const parseTokenData = compressedTokenAccounts => {
4611
+ const parseTokenData = (compressedTokenAccounts) => {
4942
4612
  const mint = compressedTokenAccounts[0].parsed.mint;
4943
4613
  const currentOwner = compressedTokenAccounts[0].parsed.owner;
4944
4614
  const delegate = compressedTokenAccounts[0].parsed.delegate;
@@ -4952,22 +4622,13 @@ const parseTokenData = compressedTokenAccounts => {
4952
4622
  * @returns Output token data for the transfer
4953
4623
  * instruction
4954
4624
  */
4955
- function createTransferOutputState(
4956
- inputCompressedTokenAccounts,
4957
- toAddress,
4958
- amount,
4959
- ) {
4625
+ function createTransferOutputState(inputCompressedTokenAccounts, toAddress, amount) {
4960
4626
  amount = stateless_js.bn(amount);
4961
4627
  const inputAmount = sumUpTokenAmount(inputCompressedTokenAccounts);
4962
- const inputLamports = stateless_js.sumUpLamports(
4963
- inputCompressedTokenAccounts.map(acc => acc.compressedAccount),
4964
- );
4628
+ const inputLamports = stateless_js.sumUpLamports(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
4965
4629
  const changeAmount = inputAmount.sub(amount);
4966
4630
  stateless_js.validateSufficientBalance(changeAmount);
4967
- if (
4968
- changeAmount.eq(stateless_js.bn(0)) &&
4969
- inputLamports.eq(stateless_js.bn(0))
4970
- ) {
4631
+ if (changeAmount.eq(stateless_js.bn(0)) && inputLamports.eq(stateless_js.bn(0))) {
4971
4632
  return [
4972
4633
  {
4973
4634
  owner: toAddress,
@@ -4978,9 +4639,7 @@ function createTransferOutputState(
4978
4639
  ];
4979
4640
  }
4980
4641
  /// validates token program
4981
- stateless_js.validateSameOwner(
4982
- inputCompressedTokenAccounts.map(acc => acc.compressedAccount),
4983
- );
4642
+ stateless_js.validateSameOwner(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
4984
4643
  validateSameTokenOwner(inputCompressedTokenAccounts);
4985
4644
  const outputCompressedAccounts = [
4986
4645
  {
@@ -5007,22 +4666,15 @@ function createTransferOutputState(
5007
4666
  */
5008
4667
  function createDecompressOutputState(inputCompressedTokenAccounts, amount) {
5009
4668
  amount = stateless_js.bn(amount);
5010
- const inputLamports = stateless_js.sumUpLamports(
5011
- inputCompressedTokenAccounts.map(acc => acc.compressedAccount),
5012
- );
4669
+ const inputLamports = stateless_js.sumUpLamports(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
5013
4670
  const inputAmount = sumUpTokenAmount(inputCompressedTokenAccounts);
5014
4671
  const changeAmount = inputAmount.sub(amount);
5015
4672
  stateless_js.validateSufficientBalance(changeAmount);
5016
4673
  /// lamports gets decompressed
5017
- if (
5018
- changeAmount.eq(stateless_js.bn(0)) &&
5019
- inputLamports.eq(stateless_js.bn(0))
5020
- ) {
4674
+ if (changeAmount.eq(stateless_js.bn(0)) && inputLamports.eq(stateless_js.bn(0))) {
5021
4675
  return [];
5022
4676
  }
5023
- stateless_js.validateSameOwner(
5024
- inputCompressedTokenAccounts.map(acc => acc.compressedAccount),
5025
- );
4677
+ stateless_js.validateSameOwner(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
5026
4678
  validateSameTokenOwner(inputCompressedTokenAccounts);
5027
4679
  const tokenTransferOutputs = [
5028
4680
  {
@@ -5038,7 +4690,7 @@ class CompressedTokenProgram {
5038
4690
  /**
5039
4691
  * @internal
5040
4692
  */
5041
- constructor() {}
4693
+ constructor() { }
5042
4694
  /** @internal */
5043
4695
  static get program() {
5044
4696
  if (!this._program) {
@@ -5056,38 +4708,21 @@ class CompressedTokenProgram {
5056
4708
  /// program only for serde and building instructions, not for
5057
4709
  /// interacting with the network.
5058
4710
  const mockKeypair = web3_js.Keypair.generate();
5059
- const mockConnection = new web3_js.Connection(
5060
- 'http://127.0.0.1:8899',
5061
- 'confirmed',
5062
- );
5063
- const mockProvider = new anchor.AnchorProvider(
5064
- mockConnection,
5065
- stateless_js.useWallet(mockKeypair),
5066
- stateless_js.confirmConfig,
5067
- );
4711
+ const mockConnection = new web3_js.Connection('http://127.0.0.1:8899', 'confirmed');
4712
+ const mockProvider = new anchor.AnchorProvider(mockConnection, stateless_js.useWallet(mockKeypair), stateless_js.confirmConfig);
5068
4713
  anchor.setProvider(mockProvider);
5069
- this._program = new anchor.Program(
5070
- IDL,
5071
- this.programId,
5072
- mockProvider,
5073
- );
4714
+ this._program = new anchor.Program(IDL, this.programId, mockProvider);
5074
4715
  }
5075
4716
  }
5076
4717
  /** @internal */
5077
4718
  static deriveTokenPoolPda(mint) {
5078
4719
  const seeds = [POOL_SEED, mint.toBuffer()];
5079
- const [address, _] = web3_js.PublicKey.findProgramAddressSync(
5080
- seeds,
5081
- this.programId,
5082
- );
4720
+ const [address, _] = web3_js.PublicKey.findProgramAddressSync(seeds, this.programId);
5083
4721
  return address;
5084
4722
  }
5085
4723
  /** @internal */
5086
4724
  static get deriveCpiAuthorityPda() {
5087
- const [address, _] = web3_js.PublicKey.findProgramAddressSync(
5088
- [CPI_AUTHORITY_SEED],
5089
- this.programId,
5090
- );
4725
+ const [address, _] = web3_js.PublicKey.findProgramAddressSync([CPI_AUTHORITY_SEED], this.programId);
5091
4726
  return address;
5092
4727
  }
5093
4728
  /**
@@ -5096,21 +4731,14 @@ class CompressedTokenProgram {
5096
4731
  static async createMint(params) {
5097
4732
  const { mint, authority, feePayer, rentExemptBalance } = params;
5098
4733
  /// Create and initialize SPL Mint account
5099
- const createMintAccountInstruction =
5100
- web3_js.SystemProgram.createAccount({
5101
- fromPubkey: feePayer,
5102
- lamports: rentExemptBalance,
5103
- newAccountPubkey: mint,
5104
- programId: TOKEN_PROGRAM_ID,
5105
- space: MINT_SIZE,
5106
- });
5107
- const initializeMintInstruction = createInitializeMint2Instruction(
5108
- mint,
5109
- params.decimals,
5110
- authority,
5111
- params.freezeAuthority,
5112
- TOKEN_PROGRAM_ID,
5113
- );
4734
+ const createMintAccountInstruction = web3_js.SystemProgram.createAccount({
4735
+ fromPubkey: feePayer,
4736
+ lamports: rentExemptBalance,
4737
+ newAccountPubkey: mint,
4738
+ programId: TOKEN_PROGRAM_ID,
4739
+ space: MINT_SIZE,
4740
+ });
4741
+ const initializeMintInstruction = createInitializeMint2Instruction(mint, params.decimals, authority, params.freezeAuthority, TOKEN_PROGRAM_ID);
5114
4742
  const ix = await this.createTokenPool({
5115
4743
  feePayer,
5116
4744
  mint,
@@ -5127,13 +4755,13 @@ class CompressedTokenProgram {
5127
4755
  const ix = await this.program.methods
5128
4756
  .createTokenPool()
5129
4757
  .accounts({
5130
- mint,
5131
- feePayer,
5132
- tokenPoolPda,
5133
- systemProgram: web3_js.SystemProgram.programId,
5134
- tokenProgram: TOKEN_PROGRAM_ID,
5135
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
5136
- })
4758
+ mint,
4759
+ feePayer,
4760
+ tokenPoolPda,
4761
+ systemProgram: web3_js.SystemProgram.programId,
4762
+ tokenProgram: TOKEN_PROGRAM_ID,
4763
+ cpiAuthorityPda: this.deriveCpiAuthorityPda,
4764
+ })
5137
4765
  .instruction();
5138
4766
  return ix;
5139
4767
  }
@@ -5142,41 +4770,31 @@ class CompressedTokenProgram {
5142
4770
  */
5143
4771
  static async mintTo(params) {
5144
4772
  const systemKeys = stateless_js.defaultStaticAccountsStruct();
5145
- const { mint, feePayer, authority, merkleTree, toPubkey, amount } =
5146
- params;
4773
+ const { mint, feePayer, authority, merkleTree, toPubkey, amount } = params;
5147
4774
  const tokenPoolPda = this.deriveTokenPoolPda(mint);
5148
- const amounts = stateless_js
5149
- .toArray(amount)
5150
- .map(amount => stateless_js.bn(amount));
4775
+ const amounts = stateless_js.toArray(amount).map(amount => stateless_js.bn(amount));
5151
4776
  const toPubkeys = stateless_js.toArray(toPubkey);
5152
4777
  if (amounts.length !== toPubkeys.length) {
5153
- throw new Error(
5154
- 'Amount and toPubkey arrays must have the same length',
5155
- );
4778
+ throw new Error('Amount and toPubkey arrays must have the same length');
5156
4779
  }
5157
4780
  const instruction = await this.program.methods
5158
4781
  .mintTo(toPubkeys, amounts, null)
5159
4782
  .accounts({
5160
- feePayer,
5161
- authority,
5162
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
5163
- mint,
5164
- tokenPoolPda,
5165
- tokenProgram: TOKEN_PROGRAM_ID,
5166
- lightSystemProgram: stateless_js.LightSystemProgram.programId,
5167
- registeredProgramPda: systemKeys.registeredProgramPda,
5168
- noopProgram: systemKeys.noopProgram,
5169
- accountCompressionAuthority:
5170
- systemKeys.accountCompressionAuthority,
5171
- accountCompressionProgram: systemKeys.accountCompressionProgram,
5172
- merkleTree:
5173
- merkleTree !== null && merkleTree !== void 0
5174
- ? merkleTree
5175
- : stateless_js.defaultTestStateTreeAccounts()
5176
- .merkleTree,
5177
- selfProgram: this.programId,
5178
- solPoolPda: null,
5179
- })
4783
+ feePayer,
4784
+ authority,
4785
+ cpiAuthorityPda: this.deriveCpiAuthorityPda,
4786
+ mint,
4787
+ tokenPoolPda,
4788
+ tokenProgram: TOKEN_PROGRAM_ID,
4789
+ lightSystemProgram: stateless_js.LightSystemProgram.programId,
4790
+ registeredProgramPda: systemKeys.registeredProgramPda,
4791
+ noopProgram: systemKeys.noopProgram,
4792
+ accountCompressionAuthority: systemKeys.accountCompressionAuthority,
4793
+ accountCompressionProgram: systemKeys.accountCompressionProgram,
4794
+ merkleTree: merkleTree !== null && merkleTree !== void 0 ? merkleTree : stateless_js.defaultTestStateTreeAccounts().merkleTree,
4795
+ selfProgram: this.programId,
4796
+ solPoolPda: null,
4797
+ })
5180
4798
  .instruction();
5181
4799
  return instruction;
5182
4800
  }
@@ -5185,22 +4803,10 @@ class CompressedTokenProgram {
5185
4803
  * Mint tokens from registed SPL mint account to a compressed account
5186
4804
  */
5187
4805
  static async approveAndMintTo(params) {
5188
- const {
5189
- mint,
5190
- feePayer,
5191
- authorityTokenAccount,
5192
- authority,
5193
- merkleTree,
5194
- toPubkey,
5195
- } = params;
4806
+ const { mint, feePayer, authorityTokenAccount, authority, merkleTree, toPubkey, } = params;
5196
4807
  const amount = BigInt(params.amount.toString());
5197
4808
  /// 1. Mint to existing ATA of mintAuthority.
5198
- const splMintToInstruction = createMintToInstruction(
5199
- mint,
5200
- authorityTokenAccount,
5201
- authority,
5202
- amount,
5203
- );
4809
+ const splMintToInstruction = createMintToInstruction(mint, authorityTokenAccount, authority, amount);
5204
4810
  /// 2. Compress from mint authority ATA to recipient compressed account
5205
4811
  const compressInstruction = await this.compress({
5206
4812
  payer: feePayer,
@@ -5217,33 +4823,15 @@ class CompressedTokenProgram {
5217
4823
  * Construct transfer instruction for compressed tokens
5218
4824
  */
5219
4825
  static async transfer(params) {
5220
- const {
5221
- payer,
5222
- inputCompressedTokenAccounts,
5223
- recentInputStateRootIndices,
5224
- recentValidityProof,
5225
- amount,
5226
- outputStateTrees,
5227
- toAddress,
5228
- } = params;
5229
- const tokenTransferOutputs = createTransferOutputState(
5230
- inputCompressedTokenAccounts,
5231
- toAddress,
5232
- amount,
5233
- );
5234
- const {
5235
- inputTokenDataWithContext,
5236
- packedOutputTokenData,
5237
- remainingAccountMetas,
5238
- } = packCompressedTokenAccounts({
4826
+ const { payer, inputCompressedTokenAccounts, recentInputStateRootIndices, recentValidityProof, amount, outputStateTrees, toAddress, } = params;
4827
+ const tokenTransferOutputs = createTransferOutputState(inputCompressedTokenAccounts, toAddress, amount);
4828
+ const { inputTokenDataWithContext, packedOutputTokenData, remainingAccountMetas, } = packCompressedTokenAccounts({
5239
4829
  inputCompressedTokenAccounts,
5240
4830
  outputStateTrees,
5241
4831
  rootIndices: recentInputStateRootIndices,
5242
4832
  tokenTransferOutputs,
5243
4833
  });
5244
- const { mint, currentOwner } = parseTokenData(
5245
- inputCompressedTokenAccounts,
5246
- );
4834
+ const { mint, currentOwner } = parseTokenData(inputCompressedTokenAccounts);
5247
4835
  const data = {
5248
4836
  proof: recentValidityProof,
5249
4837
  mint,
@@ -5255,32 +4843,24 @@ class CompressedTokenProgram {
5255
4843
  cpiContext: null,
5256
4844
  lamportsChangeAccountMerkleTreeIndex: null,
5257
4845
  };
5258
- const encodedData = this.program.coder.types.encode(
5259
- 'CompressedTokenInstructionDataTransfer',
5260
- data,
5261
- );
5262
- const {
5263
- accountCompressionAuthority,
5264
- noopProgram,
5265
- registeredProgramPda,
5266
- accountCompressionProgram,
5267
- } = stateless_js.defaultStaticAccountsStruct();
4846
+ const encodedData = this.program.coder.types.encode('CompressedTokenInstructionDataTransfer', data);
4847
+ const { accountCompressionAuthority, noopProgram, registeredProgramPda, accountCompressionProgram, } = stateless_js.defaultStaticAccountsStruct();
5268
4848
  const instruction = await this.program.methods
5269
4849
  .transfer(encodedData)
5270
4850
  .accounts({
5271
- feePayer: payer,
5272
- authority: currentOwner,
5273
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
5274
- lightSystemProgram: stateless_js.LightSystemProgram.programId,
5275
- registeredProgramPda: registeredProgramPda,
5276
- noopProgram: noopProgram,
5277
- accountCompressionAuthority: accountCompressionAuthority,
5278
- accountCompressionProgram: accountCompressionProgram,
5279
- selfProgram: this.programId,
5280
- tokenPoolPda: null,
5281
- compressOrDecompressTokenAccount: null,
5282
- tokenProgram: null,
5283
- })
4851
+ feePayer: payer,
4852
+ authority: currentOwner,
4853
+ cpiAuthorityPda: this.deriveCpiAuthorityPda,
4854
+ lightSystemProgram: stateless_js.LightSystemProgram.programId,
4855
+ registeredProgramPda: registeredProgramPda,
4856
+ noopProgram: noopProgram,
4857
+ accountCompressionAuthority: accountCompressionAuthority,
4858
+ accountCompressionProgram: accountCompressionProgram,
4859
+ selfProgram: this.programId,
4860
+ tokenPoolPda: null,
4861
+ compressOrDecompressTokenAccount: null,
4862
+ tokenProgram: null,
4863
+ })
5284
4864
  .remainingAccounts(remainingAccountMetas)
5285
4865
  .instruction();
5286
4866
  return instruction;
@@ -5289,14 +4869,12 @@ class CompressedTokenProgram {
5289
4869
  * Create lookup table instructions for the token program's default accounts.
5290
4870
  */
5291
4871
  static async createTokenProgramLookupTable(params) {
5292
- const { authority, mints, recentSlot, payer, remainingAccounts } =
5293
- params;
5294
- const [createInstruction, lookupTableAddress] =
5295
- web3_js.AddressLookupTableProgram.createLookupTable({
5296
- authority,
5297
- payer: authority,
5298
- recentSlot,
5299
- });
4872
+ const { authority, mints, recentSlot, payer, remainingAccounts } = params;
4873
+ const [createInstruction, lookupTableAddress] = web3_js.AddressLookupTableProgram.createLookupTable({
4874
+ authority,
4875
+ payer: authority,
4876
+ recentSlot,
4877
+ });
5300
4878
  let optionalMintKeys = [];
5301
4879
  if (mints) {
5302
4880
  optionalMintKeys = [
@@ -5304,35 +4882,28 @@ class CompressedTokenProgram {
5304
4882
  ...mints.map(mint => this.deriveTokenPoolPda(mint)),
5305
4883
  ];
5306
4884
  }
5307
- const extendInstruction =
5308
- web3_js.AddressLookupTableProgram.extendLookupTable({
5309
- payer,
4885
+ const extendInstruction = web3_js.AddressLookupTableProgram.extendLookupTable({
4886
+ payer,
4887
+ authority,
4888
+ lookupTable: lookupTableAddress,
4889
+ addresses: [
4890
+ this.deriveCpiAuthorityPda,
4891
+ stateless_js.LightSystemProgram.programId,
4892
+ stateless_js.defaultStaticAccountsStruct().registeredProgramPda,
4893
+ stateless_js.defaultStaticAccountsStruct().noopProgram,
4894
+ stateless_js.defaultStaticAccountsStruct().accountCompressionAuthority,
4895
+ stateless_js.defaultStaticAccountsStruct().accountCompressionProgram,
4896
+ stateless_js.defaultTestStateTreeAccounts().merkleTree,
4897
+ stateless_js.defaultTestStateTreeAccounts().nullifierQueue,
4898
+ stateless_js.defaultTestStateTreeAccounts().addressTree,
4899
+ stateless_js.defaultTestStateTreeAccounts().addressQueue,
4900
+ this.programId,
4901
+ TOKEN_PROGRAM_ID,
5310
4902
  authority,
5311
- lookupTable: lookupTableAddress,
5312
- addresses: [
5313
- this.deriveCpiAuthorityPda,
5314
- stateless_js.LightSystemProgram.programId,
5315
- stateless_js.defaultStaticAccountsStruct()
5316
- .registeredProgramPda,
5317
- stateless_js.defaultStaticAccountsStruct().noopProgram,
5318
- stateless_js.defaultStaticAccountsStruct()
5319
- .accountCompressionAuthority,
5320
- stateless_js.defaultStaticAccountsStruct()
5321
- .accountCompressionProgram,
5322
- stateless_js.defaultTestStateTreeAccounts().merkleTree,
5323
- stateless_js.defaultTestStateTreeAccounts().nullifierQueue,
5324
- stateless_js.defaultTestStateTreeAccounts().addressTree,
5325
- stateless_js.defaultTestStateTreeAccounts().addressQueue,
5326
- this.programId,
5327
- TOKEN_PROGRAM_ID,
5328
- authority,
5329
- ...optionalMintKeys,
5330
- ...(remainingAccounts !== null &&
5331
- remainingAccounts !== void 0
5332
- ? remainingAccounts
5333
- : []),
5334
- ],
5335
- });
4903
+ ...optionalMintKeys,
4904
+ ...(remainingAccounts !== null && remainingAccounts !== void 0 ? remainingAccounts : []),
4905
+ ],
4906
+ });
5336
4907
  return {
5337
4908
  instructions: [createInstruction, extendInstruction],
5338
4909
  address: lookupTableAddress,
@@ -5343,19 +4914,14 @@ class CompressedTokenProgram {
5343
4914
  * @returns compressInstruction
5344
4915
  */
5345
4916
  static async compress(params) {
5346
- const { payer, owner, source, toAddress, mint, outputStateTree } =
5347
- params;
4917
+ const { payer, owner, source, toAddress, mint, outputStateTree } = params;
5348
4918
  if (Array.isArray(params.amount) !== Array.isArray(params.toAddress)) {
5349
- throw new Error(
5350
- 'Both amount and toAddress must be arrays or both must be single values',
5351
- );
4919
+ throw new Error('Both amount and toAddress must be arrays or both must be single values');
5352
4920
  }
5353
4921
  let tokenTransferOutputs;
5354
4922
  if (Array.isArray(params.amount) && Array.isArray(params.toAddress)) {
5355
4923
  if (params.amount.length !== params.toAddress.length) {
5356
- throw new Error(
5357
- 'Amount and toAddress arrays must have the same length',
5358
- );
4924
+ throw new Error('Amount and toAddress arrays must have the same length');
5359
4925
  }
5360
4926
  tokenTransferOutputs = params.amount.map((amt, index) => {
5361
4927
  const amount = stateless_js.bn(amt);
@@ -5366,7 +4932,8 @@ class CompressedTokenProgram {
5366
4932
  tlv: null,
5367
4933
  };
5368
4934
  });
5369
- } else {
4935
+ }
4936
+ else {
5370
4937
  tokenTransferOutputs = [
5371
4938
  {
5372
4939
  owner: toAddress,
@@ -5376,11 +4943,7 @@ class CompressedTokenProgram {
5376
4943
  },
5377
4944
  ];
5378
4945
  }
5379
- const {
5380
- inputTokenDataWithContext,
5381
- packedOutputTokenData,
5382
- remainingAccountMetas,
5383
- } = packCompressedTokenAccounts({
4946
+ const { inputTokenDataWithContext, packedOutputTokenData, remainingAccountMetas, } = packCompressedTokenAccounts({
5384
4947
  inputCompressedTokenAccounts: [],
5385
4948
  outputStateTrees: outputStateTree,
5386
4949
  rootIndices: [],
@@ -5394,40 +4957,30 @@ class CompressedTokenProgram {
5394
4957
  outputCompressedAccounts: packedOutputTokenData,
5395
4958
  compressOrDecompressAmount: Array.isArray(params.amount)
5396
4959
  ? params.amount
5397
- .map(amt => new anchor.BN(amt))
5398
- .reduce((sum, amt) => sum.add(amt), new anchor.BN(0))
4960
+ .map(amt => new anchor.BN(amt))
4961
+ .reduce((sum, amt) => sum.add(amt), new anchor.BN(0))
5399
4962
  : new anchor.BN(params.amount),
5400
4963
  isCompress: true,
5401
4964
  cpiContext: null,
5402
4965
  lamportsChangeAccountMerkleTreeIndex: null,
5403
4966
  };
5404
- const encodedData = this.program.coder.types.encode(
5405
- 'CompressedTokenInstructionDataTransfer',
5406
- data,
5407
- );
4967
+ const encodedData = this.program.coder.types.encode('CompressedTokenInstructionDataTransfer', data);
5408
4968
  const instruction = await this.program.methods
5409
4969
  .transfer(encodedData)
5410
4970
  .accounts({
5411
- feePayer: payer,
5412
- authority: owner,
5413
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
5414
- lightSystemProgram: stateless_js.LightSystemProgram.programId,
5415
- registeredProgramPda:
5416
- stateless_js.defaultStaticAccountsStruct()
5417
- .registeredProgramPda,
5418
- noopProgram:
5419
- stateless_js.defaultStaticAccountsStruct().noopProgram,
5420
- accountCompressionAuthority:
5421
- stateless_js.defaultStaticAccountsStruct()
5422
- .accountCompressionAuthority,
5423
- accountCompressionProgram:
5424
- stateless_js.defaultStaticAccountsStruct()
5425
- .accountCompressionProgram,
5426
- selfProgram: this.programId,
5427
- tokenPoolPda: this.deriveTokenPoolPda(mint),
5428
- compressOrDecompressTokenAccount: source, // token
5429
- tokenProgram: TOKEN_PROGRAM_ID,
5430
- })
4971
+ feePayer: payer,
4972
+ authority: owner,
4973
+ cpiAuthorityPda: this.deriveCpiAuthorityPda,
4974
+ lightSystemProgram: stateless_js.LightSystemProgram.programId,
4975
+ registeredProgramPda: stateless_js.defaultStaticAccountsStruct().registeredProgramPda,
4976
+ noopProgram: stateless_js.defaultStaticAccountsStruct().noopProgram,
4977
+ accountCompressionAuthority: stateless_js.defaultStaticAccountsStruct().accountCompressionAuthority,
4978
+ accountCompressionProgram: stateless_js.defaultStaticAccountsStruct().accountCompressionProgram,
4979
+ selfProgram: this.programId,
4980
+ tokenPoolPda: this.deriveTokenPoolPda(mint),
4981
+ compressOrDecompressTokenAccount: source, // token
4982
+ tokenProgram: TOKEN_PROGRAM_ID,
4983
+ })
5431
4984
  .remainingAccounts(remainingAccountMetas)
5432
4985
  .instruction();
5433
4986
  return instruction;
@@ -5436,33 +4989,17 @@ class CompressedTokenProgram {
5436
4989
  * Construct decompress instruction
5437
4990
  */
5438
4991
  static async decompress(params) {
5439
- const {
5440
- payer,
5441
- inputCompressedTokenAccounts,
5442
- toAddress,
5443
- outputStateTree,
5444
- recentValidityProof,
5445
- recentInputStateRootIndices,
5446
- } = params;
4992
+ const { payer, inputCompressedTokenAccounts, toAddress, outputStateTree, recentValidityProof, recentInputStateRootIndices, } = params;
5447
4993
  const amount = stateless_js.bn(params.amount);
5448
- const tokenTransferOutputs = createDecompressOutputState(
5449
- inputCompressedTokenAccounts,
5450
- amount,
5451
- );
4994
+ const tokenTransferOutputs = createDecompressOutputState(inputCompressedTokenAccounts, amount);
5452
4995
  /// Pack
5453
- const {
5454
- inputTokenDataWithContext,
5455
- packedOutputTokenData,
5456
- remainingAccountMetas,
5457
- } = packCompressedTokenAccounts({
4996
+ const { inputTokenDataWithContext, packedOutputTokenData, remainingAccountMetas, } = packCompressedTokenAccounts({
5458
4997
  inputCompressedTokenAccounts,
5459
4998
  outputStateTrees: outputStateTree,
5460
4999
  rootIndices: recentInputStateRootIndices,
5461
5000
  tokenTransferOutputs: tokenTransferOutputs,
5462
5001
  });
5463
- const { mint, currentOwner } = parseTokenData(
5464
- inputCompressedTokenAccounts,
5465
- );
5002
+ const { mint, currentOwner } = parseTokenData(inputCompressedTokenAccounts);
5466
5003
  const data = {
5467
5004
  proof: recentValidityProof,
5468
5005
  mint,
@@ -5474,45 +5011,30 @@ class CompressedTokenProgram {
5474
5011
  cpiContext: null,
5475
5012
  lamportsChangeAccountMerkleTreeIndex: null,
5476
5013
  };
5477
- const encodedData = this.program.coder.types.encode(
5478
- 'CompressedTokenInstructionDataTransfer',
5479
- data,
5480
- );
5481
- const {
5482
- accountCompressionAuthority,
5483
- noopProgram,
5484
- registeredProgramPda,
5485
- accountCompressionProgram,
5486
- } = stateless_js.defaultStaticAccountsStruct();
5014
+ const encodedData = this.program.coder.types.encode('CompressedTokenInstructionDataTransfer', data);
5015
+ const { accountCompressionAuthority, noopProgram, registeredProgramPda, accountCompressionProgram, } = stateless_js.defaultStaticAccountsStruct();
5487
5016
  const instruction = await this.program.methods
5488
5017
  .transfer(encodedData)
5489
5018
  .accounts({
5490
- feePayer: payer,
5491
- authority: currentOwner,
5492
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
5493
- lightSystemProgram: stateless_js.LightSystemProgram.programId,
5494
- registeredProgramPda: registeredProgramPda,
5495
- noopProgram: noopProgram,
5496
- accountCompressionAuthority: accountCompressionAuthority,
5497
- accountCompressionProgram: accountCompressionProgram,
5498
- selfProgram: this.programId,
5499
- tokenPoolPda: this.deriveTokenPoolPda(mint),
5500
- compressOrDecompressTokenAccount: toAddress,
5501
- tokenProgram: TOKEN_PROGRAM_ID,
5502
- })
5019
+ feePayer: payer,
5020
+ authority: currentOwner,
5021
+ cpiAuthorityPda: this.deriveCpiAuthorityPda,
5022
+ lightSystemProgram: stateless_js.LightSystemProgram.programId,
5023
+ registeredProgramPda: registeredProgramPda,
5024
+ noopProgram: noopProgram,
5025
+ accountCompressionAuthority: accountCompressionAuthority,
5026
+ accountCompressionProgram: accountCompressionProgram,
5027
+ selfProgram: this.programId,
5028
+ tokenPoolPda: this.deriveTokenPoolPda(mint),
5029
+ compressOrDecompressTokenAccount: toAddress,
5030
+ tokenProgram: TOKEN_PROGRAM_ID,
5031
+ })
5503
5032
  .remainingAccounts(remainingAccountMetas)
5504
5033
  .instruction();
5505
5034
  return instruction;
5506
5035
  }
5507
5036
  static async mergeTokenAccounts(params) {
5508
- const {
5509
- payer,
5510
- owner,
5511
- inputCompressedTokenAccounts,
5512
- outputStateTree,
5513
- recentValidityProof,
5514
- recentInputStateRootIndices,
5515
- } = params;
5037
+ const { payer, owner, inputCompressedTokenAccounts, outputStateTree, recentValidityProof, recentInputStateRootIndices, } = params;
5516
5038
  if (inputCompressedTokenAccounts.length > 3) {
5517
5039
  throw new Error('Cannot merge more than 3 token accounts at once');
5518
5040
  }
@@ -5520,10 +5042,7 @@ class CompressedTokenProgram {
5520
5042
  payer,
5521
5043
  inputCompressedTokenAccounts,
5522
5044
  toAddress: owner,
5523
- amount: inputCompressedTokenAccounts.reduce(
5524
- (sum, account) => sum.add(account.parsed.amount),
5525
- new anchor.BN(0),
5526
- ),
5045
+ amount: inputCompressedTokenAccounts.reduce((sum, account) => sum.add(account.parsed.amount), new anchor.BN(0)),
5527
5046
  outputStateTrees: outputStateTree,
5528
5047
  recentInputStateRootIndices,
5529
5048
  recentValidityProof,
@@ -5534,9 +5053,7 @@ class CompressedTokenProgram {
5534
5053
  /**
5535
5054
  * Public key that identifies the CompressedPda program
5536
5055
  */
5537
- CompressedTokenProgram.programId = new web3_js.PublicKey(
5538
- 'cTokenmWW8bLPjZEBAUgYy3zKxQZW6VKi7bqNFEVv3m',
5539
- );
5056
+ CompressedTokenProgram.programId = new web3_js.PublicKey('cTokenmWW8bLPjZEBAUgYy3zKxQZW6VKi7bqNFEVv3m');
5540
5057
  CompressedTokenProgram._program = null;
5541
5058
 
5542
5059
  /**
@@ -5554,22 +5071,8 @@ CompressedTokenProgram._program = null;
5554
5071
  *
5555
5072
  * @return Signature of the confirmed transaction
5556
5073
  */
5557
- async function approveAndMintTo(
5558
- rpc,
5559
- payer,
5560
- mint,
5561
- destination,
5562
- authority,
5563
- amount,
5564
- merkleTree,
5565
- confirmOptions,
5566
- ) {
5567
- const authorityTokenAccount = await getOrCreateAssociatedTokenAccount(
5568
- rpc,
5569
- payer,
5570
- mint,
5571
- authority.publicKey,
5572
- );
5074
+ async function approveAndMintTo(rpc, payer, mint, destination, authority, amount, merkleTree, confirmOptions) {
5075
+ const authorityTokenAccount = await getOrCreateAssociatedTokenAccount(rpc, payer, mint, authority.publicKey);
5573
5076
  const ixs = await CompressedTokenProgram.approveAndMintTo({
5574
5077
  feePayer: payer.publicKey,
5575
5078
  mint,
@@ -5581,17 +5084,10 @@ async function approveAndMintTo(
5581
5084
  });
5582
5085
  const { blockhash } = await rpc.getLatestBlockhash();
5583
5086
  const additionalSigners = stateless_js.dedupeSigner(payer, [authority]);
5584
- const tx = stateless_js.buildAndSignTx(
5585
- [
5586
- web3_js.ComputeBudgetProgram.setComputeUnitLimit({
5587
- units: 1000000,
5588
- }),
5589
- ...ixs,
5590
- ],
5591
- payer,
5592
- blockhash,
5593
- additionalSigners,
5594
- );
5087
+ const tx = stateless_js.buildAndSignTx([
5088
+ web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }),
5089
+ ...ixs,
5090
+ ], payer, blockhash, additionalSigners);
5595
5091
  const txId = await stateless_js.sendAndConfirmTx(rpc, tx, confirmOptions);
5596
5092
  return txId;
5597
5093
  }
@@ -5614,17 +5110,7 @@ async function approveAndMintTo(
5614
5110
  *
5615
5111
  * @return Signature of the confirmed transaction
5616
5112
  */
5617
- async function compress(
5618
- rpc,
5619
- payer,
5620
- mint,
5621
- amount,
5622
- owner,
5623
- sourceTokenAccount,
5624
- toAddress,
5625
- merkleTree,
5626
- confirmOptions,
5627
- ) {
5113
+ async function compress(rpc, payer, mint, amount, owner, sourceTokenAccount, toAddress, merkleTree, confirmOptions) {
5628
5114
  const compressIx = await CompressedTokenProgram.compress({
5629
5115
  payer: payer.publicKey,
5630
5116
  owner: owner.publicKey,
@@ -5636,23 +5122,13 @@ async function compress(
5636
5122
  });
5637
5123
  const blockhashCtx = await rpc.getLatestBlockhash();
5638
5124
  const additionalSigners = stateless_js.dedupeSigner(payer, [owner]);
5639
- const signedTx = stateless_js.buildAndSignTx(
5640
- [
5641
- web3_js.ComputeBudgetProgram.setComputeUnitLimit({
5642
- units: 1000000,
5643
- }),
5644
- compressIx,
5645
- ],
5646
- payer,
5647
- blockhashCtx.blockhash,
5648
- additionalSigners,
5649
- );
5650
- const txId = await stateless_js.sendAndConfirmTx(
5651
- rpc,
5652
- signedTx,
5653
- confirmOptions,
5654
- blockhashCtx,
5655
- );
5125
+ const signedTx = stateless_js.buildAndSignTx([
5126
+ web3_js.ComputeBudgetProgram.setComputeUnitLimit({
5127
+ units: 1000000,
5128
+ }),
5129
+ compressIx,
5130
+ ], payer, blockhashCtx.blockhash, additionalSigners);
5131
+ const txId = await stateless_js.sendAndConfirmTx(rpc, signedTx, confirmOptions, blockhashCtx);
5656
5132
  return txId;
5657
5133
  }
5658
5134
 
@@ -5673,33 +5149,15 @@ async function compress(
5673
5149
  *
5674
5150
  * @return Signature of the confirmed transaction
5675
5151
  */
5676
- async function transfer(
5677
- rpc,
5678
- payer,
5679
- mint,
5680
- amount,
5681
- owner,
5682
- toAddress,
5683
- /// TODO: allow multiple
5684
- merkleTree,
5685
- confirmOptions,
5686
- ) {
5152
+ async function transfer(rpc, payer, mint, amount, owner, toAddress,
5153
+ /// TODO: allow multiple
5154
+ merkleTree, confirmOptions) {
5687
5155
  amount = stateless_js.bn(amount);
5688
- const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(
5689
- owner.publicKey,
5690
- {
5691
- mint,
5692
- },
5693
- );
5694
- const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(
5695
- compressedTokenAccounts.items,
5696
- amount,
5697
- );
5698
- const proof = await rpc.getValidityProof(
5699
- inputAccounts.map(account =>
5700
- stateless_js.bn(account.compressedAccount.hash),
5701
- ),
5702
- );
5156
+ const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(owner.publicKey, {
5157
+ mint,
5158
+ });
5159
+ const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(compressedTokenAccounts.items, amount);
5160
+ const proof = await rpc.getValidityProof(inputAccounts.map(account => stateless_js.bn(account.compressedAccount.hash)));
5703
5161
  const ix = await CompressedTokenProgram.transfer({
5704
5162
  payer: payer.publicKey,
5705
5163
  inputCompressedTokenAccounts: inputAccounts,
@@ -5711,22 +5169,8 @@ async function transfer(
5711
5169
  });
5712
5170
  const { blockhash } = await rpc.getLatestBlockhash();
5713
5171
  const additionalSigners = stateless_js.dedupeSigner(payer, [owner]);
5714
- const signedTx = stateless_js.buildAndSignTx(
5715
- [
5716
- web3_js.ComputeBudgetProgram.setComputeUnitLimit({
5717
- units: 1000000,
5718
- }),
5719
- ix,
5720
- ],
5721
- payer,
5722
- blockhash,
5723
- additionalSigners,
5724
- );
5725
- const txId = await stateless_js.sendAndConfirmTx(
5726
- rpc,
5727
- signedTx,
5728
- confirmOptions,
5729
- );
5172
+ const signedTx = stateless_js.buildAndSignTx([web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }), ix], payer, blockhash, additionalSigners);
5173
+ const txId = await stateless_js.sendAndConfirmTx(rpc, signedTx, confirmOptions);
5730
5174
  return txId;
5731
5175
  }
5732
5176
  /**
@@ -5742,17 +5186,14 @@ function selectMinCompressedTokenAccountsForTransfer(accounts, transferAmount) {
5742
5186
  const selectedAccounts = [];
5743
5187
  accounts.sort((a, b) => b.parsed.amount.cmp(a.parsed.amount));
5744
5188
  for (const account of accounts) {
5745
- if (accumulatedAmount.gte(stateless_js.bn(transferAmount))) break;
5189
+ if (accumulatedAmount.gte(stateless_js.bn(transferAmount)))
5190
+ break;
5746
5191
  accumulatedAmount = accumulatedAmount.add(account.parsed.amount);
5747
- accumulatedLamports = accumulatedLamports.add(
5748
- account.compressedAccount.lamports,
5749
- );
5192
+ accumulatedLamports = accumulatedLamports.add(account.compressedAccount.lamports);
5750
5193
  selectedAccounts.push(account);
5751
5194
  }
5752
5195
  if (accumulatedAmount.lt(stateless_js.bn(transferAmount))) {
5753
- throw new Error(
5754
- `Not enough balance for transfer. Required: ${transferAmount.toString()}, available: ${accumulatedAmount.toString()}`,
5755
- );
5196
+ throw new Error(`Not enough balance for transfer. Required: ${transferAmount.toString()}, available: ${accumulatedAmount.toString()}`);
5756
5197
  }
5757
5198
  return [
5758
5199
  selectedAccounts,
@@ -5779,34 +5220,16 @@ function selectMinCompressedTokenAccountsForTransfer(accounts, transferAmount) {
5779
5220
  *
5780
5221
  * @return Signature of the confirmed transaction
5781
5222
  */
5782
- async function decompress(
5783
- rpc,
5784
- payer,
5785
- mint,
5786
- amount,
5787
- owner,
5788
- toAddress,
5789
- /// TODO: allow multiple
5790
- merkleTree,
5791
- confirmOptions,
5792
- ) {
5223
+ async function decompress(rpc, payer, mint, amount, owner, toAddress,
5224
+ /// TODO: allow multiple
5225
+ merkleTree, confirmOptions) {
5793
5226
  amount = stateless_js.bn(amount);
5794
- const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(
5795
- owner.publicKey,
5796
- {
5797
- mint,
5798
- },
5799
- );
5227
+ const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(owner.publicKey, {
5228
+ mint,
5229
+ });
5800
5230
  /// TODO: consider using a different selection algorithm
5801
- const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(
5802
- compressedTokenAccounts.items,
5803
- amount,
5804
- );
5805
- const proof = await rpc.getValidityProof(
5806
- inputAccounts.map(account =>
5807
- stateless_js.bn(account.compressedAccount.hash),
5808
- ),
5809
- );
5231
+ const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(compressedTokenAccounts.items, amount);
5232
+ const proof = await rpc.getValidityProof(inputAccounts.map(account => stateless_js.bn(account.compressedAccount.hash)));
5810
5233
  const ix = await CompressedTokenProgram.decompress({
5811
5234
  payer: payer.publicKey,
5812
5235
  inputCompressedTokenAccounts: inputAccounts,
@@ -5818,22 +5241,8 @@ async function decompress(
5818
5241
  });
5819
5242
  const { blockhash } = await rpc.getLatestBlockhash();
5820
5243
  const additionalSigners = stateless_js.dedupeSigner(payer, [owner]);
5821
- const signedTx = stateless_js.buildAndSignTx(
5822
- [
5823
- web3_js.ComputeBudgetProgram.setComputeUnitLimit({
5824
- units: 1000000,
5825
- }),
5826
- ix,
5827
- ],
5828
- payer,
5829
- blockhash,
5830
- additionalSigners,
5831
- );
5832
- const txId = await stateless_js.sendAndConfirmTx(
5833
- rpc,
5834
- signedTx,
5835
- confirmOptions,
5836
- );
5244
+ const signedTx = stateless_js.buildAndSignTx([web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }), ix], payer, blockhash, additionalSigners);
5245
+ const txId = await stateless_js.sendAndConfirmTx(rpc, signedTx, confirmOptions);
5837
5246
  return txId;
5838
5247
  }
5839
5248
 
@@ -5849,16 +5258,8 @@ async function decompress(
5849
5258
  *
5850
5259
  * @return Address of the new mint and the transaction signature
5851
5260
  */
5852
- async function createMint(
5853
- rpc,
5854
- payer,
5855
- mintAuthority,
5856
- decimals,
5857
- keypair = web3_js.Keypair.generate(),
5858
- confirmOptions,
5859
- ) {
5860
- const rentExemptBalance =
5861
- await rpc.getMinimumBalanceForRentExemption(MINT_SIZE);
5261
+ async function createMint(rpc, payer, mintAuthority, decimals, keypair = web3_js.Keypair.generate(), confirmOptions) {
5262
+ const rentExemptBalance = await rpc.getMinimumBalanceForRentExemption(MINT_SIZE);
5862
5263
  const ixs = await CompressedTokenProgram.createMint({
5863
5264
  feePayer: payer.publicKey,
5864
5265
  mint: keypair.publicKey,
@@ -5869,12 +5270,7 @@ async function createMint(
5869
5270
  });
5870
5271
  const { blockhash } = await rpc.getLatestBlockhash();
5871
5272
  const additionalSigners = stateless_js.dedupeSigner(payer, [keypair]);
5872
- const tx = stateless_js.buildAndSignTx(
5873
- ixs,
5874
- payer,
5875
- blockhash,
5876
- additionalSigners,
5877
- );
5273
+ const tx = stateless_js.buildAndSignTx(ixs, payer, blockhash, additionalSigners);
5878
5274
  const txId = await stateless_js.sendAndConfirmTx(rpc, tx, confirmOptions);
5879
5275
  return { mint: keypair.publicKey, transactionSignature: txId };
5880
5276
  }
@@ -5896,16 +5292,7 @@ async function createMint(
5896
5292
  *
5897
5293
  * @return Signature of the confirmed transaction
5898
5294
  */
5899
- async function mintTo(
5900
- rpc,
5901
- payer,
5902
- mint,
5903
- destination,
5904
- authority,
5905
- amount,
5906
- merkleTree,
5907
- confirmOptions,
5908
- ) {
5295
+ async function mintTo(rpc, payer, mint, destination, authority, amount, merkleTree, confirmOptions) {
5909
5296
  const additionalSigners = stateless_js.dedupeSigner(payer, [authority]);
5910
5297
  const ix = await CompressedTokenProgram.mintTo({
5911
5298
  feePayer: payer.publicKey,
@@ -5916,17 +5303,7 @@ async function mintTo(
5916
5303
  merkleTree,
5917
5304
  });
5918
5305
  const { blockhash } = await rpc.getLatestBlockhash();
5919
- const tx = stateless_js.buildAndSignTx(
5920
- [
5921
- web3_js.ComputeBudgetProgram.setComputeUnitLimit({
5922
- units: 1000000,
5923
- }),
5924
- ix,
5925
- ],
5926
- payer,
5927
- blockhash,
5928
- additionalSigners,
5929
- );
5306
+ const tx = stateless_js.buildAndSignTx([web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }), ix], payer, blockhash, additionalSigners);
5930
5307
  const txId = await stateless_js.sendAndConfirmTx(rpc, tx, confirmOptions);
5931
5308
  return txId;
5932
5309
  }
@@ -5944,67 +5321,35 @@ async function mintTo(
5944
5321
  *
5945
5322
  * @return Array of transaction signatures
5946
5323
  */
5947
- async function mergeTokenAccounts(
5948
- rpc,
5949
- payer,
5950
- mint,
5951
- owner,
5952
- merkleTree,
5953
- confirmOptions,
5954
- ) {
5955
- const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(
5956
- owner.publicKey,
5957
- { mint },
5958
- );
5324
+ async function mergeTokenAccounts(rpc, payer, mint, owner, merkleTree, confirmOptions) {
5325
+ const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(owner.publicKey, { mint });
5959
5326
  if (compressedTokenAccounts.items.length === 0) {
5960
- throw new Error(
5961
- `No compressed token accounts found for mint ${mint.toBase58()}`,
5962
- );
5327
+ throw new Error(`No compressed token accounts found for mint ${mint.toBase58()}`);
5963
5328
  }
5964
5329
  if (compressedTokenAccounts.items.length >= 6) {
5965
- throw new Error(
5966
- `Too many compressed token accounts used for mint ${mint.toBase58()}`,
5967
- );
5330
+ throw new Error(`Too many compressed token accounts used for mint ${mint.toBase58()}`);
5968
5331
  }
5969
5332
  const instructions = [
5970
5333
  web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }),
5971
5334
  ];
5972
- for (
5973
- let i = 0;
5974
- i < compressedTokenAccounts.items.slice(0, 6).length;
5975
- i += 3
5976
- ) {
5335
+ for (let i = 0; i < compressedTokenAccounts.items.slice(0, 6).length; i += 3) {
5977
5336
  const batch = compressedTokenAccounts.items.slice(i, i + 3);
5978
- const proof = await rpc.getValidityProof(
5979
- batch.map(account =>
5980
- stateless_js.bn(account.compressedAccount.hash),
5981
- ),
5982
- );
5983
- const batchInstructions =
5984
- await CompressedTokenProgram.mergeTokenAccounts({
5985
- payer: payer.publicKey,
5986
- owner: owner.publicKey,
5987
- mint,
5988
- inputCompressedTokenAccounts: batch,
5989
- outputStateTree: merkleTree,
5990
- recentValidityProof: proof.compressedProof,
5991
- recentInputStateRootIndices: proof.rootIndices,
5992
- });
5337
+ const proof = await rpc.getValidityProof(batch.map(account => stateless_js.bn(account.compressedAccount.hash)));
5338
+ const batchInstructions = await CompressedTokenProgram.mergeTokenAccounts({
5339
+ payer: payer.publicKey,
5340
+ owner: owner.publicKey,
5341
+ mint,
5342
+ inputCompressedTokenAccounts: batch,
5343
+ outputStateTree: merkleTree,
5344
+ recentValidityProof: proof.compressedProof,
5345
+ recentInputStateRootIndices: proof.rootIndices,
5346
+ });
5993
5347
  instructions.push(...batchInstructions);
5994
5348
  }
5995
5349
  const { blockhash } = await rpc.getLatestBlockhash();
5996
5350
  const additionalSigners = stateless_js.dedupeSigner(payer, [owner]);
5997
- const signedTx = stateless_js.buildAndSignTx(
5998
- instructions,
5999
- payer,
6000
- blockhash,
6001
- additionalSigners,
6002
- );
6003
- const txId = await stateless_js.sendAndConfirmTx(
6004
- rpc,
6005
- signedTx,
6006
- confirmOptions,
6007
- );
5351
+ const signedTx = stateless_js.buildAndSignTx(instructions, payer, blockhash, additionalSigners);
5352
+ const txId = await stateless_js.sendAndConfirmTx(rpc, signedTx, confirmOptions);
6008
5353
  return txId;
6009
5354
  }
6010
5355
 
@@ -6043,50 +5388,23 @@ async function createTokenPool(rpc, payer, mintAddress, confirmOptions) {
6043
5388
  *
6044
5389
  * @return Transaction signatures and the address of the created lookup table
6045
5390
  */
6046
- async function createTokenProgramLookupTable(
6047
- rpc,
6048
- payer,
6049
- authority,
6050
- mints,
6051
- additionalAccounts,
6052
- ) {
5391
+ async function createTokenProgramLookupTable(rpc, payer, authority, mints, additionalAccounts) {
6053
5392
  const recentSlot = await rpc.getSlot('finalized');
6054
- const { instructions, address } =
6055
- await CompressedTokenProgram.createTokenProgramLookupTable({
6056
- payer: payer.publicKey,
6057
- authority: authority.publicKey,
6058
- mints,
6059
- remainingAccounts: additionalAccounts,
6060
- recentSlot,
6061
- });
5393
+ const { instructions, address } = await CompressedTokenProgram.createTokenProgramLookupTable({
5394
+ payer: payer.publicKey,
5395
+ authority: authority.publicKey,
5396
+ mints,
5397
+ remainingAccounts: additionalAccounts,
5398
+ recentSlot,
5399
+ });
6062
5400
  const additionalSigners = stateless_js.dedupeSigner(payer, [authority]);
6063
5401
  const blockhashCtx = await rpc.getLatestBlockhash();
6064
- const signedTx = stateless_js.buildAndSignTx(
6065
- [instructions[0]],
6066
- payer,
6067
- blockhashCtx.blockhash,
6068
- additionalSigners,
6069
- );
5402
+ const signedTx = stateless_js.buildAndSignTx([instructions[0]], payer, blockhashCtx.blockhash, additionalSigners);
6070
5403
  /// Must wait for the first instruction to be finalized.
6071
- const txId = await stateless_js.sendAndConfirmTx(
6072
- rpc,
6073
- signedTx,
6074
- { commitment: 'finalized' },
6075
- blockhashCtx,
6076
- );
5404
+ const txId = await stateless_js.sendAndConfirmTx(rpc, signedTx, { commitment: 'finalized' }, blockhashCtx);
6077
5405
  const blockhashCtx2 = await rpc.getLatestBlockhash();
6078
- const signedTx2 = stateless_js.buildAndSignTx(
6079
- [instructions[1]],
6080
- payer,
6081
- blockhashCtx2.blockhash,
6082
- additionalSigners,
6083
- );
6084
- const txId2 = await stateless_js.sendAndConfirmTx(
6085
- rpc,
6086
- signedTx2,
6087
- { commitment: 'finalized' },
6088
- blockhashCtx2,
6089
- );
5406
+ const signedTx2 = stateless_js.buildAndSignTx([instructions[1]], payer, blockhashCtx2.blockhash, additionalSigners);
5407
+ const txId2 = await stateless_js.sendAndConfirmTx(rpc, signedTx2, { commitment: 'finalized' }, blockhashCtx2);
6090
5408
  return { txIds: [txId, txId2], address };
6091
5409
  }
6092
5410
 
@@ -6107,8 +5425,7 @@ exports.mergeTokenAccounts = mergeTokenAccounts;
6107
5425
  exports.mintTo = mintTo;
6108
5426
  exports.packCompressedTokenAccounts = packCompressedTokenAccounts;
6109
5427
  exports.parseTokenData = parseTokenData;
6110
- exports.selectMinCompressedTokenAccountsForTransfer =
6111
- selectMinCompressedTokenAccountsForTransfer;
5428
+ exports.selectMinCompressedTokenAccountsForTransfer = selectMinCompressedTokenAccountsForTransfer;
6112
5429
  exports.sumUpTokenAmount = sumUpTokenAmount;
6113
5430
  exports.transfer = transfer;
6114
5431
  exports.validateSameTokenOwner = validateSameTokenOwner;