@debridge-finance/solana-utils 2.3.0 → 3.0.0

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.
@@ -1,4 +1,4 @@
1
- import { Transaction, VersionedTransaction, MessageV0, PublicKey } from '@solana/web3.js';
1
+ import { Transaction, VersionedTransaction, MessageV0, PublicKey, TransactionInstruction, SystemProgram } from '@solana/web3.js';
2
2
 
3
3
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4
4
 
@@ -7501,9 +7501,9 @@ function __awaiter(thisArg, _arguments, P, generator) {
7501
7501
  });
7502
7502
  }
7503
7503
 
7504
- function getAccountInfo(connection, account) {
7504
+ function getAccountInfo(connection, account, commitment = "confirmed") {
7505
7505
  return __awaiter(this, void 0, void 0, function* () {
7506
- const info = yield connection.getAccountInfo(account);
7506
+ const info = yield connection.getAccountInfo(account, commitment);
7507
7507
  if (info) {
7508
7508
  // alchemy bug fix
7509
7509
  if (info.lamports === 0 && info.rentEpoch === 0)
@@ -7557,7 +7557,7 @@ function getTransactionSize(transaction, feePayer) {
7557
7557
  return serializedMessage.length + uniqueSigners.size * 64 + 1;
7558
7558
  }
7559
7559
  function isVersionedTx(arg) {
7560
- return 'version' in arg;
7560
+ return "version" in arg;
7561
7561
  }
7562
7562
  class Wallet {
7563
7563
  constructor(keypair) {
@@ -7585,7 +7585,7 @@ class Wallet {
7585
7585
  });
7586
7586
  }
7587
7587
  }
7588
- function sendWithRetries(connection, serialized, lastValidBlockHeight, timesToSend = 5) {
7588
+ function sendWithRetries(connection, serialized, lastValidBlockHeight, timesToSend = 5, blockhashCommitment = "finalized") {
7589
7589
  return __awaiter(this, void 0, void 0, function* () {
7590
7590
  const txId = yield connection.sendRawTransaction(serialized, {
7591
7591
  skipPreflight: true,
@@ -7596,7 +7596,8 @@ function sendWithRetries(connection, serialized, lastValidBlockHeight, timesToSe
7596
7596
  while (blockheight < lastValidBlockHeight && sent < timesToSend) {
7597
7597
  yield connection.sendRawTransaction(serialized, {
7598
7598
  skipPreflight: true,
7599
- maxRetries: 1000,
7599
+ preflightCommitment: blockhashCommitment,
7600
+ maxRetries: 100,
7600
7601
  });
7601
7602
  yield sleep(300);
7602
7603
  blockheight = yield connection.getBlockHeight();
@@ -7618,48 +7619,82 @@ function txToV0(transaction, payer, blockhash) {
7618
7619
  return new VersionedTransaction(v0Message);
7619
7620
  }
7620
7621
  }
7621
- function sendAll(connection, wallet, transactions, signers, waitBetweenSend, skipPreflight = false, debug = false, convertIntoTxV0 = true, rpcCalls = 5) {
7622
+ function setBlockhash(transaction, blockhash) {
7623
+ if (isVersionedTx(transaction)) {
7624
+ transaction.message.recentBlockhash = blockhash;
7625
+ }
7626
+ else {
7627
+ transaction.recentBlockhash = blockhash;
7628
+ }
7629
+ }
7630
+ /**
7631
+ *
7632
+ * @param connection rpc connection
7633
+ * @param wallet wallet interface to sign transaction
7634
+ * @param transactions transaction(s) to send
7635
+ * @param options additional {@link SendAllOptions|options}
7636
+ * @returns
7637
+ */
7638
+ function sendAll(connection, wallet, transactions, options) {
7622
7639
  var _a;
7623
7640
  return __awaiter(this, void 0, void 0, function* () {
7641
+ const blockhashCommitment = (options === null || options === void 0 ? void 0 : options.blockhashCommitment) === undefined ? "finalized" : options.blockhashCommitment;
7642
+ const fakeBlockHash = "1".repeat(32);
7643
+ const convertIntoTxV0 = (options === null || options === void 0 ? void 0 : options.convertIntoTxV0) === undefined ? true : options.convertIntoTxV0;
7644
+ const debug = (options === null || options === void 0 ? void 0 : options.debug) === undefined ? false : options.debug;
7645
+ const skipPreflight = (options === null || options === void 0 ? void 0 : options.skipPreflight) === undefined ? false : options.skipPreflight;
7646
+ const rpcCalls = (options === null || options === void 0 ? void 0 : options.rpcCalls) === undefined ? 5 : options.rpcCalls;
7647
+ if (!Array.isArray(transactions))
7648
+ transactions = [transactions];
7624
7649
  if (convertIntoTxV0) {
7625
- const fakeBlockHash = "1".repeat(32);
7626
7650
  transactions = transactions.map((tx) => txToV0(tx, wallet.publicKey, fakeBlockHash));
7627
7651
  }
7628
7652
  let txIds = [];
7629
- if (waitBetweenSend === undefined || waitBetweenSend === 0) {
7630
- const { blockhash, lastValidBlockHeight } = yield connection.getLatestBlockhash({ commitment: "confirmed" });
7653
+ if ((options === null || options === void 0 ? void 0 : options.waitBetweenSend) === undefined || options.waitBetweenSend === 0) {
7631
7654
  yield Promise.all(transactions.map((tx) => __awaiter(this, void 0, void 0, function* () {
7632
7655
  var _b;
7633
7656
  let txV0;
7634
7657
  if (isVersionedTx(tx)) {
7635
- tx.message.recentBlockhash = blockhash;
7658
+ tx.message.recentBlockhash = fakeBlockHash;
7636
7659
  txV0 = tx;
7637
7660
  }
7638
7661
  else {
7639
- tx.recentBlockhash = blockhash;
7662
+ tx.recentBlockhash = fakeBlockHash;
7640
7663
  tx.feePayer = wallet.publicKey;
7641
- txV0 = new VersionedTransaction(MessageV0.compile({ addressLookupTableAccounts: [], instructions: tx.instructions, recentBlockhash: blockhash, payerKey: tx.feePayer }));
7664
+ txV0 = new VersionedTransaction(MessageV0.compile({
7665
+ addressLookupTableAccounts: [],
7666
+ instructions: tx.instructions,
7667
+ recentBlockhash: fakeBlockHash,
7668
+ payerKey: tx.feePayer,
7669
+ }));
7642
7670
  }
7643
7671
  if (!skipPreflight) {
7644
- const simulationResult = yield connection.simulateTransaction(txV0, { sigVerify: false, replaceRecentBlockhash: true, commitment: "confirmed" });
7672
+ const simulationResult = yield connection.simulateTransaction(txV0, {
7673
+ sigVerify: false,
7674
+ replaceRecentBlockhash: true,
7675
+ commitment: "confirmed",
7676
+ });
7645
7677
  if (simulationResult.value.err !== null) {
7646
7678
  throw new Error(`Tx simulation Error! Transaction message dump: ${buffer.Buffer.from(txV0.serialize()).toString("base64")}\n Error: ${JSON.stringify(simulationResult.value.err)}, logs:\n ${(_b = simulationResult.value.logs) === null || _b === void 0 ? void 0 : _b.join("\n")}`);
7647
7679
  }
7648
7680
  }
7649
7681
  })));
7682
+ const { blockhash, lastValidBlockHeight } = yield connection.getLatestBlockhash({ commitment: blockhashCommitment });
7683
+ // set real blockhash
7684
+ transactions.map((tx) => setBlockhash(tx, blockhash));
7650
7685
  // sign after setting correct blockhashes
7651
- const signed = yield wallet.signAllTransactions(transactions, signers);
7686
+ const signed = yield wallet.signAllTransactions(transactions, options === null || options === void 0 ? void 0 : options.signers);
7652
7687
  txIds = yield Promise.all(signed.map((signedTx) => {
7653
7688
  const serialized = buffer.Buffer.from(signedTx.serialize());
7654
7689
  if (debug)
7655
7690
  console.debug(serialized.toString("base64"));
7656
- return sendWithRetries(connection, serialized, lastValidBlockHeight, rpcCalls);
7691
+ return sendWithRetries(connection, serialized, lastValidBlockHeight, rpcCalls, blockhashCommitment);
7657
7692
  }));
7658
7693
  }
7659
7694
  else {
7660
7695
  for (let i = 0; i < transactions.length; i++) {
7661
7696
  const tx = transactions[i];
7662
- const { blockhash, lastValidBlockHeight } = yield connection.getLatestBlockhash();
7697
+ const { blockhash, lastValidBlockHeight } = yield connection.getLatestBlockhash({ commitment: blockhashCommitment });
7663
7698
  let txV0;
7664
7699
  if (isVersionedTx(tx)) {
7665
7700
  tx.message.recentBlockhash = blockhash;
@@ -7668,11 +7703,20 @@ function sendAll(connection, wallet, transactions, signers, waitBetweenSend, ski
7668
7703
  else {
7669
7704
  tx.recentBlockhash = blockhash;
7670
7705
  tx.feePayer = wallet.publicKey;
7671
- txV0 = new VersionedTransaction(MessageV0.compile({ addressLookupTableAccounts: [], instructions: tx.instructions, recentBlockhash: blockhash, payerKey: tx.feePayer }));
7706
+ txV0 = new VersionedTransaction(MessageV0.compile({
7707
+ addressLookupTableAccounts: [],
7708
+ instructions: tx.instructions,
7709
+ recentBlockhash: blockhash,
7710
+ payerKey: tx.feePayer,
7711
+ }));
7672
7712
  }
7673
- const signed = yield wallet.signTransaction(tx, signers && signers.length > i ? signers[i] : undefined);
7713
+ const signed = yield wallet.signTransaction(tx, (options === null || options === void 0 ? void 0 : options.signers) && (options === null || options === void 0 ? void 0 : options.signers.length) > i ? options.signers[i] : undefined);
7674
7714
  if (!skipPreflight) {
7675
- const simulationResult = yield connection.simulateTransaction(txV0, { sigVerify: false, replaceRecentBlockhash: true, commitment: "confirmed" });
7715
+ const simulationResult = yield connection.simulateTransaction(txV0, {
7716
+ sigVerify: false,
7717
+ replaceRecentBlockhash: true,
7718
+ commitment: "confirmed",
7719
+ });
7676
7720
  if (simulationResult.value.err !== null) {
7677
7721
  throw new Error(`Tx simulation Error! Transaction message dump: ${buffer.Buffer.from(txV0.serialize()).toString("base64")}\n Error: ${JSON.stringify(simulationResult.value.err)}, logs:\n ${(_a = simulationResult.value.logs) === null || _a === void 0 ? void 0 : _a.join("\n")}`);
7678
7722
  }
@@ -7680,8 +7724,8 @@ function sendAll(connection, wallet, transactions, signers, waitBetweenSend, ski
7680
7724
  const serialized = buffer.Buffer.from(signed.serialize());
7681
7725
  if (debug)
7682
7726
  console.debug(serialized.toString("base64"));
7683
- txIds.push(yield sendWithRetries(connection, serialized, lastValidBlockHeight, rpcCalls));
7684
- yield sleep(waitBetweenSend);
7727
+ txIds.push(yield sendWithRetries(connection, serialized, lastValidBlockHeight, rpcCalls, blockhashCommitment));
7728
+ yield sleep(options.waitBetweenSend);
7685
7729
  }
7686
7730
  }
7687
7731
  return txIds;
@@ -7815,57 +7859,58 @@ const TOKEN_PROGRAM_ID = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ
7815
7859
  const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
7816
7860
  const WRAPPED_SOL_MINT = new PublicKey("So11111111111111111111111111111111111111112");
7817
7861
  function findAssociatedTokenAddress(wallet, tokenMint, tokenProgramId = TOKEN_PROGRAM_ID, associatedTokenProramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
7818
- return __awaiter(this, void 0, void 0, function* () {
7819
- return PublicKey.findProgramAddress([wallet.toBytes(), tokenProgramId.toBytes(), tokenMint.toBytes()], associatedTokenProramId);
7820
- });
7862
+ return PublicKey.findProgramAddressSync([wallet.toBytes(), tokenProgramId.toBytes(), tokenMint.toBytes()], associatedTokenProramId);
7821
7863
  }
7864
+ /**
7865
+ * @deprecated same as findAssociatedTokenAddress
7866
+ */
7822
7867
  function findAssociatedTokenAddressSync(wallet, tokenMint, tokenProgramId = TOKEN_PROGRAM_ID, associatedTokenProramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
7823
7868
  return PublicKey.findProgramAddressSync([wallet.toBytes(), tokenProgramId.toBytes(), tokenMint.toBytes()], associatedTokenProramId);
7824
7869
  }
7825
7870
  function getTokenMetadataAddress(tokenMint, tokenMetedataProgramId) {
7826
- return PublicKey.findProgramAddress([buffer.Buffer.from("metadata"), tokenMetedataProgramId.toBytes(), tokenMint.toBytes()], tokenMetedataProgramId);
7871
+ return PublicKey.findProgramAddressSync([buffer.Buffer.from("metadata"), tokenMetedataProgramId.toBytes(), tokenMint.toBytes()], tokenMetedataProgramId);
7827
7872
  }
7828
7873
  const deBridge = {
7829
- getClaimMarkerAddress: (DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridge$1.Seeds.CLAIM_MARKER)], DEBRIDGE_PROGRAM_ID),
7830
- getExternalCallStorageAddress: (submissionId, executorPubkey, sourceChainId, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([
7874
+ getClaimMarkerAddress: (DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$1.Seeds.CLAIM_MARKER)], DEBRIDGE_PROGRAM_ID),
7875
+ getExternalCallStorageAddress: (submissionId, executorPubkey, sourceChainId, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([
7831
7876
  buffer.Buffer.from(deBridge$1.Seeds.EXTERNAL_CALL_STORAGE),
7832
7877
  submissionId,
7833
7878
  new PublicKey(executorPubkey).toBytes(),
7834
7879
  normalizeChainId(sourceChainId),
7835
7880
  ], DEBRIDGE_PROGRAM_ID),
7836
- getExternalCallMetaAddress: (externalCallStorage, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridge$1.Seeds.EXTERNAL_CALL_META), new PublicKey(externalCallStorage).toBytes()], DEBRIDGE_PROGRAM_ID),
7837
- getNonceAddress: (DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridge$1.Seeds.NONCE)], DEBRIDGE_PROGRAM_ID),
7838
- getSubmissionAddress: (submissionId, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridge$1.Seeds.SUBMISSION), submissionId], DEBRIDGE_PROGRAM_ID),
7839
- getSubmissionAuthAddress: (submissionAddress, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridge$1.Seeds.SUBMISSION_AUTH), new PublicKey(submissionAddress).toBytes()], DEBRIDGE_PROGRAM_ID),
7840
- getMintAuthorityAddress: (bridge, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridge$1.Seeds.BRIDGE_MINTER), new PublicKey(bridge).toBytes()], DEBRIDGE_PROGRAM_ID),
7881
+ getExternalCallMetaAddress: (externalCallStorage, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$1.Seeds.EXTERNAL_CALL_META), new PublicKey(externalCallStorage).toBytes()], DEBRIDGE_PROGRAM_ID),
7882
+ getNonceAddress: (DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$1.Seeds.NONCE)], DEBRIDGE_PROGRAM_ID),
7883
+ getSubmissionAddress: (submissionId, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$1.Seeds.SUBMISSION), submissionId], DEBRIDGE_PROGRAM_ID),
7884
+ getSubmissionAuthAddress: (submissionAddress, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$1.Seeds.SUBMISSION_AUTH), new PublicKey(submissionAddress).toBytes()], DEBRIDGE_PROGRAM_ID),
7885
+ getMintAuthorityAddress: (bridge, DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$1.Seeds.BRIDGE_MINTER), new PublicKey(bridge).toBytes()], DEBRIDGE_PROGRAM_ID),
7841
7886
  };
7842
7887
  const deBridgeSettings = {
7843
- getTokenMetadataMasterAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.TOKEN_METADATA)], SETTINGS_PROGRAM_ID),
7844
- getTokenMintAddress: (debridgeId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.WRAPPER_TOKEN), debridgeId], SETTINGS_PROGRAM_ID),
7845
- getStateAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.STATE)], SETTINGS_PROGRAM_ID),
7846
- getConfirmationsStorageAddress: (message, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.CONFIRMATION_STORAGE), message], SETTINGS_PROGRAM_ID),
7847
- getBridgeFeeAddress: (bridge, chainId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.BRIDGE_FEE_INFO), bridge.toBytes(), normalizeChainId(chainId)], SETTINGS_PROGRAM_ID),
7848
- getChainSupportInfoAddress: (chainId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.CHAIN_SUPPORT_INFO), normalizeChainId(chainId)], SETTINGS_PROGRAM_ID),
7849
- getDiscountInfoAddress: (user, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.DISCOUNT_INFO), user.toBytes()], SETTINGS_PROGRAM_ID),
7850
- getBridgeAddress: (tokenMint, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.BRIDGE), tokenMint.toBytes()], SETTINGS_PROGRAM_ID),
7851
- getBridgeMapAddress: (bridgeId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.SEND_BRIDGE_MAP), bridgeId], SETTINGS_PROGRAM_ID),
7852
- getNoDiscountAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.NO_DISCOUNT)], SETTINGS_PROGRAM_ID),
7853
- getNoBridgeFeeAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(deBridgeSettings$1.Seeds.NO_BRIDGE_FEE_INFO)], SETTINGS_PROGRAM_ID),
7888
+ getTokenMetadataMasterAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.TOKEN_METADATA)], SETTINGS_PROGRAM_ID),
7889
+ getTokenMintAddress: (debridgeId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.WRAPPER_TOKEN), debridgeId], SETTINGS_PROGRAM_ID),
7890
+ getStateAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.STATE)], SETTINGS_PROGRAM_ID),
7891
+ getConfirmationsStorageAddress: (message, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.CONFIRMATION_STORAGE), message], SETTINGS_PROGRAM_ID),
7892
+ getBridgeFeeAddress: (bridge, chainId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.BRIDGE_FEE_INFO), bridge.toBytes(), normalizeChainId(chainId)], SETTINGS_PROGRAM_ID),
7893
+ getChainSupportInfoAddress: (chainId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.CHAIN_SUPPORT_INFO), normalizeChainId(chainId)], SETTINGS_PROGRAM_ID),
7894
+ getDiscountInfoAddress: (user, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.DISCOUNT_INFO), user.toBytes()], SETTINGS_PROGRAM_ID),
7895
+ getBridgeAddress: (tokenMint, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.BRIDGE), tokenMint.toBytes()], SETTINGS_PROGRAM_ID),
7896
+ getBridgeMapAddress: (bridgeId, SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.SEND_BRIDGE_MAP), bridgeId], SETTINGS_PROGRAM_ID),
7897
+ getNoDiscountAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.NO_DISCOUNT)], SETTINGS_PROGRAM_ID),
7898
+ getNoBridgeFeeAddress: (SETTINGS_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridgeSettings$1.Seeds.NO_BRIDGE_FEE_INFO)], SETTINGS_PROGRAM_ID),
7854
7899
  };
7855
7900
  const PmmSrc = {
7856
- getStateAccount: (PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.STATE)], PMM_SRC_PROGRAM_ID),
7857
- getNonceAccount: (maker, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.NONCE), isBuffer(maker) ? maker : maker.toBuffer()], PMM_SRC_PROGRAM_ID),
7858
- getGiveOrderStateAccount: (orderId, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.ORDER_STATE), orderId], PMM_SRC_PROGRAM_ID),
7859
- getAuthorizedNativeSenderAddress: (chainId, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.AUTHORIZED_NATIVE_SENDER), chainId], PMM_SRC_PROGRAM_ID),
7860
- getGiveOrderWalletAddress: (orderId, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.GIVE_ORDER_WALLET), orderId], PMM_SRC_PROGRAM_ID),
7861
- getFeeLedgerWalletAddress: (tokenMint, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.FEE_LEDGER_WALLET), tokenMint.toBuffer()], PMM_SRC_PROGRAM_ID),
7862
- getFeeLedgerAddress: (PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmSrc.Seeds.FEE_LEDGER)], PMM_SRC_PROGRAM_ID),
7901
+ getStateAccount: (PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.STATE)], PMM_SRC_PROGRAM_ID),
7902
+ getNonceAccount: (maker, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.NONCE), isBuffer(maker) ? maker : maker.toBuffer()], PMM_SRC_PROGRAM_ID),
7903
+ getGiveOrderStateAccount: (orderId, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.ORDER_STATE), orderId], PMM_SRC_PROGRAM_ID),
7904
+ getAuthorizedNativeSenderAddress: (chainId, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.AUTHORIZED_NATIVE_SENDER), chainId], PMM_SRC_PROGRAM_ID),
7905
+ getGiveOrderWalletAddress: (orderId, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.GIVE_ORDER_WALLET), orderId], PMM_SRC_PROGRAM_ID),
7906
+ getFeeLedgerWalletAddress: (tokenMint, PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.FEE_LEDGER_WALLET), tokenMint.toBuffer()], PMM_SRC_PROGRAM_ID),
7907
+ getFeeLedgerAddress: (PMM_SRC_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmSrc.Seeds.FEE_LEDGER)], PMM_SRC_PROGRAM_ID),
7863
7908
  };
7864
7909
  const PmmDst = {
7865
- getAuthorizedSrcContractAddress: (chainId, PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmDst.Seeds.AUTHORIZED_SRC_CONTRACT), chainId], PMM_DST_PROGRAM_ID),
7866
- getAuthorizedDstNativeSenderAddress: (PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmDst.Seeds.AUTHORIZED_DST_NATIVE_SENDER)], PMM_DST_PROGRAM_ID),
7867
- getTakeOrderStateAddress: (orderId, PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmDst.Seeds.ORDER_STATE), orderId], PMM_DST_PROGRAM_ID),
7868
- getTakePatchAddress: (orderId, PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddress([buffer.Buffer.from(pmmDst.Seeds.TAKE_PATCH), orderId], PMM_DST_PROGRAM_ID),
7910
+ getAuthorizedSrcContractAddress: (chainId, PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmDst.Seeds.AUTHORIZED_SRC_CONTRACT), chainId], PMM_DST_PROGRAM_ID),
7911
+ getAuthorizedDstNativeSenderAddress: (PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmDst.Seeds.AUTHORIZED_DST_NATIVE_SENDER)], PMM_DST_PROGRAM_ID),
7912
+ getTakeOrderStateAddress: (orderId, PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmDst.Seeds.ORDER_STATE), orderId], PMM_DST_PROGRAM_ID),
7913
+ getTakePatchAddress: (orderId, PMM_DST_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(pmmDst.Seeds.TAKE_PATCH), orderId], PMM_DST_PROGRAM_ID),
7869
7914
  };
7870
7915
  function wrapFn(fn, arg) {
7871
7916
  return (...args) => fn(...args, arg);
@@ -7895,5 +7940,2671 @@ const DeBridgeResolver = (programId, settingsProgramId) => new ResolverContainer
7895
7940
  const PmmSrcResolver = (programId) => new Resolver(programId, PmmSrc);
7896
7941
  const PmmDstResolver = (programId) => new Resolver(programId, PmmDst);
7897
7942
 
7898
- export { ASSOCIATED_TOKEN_PROGRAM_ID, DeBridgeResolver, PmmDstResolver, PmmSrcResolver, TOKEN_METADATA_PROGRAM_ID, TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT, constants, crypto, findAssociatedTokenAddress, findAssociatedTokenAddressSync, getTokenMetadataAddress, helpers, interfaces };
7943
+ var Layout$1 = {};
7944
+
7945
+ /* The MIT License (MIT)
7946
+ *
7947
+ * Copyright 2015-2018 Peter A. Bigot
7948
+ *
7949
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7950
+ * of this software and associated documentation files (the "Software"), to deal
7951
+ * in the Software without restriction, including without limitation the rights
7952
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7953
+ * copies of the Software, and to permit persons to whom the Software is
7954
+ * furnished to do so, subject to the following conditions:
7955
+ *
7956
+ * The above copyright notice and this permission notice shall be included in
7957
+ * all copies or substantial portions of the Software.
7958
+ *
7959
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
7960
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7961
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7962
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
7963
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
7964
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
7965
+ * THE SOFTWARE.
7966
+ */
7967
+ Object.defineProperty(Layout$1, "__esModule", { value: true });
7968
+ 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$1.Layout = Layout$1.uint8ArrayToBuffer = Layout$1.checkUint8Array = void 0;
7969
+ 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;
7970
+ const buffer_1 = buffer;
7971
+ /* Check if a value is a Uint8Array.
7972
+ *
7973
+ * @ignore */
7974
+ function checkUint8Array(b) {
7975
+ if (!(b instanceof Uint8Array)) {
7976
+ throw new TypeError('b must be a Uint8Array');
7977
+ }
7978
+ }
7979
+ Layout$1.checkUint8Array = checkUint8Array;
7980
+ /* Create a Buffer instance from a Uint8Array.
7981
+ *
7982
+ * @ignore */
7983
+ function uint8ArrayToBuffer(b) {
7984
+ checkUint8Array(b);
7985
+ return buffer_1.Buffer.from(b.buffer, b.byteOffset, b.length);
7986
+ }
7987
+ Layout$1.uint8ArrayToBuffer = uint8ArrayToBuffer;
7988
+ /**
7989
+ * Base class for layout objects.
7990
+ *
7991
+ * **NOTE** This is an abstract base class; you can create instances
7992
+ * if it amuses you, but they won't support the {@link
7993
+ * Layout#encode|encode} or {@link Layout#decode|decode} functions.
7994
+ *
7995
+ * @param {Number} span - Initializer for {@link Layout#span|span}. The
7996
+ * parameter must be an integer; a negative value signifies that the
7997
+ * span is {@link Layout#getSpan|value-specific}.
7998
+ *
7999
+ * @param {string} [property] - Initializer for {@link
8000
+ * Layout#property|property}.
8001
+ *
8002
+ * @abstract
8003
+ */
8004
+ class Layout {
8005
+ constructor(span, property) {
8006
+ if (!Number.isInteger(span)) {
8007
+ throw new TypeError('span must be an integer');
8008
+ }
8009
+ /** The span of the layout in bytes.
8010
+ *
8011
+ * Positive values are generally expected.
8012
+ *
8013
+ * Zero will only appear in {@link Constant}s and in {@link
8014
+ * Sequence}s where the {@link Sequence#count|count} is zero.
8015
+ *
8016
+ * A negative value indicates that the span is value-specific, and
8017
+ * must be obtained using {@link Layout#getSpan|getSpan}. */
8018
+ this.span = span;
8019
+ /** The property name used when this layout is represented in an
8020
+ * Object.
8021
+ *
8022
+ * Used only for layouts that {@link Layout#decode|decode} to Object
8023
+ * instances. If left undefined the span of the unnamed layout will
8024
+ * be treated as padding: it will not be mutated by {@link
8025
+ * Layout#encode|encode} nor represented as a property in the
8026
+ * decoded Object. */
8027
+ this.property = property;
8028
+ }
8029
+ /** Function to create an Object into which decoded properties will
8030
+ * be written.
8031
+ *
8032
+ * Used only for layouts that {@link Layout#decode|decode} to Object
8033
+ * instances, which means:
8034
+ * * {@link Structure}
8035
+ * * {@link Union}
8036
+ * * {@link VariantLayout}
8037
+ * * {@link BitStructure}
8038
+ *
8039
+ * If left undefined the JavaScript representation of these layouts
8040
+ * will be Object instances.
8041
+ *
8042
+ * See {@link bindConstructorLayout}.
8043
+ */
8044
+ makeDestinationObject() {
8045
+ return {};
8046
+ }
8047
+ /**
8048
+ * Calculate the span of a specific instance of a layout.
8049
+ *
8050
+ * @param {Uint8Array} b - the buffer that contains an encoded instance.
8051
+ *
8052
+ * @param {Number} [offset] - the offset at which the encoded instance
8053
+ * starts. If absent a zero offset is inferred.
8054
+ *
8055
+ * @return {Number} - the number of bytes covered by the layout
8056
+ * instance. If this method is not overridden in a subclass the
8057
+ * definition-time constant {@link Layout#span|span} will be
8058
+ * returned.
8059
+ *
8060
+ * @throws {RangeError} - if the length of the value cannot be
8061
+ * determined.
8062
+ */
8063
+ getSpan(b, offset) {
8064
+ if (0 > this.span) {
8065
+ throw new RangeError('indeterminate span');
8066
+ }
8067
+ return this.span;
8068
+ }
8069
+ /**
8070
+ * Replicate the layout using a new property.
8071
+ *
8072
+ * This function must be used to get a structurally-equivalent layout
8073
+ * with a different name since all {@link Layout} instances are
8074
+ * immutable.
8075
+ *
8076
+ * **NOTE** This is a shallow copy. All fields except {@link
8077
+ * Layout#property|property} are strictly equal to the origin layout.
8078
+ *
8079
+ * @param {String} property - the value for {@link
8080
+ * Layout#property|property} in the replica.
8081
+ *
8082
+ * @returns {Layout} - the copy with {@link Layout#property|property}
8083
+ * set to `property`.
8084
+ */
8085
+ replicate(property) {
8086
+ const rv = Object.create(this.constructor.prototype);
8087
+ Object.assign(rv, this);
8088
+ rv.property = property;
8089
+ return rv;
8090
+ }
8091
+ /**
8092
+ * Create an object from layout properties and an array of values.
8093
+ *
8094
+ * **NOTE** This function returns `undefined` if invoked on a layout
8095
+ * that does not return its value as an Object. Objects are
8096
+ * returned for things that are a {@link Structure}, which includes
8097
+ * {@link VariantLayout|variant layouts} if they are structures, and
8098
+ * excludes {@link Union}s. If you want this feature for a union
8099
+ * you must use {@link Union.getVariant|getVariant} to select the
8100
+ * desired layout.
8101
+ *
8102
+ * @param {Array} values - an array of values that correspond to the
8103
+ * default order for properties. As with {@link Layout#decode|decode}
8104
+ * layout elements that have no property name are skipped when
8105
+ * iterating over the array values. Only the top-level properties are
8106
+ * assigned; arguments are not assigned to properties of contained
8107
+ * layouts. Any unused values are ignored.
8108
+ *
8109
+ * @return {(Object|undefined)}
8110
+ */
8111
+ fromArray(values) {
8112
+ return undefined;
8113
+ }
8114
+ }
8115
+ Layout$1.Layout = Layout;
8116
+ /* Provide text that carries a name (such as for a function that will
8117
+ * be throwing an error) annotated with the property of a given layout
8118
+ * (such as one for which the value was unacceptable).
8119
+ *
8120
+ * @ignore */
8121
+ function nameWithProperty(name, lo) {
8122
+ if (lo.property) {
8123
+ return name + '[' + lo.property + ']';
8124
+ }
8125
+ return name;
8126
+ }
8127
+ Layout$1.nameWithProperty = nameWithProperty;
8128
+ /**
8129
+ * Augment a class so that instances can be encoded/decoded using a
8130
+ * given layout.
8131
+ *
8132
+ * Calling this function couples `Class` with `layout` in several ways:
8133
+ *
8134
+ * * `Class.layout_` becomes a static member property equal to `layout`;
8135
+ * * `layout.boundConstructor_` becomes a static member property equal
8136
+ * to `Class`;
8137
+ * * The {@link Layout#makeDestinationObject|makeDestinationObject()}
8138
+ * property of `layout` is set to a function that returns a `new
8139
+ * Class()`;
8140
+ * * `Class.decode(b, offset)` becomes a static member function that
8141
+ * delegates to {@link Layout#decode|layout.decode}. The
8142
+ * synthesized function may be captured and extended.
8143
+ * * `Class.prototype.encode(b, offset)` provides an instance member
8144
+ * function that delegates to {@link Layout#encode|layout.encode}
8145
+ * with `src` set to `this`. The synthesized function may be
8146
+ * captured and extended, but when the extension is invoked `this`
8147
+ * must be explicitly bound to the instance.
8148
+ *
8149
+ * @param {class} Class - a JavaScript class with a nullary
8150
+ * constructor.
8151
+ *
8152
+ * @param {Layout} layout - the {@link Layout} instance used to encode
8153
+ * instances of `Class`.
8154
+ */
8155
+ // `Class` must be a constructor Function, but the assignment of a `layout_` property to it makes it difficult to type
8156
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
8157
+ function bindConstructorLayout(Class, layout) {
8158
+ if ('function' !== typeof Class) {
8159
+ throw new TypeError('Class must be constructor');
8160
+ }
8161
+ if (Object.prototype.hasOwnProperty.call(Class, 'layout_')) {
8162
+ throw new Error('Class is already bound to a layout');
8163
+ }
8164
+ if (!(layout && (layout instanceof Layout))) {
8165
+ throw new TypeError('layout must be a Layout');
8166
+ }
8167
+ if (Object.prototype.hasOwnProperty.call(layout, 'boundConstructor_')) {
8168
+ throw new Error('layout is already bound to a constructor');
8169
+ }
8170
+ Class.layout_ = layout;
8171
+ layout.boundConstructor_ = Class;
8172
+ layout.makeDestinationObject = (() => new Class());
8173
+ Object.defineProperty(Class.prototype, 'encode', {
8174
+ value(b, offset) {
8175
+ return layout.encode(this, b, offset);
8176
+ },
8177
+ writable: true,
8178
+ });
8179
+ Object.defineProperty(Class, 'decode', {
8180
+ value(b, offset) {
8181
+ return layout.decode(b, offset);
8182
+ },
8183
+ writable: true,
8184
+ });
8185
+ }
8186
+ Layout$1.bindConstructorLayout = bindConstructorLayout;
8187
+ /**
8188
+ * An object that behaves like a layout but does not consume space
8189
+ * within its containing layout.
8190
+ *
8191
+ * This is primarily used to obtain metadata about a member, such as a
8192
+ * {@link OffsetLayout} that can provide data about a {@link
8193
+ * Layout#getSpan|value-specific span}.
8194
+ *
8195
+ * **NOTE** This is an abstract base class; you can create instances
8196
+ * if it amuses you, but they won't support {@link
8197
+ * ExternalLayout#isCount|isCount} or other {@link Layout} functions.
8198
+ *
8199
+ * @param {Number} span - initializer for {@link Layout#span|span}.
8200
+ * The parameter can range from 1 through 6.
8201
+ *
8202
+ * @param {string} [property] - initializer for {@link
8203
+ * Layout#property|property}.
8204
+ *
8205
+ * @abstract
8206
+ * @augments {Layout}
8207
+ */
8208
+ class ExternalLayout extends Layout {
8209
+ /**
8210
+ * Return `true` iff the external layout decodes to an unsigned
8211
+ * integer layout.
8212
+ *
8213
+ * In that case it can be used as the source of {@link
8214
+ * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},
8215
+ * or as {@link UnionLayoutDiscriminator#layout|external union
8216
+ * discriminators}.
8217
+ *
8218
+ * @abstract
8219
+ */
8220
+ isCount() {
8221
+ throw new Error('ExternalLayout is abstract');
8222
+ }
8223
+ }
8224
+ Layout$1.ExternalLayout = ExternalLayout;
8225
+ /**
8226
+ * An {@link ExternalLayout} that determines its {@link
8227
+ * Layout#decode|value} based on offset into and length of the buffer
8228
+ * on which it is invoked.
8229
+ *
8230
+ * *Factory*: {@link module:Layout.greedy|greedy}
8231
+ *
8232
+ * @param {Number} [elementSpan] - initializer for {@link
8233
+ * GreedyCount#elementSpan|elementSpan}.
8234
+ *
8235
+ * @param {string} [property] - initializer for {@link
8236
+ * Layout#property|property}.
8237
+ *
8238
+ * @augments {ExternalLayout}
8239
+ */
8240
+ class GreedyCount extends ExternalLayout {
8241
+ constructor(elementSpan = 1, property) {
8242
+ if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {
8243
+ throw new TypeError('elementSpan must be a (positive) integer');
8244
+ }
8245
+ super(-1, property);
8246
+ /** The layout for individual elements of the sequence. The value
8247
+ * must be a positive integer. If not provided, the value will be
8248
+ * 1. */
8249
+ this.elementSpan = elementSpan;
8250
+ }
8251
+ /** @override */
8252
+ isCount() {
8253
+ return true;
8254
+ }
8255
+ /** @override */
8256
+ decode(b, offset = 0) {
8257
+ checkUint8Array(b);
8258
+ const rem = b.length - offset;
8259
+ return Math.floor(rem / this.elementSpan);
8260
+ }
8261
+ /** @override */
8262
+ encode(src, b, offset) {
8263
+ return 0;
8264
+ }
8265
+ }
8266
+ Layout$1.GreedyCount = GreedyCount;
8267
+ /**
8268
+ * An {@link ExternalLayout} that supports accessing a {@link Layout}
8269
+ * at a fixed offset from the start of another Layout. The offset may
8270
+ * be before, within, or after the base layout.
8271
+ *
8272
+ * *Factory*: {@link module:Layout.offset|offset}
8273
+ *
8274
+ * @param {Layout} layout - initializer for {@link
8275
+ * OffsetLayout#layout|layout}, modulo `property`.
8276
+ *
8277
+ * @param {Number} [offset] - Initializes {@link
8278
+ * OffsetLayout#offset|offset}. Defaults to zero.
8279
+ *
8280
+ * @param {string} [property] - Optional new property name for a
8281
+ * {@link Layout#replicate| replica} of `layout` to be used as {@link
8282
+ * OffsetLayout#layout|layout}. If not provided the `layout` is used
8283
+ * unchanged.
8284
+ *
8285
+ * @augments {Layout}
8286
+ */
8287
+ class OffsetLayout extends ExternalLayout {
8288
+ constructor(layout, offset = 0, property) {
8289
+ if (!(layout instanceof Layout)) {
8290
+ throw new TypeError('layout must be a Layout');
8291
+ }
8292
+ if (!Number.isInteger(offset)) {
8293
+ throw new TypeError('offset must be integer or undefined');
8294
+ }
8295
+ super(layout.span, property || layout.property);
8296
+ /** The subordinated layout. */
8297
+ this.layout = layout;
8298
+ /** The location of {@link OffsetLayout#layout} relative to the
8299
+ * start of another layout.
8300
+ *
8301
+ * The value may be positive or negative, but an error will thrown
8302
+ * if at the point of use it goes outside the span of the Uint8Array
8303
+ * being accessed. */
8304
+ this.offset = offset;
8305
+ }
8306
+ /** @override */
8307
+ isCount() {
8308
+ return ((this.layout instanceof UInt)
8309
+ || (this.layout instanceof UIntBE));
8310
+ }
8311
+ /** @override */
8312
+ decode(b, offset = 0) {
8313
+ return this.layout.decode(b, offset + this.offset);
8314
+ }
8315
+ /** @override */
8316
+ encode(src, b, offset = 0) {
8317
+ return this.layout.encode(src, b, offset + this.offset);
8318
+ }
8319
+ }
8320
+ Layout$1.OffsetLayout = OffsetLayout;
8321
+ /**
8322
+ * Represent an unsigned integer in little-endian format.
8323
+ *
8324
+ * *Factory*: {@link module:Layout.u8|u8}, {@link
8325
+ * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link
8326
+ * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link
8327
+ * module:Layout.u48|u48}
8328
+ *
8329
+ * @param {Number} span - initializer for {@link Layout#span|span}.
8330
+ * The parameter can range from 1 through 6.
8331
+ *
8332
+ * @param {string} [property] - initializer for {@link
8333
+ * Layout#property|property}.
8334
+ *
8335
+ * @augments {Layout}
8336
+ */
8337
+ class UInt extends Layout {
8338
+ constructor(span, property) {
8339
+ super(span, property);
8340
+ if (6 < this.span) {
8341
+ throw new RangeError('span must not exceed 6 bytes');
8342
+ }
8343
+ }
8344
+ /** @override */
8345
+ decode(b, offset = 0) {
8346
+ return uint8ArrayToBuffer(b).readUIntLE(offset, this.span);
8347
+ }
8348
+ /** @override */
8349
+ encode(src, b, offset = 0) {
8350
+ uint8ArrayToBuffer(b).writeUIntLE(src, offset, this.span);
8351
+ return this.span;
8352
+ }
8353
+ }
8354
+ Layout$1.UInt = UInt;
8355
+ /**
8356
+ * Represent an unsigned integer in big-endian format.
8357
+ *
8358
+ * *Factory*: {@link module:Layout.u8be|u8be}, {@link
8359
+ * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},
8360
+ * {@link module:Layout.u32be|u32be}, {@link
8361
+ * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}
8362
+ *
8363
+ * @param {Number} span - initializer for {@link Layout#span|span}.
8364
+ * The parameter can range from 1 through 6.
8365
+ *
8366
+ * @param {string} [property] - initializer for {@link
8367
+ * Layout#property|property}.
8368
+ *
8369
+ * @augments {Layout}
8370
+ */
8371
+ class UIntBE extends Layout {
8372
+ constructor(span, property) {
8373
+ super(span, property);
8374
+ if (6 < this.span) {
8375
+ throw new RangeError('span must not exceed 6 bytes');
8376
+ }
8377
+ }
8378
+ /** @override */
8379
+ decode(b, offset = 0) {
8380
+ return uint8ArrayToBuffer(b).readUIntBE(offset, this.span);
8381
+ }
8382
+ /** @override */
8383
+ encode(src, b, offset = 0) {
8384
+ uint8ArrayToBuffer(b).writeUIntBE(src, offset, this.span);
8385
+ return this.span;
8386
+ }
8387
+ }
8388
+ Layout$1.UIntBE = UIntBE;
8389
+ /**
8390
+ * Represent a signed integer in little-endian format.
8391
+ *
8392
+ * *Factory*: {@link module:Layout.s8|s8}, {@link
8393
+ * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link
8394
+ * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link
8395
+ * module:Layout.s48|s48}
8396
+ *
8397
+ * @param {Number} span - initializer for {@link Layout#span|span}.
8398
+ * The parameter can range from 1 through 6.
8399
+ *
8400
+ * @param {string} [property] - initializer for {@link
8401
+ * Layout#property|property}.
8402
+ *
8403
+ * @augments {Layout}
8404
+ */
8405
+ class Int extends Layout {
8406
+ constructor(span, property) {
8407
+ super(span, property);
8408
+ if (6 < this.span) {
8409
+ throw new RangeError('span must not exceed 6 bytes');
8410
+ }
8411
+ }
8412
+ /** @override */
8413
+ decode(b, offset = 0) {
8414
+ return uint8ArrayToBuffer(b).readIntLE(offset, this.span);
8415
+ }
8416
+ /** @override */
8417
+ encode(src, b, offset = 0) {
8418
+ uint8ArrayToBuffer(b).writeIntLE(src, offset, this.span);
8419
+ return this.span;
8420
+ }
8421
+ }
8422
+ Layout$1.Int = Int;
8423
+ /**
8424
+ * Represent a signed integer in big-endian format.
8425
+ *
8426
+ * *Factory*: {@link module:Layout.s8be|s8be}, {@link
8427
+ * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},
8428
+ * {@link module:Layout.s32be|s32be}, {@link
8429
+ * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}
8430
+ *
8431
+ * @param {Number} span - initializer for {@link Layout#span|span}.
8432
+ * The parameter can range from 1 through 6.
8433
+ *
8434
+ * @param {string} [property] - initializer for {@link
8435
+ * Layout#property|property}.
8436
+ *
8437
+ * @augments {Layout}
8438
+ */
8439
+ class IntBE extends Layout {
8440
+ constructor(span, property) {
8441
+ super(span, property);
8442
+ if (6 < this.span) {
8443
+ throw new RangeError('span must not exceed 6 bytes');
8444
+ }
8445
+ }
8446
+ /** @override */
8447
+ decode(b, offset = 0) {
8448
+ return uint8ArrayToBuffer(b).readIntBE(offset, this.span);
8449
+ }
8450
+ /** @override */
8451
+ encode(src, b, offset = 0) {
8452
+ uint8ArrayToBuffer(b).writeIntBE(src, offset, this.span);
8453
+ return this.span;
8454
+ }
8455
+ }
8456
+ Layout$1.IntBE = IntBE;
8457
+ const V2E32 = Math.pow(2, 32);
8458
+ /* True modulus high and low 32-bit words, where low word is always
8459
+ * non-negative. */
8460
+ function divmodInt64(src) {
8461
+ const hi32 = Math.floor(src / V2E32);
8462
+ const lo32 = src - (hi32 * V2E32);
8463
+ return { hi32, lo32 };
8464
+ }
8465
+ /* Reconstruct Number from quotient and non-negative remainder */
8466
+ function roundedInt64(hi32, lo32) {
8467
+ return hi32 * V2E32 + lo32;
8468
+ }
8469
+ /**
8470
+ * Represent an unsigned 64-bit integer in little-endian format when
8471
+ * encoded and as a near integral JavaScript Number when decoded.
8472
+ *
8473
+ * *Factory*: {@link module:Layout.nu64|nu64}
8474
+ *
8475
+ * **NOTE** Values with magnitude greater than 2^52 may not decode to
8476
+ * the exact value of the encoded representation.
8477
+ *
8478
+ * @augments {Layout}
8479
+ */
8480
+ class NearUInt64 extends Layout {
8481
+ constructor(property) {
8482
+ super(8, property);
8483
+ }
8484
+ /** @override */
8485
+ decode(b, offset = 0) {
8486
+ const buffer = uint8ArrayToBuffer(b);
8487
+ const lo32 = buffer.readUInt32LE(offset);
8488
+ const hi32 = buffer.readUInt32LE(offset + 4);
8489
+ return roundedInt64(hi32, lo32);
8490
+ }
8491
+ /** @override */
8492
+ encode(src, b, offset = 0) {
8493
+ const split = divmodInt64(src);
8494
+ const buffer = uint8ArrayToBuffer(b);
8495
+ buffer.writeUInt32LE(split.lo32, offset);
8496
+ buffer.writeUInt32LE(split.hi32, offset + 4);
8497
+ return 8;
8498
+ }
8499
+ }
8500
+ Layout$1.NearUInt64 = NearUInt64;
8501
+ /**
8502
+ * Represent an unsigned 64-bit integer in big-endian format when
8503
+ * encoded and as a near integral JavaScript Number when decoded.
8504
+ *
8505
+ * *Factory*: {@link module:Layout.nu64be|nu64be}
8506
+ *
8507
+ * **NOTE** Values with magnitude greater than 2^52 may not decode to
8508
+ * the exact value of the encoded representation.
8509
+ *
8510
+ * @augments {Layout}
8511
+ */
8512
+ class NearUInt64BE extends Layout {
8513
+ constructor(property) {
8514
+ super(8, property);
8515
+ }
8516
+ /** @override */
8517
+ decode(b, offset = 0) {
8518
+ const buffer = uint8ArrayToBuffer(b);
8519
+ const hi32 = buffer.readUInt32BE(offset);
8520
+ const lo32 = buffer.readUInt32BE(offset + 4);
8521
+ return roundedInt64(hi32, lo32);
8522
+ }
8523
+ /** @override */
8524
+ encode(src, b, offset = 0) {
8525
+ const split = divmodInt64(src);
8526
+ const buffer = uint8ArrayToBuffer(b);
8527
+ buffer.writeUInt32BE(split.hi32, offset);
8528
+ buffer.writeUInt32BE(split.lo32, offset + 4);
8529
+ return 8;
8530
+ }
8531
+ }
8532
+ Layout$1.NearUInt64BE = NearUInt64BE;
8533
+ /**
8534
+ * Represent a signed 64-bit integer in little-endian format when
8535
+ * encoded and as a near integral JavaScript Number when decoded.
8536
+ *
8537
+ * *Factory*: {@link module:Layout.ns64|ns64}
8538
+ *
8539
+ * **NOTE** Values with magnitude greater than 2^52 may not decode to
8540
+ * the exact value of the encoded representation.
8541
+ *
8542
+ * @augments {Layout}
8543
+ */
8544
+ class NearInt64 extends Layout {
8545
+ constructor(property) {
8546
+ super(8, property);
8547
+ }
8548
+ /** @override */
8549
+ decode(b, offset = 0) {
8550
+ const buffer = uint8ArrayToBuffer(b);
8551
+ const lo32 = buffer.readUInt32LE(offset);
8552
+ const hi32 = buffer.readInt32LE(offset + 4);
8553
+ return roundedInt64(hi32, lo32);
8554
+ }
8555
+ /** @override */
8556
+ encode(src, b, offset = 0) {
8557
+ const split = divmodInt64(src);
8558
+ const buffer = uint8ArrayToBuffer(b);
8559
+ buffer.writeUInt32LE(split.lo32, offset);
8560
+ buffer.writeInt32LE(split.hi32, offset + 4);
8561
+ return 8;
8562
+ }
8563
+ }
8564
+ Layout$1.NearInt64 = NearInt64;
8565
+ /**
8566
+ * Represent a signed 64-bit integer in big-endian format when
8567
+ * encoded and as a near integral JavaScript Number when decoded.
8568
+ *
8569
+ * *Factory*: {@link module:Layout.ns64be|ns64be}
8570
+ *
8571
+ * **NOTE** Values with magnitude greater than 2^52 may not decode to
8572
+ * the exact value of the encoded representation.
8573
+ *
8574
+ * @augments {Layout}
8575
+ */
8576
+ class NearInt64BE extends Layout {
8577
+ constructor(property) {
8578
+ super(8, property);
8579
+ }
8580
+ /** @override */
8581
+ decode(b, offset = 0) {
8582
+ const buffer = uint8ArrayToBuffer(b);
8583
+ const hi32 = buffer.readInt32BE(offset);
8584
+ const lo32 = buffer.readUInt32BE(offset + 4);
8585
+ return roundedInt64(hi32, lo32);
8586
+ }
8587
+ /** @override */
8588
+ encode(src, b, offset = 0) {
8589
+ const split = divmodInt64(src);
8590
+ const buffer = uint8ArrayToBuffer(b);
8591
+ buffer.writeInt32BE(split.hi32, offset);
8592
+ buffer.writeUInt32BE(split.lo32, offset + 4);
8593
+ return 8;
8594
+ }
8595
+ }
8596
+ Layout$1.NearInt64BE = NearInt64BE;
8597
+ /**
8598
+ * Represent a 32-bit floating point number in little-endian format.
8599
+ *
8600
+ * *Factory*: {@link module:Layout.f32|f32}
8601
+ *
8602
+ * @param {string} [property] - initializer for {@link
8603
+ * Layout#property|property}.
8604
+ *
8605
+ * @augments {Layout}
8606
+ */
8607
+ class Float extends Layout {
8608
+ constructor(property) {
8609
+ super(4, property);
8610
+ }
8611
+ /** @override */
8612
+ decode(b, offset = 0) {
8613
+ return uint8ArrayToBuffer(b).readFloatLE(offset);
8614
+ }
8615
+ /** @override */
8616
+ encode(src, b, offset = 0) {
8617
+ uint8ArrayToBuffer(b).writeFloatLE(src, offset);
8618
+ return 4;
8619
+ }
8620
+ }
8621
+ Layout$1.Float = Float;
8622
+ /**
8623
+ * Represent a 32-bit floating point number in big-endian format.
8624
+ *
8625
+ * *Factory*: {@link module:Layout.f32be|f32be}
8626
+ *
8627
+ * @param {string} [property] - initializer for {@link
8628
+ * Layout#property|property}.
8629
+ *
8630
+ * @augments {Layout}
8631
+ */
8632
+ class FloatBE extends Layout {
8633
+ constructor(property) {
8634
+ super(4, property);
8635
+ }
8636
+ /** @override */
8637
+ decode(b, offset = 0) {
8638
+ return uint8ArrayToBuffer(b).readFloatBE(offset);
8639
+ }
8640
+ /** @override */
8641
+ encode(src, b, offset = 0) {
8642
+ uint8ArrayToBuffer(b).writeFloatBE(src, offset);
8643
+ return 4;
8644
+ }
8645
+ }
8646
+ Layout$1.FloatBE = FloatBE;
8647
+ /**
8648
+ * Represent a 64-bit floating point number in little-endian format.
8649
+ *
8650
+ * *Factory*: {@link module:Layout.f64|f64}
8651
+ *
8652
+ * @param {string} [property] - initializer for {@link
8653
+ * Layout#property|property}.
8654
+ *
8655
+ * @augments {Layout}
8656
+ */
8657
+ class Double extends Layout {
8658
+ constructor(property) {
8659
+ super(8, property);
8660
+ }
8661
+ /** @override */
8662
+ decode(b, offset = 0) {
8663
+ return uint8ArrayToBuffer(b).readDoubleLE(offset);
8664
+ }
8665
+ /** @override */
8666
+ encode(src, b, offset = 0) {
8667
+ uint8ArrayToBuffer(b).writeDoubleLE(src, offset);
8668
+ return 8;
8669
+ }
8670
+ }
8671
+ Layout$1.Double = Double;
8672
+ /**
8673
+ * Represent a 64-bit floating point number in big-endian format.
8674
+ *
8675
+ * *Factory*: {@link module:Layout.f64be|f64be}
8676
+ *
8677
+ * @param {string} [property] - initializer for {@link
8678
+ * Layout#property|property}.
8679
+ *
8680
+ * @augments {Layout}
8681
+ */
8682
+ class DoubleBE extends Layout {
8683
+ constructor(property) {
8684
+ super(8, property);
8685
+ }
8686
+ /** @override */
8687
+ decode(b, offset = 0) {
8688
+ return uint8ArrayToBuffer(b).readDoubleBE(offset);
8689
+ }
8690
+ /** @override */
8691
+ encode(src, b, offset = 0) {
8692
+ uint8ArrayToBuffer(b).writeDoubleBE(src, offset);
8693
+ return 8;
8694
+ }
8695
+ }
8696
+ Layout$1.DoubleBE = DoubleBE;
8697
+ /**
8698
+ * Represent a contiguous sequence of a specific layout as an Array.
8699
+ *
8700
+ * *Factory*: {@link module:Layout.seq|seq}
8701
+ *
8702
+ * @param {Layout} elementLayout - initializer for {@link
8703
+ * Sequence#elementLayout|elementLayout}.
8704
+ *
8705
+ * @param {(Number|ExternalLayout)} count - initializer for {@link
8706
+ * Sequence#count|count}. The parameter must be either a positive
8707
+ * integer or an instance of {@link ExternalLayout}.
8708
+ *
8709
+ * @param {string} [property] - initializer for {@link
8710
+ * Layout#property|property}.
8711
+ *
8712
+ * @augments {Layout}
8713
+ */
8714
+ class Sequence extends Layout {
8715
+ constructor(elementLayout, count, property) {
8716
+ if (!(elementLayout instanceof Layout)) {
8717
+ throw new TypeError('elementLayout must be a Layout');
8718
+ }
8719
+ if (!(((count instanceof ExternalLayout) && count.isCount())
8720
+ || (Number.isInteger(count) && (0 <= count)))) {
8721
+ throw new TypeError('count must be non-negative integer '
8722
+ + 'or an unsigned integer ExternalLayout');
8723
+ }
8724
+ let span = -1;
8725
+ if ((!(count instanceof ExternalLayout))
8726
+ && (0 < elementLayout.span)) {
8727
+ span = count * elementLayout.span;
8728
+ }
8729
+ super(span, property);
8730
+ /** The layout for individual elements of the sequence. */
8731
+ this.elementLayout = elementLayout;
8732
+ /** The number of elements in the sequence.
8733
+ *
8734
+ * This will be either a non-negative integer or an instance of
8735
+ * {@link ExternalLayout} for which {@link
8736
+ * ExternalLayout#isCount|isCount()} is `true`. */
8737
+ this.count = count;
8738
+ }
8739
+ /** @override */
8740
+ getSpan(b, offset = 0) {
8741
+ if (0 <= this.span) {
8742
+ return this.span;
8743
+ }
8744
+ let span = 0;
8745
+ let count = this.count;
8746
+ if (count instanceof ExternalLayout) {
8747
+ count = count.decode(b, offset);
8748
+ }
8749
+ if (0 < this.elementLayout.span) {
8750
+ span = count * this.elementLayout.span;
8751
+ }
8752
+ else {
8753
+ let idx = 0;
8754
+ while (idx < count) {
8755
+ span += this.elementLayout.getSpan(b, offset + span);
8756
+ ++idx;
8757
+ }
8758
+ }
8759
+ return span;
8760
+ }
8761
+ /** @override */
8762
+ decode(b, offset = 0) {
8763
+ const rv = [];
8764
+ let i = 0;
8765
+ let count = this.count;
8766
+ if (count instanceof ExternalLayout) {
8767
+ count = count.decode(b, offset);
8768
+ }
8769
+ while (i < count) {
8770
+ rv.push(this.elementLayout.decode(b, offset));
8771
+ offset += this.elementLayout.getSpan(b, offset);
8772
+ i += 1;
8773
+ }
8774
+ return rv;
8775
+ }
8776
+ /** Implement {@link Layout#encode|encode} for {@link Sequence}.
8777
+ *
8778
+ * **NOTE** If `src` is shorter than {@link Sequence#count|count} then
8779
+ * the unused space in the buffer is left unchanged. If `src` is
8780
+ * longer than {@link Sequence#count|count} the unneeded elements are
8781
+ * ignored.
8782
+ *
8783
+ * **NOTE** If {@link Layout#count|count} is an instance of {@link
8784
+ * ExternalLayout} then the length of `src` will be encoded as the
8785
+ * count after `src` is encoded. */
8786
+ encode(src, b, offset = 0) {
8787
+ const elo = this.elementLayout;
8788
+ const span = src.reduce((span, v) => {
8789
+ return span + elo.encode(v, b, offset + span);
8790
+ }, 0);
8791
+ if (this.count instanceof ExternalLayout) {
8792
+ this.count.encode(src.length, b, offset);
8793
+ }
8794
+ return span;
8795
+ }
8796
+ }
8797
+ Layout$1.Sequence = Sequence;
8798
+ /**
8799
+ * Represent a contiguous sequence of arbitrary layout elements as an
8800
+ * Object.
8801
+ *
8802
+ * *Factory*: {@link module:Layout.struct|struct}
8803
+ *
8804
+ * **NOTE** The {@link Layout#span|span} of the structure is variable
8805
+ * if any layout in {@link Structure#fields|fields} has a variable
8806
+ * span. When {@link Layout#encode|encoding} we must have a value for
8807
+ * all variable-length fields, or we wouldn't be able to figure out
8808
+ * how much space to use for storage. We can only identify the value
8809
+ * for a field when it has a {@link Layout#property|property}. As
8810
+ * such, although a structure may contain both unnamed fields and
8811
+ * variable-length fields, it cannot contain an unnamed
8812
+ * variable-length field.
8813
+ *
8814
+ * @param {Layout[]} fields - initializer for {@link
8815
+ * Structure#fields|fields}. An error is raised if this contains a
8816
+ * variable-length field for which a {@link Layout#property|property}
8817
+ * is not defined.
8818
+ *
8819
+ * @param {string} [property] - initializer for {@link
8820
+ * Layout#property|property}.
8821
+ *
8822
+ * @param {Boolean} [decodePrefixes] - initializer for {@link
8823
+ * Structure#decodePrefixes|property}.
8824
+ *
8825
+ * @throws {Error} - if `fields` contains an unnamed variable-length
8826
+ * layout.
8827
+ *
8828
+ * @augments {Layout}
8829
+ */
8830
+ class Structure extends Layout {
8831
+ constructor(fields, property, decodePrefixes) {
8832
+ if (!(Array.isArray(fields)
8833
+ && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {
8834
+ throw new TypeError('fields must be array of Layout instances');
8835
+ }
8836
+ if (('boolean' === typeof property)
8837
+ && (undefined === decodePrefixes)) {
8838
+ decodePrefixes = property;
8839
+ property = undefined;
8840
+ }
8841
+ /* Verify absence of unnamed variable-length fields. */
8842
+ for (const fd of fields) {
8843
+ if ((0 > fd.span)
8844
+ && (undefined === fd.property)) {
8845
+ throw new Error('fields cannot contain unnamed variable-length layout');
8846
+ }
8847
+ }
8848
+ let span = -1;
8849
+ try {
8850
+ span = fields.reduce((span, fd) => span + fd.getSpan(), 0);
8851
+ }
8852
+ catch (e) {
8853
+ // ignore error
8854
+ }
8855
+ super(span, property);
8856
+ /** The sequence of {@link Layout} values that comprise the
8857
+ * structure.
8858
+ *
8859
+ * The individual elements need not be the same type, and may be
8860
+ * either scalar or aggregate layouts. If a member layout leaves
8861
+ * its {@link Layout#property|property} undefined the
8862
+ * corresponding region of the buffer associated with the element
8863
+ * will not be mutated.
8864
+ *
8865
+ * @type {Layout[]} */
8866
+ this.fields = fields;
8867
+ /** Control behavior of {@link Layout#decode|decode()} given short
8868
+ * buffers.
8869
+ *
8870
+ * In some situations a structure many be extended with additional
8871
+ * fields over time, with older installations providing only a
8872
+ * prefix of the full structure. If this property is `true`
8873
+ * decoding will accept those buffers and leave subsequent fields
8874
+ * undefined, as long as the buffer ends at a field boundary.
8875
+ * Defaults to `false`. */
8876
+ this.decodePrefixes = !!decodePrefixes;
8877
+ }
8878
+ /** @override */
8879
+ getSpan(b, offset = 0) {
8880
+ if (0 <= this.span) {
8881
+ return this.span;
8882
+ }
8883
+ let span = 0;
8884
+ try {
8885
+ span = this.fields.reduce((span, fd) => {
8886
+ const fsp = fd.getSpan(b, offset);
8887
+ offset += fsp;
8888
+ return span + fsp;
8889
+ }, 0);
8890
+ }
8891
+ catch (e) {
8892
+ throw new RangeError('indeterminate span');
8893
+ }
8894
+ return span;
8895
+ }
8896
+ /** @override */
8897
+ decode(b, offset = 0) {
8898
+ checkUint8Array(b);
8899
+ const dest = this.makeDestinationObject();
8900
+ for (const fd of this.fields) {
8901
+ if (undefined !== fd.property) {
8902
+ dest[fd.property] = fd.decode(b, offset);
8903
+ }
8904
+ offset += fd.getSpan(b, offset);
8905
+ if (this.decodePrefixes
8906
+ && (b.length === offset)) {
8907
+ break;
8908
+ }
8909
+ }
8910
+ return dest;
8911
+ }
8912
+ /** Implement {@link Layout#encode|encode} for {@link Structure}.
8913
+ *
8914
+ * If `src` is missing a property for a member with a defined {@link
8915
+ * Layout#property|property} the corresponding region of the buffer is
8916
+ * left unmodified. */
8917
+ encode(src, b, offset = 0) {
8918
+ const firstOffset = offset;
8919
+ let lastOffset = 0;
8920
+ let lastWrote = 0;
8921
+ for (const fd of this.fields) {
8922
+ let span = fd.span;
8923
+ lastWrote = (0 < span) ? span : 0;
8924
+ if (undefined !== fd.property) {
8925
+ const fv = src[fd.property];
8926
+ if (undefined !== fv) {
8927
+ lastWrote = fd.encode(fv, b, offset);
8928
+ if (0 > span) {
8929
+ /* Read the as-encoded span, which is not necessarily the
8930
+ * same as what we wrote. */
8931
+ span = fd.getSpan(b, offset);
8932
+ }
8933
+ }
8934
+ }
8935
+ lastOffset = offset;
8936
+ offset += span;
8937
+ }
8938
+ /* Use (lastOffset + lastWrote) instead of offset because the last
8939
+ * item may have had a dynamic length and we don't want to include
8940
+ * the padding between it and the end of the space reserved for
8941
+ * it. */
8942
+ return (lastOffset + lastWrote) - firstOffset;
8943
+ }
8944
+ /** @override */
8945
+ fromArray(values) {
8946
+ const dest = this.makeDestinationObject();
8947
+ for (const fd of this.fields) {
8948
+ if ((undefined !== fd.property)
8949
+ && (0 < values.length)) {
8950
+ dest[fd.property] = values.shift();
8951
+ }
8952
+ }
8953
+ return dest;
8954
+ }
8955
+ /**
8956
+ * Get access to the layout of a given property.
8957
+ *
8958
+ * @param {String} property - the structure member of interest.
8959
+ *
8960
+ * @return {Layout} - the layout associated with `property`, or
8961
+ * undefined if there is no such property.
8962
+ */
8963
+ layoutFor(property) {
8964
+ if ('string' !== typeof property) {
8965
+ throw new TypeError('property must be string');
8966
+ }
8967
+ for (const fd of this.fields) {
8968
+ if (fd.property === property) {
8969
+ return fd;
8970
+ }
8971
+ }
8972
+ return undefined;
8973
+ }
8974
+ /**
8975
+ * Get the offset of a structure member.
8976
+ *
8977
+ * @param {String} property - the structure member of interest.
8978
+ *
8979
+ * @return {Number} - the offset in bytes to the start of `property`
8980
+ * within the structure, or undefined if `property` is not a field
8981
+ * within the structure. If the property is a member but follows a
8982
+ * variable-length structure member a negative number will be
8983
+ * returned.
8984
+ */
8985
+ offsetOf(property) {
8986
+ if ('string' !== typeof property) {
8987
+ throw new TypeError('property must be string');
8988
+ }
8989
+ let offset = 0;
8990
+ for (const fd of this.fields) {
8991
+ if (fd.property === property) {
8992
+ return offset;
8993
+ }
8994
+ if (0 > fd.span) {
8995
+ offset = -1;
8996
+ }
8997
+ else if (0 <= offset) {
8998
+ offset += fd.span;
8999
+ }
9000
+ }
9001
+ return undefined;
9002
+ }
9003
+ }
9004
+ Layout$1.Structure = Structure;
9005
+ /**
9006
+ * An object that can provide a {@link
9007
+ * Union#discriminator|discriminator} API for {@link Union}.
9008
+ *
9009
+ * **NOTE** This is an abstract base class; you can create instances
9010
+ * if it amuses you, but they won't support the {@link
9011
+ * UnionDiscriminator#encode|encode} or {@link
9012
+ * UnionDiscriminator#decode|decode} functions.
9013
+ *
9014
+ * @param {string} [property] - Default for {@link
9015
+ * UnionDiscriminator#property|property}.
9016
+ *
9017
+ * @abstract
9018
+ */
9019
+ class UnionDiscriminator {
9020
+ constructor(property) {
9021
+ /** The {@link Layout#property|property} to be used when the
9022
+ * discriminator is referenced in isolation (generally when {@link
9023
+ * Union#decode|Union decode} cannot delegate to a specific
9024
+ * variant). */
9025
+ this.property = property;
9026
+ }
9027
+ /** Analog to {@link Layout#decode|Layout decode} for union discriminators.
9028
+ *
9029
+ * The implementation of this method need not reference the buffer if
9030
+ * variant information is available through other means. */
9031
+ decode(b, offset) {
9032
+ throw new Error('UnionDiscriminator is abstract');
9033
+ }
9034
+ /** Analog to {@link Layout#decode|Layout encode} for union discriminators.
9035
+ *
9036
+ * The implementation of this method need not store the value if
9037
+ * variant information is maintained through other means. */
9038
+ encode(src, b, offset) {
9039
+ throw new Error('UnionDiscriminator is abstract');
9040
+ }
9041
+ }
9042
+ Layout$1.UnionDiscriminator = UnionDiscriminator;
9043
+ /**
9044
+ * An object that can provide a {@link
9045
+ * UnionDiscriminator|discriminator API} for {@link Union} using an
9046
+ * unsigned integral {@link Layout} instance located either inside or
9047
+ * outside the union.
9048
+ *
9049
+ * @param {ExternalLayout} layout - initializes {@link
9050
+ * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link
9051
+ * ExternalLayout#isCount|isCount()}.
9052
+ *
9053
+ * @param {string} [property] - Default for {@link
9054
+ * UnionDiscriminator#property|property}, superseding the property
9055
+ * from `layout`, but defaulting to `variant` if neither `property`
9056
+ * nor layout provide a property name.
9057
+ *
9058
+ * @augments {UnionDiscriminator}
9059
+ */
9060
+ class UnionLayoutDiscriminator extends UnionDiscriminator {
9061
+ constructor(layout, property) {
9062
+ if (!((layout instanceof ExternalLayout)
9063
+ && layout.isCount())) {
9064
+ throw new TypeError('layout must be an unsigned integer ExternalLayout');
9065
+ }
9066
+ super(property || layout.property || 'variant');
9067
+ /** The {@link ExternalLayout} used to access the discriminator
9068
+ * value. */
9069
+ this.layout = layout;
9070
+ }
9071
+ /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */
9072
+ decode(b, offset) {
9073
+ return this.layout.decode(b, offset);
9074
+ }
9075
+ /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */
9076
+ encode(src, b, offset) {
9077
+ return this.layout.encode(src, b, offset);
9078
+ }
9079
+ }
9080
+ Layout$1.UnionLayoutDiscriminator = UnionLayoutDiscriminator;
9081
+ /**
9082
+ * Represent any number of span-compatible layouts.
9083
+ *
9084
+ * *Factory*: {@link module:Layout.union|union}
9085
+ *
9086
+ * If the union has a {@link Union#defaultLayout|default layout} that
9087
+ * layout must have a non-negative {@link Layout#span|span}. The span
9088
+ * of a fixed-span union includes its {@link
9089
+ * Union#discriminator|discriminator} if the variant is a {@link
9090
+ * Union#usesPrefixDiscriminator|prefix of the union}, plus the span
9091
+ * of its {@link Union#defaultLayout|default layout}.
9092
+ *
9093
+ * If the union does not have a default layout then the encoded span
9094
+ * of the union depends on the encoded span of its variant (which may
9095
+ * be fixed or variable).
9096
+ *
9097
+ * {@link VariantLayout#layout|Variant layout}s are added through
9098
+ * {@link Union#addVariant|addVariant}. If the union has a default
9099
+ * layout, the span of the {@link VariantLayout#layout|layout
9100
+ * contained by the variant} must not exceed the span of the {@link
9101
+ * Union#defaultLayout|default layout} (minus the span of a {@link
9102
+ * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The
9103
+ * span of the variant will equal the span of the union itself.
9104
+ *
9105
+ * The variant for a buffer can only be identified from the {@link
9106
+ * Union#discriminator|discriminator} {@link
9107
+ * UnionDiscriminator#property|property} (in the case of the {@link
9108
+ * Union#defaultLayout|default layout}), or by using {@link
9109
+ * Union#getVariant|getVariant} and examining the resulting {@link
9110
+ * VariantLayout} instance.
9111
+ *
9112
+ * A variant compatible with a JavaScript object can be identified
9113
+ * using {@link Union#getSourceVariant|getSourceVariant}.
9114
+ *
9115
+ * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to
9116
+ * identify the layout used to interpret the union contents. The
9117
+ * parameter must be an instance of {@link UnionDiscriminator}, an
9118
+ * {@link ExternalLayout} that satisfies {@link
9119
+ * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link
9120
+ * UIntBE}). When a non-external layout element is passed the layout
9121
+ * appears at the start of the union. In all cases the (synthesized)
9122
+ * {@link UnionDiscriminator} instance is recorded as {@link
9123
+ * Union#discriminator|discriminator}.
9124
+ *
9125
+ * @param {(Layout|null)} defaultLayout - initializer for {@link
9126
+ * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.
9127
+ * If `null` there is no default layout: the union has data-dependent
9128
+ * length and attempts to decode or encode unrecognized variants will
9129
+ * throw an exception. A {@link Layout} instance must have a
9130
+ * non-negative {@link Layout#span|span}, and if it lacks a {@link
9131
+ * Layout#property|property} the {@link
9132
+ * Union#defaultLayout|defaultLayout} will be a {@link
9133
+ * Layout#replicate|replica} with property `content`.
9134
+ *
9135
+ * @param {string} [property] - initializer for {@link
9136
+ * Layout#property|property}.
9137
+ *
9138
+ * @augments {Layout}
9139
+ */
9140
+ class Union extends Layout {
9141
+ constructor(discr, defaultLayout, property) {
9142
+ let discriminator;
9143
+ if ((discr instanceof UInt)
9144
+ || (discr instanceof UIntBE)) {
9145
+ discriminator = new UnionLayoutDiscriminator(new OffsetLayout(discr));
9146
+ }
9147
+ else if ((discr instanceof ExternalLayout)
9148
+ && discr.isCount()) {
9149
+ discriminator = new UnionLayoutDiscriminator(discr);
9150
+ }
9151
+ else if (!(discr instanceof UnionDiscriminator)) {
9152
+ throw new TypeError('discr must be a UnionDiscriminator '
9153
+ + 'or an unsigned integer layout');
9154
+ }
9155
+ else {
9156
+ discriminator = discr;
9157
+ }
9158
+ if (undefined === defaultLayout) {
9159
+ defaultLayout = null;
9160
+ }
9161
+ if (!((null === defaultLayout)
9162
+ || (defaultLayout instanceof Layout))) {
9163
+ throw new TypeError('defaultLayout must be null or a Layout');
9164
+ }
9165
+ if (null !== defaultLayout) {
9166
+ if (0 > defaultLayout.span) {
9167
+ throw new Error('defaultLayout must have constant span');
9168
+ }
9169
+ if (undefined === defaultLayout.property) {
9170
+ defaultLayout = defaultLayout.replicate('content');
9171
+ }
9172
+ }
9173
+ /* The union span can be estimated only if there's a default
9174
+ * layout. The union spans its default layout, plus any prefix
9175
+ * variant layout. By construction both layouts, if present, have
9176
+ * non-negative span. */
9177
+ let span = -1;
9178
+ if (defaultLayout) {
9179
+ span = defaultLayout.span;
9180
+ if ((0 <= span) && ((discr instanceof UInt)
9181
+ || (discr instanceof UIntBE))) {
9182
+ span += discriminator.layout.span;
9183
+ }
9184
+ }
9185
+ super(span, property);
9186
+ /** The interface for the discriminator value in isolation.
9187
+ *
9188
+ * This a {@link UnionDiscriminator} either passed to the
9189
+ * constructor or synthesized from the `discr` constructor
9190
+ * argument. {@link
9191
+ * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be
9192
+ * `true` iff the `discr` parameter was a non-offset {@link
9193
+ * Layout} instance. */
9194
+ this.discriminator = discriminator;
9195
+ /** `true` if the {@link Union#discriminator|discriminator} is the
9196
+ * first field in the union.
9197
+ *
9198
+ * If `false` the discriminator is obtained from somewhere
9199
+ * else. */
9200
+ this.usesPrefixDiscriminator = (discr instanceof UInt)
9201
+ || (discr instanceof UIntBE);
9202
+ /** The layout for non-discriminator content when the value of the
9203
+ * discriminator is not recognized.
9204
+ *
9205
+ * This is the value passed to the constructor. It is
9206
+ * structurally equivalent to the second component of {@link
9207
+ * Union#layout|layout} but may have a different property
9208
+ * name. */
9209
+ this.defaultLayout = defaultLayout;
9210
+ /** A registry of allowed variants.
9211
+ *
9212
+ * The keys are unsigned integers which should be compatible with
9213
+ * {@link Union.discriminator|discriminator}. The property value
9214
+ * is the corresponding {@link VariantLayout} instances assigned
9215
+ * to this union by {@link Union#addVariant|addVariant}.
9216
+ *
9217
+ * **NOTE** The registry remains mutable so that variants can be
9218
+ * {@link Union#addVariant|added} at any time. Users should not
9219
+ * manipulate the content of this property. */
9220
+ this.registry = {};
9221
+ /* Private variable used when invoking getSourceVariant */
9222
+ let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);
9223
+ /** Function to infer the variant selected by a source object.
9224
+ *
9225
+ * Defaults to {@link
9226
+ * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may
9227
+ * be overridden using {@link
9228
+ * Union#configGetSourceVariant|configGetSourceVariant}.
9229
+ *
9230
+ * @param {Object} src - as with {@link
9231
+ * Union#defaultGetSourceVariant|defaultGetSourceVariant}.
9232
+ *
9233
+ * @returns {(undefined|VariantLayout)} The default variant
9234
+ * (`undefined`) or first registered variant that uses a property
9235
+ * available in `src`. */
9236
+ this.getSourceVariant = function (src) {
9237
+ return boundGetSourceVariant(src);
9238
+ };
9239
+ /** Function to override the implementation of {@link
9240
+ * Union#getSourceVariant|getSourceVariant}.
9241
+ *
9242
+ * Use this if the desired variant cannot be identified using the
9243
+ * algorithm of {@link
9244
+ * Union#defaultGetSourceVariant|defaultGetSourceVariant}.
9245
+ *
9246
+ * **NOTE** The provided function will be invoked bound to this
9247
+ * Union instance, providing local access to {@link
9248
+ * Union#registry|registry}.
9249
+ *
9250
+ * @param {Function} gsv - a function that follows the API of
9251
+ * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */
9252
+ this.configGetSourceVariant = function (gsv) {
9253
+ boundGetSourceVariant = gsv.bind(this);
9254
+ };
9255
+ }
9256
+ /** @override */
9257
+ getSpan(b, offset = 0) {
9258
+ if (0 <= this.span) {
9259
+ return this.span;
9260
+ }
9261
+ /* Default layouts always have non-negative span, so we don't have
9262
+ * one and we have to recognize the variant which will in turn
9263
+ * determine the span. */
9264
+ const vlo = this.getVariant(b, offset);
9265
+ if (!vlo) {
9266
+ throw new Error('unable to determine span for unrecognized variant');
9267
+ }
9268
+ return vlo.getSpan(b, offset);
9269
+ }
9270
+ /**
9271
+ * Method to infer a registered Union variant compatible with `src`.
9272
+ *
9273
+ * The first satisfied rule in the following sequence defines the
9274
+ * return value:
9275
+ * * If `src` has properties matching the Union discriminator and
9276
+ * the default layout, `undefined` is returned regardless of the
9277
+ * value of the discriminator property (this ensures the default
9278
+ * layout will be used);
9279
+ * * If `src` has a property matching the Union discriminator, the
9280
+ * value of the discriminator identifies a registered variant, and
9281
+ * either (a) the variant has no layout, or (b) `src` has the
9282
+ * variant's property, then the variant is returned (because the
9283
+ * source satisfies the constraints of the variant it identifies);
9284
+ * * If `src` does not have a property matching the Union
9285
+ * discriminator, but does have a property matching a registered
9286
+ * variant, then the variant is returned (because the source
9287
+ * matches a variant without an explicit conflict);
9288
+ * * An error is thrown (because we either can't identify a variant,
9289
+ * or we were explicitly told the variant but can't satisfy it).
9290
+ *
9291
+ * @param {Object} src - an object presumed to be compatible with
9292
+ * the content of the Union.
9293
+ *
9294
+ * @return {(undefined|VariantLayout)} - as described above.
9295
+ *
9296
+ * @throws {Error} - if `src` cannot be associated with a default or
9297
+ * registered variant.
9298
+ */
9299
+ defaultGetSourceVariant(src) {
9300
+ if (Object.prototype.hasOwnProperty.call(src, this.discriminator.property)) {
9301
+ if (this.defaultLayout && this.defaultLayout.property
9302
+ && Object.prototype.hasOwnProperty.call(src, this.defaultLayout.property)) {
9303
+ return undefined;
9304
+ }
9305
+ const vlo = this.registry[src[this.discriminator.property]];
9306
+ if (vlo
9307
+ && ((!vlo.layout)
9308
+ || (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)))) {
9309
+ return vlo;
9310
+ }
9311
+ }
9312
+ else {
9313
+ for (const tag in this.registry) {
9314
+ const vlo = this.registry[tag];
9315
+ if (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)) {
9316
+ return vlo;
9317
+ }
9318
+ }
9319
+ }
9320
+ throw new Error('unable to infer src variant');
9321
+ }
9322
+ /** Implement {@link Layout#decode|decode} for {@link Union}.
9323
+ *
9324
+ * If the variant is {@link Union#addVariant|registered} the return
9325
+ * value is an instance of that variant, with no explicit
9326
+ * discriminator. Otherwise the {@link Union#defaultLayout|default
9327
+ * layout} is used to decode the content. */
9328
+ decode(b, offset = 0) {
9329
+ let dest;
9330
+ const dlo = this.discriminator;
9331
+ const discr = dlo.decode(b, offset);
9332
+ const clo = this.registry[discr];
9333
+ if (undefined === clo) {
9334
+ const defaultLayout = this.defaultLayout;
9335
+ let contentOffset = 0;
9336
+ if (this.usesPrefixDiscriminator) {
9337
+ contentOffset = dlo.layout.span;
9338
+ }
9339
+ dest = this.makeDestinationObject();
9340
+ dest[dlo.property] = discr;
9341
+ // defaultLayout.property can be undefined, but this is allowed by buffer-layout
9342
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9343
+ dest[defaultLayout.property] = defaultLayout.decode(b, offset + contentOffset);
9344
+ }
9345
+ else {
9346
+ dest = clo.decode(b, offset);
9347
+ }
9348
+ return dest;
9349
+ }
9350
+ /** Implement {@link Layout#encode|encode} for {@link Union}.
9351
+ *
9352
+ * This API assumes the `src` object is consistent with the union's
9353
+ * {@link Union#defaultLayout|default layout}. To encode variants
9354
+ * use the appropriate variant-specific {@link VariantLayout#encode}
9355
+ * method. */
9356
+ encode(src, b, offset = 0) {
9357
+ const vlo = this.getSourceVariant(src);
9358
+ if (undefined === vlo) {
9359
+ const dlo = this.discriminator;
9360
+ // this.defaultLayout is not undefined when vlo is undefined
9361
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9362
+ const clo = this.defaultLayout;
9363
+ let contentOffset = 0;
9364
+ if (this.usesPrefixDiscriminator) {
9365
+ contentOffset = dlo.layout.span;
9366
+ }
9367
+ dlo.encode(src[dlo.property], b, offset);
9368
+ // clo.property is not undefined when vlo is undefined
9369
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9370
+ return contentOffset + clo.encode(src[clo.property], b, offset + contentOffset);
9371
+ }
9372
+ return vlo.encode(src, b, offset);
9373
+ }
9374
+ /** Register a new variant structure within a union. The newly
9375
+ * created variant is returned.
9376
+ *
9377
+ * @param {Number} variant - initializer for {@link
9378
+ * VariantLayout#variant|variant}.
9379
+ *
9380
+ * @param {Layout} layout - initializer for {@link
9381
+ * VariantLayout#layout|layout}.
9382
+ *
9383
+ * @param {String} property - initializer for {@link
9384
+ * Layout#property|property}.
9385
+ *
9386
+ * @return {VariantLayout} */
9387
+ addVariant(variant, layout, property) {
9388
+ const rv = new VariantLayout(this, variant, layout, property);
9389
+ this.registry[variant] = rv;
9390
+ return rv;
9391
+ }
9392
+ /**
9393
+ * Get the layout associated with a registered variant.
9394
+ *
9395
+ * If `vb` does not produce a registered variant the function returns
9396
+ * `undefined`.
9397
+ *
9398
+ * @param {(Number|Uint8Array)} vb - either the variant number, or a
9399
+ * buffer from which the discriminator is to be read.
9400
+ *
9401
+ * @param {Number} offset - offset into `vb` for the start of the
9402
+ * union. Used only when `vb` is an instance of {Uint8Array}.
9403
+ *
9404
+ * @return {({VariantLayout}|undefined)}
9405
+ */
9406
+ getVariant(vb, offset = 0) {
9407
+ let variant;
9408
+ if (vb instanceof Uint8Array) {
9409
+ variant = this.discriminator.decode(vb, offset);
9410
+ }
9411
+ else {
9412
+ variant = vb;
9413
+ }
9414
+ return this.registry[variant];
9415
+ }
9416
+ }
9417
+ Layout$1.Union = Union;
9418
+ /**
9419
+ * Represent a specific variant within a containing union.
9420
+ *
9421
+ * **NOTE** The {@link Layout#span|span} of the variant may include
9422
+ * the span of the {@link Union#discriminator|discriminator} used to
9423
+ * identify it, but values read and written using the variant strictly
9424
+ * conform to the content of {@link VariantLayout#layout|layout}.
9425
+ *
9426
+ * **NOTE** User code should not invoke this constructor directly. Use
9427
+ * the union {@link Union#addVariant|addVariant} helper method.
9428
+ *
9429
+ * @param {Union} union - initializer for {@link
9430
+ * VariantLayout#union|union}.
9431
+ *
9432
+ * @param {Number} variant - initializer for {@link
9433
+ * VariantLayout#variant|variant}.
9434
+ *
9435
+ * @param {Layout} [layout] - initializer for {@link
9436
+ * VariantLayout#layout|layout}. If absent the variant carries no
9437
+ * data.
9438
+ *
9439
+ * @param {String} [property] - initializer for {@link
9440
+ * Layout#property|property}. Unlike many other layouts, variant
9441
+ * layouts normally include a property name so they can be identified
9442
+ * within their containing {@link Union}. The property identifier may
9443
+ * be absent only if `layout` is is absent.
9444
+ *
9445
+ * @augments {Layout}
9446
+ */
9447
+ class VariantLayout extends Layout {
9448
+ constructor(union, variant, layout, property) {
9449
+ if (!(union instanceof Union)) {
9450
+ throw new TypeError('union must be a Union');
9451
+ }
9452
+ if ((!Number.isInteger(variant)) || (0 > variant)) {
9453
+ throw new TypeError('variant must be a (non-negative) integer');
9454
+ }
9455
+ if (('string' === typeof layout)
9456
+ && (undefined === property)) {
9457
+ property = layout;
9458
+ layout = null;
9459
+ }
9460
+ if (layout) {
9461
+ if (!(layout instanceof Layout)) {
9462
+ throw new TypeError('layout must be a Layout');
9463
+ }
9464
+ if ((null !== union.defaultLayout)
9465
+ && (0 <= layout.span)
9466
+ && (layout.span > union.defaultLayout.span)) {
9467
+ throw new Error('variant span exceeds span of containing union');
9468
+ }
9469
+ if ('string' !== typeof property) {
9470
+ throw new TypeError('variant must have a String property');
9471
+ }
9472
+ }
9473
+ let span = union.span;
9474
+ if (0 > union.span) {
9475
+ span = layout ? layout.span : 0;
9476
+ if ((0 <= span) && union.usesPrefixDiscriminator) {
9477
+ span += union.discriminator.layout.span;
9478
+ }
9479
+ }
9480
+ super(span, property);
9481
+ /** The {@link Union} to which this variant belongs. */
9482
+ this.union = union;
9483
+ /** The unsigned integral value identifying this variant within
9484
+ * the {@link Union#discriminator|discriminator} of the containing
9485
+ * union. */
9486
+ this.variant = variant;
9487
+ /** The {@link Layout} to be used when reading/writing the
9488
+ * non-discriminator part of the {@link
9489
+ * VariantLayout#union|union}. If `null` the variant carries no
9490
+ * data. */
9491
+ this.layout = layout || null;
9492
+ }
9493
+ /** @override */
9494
+ getSpan(b, offset = 0) {
9495
+ if (0 <= this.span) {
9496
+ /* Will be equal to the containing union span if that is not
9497
+ * variable. */
9498
+ return this.span;
9499
+ }
9500
+ let contentOffset = 0;
9501
+ if (this.union.usesPrefixDiscriminator) {
9502
+ contentOffset = this.union.discriminator.layout.span;
9503
+ }
9504
+ /* Span is defined solely by the variant (and prefix discriminator) */
9505
+ let span = 0;
9506
+ if (this.layout) {
9507
+ span = this.layout.getSpan(b, offset + contentOffset);
9508
+ }
9509
+ return contentOffset + span;
9510
+ }
9511
+ /** @override */
9512
+ decode(b, offset = 0) {
9513
+ const dest = this.makeDestinationObject();
9514
+ if (this !== this.union.getVariant(b, offset)) {
9515
+ throw new Error('variant mismatch');
9516
+ }
9517
+ let contentOffset = 0;
9518
+ if (this.union.usesPrefixDiscriminator) {
9519
+ contentOffset = this.union.discriminator.layout.span;
9520
+ }
9521
+ if (this.layout) {
9522
+ dest[this.property] = this.layout.decode(b, offset + contentOffset);
9523
+ }
9524
+ else if (this.property) {
9525
+ dest[this.property] = true;
9526
+ }
9527
+ else if (this.union.usesPrefixDiscriminator) {
9528
+ dest[this.union.discriminator.property] = this.variant;
9529
+ }
9530
+ return dest;
9531
+ }
9532
+ /** @override */
9533
+ encode(src, b, offset = 0) {
9534
+ let contentOffset = 0;
9535
+ if (this.union.usesPrefixDiscriminator) {
9536
+ contentOffset = this.union.discriminator.layout.span;
9537
+ }
9538
+ if (this.layout
9539
+ && (!Object.prototype.hasOwnProperty.call(src, this.property))) {
9540
+ throw new TypeError('variant lacks property ' + this.property);
9541
+ }
9542
+ this.union.discriminator.encode(this.variant, b, offset);
9543
+ let span = contentOffset;
9544
+ if (this.layout) {
9545
+ this.layout.encode(src[this.property], b, offset + contentOffset);
9546
+ span += this.layout.getSpan(b, offset + contentOffset);
9547
+ if ((0 <= this.union.span)
9548
+ && (span > this.union.span)) {
9549
+ throw new Error('encoded variant overruns containing union');
9550
+ }
9551
+ }
9552
+ return span;
9553
+ }
9554
+ /** Delegate {@link Layout#fromArray|fromArray} to {@link
9555
+ * VariantLayout#layout|layout}. */
9556
+ fromArray(values) {
9557
+ if (this.layout) {
9558
+ return this.layout.fromArray(values);
9559
+ }
9560
+ return undefined;
9561
+ }
9562
+ }
9563
+ Layout$1.VariantLayout = VariantLayout;
9564
+ /** JavaScript chose to define bitwise operations as operating on
9565
+ * signed 32-bit values in 2's complement form, meaning any integer
9566
+ * with bit 31 set is going to look negative. For right shifts that's
9567
+ * not a problem, because `>>>` is a logical shift, but for every
9568
+ * other bitwise operator we have to compensate for possible negative
9569
+ * results. */
9570
+ function fixBitwiseResult(v) {
9571
+ if (0 > v) {
9572
+ v += 0x100000000;
9573
+ }
9574
+ return v;
9575
+ }
9576
+ /**
9577
+ * Contain a sequence of bit fields as an unsigned integer.
9578
+ *
9579
+ * *Factory*: {@link module:Layout.bits|bits}
9580
+ *
9581
+ * This is a container element; within it there are {@link BitField}
9582
+ * instances that provide the extracted properties. The container
9583
+ * simply defines the aggregate representation and its bit ordering.
9584
+ * The representation is an object containing properties with numeric
9585
+ * or {@link Boolean} values.
9586
+ *
9587
+ * {@link BitField}s are added with the {@link
9588
+ * BitStructure#addField|addField} and {@link
9589
+ * BitStructure#addBoolean|addBoolean} methods.
9590
+
9591
+ * @param {Layout} word - initializer for {@link
9592
+ * BitStructure#word|word}. The parameter must be an instance of
9593
+ * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.
9594
+ *
9595
+ * @param {bool} [msb] - `true` if the bit numbering starts at the
9596
+ * most significant bit of the containing word; `false` (default) if
9597
+ * it starts at the least significant bit of the containing word. If
9598
+ * the parameter at this position is a string and `property` is
9599
+ * `undefined` the value of this argument will instead be used as the
9600
+ * value of `property`.
9601
+ *
9602
+ * @param {string} [property] - initializer for {@link
9603
+ * Layout#property|property}.
9604
+ *
9605
+ * @augments {Layout}
9606
+ */
9607
+ class BitStructure extends Layout {
9608
+ constructor(word, msb, property) {
9609
+ if (!((word instanceof UInt)
9610
+ || (word instanceof UIntBE))) {
9611
+ throw new TypeError('word must be a UInt or UIntBE layout');
9612
+ }
9613
+ if (('string' === typeof msb)
9614
+ && (undefined === property)) {
9615
+ property = msb;
9616
+ msb = false;
9617
+ }
9618
+ if (4 < word.span) {
9619
+ throw new RangeError('word cannot exceed 32 bits');
9620
+ }
9621
+ super(word.span, property);
9622
+ /** The layout used for the packed value. {@link BitField}
9623
+ * instances are packed sequentially depending on {@link
9624
+ * BitStructure#msb|msb}. */
9625
+ this.word = word;
9626
+ /** Whether the bit sequences are packed starting at the most
9627
+ * significant bit growing down (`true`), or the least significant
9628
+ * bit growing up (`false`).
9629
+ *
9630
+ * **NOTE** Regardless of this value, the least significant bit of
9631
+ * any {@link BitField} value is the least significant bit of the
9632
+ * corresponding section of the packed value. */
9633
+ this.msb = !!msb;
9634
+ /** The sequence of {@link BitField} layouts that comprise the
9635
+ * packed structure.
9636
+ *
9637
+ * **NOTE** The array remains mutable to allow fields to be {@link
9638
+ * BitStructure#addField|added} after construction. Users should
9639
+ * not manipulate the content of this property.*/
9640
+ this.fields = [];
9641
+ /* Storage for the value. Capture a variable instead of using an
9642
+ * instance property because we don't want anything to change the
9643
+ * value without going through the mutator. */
9644
+ let value = 0;
9645
+ this._packedSetValue = function (v) {
9646
+ value = fixBitwiseResult(v);
9647
+ return this;
9648
+ };
9649
+ this._packedGetValue = function () {
9650
+ return value;
9651
+ };
9652
+ }
9653
+ /** @override */
9654
+ decode(b, offset = 0) {
9655
+ const dest = this.makeDestinationObject();
9656
+ const value = this.word.decode(b, offset);
9657
+ this._packedSetValue(value);
9658
+ for (const fd of this.fields) {
9659
+ if (undefined !== fd.property) {
9660
+ dest[fd.property] = fd.decode(b);
9661
+ }
9662
+ }
9663
+ return dest;
9664
+ }
9665
+ /** Implement {@link Layout#encode|encode} for {@link BitStructure}.
9666
+ *
9667
+ * If `src` is missing a property for a member with a defined {@link
9668
+ * Layout#property|property} the corresponding region of the packed
9669
+ * value is left unmodified. Unused bits are also left unmodified. */
9670
+ encode(src, b, offset = 0) {
9671
+ const value = this.word.decode(b, offset);
9672
+ this._packedSetValue(value);
9673
+ for (const fd of this.fields) {
9674
+ if (undefined !== fd.property) {
9675
+ const fv = src[fd.property];
9676
+ if (undefined !== fv) {
9677
+ fd.encode(fv);
9678
+ }
9679
+ }
9680
+ }
9681
+ return this.word.encode(this._packedGetValue(), b, offset);
9682
+ }
9683
+ /** Register a new bitfield with a containing bit structure. The
9684
+ * resulting bitfield is returned.
9685
+ *
9686
+ * @param {Number} bits - initializer for {@link BitField#bits|bits}.
9687
+ *
9688
+ * @param {string} property - initializer for {@link
9689
+ * Layout#property|property}.
9690
+ *
9691
+ * @return {BitField} */
9692
+ addField(bits, property) {
9693
+ const bf = new BitField(this, bits, property);
9694
+ this.fields.push(bf);
9695
+ return bf;
9696
+ }
9697
+ /** As with {@link BitStructure#addField|addField} for single-bit
9698
+ * fields with `boolean` value representation.
9699
+ *
9700
+ * @param {string} property - initializer for {@link
9701
+ * Layout#property|property}.
9702
+ *
9703
+ * @return {Boolean} */
9704
+ // `Boolean` conflicts with the native primitive type
9705
+ // eslint-disable-next-line @typescript-eslint/ban-types
9706
+ addBoolean(property) {
9707
+ // This is my Boolean, not the Javascript one.
9708
+ const bf = new Boolean(this, property);
9709
+ this.fields.push(bf);
9710
+ return bf;
9711
+ }
9712
+ /**
9713
+ * Get access to the bit field for a given property.
9714
+ *
9715
+ * @param {String} property - the bit field of interest.
9716
+ *
9717
+ * @return {BitField} - the field associated with `property`, or
9718
+ * undefined if there is no such property.
9719
+ */
9720
+ fieldFor(property) {
9721
+ if ('string' !== typeof property) {
9722
+ throw new TypeError('property must be string');
9723
+ }
9724
+ for (const fd of this.fields) {
9725
+ if (fd.property === property) {
9726
+ return fd;
9727
+ }
9728
+ }
9729
+ return undefined;
9730
+ }
9731
+ }
9732
+ Layout$1.BitStructure = BitStructure;
9733
+ /**
9734
+ * Represent a sequence of bits within a {@link BitStructure}.
9735
+ *
9736
+ * All bit field values are represented as unsigned integers.
9737
+ *
9738
+ * **NOTE** User code should not invoke this constructor directly.
9739
+ * Use the container {@link BitStructure#addField|addField} helper
9740
+ * method.
9741
+ *
9742
+ * **NOTE** BitField instances are not instances of {@link Layout}
9743
+ * since {@link Layout#span|span} measures 8-bit units.
9744
+ *
9745
+ * @param {BitStructure} container - initializer for {@link
9746
+ * BitField#container|container}.
9747
+ *
9748
+ * @param {Number} bits - initializer for {@link BitField#bits|bits}.
9749
+ *
9750
+ * @param {string} [property] - initializer for {@link
9751
+ * Layout#property|property}.
9752
+ */
9753
+ class BitField {
9754
+ constructor(container, bits, property) {
9755
+ if (!(container instanceof BitStructure)) {
9756
+ throw new TypeError('container must be a BitStructure');
9757
+ }
9758
+ if ((!Number.isInteger(bits)) || (0 >= bits)) {
9759
+ throw new TypeError('bits must be positive integer');
9760
+ }
9761
+ const totalBits = 8 * container.span;
9762
+ const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);
9763
+ if ((bits + usedBits) > totalBits) {
9764
+ throw new Error('bits too long for span remainder ('
9765
+ + (totalBits - usedBits) + ' of '
9766
+ + totalBits + ' remain)');
9767
+ }
9768
+ /** The {@link BitStructure} instance to which this bit field
9769
+ * belongs. */
9770
+ this.container = container;
9771
+ /** The span of this value in bits. */
9772
+ this.bits = bits;
9773
+ /** A mask of {@link BitField#bits|bits} bits isolating value bits
9774
+ * that fit within the field.
9775
+ *
9776
+ * That is, it masks a value that has not yet been shifted into
9777
+ * position within its containing packed integer. */
9778
+ this.valueMask = (1 << bits) - 1;
9779
+ if (32 === bits) { // shifted value out of range
9780
+ this.valueMask = 0xFFFFFFFF;
9781
+ }
9782
+ /** The offset of the value within the containing packed unsigned
9783
+ * integer. The least significant bit of the packed value is at
9784
+ * offset zero, regardless of bit ordering used. */
9785
+ this.start = usedBits;
9786
+ if (this.container.msb) {
9787
+ this.start = totalBits - usedBits - bits;
9788
+ }
9789
+ /** A mask of {@link BitField#bits|bits} isolating the field value
9790
+ * within the containing packed unsigned integer. */
9791
+ this.wordMask = fixBitwiseResult(this.valueMask << this.start);
9792
+ /** The property name used when this bitfield is represented in an
9793
+ * Object.
9794
+ *
9795
+ * Intended to be functionally equivalent to {@link
9796
+ * Layout#property}.
9797
+ *
9798
+ * If left undefined the corresponding span of bits will be
9799
+ * treated as padding: it will not be mutated by {@link
9800
+ * Layout#encode|encode} nor represented as a property in the
9801
+ * decoded Object. */
9802
+ this.property = property;
9803
+ }
9804
+ /** Store a value into the corresponding subsequence of the containing
9805
+ * bit field. */
9806
+ decode(b, offset) {
9807
+ const word = this.container._packedGetValue();
9808
+ const wordValue = fixBitwiseResult(word & this.wordMask);
9809
+ const value = wordValue >>> this.start;
9810
+ return value;
9811
+ }
9812
+ /** Store a value into the corresponding subsequence of the containing
9813
+ * bit field.
9814
+ *
9815
+ * **NOTE** This is not a specialization of {@link
9816
+ * Layout#encode|Layout.encode} and there is no return value. */
9817
+ encode(value) {
9818
+ if ('number' !== typeof value
9819
+ || !Number.isInteger(value)
9820
+ || (value !== fixBitwiseResult(value & this.valueMask))) {
9821
+ throw new TypeError(nameWithProperty('BitField.encode', this)
9822
+ + ' value must be integer not exceeding ' + this.valueMask);
9823
+ }
9824
+ const word = this.container._packedGetValue();
9825
+ const wordValue = fixBitwiseResult(value << this.start);
9826
+ this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)
9827
+ | wordValue);
9828
+ }
9829
+ }
9830
+ Layout$1.BitField = BitField;
9831
+ /**
9832
+ * Represent a single bit within a {@link BitStructure} as a
9833
+ * JavaScript boolean.
9834
+ *
9835
+ * **NOTE** User code should not invoke this constructor directly.
9836
+ * Use the container {@link BitStructure#addBoolean|addBoolean} helper
9837
+ * method.
9838
+ *
9839
+ * @param {BitStructure} container - initializer for {@link
9840
+ * BitField#container|container}.
9841
+ *
9842
+ * @param {string} [property] - initializer for {@link
9843
+ * Layout#property|property}.
9844
+ *
9845
+ * @augments {BitField}
9846
+ */
9847
+ /* eslint-disable no-extend-native */
9848
+ class Boolean extends BitField {
9849
+ constructor(container, property) {
9850
+ super(container, 1, property);
9851
+ }
9852
+ /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.
9853
+ *
9854
+ * @returns {boolean} */
9855
+ decode(b, offset) {
9856
+ return !!super.decode(b, offset);
9857
+ }
9858
+ /** @override */
9859
+ encode(value) {
9860
+ if ('boolean' === typeof value) {
9861
+ // BitField requires integer values
9862
+ value = +value;
9863
+ }
9864
+ super.encode(value);
9865
+ }
9866
+ }
9867
+ Layout$1.Boolean = Boolean;
9868
+ /* eslint-enable no-extend-native */
9869
+ /**
9870
+ * Contain a fixed-length block of arbitrary data, represented as a
9871
+ * Uint8Array.
9872
+ *
9873
+ * *Factory*: {@link module:Layout.blob|blob}
9874
+ *
9875
+ * @param {(Number|ExternalLayout)} length - initializes {@link
9876
+ * Blob#length|length}.
9877
+ *
9878
+ * @param {String} [property] - initializer for {@link
9879
+ * Layout#property|property}.
9880
+ *
9881
+ * @augments {Layout}
9882
+ */
9883
+ class Blob extends Layout {
9884
+ constructor(length, property) {
9885
+ if (!(((length instanceof ExternalLayout) && length.isCount())
9886
+ || (Number.isInteger(length) && (0 <= length)))) {
9887
+ throw new TypeError('length must be positive integer '
9888
+ + 'or an unsigned integer ExternalLayout');
9889
+ }
9890
+ let span = -1;
9891
+ if (!(length instanceof ExternalLayout)) {
9892
+ span = length;
9893
+ }
9894
+ super(span, property);
9895
+ /** The number of bytes in the blob.
9896
+ *
9897
+ * This may be a non-negative integer, or an instance of {@link
9898
+ * ExternalLayout} that satisfies {@link
9899
+ * ExternalLayout#isCount|isCount()}. */
9900
+ this.length = length;
9901
+ }
9902
+ /** @override */
9903
+ getSpan(b, offset) {
9904
+ let span = this.span;
9905
+ if (0 > span) {
9906
+ span = this.length.decode(b, offset);
9907
+ }
9908
+ return span;
9909
+ }
9910
+ /** @override */
9911
+ decode(b, offset = 0) {
9912
+ let span = this.span;
9913
+ if (0 > span) {
9914
+ span = this.length.decode(b, offset);
9915
+ }
9916
+ return uint8ArrayToBuffer(b).slice(offset, offset + span);
9917
+ }
9918
+ /** Implement {@link Layout#encode|encode} for {@link Blob}.
9919
+ *
9920
+ * **NOTE** If {@link Layout#count|count} is an instance of {@link
9921
+ * ExternalLayout} then the length of `src` will be encoded as the
9922
+ * count after `src` is encoded. */
9923
+ encode(src, b, offset) {
9924
+ let span = this.length;
9925
+ if (this.length instanceof ExternalLayout) {
9926
+ span = src.length;
9927
+ }
9928
+ if (!(src instanceof Uint8Array && span === src.length)) {
9929
+ throw new TypeError(nameWithProperty('Blob.encode', this)
9930
+ + ' requires (length ' + span + ') Uint8Array as src');
9931
+ }
9932
+ if ((offset + span) > b.length) {
9933
+ throw new RangeError('encoding overruns Uint8Array');
9934
+ }
9935
+ const srcBuffer = uint8ArrayToBuffer(src);
9936
+ uint8ArrayToBuffer(b).write(srcBuffer.toString('hex'), offset, span, 'hex');
9937
+ if (this.length instanceof ExternalLayout) {
9938
+ this.length.encode(span, b, offset);
9939
+ }
9940
+ return span;
9941
+ }
9942
+ }
9943
+ Layout$1.Blob = Blob;
9944
+ /**
9945
+ * Contain a `NUL`-terminated UTF8 string.
9946
+ *
9947
+ * *Factory*: {@link module:Layout.cstr|cstr}
9948
+ *
9949
+ * **NOTE** Any UTF8 string that incorporates a zero-valued byte will
9950
+ * not be correctly decoded by this layout.
9951
+ *
9952
+ * @param {String} [property] - initializer for {@link
9953
+ * Layout#property|property}.
9954
+ *
9955
+ * @augments {Layout}
9956
+ */
9957
+ class CString extends Layout {
9958
+ constructor(property) {
9959
+ super(-1, property);
9960
+ }
9961
+ /** @override */
9962
+ getSpan(b, offset = 0) {
9963
+ checkUint8Array(b);
9964
+ let idx = offset;
9965
+ while ((idx < b.length) && (0 !== b[idx])) {
9966
+ idx += 1;
9967
+ }
9968
+ return 1 + idx - offset;
9969
+ }
9970
+ /** @override */
9971
+ decode(b, offset = 0) {
9972
+ const span = this.getSpan(b, offset);
9973
+ return uint8ArrayToBuffer(b).slice(offset, offset + span - 1).toString('utf-8');
9974
+ }
9975
+ /** @override */
9976
+ encode(src, b, offset = 0) {
9977
+ /* Must force this to a string, lest it be a number and the
9978
+ * "utf8-encoding" below actually allocate a buffer of length
9979
+ * src */
9980
+ if ('string' !== typeof src) {
9981
+ src = String(src);
9982
+ }
9983
+ const srcb = buffer_1.Buffer.from(src, 'utf8');
9984
+ const span = srcb.length;
9985
+ if ((offset + span) > b.length) {
9986
+ throw new RangeError('encoding overruns Buffer');
9987
+ }
9988
+ const buffer = uint8ArrayToBuffer(b);
9989
+ srcb.copy(buffer, offset);
9990
+ buffer[offset + span] = 0;
9991
+ return span + 1;
9992
+ }
9993
+ }
9994
+ Layout$1.CString = CString;
9995
+ /**
9996
+ * Contain a UTF8 string with implicit length.
9997
+ *
9998
+ * *Factory*: {@link module:Layout.utf8|utf8}
9999
+ *
10000
+ * **NOTE** Because the length is implicit in the size of the buffer
10001
+ * this layout should be used only in isolation, or in a situation
10002
+ * where the length can be expressed by operating on a slice of the
10003
+ * containing buffer.
10004
+ *
10005
+ * @param {Number} [maxSpan] - the maximum length allowed for encoded
10006
+ * string content. If not provided there is no bound on the allowed
10007
+ * content.
10008
+ *
10009
+ * @param {String} [property] - initializer for {@link
10010
+ * Layout#property|property}.
10011
+ *
10012
+ * @augments {Layout}
10013
+ */
10014
+ class UTF8 extends Layout {
10015
+ constructor(maxSpan, property) {
10016
+ if (('string' === typeof maxSpan) && (undefined === property)) {
10017
+ property = maxSpan;
10018
+ maxSpan = undefined;
10019
+ }
10020
+ if (undefined === maxSpan) {
10021
+ maxSpan = -1;
10022
+ }
10023
+ else if (!Number.isInteger(maxSpan)) {
10024
+ throw new TypeError('maxSpan must be an integer');
10025
+ }
10026
+ super(-1, property);
10027
+ /** The maximum span of the layout in bytes.
10028
+ *
10029
+ * Positive values are generally expected. Zero is abnormal.
10030
+ * Attempts to encode or decode a value that exceeds this length
10031
+ * will throw a `RangeError`.
10032
+ *
10033
+ * A negative value indicates that there is no bound on the length
10034
+ * of the content. */
10035
+ this.maxSpan = maxSpan;
10036
+ }
10037
+ /** @override */
10038
+ getSpan(b, offset = 0) {
10039
+ checkUint8Array(b);
10040
+ return b.length - offset;
10041
+ }
10042
+ /** @override */
10043
+ decode(b, offset = 0) {
10044
+ const span = this.getSpan(b, offset);
10045
+ if ((0 <= this.maxSpan)
10046
+ && (this.maxSpan < span)) {
10047
+ throw new RangeError('text length exceeds maxSpan');
10048
+ }
10049
+ return uint8ArrayToBuffer(b).slice(offset, offset + span).toString('utf-8');
10050
+ }
10051
+ /** @override */
10052
+ encode(src, b, offset = 0) {
10053
+ /* Must force this to a string, lest it be a number and the
10054
+ * "utf8-encoding" below actually allocate a buffer of length
10055
+ * src */
10056
+ if ('string' !== typeof src) {
10057
+ src = String(src);
10058
+ }
10059
+ const srcb = buffer_1.Buffer.from(src, 'utf8');
10060
+ const span = srcb.length;
10061
+ if ((0 <= this.maxSpan)
10062
+ && (this.maxSpan < span)) {
10063
+ throw new RangeError('text length exceeds maxSpan');
10064
+ }
10065
+ if ((offset + span) > b.length) {
10066
+ throw new RangeError('encoding overruns Buffer');
10067
+ }
10068
+ srcb.copy(uint8ArrayToBuffer(b), offset);
10069
+ return span;
10070
+ }
10071
+ }
10072
+ Layout$1.UTF8 = UTF8;
10073
+ /**
10074
+ * Contain a constant value.
10075
+ *
10076
+ * This layout may be used in cases where a JavaScript value can be
10077
+ * inferred without an expression in the binary encoding. An example
10078
+ * would be a {@link VariantLayout|variant layout} where the content
10079
+ * is implied by the union {@link Union#discriminator|discriminator}.
10080
+ *
10081
+ * @param {Object|Number|String} value - initializer for {@link
10082
+ * Constant#value|value}. If the value is an object (or array) and
10083
+ * the application intends the object to remain unchanged regardless
10084
+ * of what is done to values decoded by this layout, the value should
10085
+ * be frozen prior passing it to this constructor.
10086
+ *
10087
+ * @param {String} [property] - initializer for {@link
10088
+ * Layout#property|property}.
10089
+ *
10090
+ * @augments {Layout}
10091
+ */
10092
+ class Constant extends Layout {
10093
+ constructor(value, property) {
10094
+ super(0, property);
10095
+ /** The value produced by this constant when the layout is {@link
10096
+ * Constant#decode|decoded}.
10097
+ *
10098
+ * Any JavaScript value including `null` and `undefined` is
10099
+ * permitted.
10100
+ *
10101
+ * **WARNING** If `value` passed in the constructor was not
10102
+ * frozen, it is possible for users of decoded values to change
10103
+ * the content of the value. */
10104
+ this.value = value;
10105
+ }
10106
+ /** @override */
10107
+ decode(b, offset) {
10108
+ return this.value;
10109
+ }
10110
+ /** @override */
10111
+ encode(src, b, offset) {
10112
+ /* Constants take no space */
10113
+ return 0;
10114
+ }
10115
+ }
10116
+ Layout$1.Constant = Constant;
10117
+ /** Factory for {@link GreedyCount}. */
10118
+ Layout$1.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));
10119
+ /** Factory for {@link OffsetLayout}. */
10120
+ Layout$1.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));
10121
+ /** Factory for {@link UInt|unsigned int layouts} spanning one
10122
+ * byte. */
10123
+ var u8 = Layout$1.u8 = ((property) => new UInt(1, property));
10124
+ /** Factory for {@link UInt|little-endian unsigned int layouts}
10125
+ * spanning two bytes. */
10126
+ Layout$1.u16 = ((property) => new UInt(2, property));
10127
+ /** Factory for {@link UInt|little-endian unsigned int layouts}
10128
+ * spanning three bytes. */
10129
+ Layout$1.u24 = ((property) => new UInt(3, property));
10130
+ /** Factory for {@link UInt|little-endian unsigned int layouts}
10131
+ * spanning four bytes. */
10132
+ var u32 = Layout$1.u32 = ((property) => new UInt(4, property));
10133
+ /** Factory for {@link UInt|little-endian unsigned int layouts}
10134
+ * spanning five bytes. */
10135
+ Layout$1.u40 = ((property) => new UInt(5, property));
10136
+ /** Factory for {@link UInt|little-endian unsigned int layouts}
10137
+ * spanning six bytes. */
10138
+ Layout$1.u48 = ((property) => new UInt(6, property));
10139
+ /** Factory for {@link NearUInt64|little-endian unsigned int
10140
+ * layouts} interpreted as Numbers. */
10141
+ Layout$1.nu64 = ((property) => new NearUInt64(property));
10142
+ /** Factory for {@link UInt|big-endian unsigned int layouts}
10143
+ * spanning two bytes. */
10144
+ Layout$1.u16be = ((property) => new UIntBE(2, property));
10145
+ /** Factory for {@link UInt|big-endian unsigned int layouts}
10146
+ * spanning three bytes. */
10147
+ Layout$1.u24be = ((property) => new UIntBE(3, property));
10148
+ /** Factory for {@link UInt|big-endian unsigned int layouts}
10149
+ * spanning four bytes. */
10150
+ Layout$1.u32be = ((property) => new UIntBE(4, property));
10151
+ /** Factory for {@link UInt|big-endian unsigned int layouts}
10152
+ * spanning five bytes. */
10153
+ Layout$1.u40be = ((property) => new UIntBE(5, property));
10154
+ /** Factory for {@link UInt|big-endian unsigned int layouts}
10155
+ * spanning six bytes. */
10156
+ Layout$1.u48be = ((property) => new UIntBE(6, property));
10157
+ /** Factory for {@link NearUInt64BE|big-endian unsigned int
10158
+ * layouts} interpreted as Numbers. */
10159
+ Layout$1.nu64be = ((property) => new NearUInt64BE(property));
10160
+ /** Factory for {@link Int|signed int layouts} spanning one
10161
+ * byte. */
10162
+ Layout$1.s8 = ((property) => new Int(1, property));
10163
+ /** Factory for {@link Int|little-endian signed int layouts}
10164
+ * spanning two bytes. */
10165
+ Layout$1.s16 = ((property) => new Int(2, property));
10166
+ /** Factory for {@link Int|little-endian signed int layouts}
10167
+ * spanning three bytes. */
10168
+ Layout$1.s24 = ((property) => new Int(3, property));
10169
+ /** Factory for {@link Int|little-endian signed int layouts}
10170
+ * spanning four bytes. */
10171
+ Layout$1.s32 = ((property) => new Int(4, property));
10172
+ /** Factory for {@link Int|little-endian signed int layouts}
10173
+ * spanning five bytes. */
10174
+ Layout$1.s40 = ((property) => new Int(5, property));
10175
+ /** Factory for {@link Int|little-endian signed int layouts}
10176
+ * spanning six bytes. */
10177
+ Layout$1.s48 = ((property) => new Int(6, property));
10178
+ /** Factory for {@link NearInt64|little-endian signed int layouts}
10179
+ * interpreted as Numbers. */
10180
+ Layout$1.ns64 = ((property) => new NearInt64(property));
10181
+ /** Factory for {@link Int|big-endian signed int layouts}
10182
+ * spanning two bytes. */
10183
+ Layout$1.s16be = ((property) => new IntBE(2, property));
10184
+ /** Factory for {@link Int|big-endian signed int layouts}
10185
+ * spanning three bytes. */
10186
+ Layout$1.s24be = ((property) => new IntBE(3, property));
10187
+ /** Factory for {@link Int|big-endian signed int layouts}
10188
+ * spanning four bytes. */
10189
+ Layout$1.s32be = ((property) => new IntBE(4, property));
10190
+ /** Factory for {@link Int|big-endian signed int layouts}
10191
+ * spanning five bytes. */
10192
+ Layout$1.s40be = ((property) => new IntBE(5, property));
10193
+ /** Factory for {@link Int|big-endian signed int layouts}
10194
+ * spanning six bytes. */
10195
+ Layout$1.s48be = ((property) => new IntBE(6, property));
10196
+ /** Factory for {@link NearInt64BE|big-endian signed int layouts}
10197
+ * interpreted as Numbers. */
10198
+ Layout$1.ns64be = ((property) => new NearInt64BE(property));
10199
+ /** Factory for {@link Float|little-endian 32-bit floating point} values. */
10200
+ Layout$1.f32 = ((property) => new Float(property));
10201
+ /** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */
10202
+ Layout$1.f32be = ((property) => new FloatBE(property));
10203
+ /** Factory for {@link Double|little-endian 64-bit floating point} values. */
10204
+ Layout$1.f64 = ((property) => new Double(property));
10205
+ /** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */
10206
+ Layout$1.f64be = ((property) => new DoubleBE(property));
10207
+ /** Factory for {@link Structure} values. */
10208
+ var struct = Layout$1.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));
10209
+ /** Factory for {@link BitStructure} values. */
10210
+ Layout$1.bits = ((word, msb, property) => new BitStructure(word, msb, property));
10211
+ /** Factory for {@link Sequence} values. */
10212
+ Layout$1.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));
10213
+ /** Factory for {@link Union} values. */
10214
+ Layout$1.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));
10215
+ /** Factory for {@link UnionLayoutDiscriminator} values. */
10216
+ Layout$1.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));
10217
+ /** Factory for {@link Blob} values. */
10218
+ var blob = Layout$1.blob = ((length, property) => new Blob(length, property));
10219
+ /** Factory for {@link CString} values. */
10220
+ Layout$1.cstr = ((property) => new CString(property));
10221
+ /** Factory for {@link UTF8} values. */
10222
+ Layout$1.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));
10223
+ /** Factory for {@link Constant} values. */
10224
+ Layout$1.constant = ((value, property) => new Constant(value, property));
10225
+
10226
+ const encodeDecode = (layout) => {
10227
+ const decode = layout.decode.bind(layout);
10228
+ const encode = layout.encode.bind(layout);
10229
+ return { decode, encode };
10230
+ };
10231
+
10232
+ var browser = {};
10233
+
10234
+ Object.defineProperty(browser, "__esModule", { value: true });
10235
+ /**
10236
+ * Convert a little-endian buffer into a BigInt.
10237
+ * @param buf The little-endian buffer to convert
10238
+ * @returns A BigInt with the little-endian representation of buf.
10239
+ */
10240
+ function toBigIntLE(buf) {
10241
+ {
10242
+ const reversed = Buffer.from(buf);
10243
+ reversed.reverse();
10244
+ const hex = reversed.toString('hex');
10245
+ if (hex.length === 0) {
10246
+ return BigInt(0);
10247
+ }
10248
+ return BigInt(`0x${hex}`);
10249
+ }
10250
+ }
10251
+ var toBigIntLE_1 = browser.toBigIntLE = toBigIntLE;
10252
+ /**
10253
+ * Convert a big-endian buffer into a BigInt
10254
+ * @param buf The big-endian buffer to convert.
10255
+ * @returns A BigInt with the big-endian representation of buf.
10256
+ */
10257
+ function toBigIntBE(buf) {
10258
+ {
10259
+ const hex = buf.toString('hex');
10260
+ if (hex.length === 0) {
10261
+ return BigInt(0);
10262
+ }
10263
+ return BigInt(`0x${hex}`);
10264
+ }
10265
+ }
10266
+ browser.toBigIntBE = toBigIntBE;
10267
+ /**
10268
+ * Convert a BigInt to a little-endian buffer.
10269
+ * @param num The BigInt to convert.
10270
+ * @param width The number of bytes that the resulting buffer should be.
10271
+ * @returns A little-endian buffer representation of num.
10272
+ */
10273
+ function toBufferLE(num, width) {
10274
+ {
10275
+ const hex = num.toString(16);
10276
+ const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
10277
+ buffer.reverse();
10278
+ return buffer;
10279
+ }
10280
+ }
10281
+ var toBufferLE_1 = browser.toBufferLE = toBufferLE;
10282
+ /**
10283
+ * Convert a BigInt to a big-endian buffer.
10284
+ * @param num The BigInt to convert.
10285
+ * @param width The number of bytes that the resulting buffer should be.
10286
+ * @returns A big-endian buffer representation of num.
10287
+ */
10288
+ function toBufferBE(num, width) {
10289
+ {
10290
+ const hex = num.toString(16);
10291
+ return Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
10292
+ }
10293
+ }
10294
+ browser.toBufferBE = toBufferBE;
10295
+
10296
+ const bigInt = (length) => (property) => {
10297
+ const layout = blob(length, property);
10298
+ const { encode, decode } = encodeDecode(layout);
10299
+ const bigIntLayout = layout;
10300
+ bigIntLayout.decode = (buffer, offset) => {
10301
+ const src = decode(buffer, offset);
10302
+ return toBigIntLE_1(Buffer.from(src));
10303
+ };
10304
+ bigIntLayout.encode = (bigInt, buffer, offset) => {
10305
+ const src = toBufferLE_1(bigInt, length);
10306
+ return encode(src, buffer, offset);
10307
+ };
10308
+ return bigIntLayout;
10309
+ };
10310
+ const u64 = bigInt(8);
10311
+
10312
+ const publicKey = (property) => {
10313
+ const layout = blob(32, property);
10314
+ const { encode, decode } = encodeDecode(layout);
10315
+ const publicKeyLayout = layout;
10316
+ publicKeyLayout.decode = (buffer, offset) => {
10317
+ const src = decode(buffer, offset);
10318
+ return new PublicKey(src);
10319
+ };
10320
+ publicKeyLayout.encode = (publicKey, buffer, offset) => {
10321
+ const src = publicKey.toBuffer();
10322
+ return encode(src, buffer, offset);
10323
+ };
10324
+ return publicKeyLayout;
10325
+ };
10326
+
10327
+ var AccountState;
10328
+ (function (AccountState) {
10329
+ AccountState[AccountState["Uninitialized"] = 0] = "Uninitialized";
10330
+ AccountState[AccountState["Initialized"] = 1] = "Initialized";
10331
+ AccountState[AccountState["Frozen"] = 2] = "Frozen";
10332
+ })(AccountState || (AccountState = {}));
10333
+ const AccountLayout = struct([
10334
+ publicKey('mint'),
10335
+ publicKey('owner'),
10336
+ u64('amount'),
10337
+ u32('delegateOption'),
10338
+ publicKey('delegate'),
10339
+ u8('state'),
10340
+ u32('isNativeOption'),
10341
+ u64('isNative'),
10342
+ u64('delegatedAmount'),
10343
+ u32('closeAuthorityOption'),
10344
+ publicKey('closeAuthority'),
10345
+ ]);
10346
+ var AccountType;
10347
+ (function (AccountType) {
10348
+ AccountType[AccountType["System"] = 0] = "System";
10349
+ AccountType[AccountType["Token"] = 1] = "Token";
10350
+ AccountType[AccountType["CorrectATA"] = 2] = "CorrectATA";
10351
+ AccountType[AccountType["Unknown"] = 3] = "Unknown";
10352
+ AccountType[AccountType["NotExists"] = 4] = "NotExists";
10353
+ })(AccountType || (AccountType = {}));
10354
+ /**
10355
+ * Builds instruction for creation of associated wallet for specified token
10356
+ * @param tokenMint mint account of SPL-token
10357
+ * @param associatedAccount associated account address
10358
+ * @param owner owner of the associated account
10359
+ * @param payer who pays for account creation
10360
+ */
10361
+ function createAssociatedWalletInstruction(tokenMint, associatedAccount, owner, payer, associatedTokenProramId) {
10362
+ tokenMint = new PublicKey(tokenMint);
10363
+ payer = new PublicKey(payer);
10364
+ owner = new PublicKey(owner);
10365
+ return new TransactionInstruction({
10366
+ programId: associatedTokenProramId || ASSOCIATED_TOKEN_PROGRAM_ID,
10367
+ data: buffer.Buffer.from([1]),
10368
+ keys: [
10369
+ {
10370
+ pubkey: payer,
10371
+ isSigner: true,
10372
+ isWritable: true,
10373
+ },
10374
+ {
10375
+ pubkey: associatedAccount,
10376
+ isSigner: false,
10377
+ isWritable: true,
10378
+ },
10379
+ {
10380
+ pubkey: owner,
10381
+ isSigner: false,
10382
+ isWritable: false,
10383
+ },
10384
+ {
10385
+ pubkey: tokenMint,
10386
+ isSigner: false,
10387
+ isWritable: false,
10388
+ },
10389
+ {
10390
+ pubkey: SystemProgram.programId,
10391
+ isSigner: false,
10392
+ isWritable: false,
10393
+ },
10394
+ {
10395
+ pubkey: TOKEN_PROGRAM_ID,
10396
+ isSigner: false,
10397
+ isWritable: false,
10398
+ },
10399
+ ],
10400
+ });
10401
+ }
10402
+ function parseSplAccount(data) {
10403
+ try {
10404
+ return AccountLayout.decode(data);
10405
+ }
10406
+ catch (e) {
10407
+ console.error(e);
10408
+ }
10409
+ return null;
10410
+ }
10411
+ function isWalletCorrectATA(walletAddress, data) {
10412
+ const decoded = parseSplAccount(data);
10413
+ if (!decoded)
10414
+ return false;
10415
+ const [realAta] = findAssociatedTokenAddress(decoded.owner, decoded.mint);
10416
+ return realAta.equals(new PublicKey(walletAddress));
10417
+ }
10418
+ /**
10419
+ * Requests account from blockchain and returns result with account type
10420
+ * @param account address of account
10421
+ * @returns account info and account type
10422
+ */
10423
+ function getAccountWithType(connection, account) {
10424
+ return __awaiter(this, void 0, void 0, function* () {
10425
+ account = new PublicKey(account);
10426
+ const accountData = yield getAccountInfo(connection, account);
10427
+ if (!accountData)
10428
+ return [null, AccountType.NotExists];
10429
+ if (accountData.owner.equals(TOKEN_PROGRAM_ID)) {
10430
+ return isWalletCorrectATA(account, accountData.data) ? [accountData, AccountType.CorrectATA] : [accountData, AccountType.Token];
10431
+ }
10432
+ if (accountData.owner.equals(SystemProgram.programId))
10433
+ return [accountData, AccountType.System];
10434
+ return [accountData, AccountType.Unknown];
10435
+ });
10436
+ }
10437
+ /**
10438
+ * Returns balance of specified wallet in native tokens
10439
+ * @param wallet wallet to inspect
10440
+ */
10441
+ function getNativeWalletBalance(connection, wallet) {
10442
+ return __awaiter(this, void 0, void 0, function* () {
10443
+ wallet = new PublicKey(wallet);
10444
+ const result = yield connection.getBalance(wallet);
10445
+ return new BN$1(result.toString());
10446
+ });
10447
+ }
10448
+ /**
10449
+ * Returns balance of associated wallet in SPL-tokens
10450
+ * @param originalWallet native tokens wallet address
10451
+ * @param tokenMint mint of SPL-Token
10452
+ */
10453
+ function getAssocSPLWalletBalance(connection, originalWallet, tokenMint) {
10454
+ return __awaiter(this, void 0, void 0, function* () {
10455
+ originalWallet = new PublicKey(originalWallet);
10456
+ tokenMint = new PublicKey(tokenMint);
10457
+ const [wallet] = findAssociatedTokenAddress(originalWallet, tokenMint);
10458
+ const result = yield connection.getTokenAccountBalance(wallet, "finalized");
10459
+ return new BN$1(result.value.amount);
10460
+ });
10461
+ }
10462
+ /**
10463
+ * Returns balance of specified wallet in SPL-tokens
10464
+ * @param wallet spl-tokens wallet address
10465
+ */
10466
+ function getSPLWalletBalance(connection, wallet) {
10467
+ return __awaiter(this, void 0, void 0, function* () {
10468
+ wallet = new PublicKey(wallet);
10469
+ const result = yield connection.getTokenAccountBalance(wallet, "finalized");
10470
+ return new BN$1(result.value.amount);
10471
+ });
10472
+ }
10473
+ /**
10474
+ * Gets list of user's SPL-token accounts
10475
+ * @param owner owner of the SPL wallets
10476
+ * @returns list of accounts with amount on them
10477
+ */
10478
+ function getAllTokenAccountsWithBalances(connection, owner) {
10479
+ return __awaiter(this, void 0, void 0, function* () {
10480
+ const walletsData = yield connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { programId: TOKEN_PROGRAM_ID });
10481
+ const wallets = walletsData.value;
10482
+ return wallets.map((wallet) => {
10483
+ const tokenInfo = wallet.account.data.parsed;
10484
+ return {
10485
+ address: wallet.pubkey,
10486
+ mint: new PublicKey(tokenInfo.info.mint),
10487
+ amount: new BN$1(tokenInfo.info.tokenAmount.amount),
10488
+ decimals: tokenInfo.info.tokenAmount.decimals,
10489
+ isInitialized: true,
10490
+ isNative: tokenInfo.info.isNative,
10491
+ owner: new PublicKey(tokenInfo.info.owner),
10492
+ };
10493
+ });
10494
+ });
10495
+ }
10496
+ /**
10497
+ * Gets list of user's tokenMint token accounts
10498
+ * @param tokenMint
10499
+ * @param owner owner of the wallets
10500
+ * @returns list of accounts with amount on them
10501
+ */
10502
+ function getTokenAccountsWithBalance(connection, tokenMint, owner) {
10503
+ return __awaiter(this, void 0, void 0, function* () {
10504
+ const walletsData = yield connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { mint: new PublicKey(tokenMint) });
10505
+ const wallets = walletsData.value;
10506
+ return wallets.map((wallet) => {
10507
+ const tokenInfo = wallet.account.data.parsed;
10508
+ return {
10509
+ address: wallet.pubkey,
10510
+ mint: new PublicKey(tokenInfo.info.mint),
10511
+ amount: new BN$1(tokenInfo.info.tokenAmount.amount),
10512
+ decimals: tokenInfo.info.tokenAmount.decimals,
10513
+ isInitialized: true,
10514
+ isNative: tokenInfo.info.isNative,
10515
+ owner: new PublicKey(tokenInfo.info.owner),
10516
+ };
10517
+ });
10518
+ });
10519
+ }
10520
+ /**
10521
+ * Builds transaction to transfer&wrap native sol from src wallet to dst wallet
10522
+ * @param amount number of lamports to transfer and wrap
10523
+ * @param transferFrom source native account
10524
+ * @param transferTo destination wallet
10525
+ * @returns transaction to transfer&wrap sol
10526
+ */
10527
+ function buildReplenishWsolBalanceTransaction(amount, transferFrom, transferTo) {
10528
+ transferFrom = new PublicKey(transferFrom);
10529
+ transferTo = new PublicKey(transferTo);
10530
+ const tx = new Transaction();
10531
+ tx.add(SystemProgram.transfer({ fromPubkey: transferFrom, toPubkey: transferTo, lamports: new BN$1(amount).toNumber() }));
10532
+ tx.add(
10533
+ // sync native
10534
+ new TransactionInstruction({
10535
+ keys: [{ pubkey: transferTo, isSigner: false, isWritable: true }],
10536
+ programId: TOKEN_PROGRAM_ID,
10537
+ data: buffer.Buffer.from([17]),
10538
+ }));
10539
+ tx.feePayer = transferFrom;
10540
+ return tx;
10541
+ }
10542
+ /**
10543
+ * Builds transaction that wraps specified amount of lamports into spl, if account is missing will create it
10544
+ * @param amount lamports to wrap, ATA will contain exact amount of lamports
10545
+ * @param owner owner of created wallet
10546
+ */
10547
+ function updateWsolBalance(connection, amount, owner) {
10548
+ return __awaiter(this, void 0, void 0, function* () {
10549
+ owner = new PublicKey(owner);
10550
+ const tx = new Transaction();
10551
+ const accountSize = 165;
10552
+ const [wSolATA] = findAssociatedTokenAddress(owner, WRAPPED_SOL_MINT);
10553
+ const existingATA = yield getAccountInfo(connection, wSolATA);
10554
+ let amountToWrap = new BN$1(amount);
10555
+ if (existingATA === null) {
10556
+ tx.add(SystemProgram.createAccount({
10557
+ fromPubkey: owner,
10558
+ space: accountSize,
10559
+ programId: TOKEN_PROGRAM_ID,
10560
+ newAccountPubkey: wSolATA,
10561
+ lamports: yield connection.getMinimumBalanceForRentExemption(accountSize),
10562
+ }));
10563
+ }
10564
+ else {
10565
+ const parsed = parseSplAccount(existingATA.data);
10566
+ if (!parsed)
10567
+ throw new Error("WSol account exists, but failed to decode its content");
10568
+ const parsedAmount = new BN$1(parsed.amount.toString());
10569
+ if (amountToWrap.lte(parsedAmount))
10570
+ return null; // don't need to wrap
10571
+ amountToWrap = parsedAmount.sub(amountToWrap);
10572
+ }
10573
+ const replenishTx = buildReplenishWsolBalanceTransaction(amountToWrap, owner, wSolATA);
10574
+ tx.add(replenishTx);
10575
+ return tx;
10576
+ });
10577
+ }
10578
+ /**
10579
+ * Checks existance of associated wallet for specified token
10580
+ * @param mintAccount mint account of SPL-token
10581
+ * @param originalWallet account of solana wallet
10582
+ * @returns true if account exists
10583
+ */
10584
+ function checkIfAssociatedWalletExists(connection, mintAccount, originalWallet) {
10585
+ return __awaiter(this, void 0, void 0, function* () {
10586
+ const [walletAccount] = findAssociatedTokenAddress(originalWallet, mintAccount);
10587
+ const accountData = yield getAccountInfo(connection, walletAccount);
10588
+ return accountData !== null;
10589
+ });
10590
+ }
10591
+
10592
+ var spl = /*#__PURE__*/Object.freeze({
10593
+ __proto__: null,
10594
+ get AccountType () { return AccountType; },
10595
+ createAssociatedWalletInstruction: createAssociatedWalletInstruction,
10596
+ parseSplAccount: parseSplAccount,
10597
+ isWalletCorrectATA: isWalletCorrectATA,
10598
+ getAccountWithType: getAccountWithType,
10599
+ getNativeWalletBalance: getNativeWalletBalance,
10600
+ getAssocSPLWalletBalance: getAssocSPLWalletBalance,
10601
+ getSPLWalletBalance: getSPLWalletBalance,
10602
+ getAllTokenAccountsWithBalances: getAllTokenAccountsWithBalances,
10603
+ getTokenAccountsWithBalance: getTokenAccountsWithBalance,
10604
+ buildReplenishWsolBalanceTransaction: buildReplenishWsolBalanceTransaction,
10605
+ updateWsolBalance: updateWsolBalance,
10606
+ checkIfAssociatedWalletExists: checkIfAssociatedWalletExists
10607
+ });
10608
+
10609
+ export { ASSOCIATED_TOKEN_PROGRAM_ID, DeBridgeResolver, PmmDstResolver, PmmSrcResolver, TOKEN_METADATA_PROGRAM_ID, TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT, constants, crypto, findAssociatedTokenAddress, findAssociatedTokenAddressSync, getTokenMetadataAddress, helpers, interfaces, spl };
7899
10610
  //# sourceMappingURL=index.js.map