@debridge-finance/solana-utils 5.3.2 → 5.4.1

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.
@@ -7434,24 +7434,24 @@ var memoize = microMemoize.exports;
7434
7434
 
7435
7435
  const TOKEN_2022_PROGRAM_ID = new PublicKey("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");
7436
7436
  const TOKEN_METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
7437
- const TOKEN_PROGRAM_ID = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
7437
+ const TOKEN_PROGRAM_ID$1 = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
7438
7438
  const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
7439
7439
  const WRAPPED_SOL_MINT = new PublicKey("So11111111111111111111111111111111111111112");
7440
- function findAssociatedTokenAddress(wallet, tokenMint, tokenProgramId = TOKEN_PROGRAM_ID, associatedTokenProramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
7440
+ function findAssociatedTokenAddress(wallet, tokenMint, tokenProgramId = TOKEN_PROGRAM_ID$1, associatedTokenProramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
7441
7441
  return PublicKey.findProgramAddressSync([wallet.toBytes(), tokenProgramId.toBytes(), tokenMint.toBytes()], associatedTokenProramId);
7442
7442
  }
7443
7443
  /**
7444
7444
  * @deprecated same as findAssociatedTokenAddress
7445
7445
  */
7446
- function findAssociatedTokenAddressSync(wallet, tokenMint, tokenProgramId = TOKEN_PROGRAM_ID, associatedTokenProramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
7446
+ function findAssociatedTokenAddressSync(wallet, tokenMint, tokenProgramId = TOKEN_PROGRAM_ID$1, associatedTokenProramId = ASSOCIATED_TOKEN_PROGRAM_ID) {
7447
7447
  return PublicKey.findProgramAddressSync([wallet.toBytes(), tokenProgramId.toBytes(), tokenMint.toBytes()], associatedTokenProramId);
7448
7448
  }
7449
- function getTokenMetadataAddress(tokenMint, tokenMetedataProgramId) {
7449
+ function getTokenMetadataAddress(tokenMint, tokenMetadataProgramId) {
7450
7450
  return PublicKey.findProgramAddressSync([
7451
7451
  buffer.Buffer.from("metadata"),
7452
- tokenMetedataProgramId.toBytes(),
7452
+ tokenMetadataProgramId.toBytes(),
7453
7453
  tokenMint.toBytes(),
7454
- ], tokenMetedataProgramId);
7454
+ ], tokenMetadataProgramId);
7455
7455
  }
7456
7456
  const deBridge$1 = {
7457
7457
  getClaimMarkerAddress: (DEBRIDGE_PROGRAM_ID) => PublicKey.findProgramAddressSync([buffer.Buffer.from(deBridge$2.Seeds.CLAIM_MARKER)], DEBRIDGE_PROGRAM_ID),
@@ -7593,6 +7593,17 @@ const dlnDstResolver = (programId) => {
7593
7593
  return new Resolver(programId, DlnDst, dstMemoizeList);
7594
7594
  };
7595
7595
 
7596
+ /** Address of the SPL Token program */
7597
+ const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
7598
+ /** Address of the SPL Token 2022 program */
7599
+ new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
7600
+ /** Address of the SPL Associated Token Account program */
7601
+ new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
7602
+ /** Address of the special mint for wrapped native SOL in spl-token */
7603
+ new PublicKey('So11111111111111111111111111111111111111112');
7604
+ /** Address of the special mint for wrapped native SOL in spl-token-2022 */
7605
+ new PublicKey('9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP');
7606
+
7596
7607
  var Layout$4 = {};
7597
7608
 
7598
7609
  /* The MIT License (MIT)
@@ -9992,903 +10003,439 @@ const publicKey$4 = (property) => {
9992
10003
  return publicKeyLayout;
9993
10004
  };
9994
10005
 
10006
+ /** Base class for errors */
10007
+ class TokenError extends Error {
10008
+ constructor(message) {
10009
+ super(message);
10010
+ }
10011
+ }
10012
+ /** Thrown if an account is not found at the expected address */
10013
+ class TokenAccountNotFoundError extends TokenError {
10014
+ constructor() {
10015
+ super(...arguments);
10016
+ this.name = 'TokenAccountNotFoundError';
10017
+ }
10018
+ }
10019
+ /** Thrown if a program state account is not owned by the expected token program */
10020
+ class TokenInvalidAccountOwnerError extends TokenError {
10021
+ constructor() {
10022
+ super(...arguments);
10023
+ this.name = 'TokenInvalidAccountOwnerError';
10024
+ }
10025
+ }
10026
+ /** Thrown if the byte length of an program state account doesn't match the expected size */
10027
+ class TokenInvalidAccountSizeError extends TokenError {
10028
+ constructor() {
10029
+ super(...arguments);
10030
+ this.name = 'TokenInvalidAccountSizeError';
10031
+ }
10032
+ }
10033
+ /** Thrown if the mint of a token account doesn't match the expected mint */
10034
+ class TokenInvalidMintError extends TokenError {
10035
+ constructor() {
10036
+ super(...arguments);
10037
+ this.name = 'TokenInvalidMintError';
10038
+ }
10039
+ }
10040
+
10041
+ /** Instructions defined by the program */
10042
+ var TokenInstruction;
10043
+ (function (TokenInstruction) {
10044
+ TokenInstruction[TokenInstruction["InitializeMint"] = 0] = "InitializeMint";
10045
+ TokenInstruction[TokenInstruction["InitializeAccount"] = 1] = "InitializeAccount";
10046
+ TokenInstruction[TokenInstruction["InitializeMultisig"] = 2] = "InitializeMultisig";
10047
+ TokenInstruction[TokenInstruction["Transfer"] = 3] = "Transfer";
10048
+ TokenInstruction[TokenInstruction["Approve"] = 4] = "Approve";
10049
+ TokenInstruction[TokenInstruction["Revoke"] = 5] = "Revoke";
10050
+ TokenInstruction[TokenInstruction["SetAuthority"] = 6] = "SetAuthority";
10051
+ TokenInstruction[TokenInstruction["MintTo"] = 7] = "MintTo";
10052
+ TokenInstruction[TokenInstruction["Burn"] = 8] = "Burn";
10053
+ TokenInstruction[TokenInstruction["CloseAccount"] = 9] = "CloseAccount";
10054
+ TokenInstruction[TokenInstruction["FreezeAccount"] = 10] = "FreezeAccount";
10055
+ TokenInstruction[TokenInstruction["ThawAccount"] = 11] = "ThawAccount";
10056
+ TokenInstruction[TokenInstruction["TransferChecked"] = 12] = "TransferChecked";
10057
+ TokenInstruction[TokenInstruction["ApproveChecked"] = 13] = "ApproveChecked";
10058
+ TokenInstruction[TokenInstruction["MintToChecked"] = 14] = "MintToChecked";
10059
+ TokenInstruction[TokenInstruction["BurnChecked"] = 15] = "BurnChecked";
10060
+ TokenInstruction[TokenInstruction["InitializeAccount2"] = 16] = "InitializeAccount2";
10061
+ TokenInstruction[TokenInstruction["SyncNative"] = 17] = "SyncNative";
10062
+ TokenInstruction[TokenInstruction["InitializeAccount3"] = 18] = "InitializeAccount3";
10063
+ TokenInstruction[TokenInstruction["InitializeMultisig2"] = 19] = "InitializeMultisig2";
10064
+ TokenInstruction[TokenInstruction["InitializeMint2"] = 20] = "InitializeMint2";
10065
+ TokenInstruction[TokenInstruction["GetAccountDataSize"] = 21] = "GetAccountDataSize";
10066
+ TokenInstruction[TokenInstruction["InitializeImmutableOwner"] = 22] = "InitializeImmutableOwner";
10067
+ TokenInstruction[TokenInstruction["AmountToUiAmount"] = 23] = "AmountToUiAmount";
10068
+ TokenInstruction[TokenInstruction["UiAmountToAmount"] = 24] = "UiAmountToAmount";
10069
+ TokenInstruction[TokenInstruction["InitializeMintCloseAuthority"] = 25] = "InitializeMintCloseAuthority";
10070
+ TokenInstruction[TokenInstruction["TransferFeeExtension"] = 26] = "TransferFeeExtension";
10071
+ TokenInstruction[TokenInstruction["ConfidentialTransferExtension"] = 27] = "ConfidentialTransferExtension";
10072
+ TokenInstruction[TokenInstruction["DefaultAccountStateExtension"] = 28] = "DefaultAccountStateExtension";
10073
+ TokenInstruction[TokenInstruction["Reallocate"] = 29] = "Reallocate";
10074
+ TokenInstruction[TokenInstruction["MemoTransferExtension"] = 30] = "MemoTransferExtension";
10075
+ TokenInstruction[TokenInstruction["CreateNativeMint"] = 31] = "CreateNativeMint";
10076
+ TokenInstruction[TokenInstruction["InitializeNonTransferableMint"] = 32] = "InitializeNonTransferableMint";
10077
+ TokenInstruction[TokenInstruction["InterestBearingMintExtension"] = 33] = "InterestBearingMintExtension";
10078
+ TokenInstruction[TokenInstruction["CpiGuardExtension"] = 34] = "CpiGuardExtension";
10079
+ TokenInstruction[TokenInstruction["InitializePermanentDelegate"] = 35] = "InitializePermanentDelegate";
10080
+ TokenInstruction[TokenInstruction["TransferHookExtension"] = 36] = "TransferHookExtension";
10081
+ // ConfidentialTransferFeeExtension = 37,
10082
+ // WithdrawalExcessLamports = 38,
10083
+ TokenInstruction[TokenInstruction["MetadataPointerExtension"] = 39] = "MetadataPointerExtension";
10084
+ TokenInstruction[TokenInstruction["GroupPointerExtension"] = 40] = "GroupPointerExtension";
10085
+ TokenInstruction[TokenInstruction["GroupMemberPointerExtension"] = 41] = "GroupMemberPointerExtension";
10086
+ // ConfidentialMintBurnExtension = 42,
10087
+ TokenInstruction[TokenInstruction["ScaledUiAmountExtension"] = 43] = "ScaledUiAmountExtension";
10088
+ TokenInstruction[TokenInstruction["PausableExtension"] = 44] = "PausableExtension";
10089
+ })(TokenInstruction || (TokenInstruction = {}));
10090
+
10091
+ /** TODO: docs */
10092
+ struct$1([
10093
+ u8$1('instruction'),
10094
+ u64$1('amount'),
10095
+ ]);
10096
+
10097
+ var AccountType$1;
10098
+ (function (AccountType) {
10099
+ AccountType[AccountType["Uninitialized"] = 0] = "Uninitialized";
10100
+ AccountType[AccountType["Mint"] = 1] = "Mint";
10101
+ AccountType[AccountType["Account"] = 2] = "Account";
10102
+ })(AccountType$1 || (AccountType$1 = {}));
10103
+ const ACCOUNT_TYPE_SIZE = 1;
10104
+
10105
+ /** Buffer layout for de/serializing a multisig */
10106
+ const MultisigLayout = struct$1([
10107
+ u8$1('m'),
10108
+ u8$1('n'),
10109
+ bool$1('isInitialized'),
10110
+ publicKey$4('signer1'),
10111
+ publicKey$4('signer2'),
10112
+ publicKey$4('signer3'),
10113
+ publicKey$4('signer4'),
10114
+ publicKey$4('signer5'),
10115
+ publicKey$4('signer6'),
10116
+ publicKey$4('signer7'),
10117
+ publicKey$4('signer8'),
10118
+ publicKey$4('signer9'),
10119
+ publicKey$4('signer10'),
10120
+ publicKey$4('signer11'),
10121
+ ]);
10122
+ /** Byte length of a multisig */
10123
+ const MULTISIG_SIZE = MultisigLayout.span;
10124
+
10125
+ /** Token account state as stored by the program */
9995
10126
  var AccountState$1;
9996
10127
  (function (AccountState) {
9997
10128
  AccountState[AccountState["Uninitialized"] = 0] = "Uninitialized";
9998
10129
  AccountState[AccountState["Initialized"] = 1] = "Initialized";
9999
10130
  AccountState[AccountState["Frozen"] = 2] = "Frozen";
10000
10131
  })(AccountState$1 || (AccountState$1 = {}));
10132
+ /** Buffer layout for de/serializing a token account */
10001
10133
  const AccountLayout$1 = struct$1([
10002
- publicKey$4("mint"),
10003
- publicKey$4("owner"),
10004
- u64$1("amount"),
10005
- u32$1("delegateOption"),
10006
- publicKey$4("delegate"),
10007
- u8$1("state"),
10008
- u32$1("isNativeOption"),
10009
- u64$1("isNative"),
10010
- u64$1("delegatedAmount"),
10011
- u32$1("closeAuthorityOption"),
10012
- publicKey$4("closeAuthority"),
10134
+ publicKey$4('mint'),
10135
+ publicKey$4('owner'),
10136
+ u64$1('amount'),
10137
+ u32$1('delegateOption'),
10138
+ publicKey$4('delegate'),
10139
+ u8$1('state'),
10140
+ u32$1('isNativeOption'),
10141
+ u64$1('isNative'),
10142
+ u64$1('delegatedAmount'),
10143
+ u32$1('closeAuthorityOption'),
10144
+ publicKey$4('closeAuthority'),
10013
10145
  ]);
10014
- var AccountType$1;
10015
- (function (AccountType) {
10016
- AccountType[AccountType["System"] = 0] = "System";
10017
- AccountType[AccountType["Token"] = 1] = "Token";
10018
- AccountType[AccountType["CorrectATA"] = 2] = "CorrectATA";
10019
- AccountType[AccountType["Unknown"] = 3] = "Unknown";
10020
- AccountType[AccountType["NotExists"] = 4] = "NotExists";
10021
- })(AccountType$1 || (AccountType$1 = {}));
10022
- /**
10023
- * Get name, symbol and decimals for provided token
10024
- * @param connection solana web3 connection
10025
- * @param tokenAddress address to get metaplex info for
10026
- * @returns
10027
- */
10028
- function getTokenInfo(connection, tokenAddress) {
10029
- return __awaiter(this, void 0, void 0, function* () {
10030
- const tokenMetaProgramId = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
10031
- const findMetaplexMetadataPda = (tokenMint) => PublicKey.findProgramAddressSync([
10032
- buffer.Buffer.from("metadata", "utf-8"),
10033
- tokenMetaProgramId.toBuffer(),
10034
- tokenMint.toBuffer(),
10035
- ], tokenMetaProgramId)[0];
10036
- const decodeMetaplexMetadataPartial = (data) => {
10037
- const rawName = data.subarray(65 + 4, 65 + 36); // omit first 4 bytes, size is already hardcoded
10038
- const rawSymbol = data.subarray(101 + 4, 115); // omit first 4 bytes, size is already hardcoded
10039
- const rawUri = data.subarray(115 + 4, 204); // omit first 4 bytes, size is already hardcoded
10040
- return {
10041
- uri: rawUri.toString("utf-8").replace(/\u0000/g, ""),
10042
- symbol: rawSymbol.toString("utf-8").replace(/\u0000/g, ""),
10043
- name: rawName.toString("utf-8").replace(/\u0000/g, ""),
10044
- };
10045
- };
10046
- const pda = findMetaplexMetadataPda(tokenAddress);
10047
- const [tokenAccount, pdaAccount] = yield connection.getMultipleAccountsInfo([
10048
- tokenAddress,
10049
- pda,
10050
- ]);
10051
- if (tokenAccount === null ||
10052
- pdaAccount === null ||
10053
- (pdaAccount === null || pdaAccount === void 0 ? void 0 : pdaAccount.lamports) === 0) {
10054
- return null;
10055
- }
10056
- // parse token account
10057
- // mint_authority - coption(pubkey) = 4 or 36
10058
- // supply - u64 = 8
10059
- // decimals - u8
10060
- let decimalsOffset = 12;
10061
- if (tokenAccount.data[0] === 1)
10062
- decimalsOffset += 32;
10063
- const decimals = tokenAccount.data[decimalsOffset];
10064
- const { name, symbol, uri } = decodeMetaplexMetadataPartial(pdaAccount.data);
10065
- return {
10066
- address: tokenAddress,
10067
- decimals,
10068
- name,
10069
- symbol,
10070
- json: uri,
10071
- };
10072
- });
10146
+ /** Byte length of a token account */
10147
+ const ACCOUNT_SIZE = AccountLayout$1.span;
10148
+
10149
+ var CpiGuardInstruction;
10150
+ (function (CpiGuardInstruction) {
10151
+ CpiGuardInstruction[CpiGuardInstruction["Enable"] = 0] = "Enable";
10152
+ CpiGuardInstruction[CpiGuardInstruction["Disable"] = 1] = "Disable";
10153
+ })(CpiGuardInstruction || (CpiGuardInstruction = {}));
10154
+ /** TODO: docs */
10155
+ struct$1([u8$1('instruction'), u8$1('cpiGuardInstruction')]);
10156
+
10157
+ /** Buffer layout for de/serializing a CPI Guard extension */
10158
+ const CpiGuardLayout = struct$1([bool$1('lockCpi')]);
10159
+ CpiGuardLayout.span;
10160
+
10161
+ var DefaultAccountStateInstruction;
10162
+ (function (DefaultAccountStateInstruction) {
10163
+ DefaultAccountStateInstruction[DefaultAccountStateInstruction["Initialize"] = 0] = "Initialize";
10164
+ DefaultAccountStateInstruction[DefaultAccountStateInstruction["Update"] = 1] = "Update";
10165
+ })(DefaultAccountStateInstruction || (DefaultAccountStateInstruction = {}));
10166
+ /** TODO: docs */
10167
+ struct$1([
10168
+ u8$1('instruction'),
10169
+ u8$1('defaultAccountStateInstruction'),
10170
+ u8$1('accountState'),
10171
+ ]);
10172
+
10173
+ /** Buffer layout for de/serializing a transfer fee config extension */
10174
+ const DefaultAccountStateLayout = struct$1([u8$1('state')]);
10175
+ DefaultAccountStateLayout.span;
10176
+
10177
+ // src/codes.ts
10178
+ var SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY$1 = 8078e3;
10179
+ var SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH$1 = 8078001;
10180
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH$1 = 8078004;
10181
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH$1 = 8078005;
10182
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH$1 = 8078006;
10183
+ var SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS$1 = 8078007;
10184
+ var SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE$1 = 8078011;
10185
+
10186
+ // src/context.ts
10187
+ function encodeValue$1(value) {
10188
+ if (Array.isArray(value)) {
10189
+ const commaSeparatedValues = value.map(encodeValue$1).join(
10190
+ "%2C%20"
10191
+ /* ", " */
10192
+ );
10193
+ return "%5B" + commaSeparatedValues + /* "]" */
10194
+ "%5D";
10195
+ } else if (typeof value === "bigint") {
10196
+ return `${value}n`;
10197
+ } else {
10198
+ return encodeURIComponent(
10199
+ String(
10200
+ value != null && Object.getPrototypeOf(value) === null ? (
10201
+ // Plain objects with no prototype don't have a `toString` method.
10202
+ // Convert them before stringifying them.
10203
+ { ...value }
10204
+ ) : value
10205
+ )
10206
+ );
10207
+ }
10073
10208
  }
10074
- /**
10075
- * Builds instruction for creation of associated wallet for specified token
10076
- * @param tokenMint mint account of SPL-token
10077
- * @param associatedAccount associated account address
10078
- * @param owner owner of the associated account
10079
- * @param payer who pays for account creation
10080
- */
10081
- function createAssociatedWalletInstruction(tokenMint, associatedAccount, owner, payer, associatedTokenProramId) {
10082
- tokenMint = new PublicKey(tokenMint);
10083
- payer = new PublicKey(payer);
10084
- owner = new PublicKey(owner);
10085
- return new TransactionInstruction({
10086
- programId: associatedTokenProramId || ASSOCIATED_TOKEN_PROGRAM_ID,
10087
- data: buffer.Buffer.from([1]),
10088
- keys: [
10089
- {
10090
- pubkey: payer,
10091
- isSigner: true,
10092
- isWritable: true,
10093
- },
10094
- {
10095
- pubkey: associatedAccount,
10096
- isSigner: false,
10097
- isWritable: true,
10098
- },
10099
- {
10100
- pubkey: owner,
10101
- isSigner: false,
10102
- isWritable: false,
10103
- },
10104
- {
10105
- pubkey: tokenMint,
10106
- isSigner: false,
10107
- isWritable: false,
10108
- },
10109
- {
10110
- pubkey: SystemProgram.programId,
10111
- isSigner: false,
10112
- isWritable: false,
10113
- },
10114
- {
10115
- pubkey: TOKEN_PROGRAM_ID,
10116
- isSigner: false,
10117
- isWritable: false,
10118
- },
10119
- ],
10120
- });
10209
+ function encodeObjectContextEntry$1([key, value]) {
10210
+ return `${key}=${encodeValue$1(value)}`;
10121
10211
  }
10122
- function parseSplAccount(dataOrInfo) {
10123
- if (dataOrInfo === null) {
10124
- return null;
10125
- }
10126
- const data = "executable" in dataOrInfo ? dataOrInfo.data : dataOrInfo;
10127
- // if (data.length === 82) return null; // token mint
10128
- try {
10129
- return AccountLayout$1.decode(data);
10212
+ function encodeContextObject$1(context) {
10213
+ const searchParamsString = Object.entries(context).map(encodeObjectContextEntry$1).join("&");
10214
+ return btoa(searchParamsString);
10215
+ }
10216
+ function getErrorMessage$1(code, context = {}) {
10217
+ {
10218
+ let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;
10219
+ if (Object.keys(context).length) {
10220
+ decodingAdviceMessage += ` '${encodeContextObject$1(context)}'`;
10130
10221
  }
10131
- catch (e) {
10132
- console.error(e);
10222
+ return `${decodingAdviceMessage}\``;
10223
+ }
10224
+ }
10225
+ var SolanaError$1 = class extends Error {
10226
+ cause = this.cause;
10227
+ context;
10228
+ constructor(...[code, contextAndErrorOptions]) {
10229
+ let context;
10230
+ let errorOptions;
10231
+ if (contextAndErrorOptions) {
10232
+ const { cause, ...contextRest } = contextAndErrorOptions;
10233
+ if (cause) {
10234
+ errorOptions = { cause };
10235
+ }
10236
+ if (Object.keys(contextRest).length > 0) {
10237
+ context = contextRest;
10238
+ }
10133
10239
  }
10134
- return null;
10240
+ const message = getErrorMessage$1(code, context);
10241
+ super(message, errorOptions);
10242
+ this.context = {
10243
+ __code: code,
10244
+ ...context
10245
+ };
10246
+ this.name = "SolanaError";
10247
+ }
10248
+ };
10249
+
10250
+ var padBytes$1 = (bytes, length) => {
10251
+ if (bytes.length >= length) return bytes;
10252
+ const paddedBytes = new Uint8Array(length).fill(0);
10253
+ paddedBytes.set(bytes);
10254
+ return paddedBytes;
10255
+ };
10256
+ var fixBytes$1 = (bytes, length) => padBytes$1(bytes.length <= length ? bytes : bytes.slice(0, length), length);
10257
+ function getEncodedSize$1(value, encoder) {
10258
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
10135
10259
  }
10136
- function isWalletCorrectATA(walletAddress, data) {
10137
- const decoded = parseSplAccount(data);
10138
- if (!decoded)
10139
- return false;
10140
- const [realAta] = findAssociatedTokenAddress(decoded.owner, decoded.mint);
10141
- return realAta.equals(new PublicKey(walletAddress));
10260
+ function createEncoder$1(encoder) {
10261
+ return Object.freeze({
10262
+ ...encoder,
10263
+ encode: (value) => {
10264
+ const bytes = new Uint8Array(getEncodedSize$1(value, encoder));
10265
+ encoder.write(value, bytes, 0);
10266
+ return bytes;
10267
+ }
10268
+ });
10142
10269
  }
10143
- /**
10144
- * Requests account from blockchain and returns result with account type
10145
- * @param account address of account
10146
- * @returns account info and account type
10147
- */
10148
- function getAccountWithType(connection, account) {
10149
- return __awaiter(this, void 0, void 0, function* () {
10150
- account = new PublicKey(account);
10151
- const accountData = yield getAccountInfo(connection, account);
10152
- if (!accountData)
10153
- return [null, AccountType$1.NotExists];
10154
- if (accountData.owner.equals(TOKEN_PROGRAM_ID)) {
10155
- return isWalletCorrectATA(account, accountData.data)
10156
- ? [accountData, AccountType$1.CorrectATA]
10157
- : [accountData, AccountType$1.Token];
10158
- }
10159
- if (accountData.owner.equals(SystemProgram.programId))
10160
- return [accountData, AccountType$1.System];
10161
- return [accountData, AccountType$1.Unknown];
10162
- });
10270
+ function createDecoder$1(decoder) {
10271
+ return Object.freeze({
10272
+ ...decoder,
10273
+ decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
10274
+ });
10163
10275
  }
10164
- /**
10165
- * Returns balance of specified wallet in native tokens
10166
- * @param wallet wallet to inspect
10167
- */
10168
- function getNativeWalletBalance(connection, wallet) {
10169
- return __awaiter(this, void 0, void 0, function* () {
10170
- wallet = new PublicKey(wallet);
10171
- const result = yield connection.getBalance(wallet);
10172
- return new BN(result.toString());
10173
- });
10276
+ function isFixedSize$1(codec) {
10277
+ return "fixedSize" in codec && typeof codec.fixedSize === "number";
10174
10278
  }
10175
- /**
10176
- * Returns balance of associated wallet in SPL-tokens
10177
- * @param originalWallet native tokens wallet address
10178
- * @param tokenMint mint of SPL-Token
10179
- */
10180
- function getAssocSPLWalletBalance(connection, originalWallet, tokenMint) {
10181
- return __awaiter(this, void 0, void 0, function* () {
10182
- originalWallet = new PublicKey(originalWallet);
10183
- tokenMint = new PublicKey(tokenMint);
10184
- const [wallet] = findAssociatedTokenAddress(originalWallet, tokenMint);
10185
- const result = yield connection.getTokenAccountBalance(wallet, "finalized");
10186
- return new BN(result.value.amount);
10279
+ function combineCodec$1(encoder, decoder) {
10280
+ if (isFixedSize$1(encoder) !== isFixedSize$1(decoder)) {
10281
+ throw new SolanaError$1(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH$1);
10282
+ }
10283
+ if (isFixedSize$1(encoder) && isFixedSize$1(decoder) && encoder.fixedSize !== decoder.fixedSize) {
10284
+ throw new SolanaError$1(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH$1, {
10285
+ decoderFixedSize: decoder.fixedSize,
10286
+ encoderFixedSize: encoder.fixedSize
10187
10287
  });
10188
- }
10189
- /**
10190
- * Returns balance of specified wallet in SPL-tokens
10191
- * @param wallet spl-tokens wallet address
10192
- */
10193
- function getSPLWalletBalance(connection, wallet) {
10194
- return __awaiter(this, void 0, void 0, function* () {
10195
- wallet = new PublicKey(wallet);
10196
- const result = yield connection.getTokenAccountBalance(wallet, "finalized");
10197
- return new BN(result.value.amount);
10288
+ }
10289
+ if (!isFixedSize$1(encoder) && !isFixedSize$1(decoder) && encoder.maxSize !== decoder.maxSize) {
10290
+ throw new SolanaError$1(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH$1, {
10291
+ decoderMaxSize: decoder.maxSize,
10292
+ encoderMaxSize: encoder.maxSize
10198
10293
  });
10294
+ }
10295
+ return {
10296
+ ...decoder,
10297
+ ...encoder,
10298
+ decode: decoder.decode,
10299
+ encode: encoder.encode,
10300
+ read: decoder.read,
10301
+ write: encoder.write
10302
+ };
10199
10303
  }
10200
- /**
10201
- * Gets list of user's SPL-token accounts
10202
- * @param owner owner of the SPL wallets
10203
- * @returns list of accounts with amount on them
10204
- */
10205
- function getAllTokenAccountsWithBalances(connection, owner) {
10206
- return __awaiter(this, void 0, void 0, function* () {
10207
- const walletsData = yield connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { programId: TOKEN_PROGRAM_ID });
10208
- const wallets = walletsData.value;
10209
- return wallets.map((wallet) => {
10210
- const tokenInfo = wallet.account.data.parsed;
10211
- return {
10212
- address: wallet.pubkey,
10213
- mint: new PublicKey(tokenInfo.info.mint),
10214
- amount: new BN(tokenInfo.info.tokenAmount.amount),
10215
- decimals: tokenInfo.info.tokenAmount.decimals,
10216
- isInitialized: true,
10217
- isNative: tokenInfo.info.isNative,
10218
- owner: new PublicKey(tokenInfo.info.owner),
10219
- };
10220
- });
10304
+ function assertByteArrayIsNotEmptyForCodec$1(codecDescription, bytes, offset = 0) {
10305
+ if (bytes.length - offset <= 0) {
10306
+ throw new SolanaError$1(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY$1, {
10307
+ codecDescription
10221
10308
  });
10309
+ }
10222
10310
  }
10223
- /**
10224
- * Gets list of user's tokenMint token accounts
10225
- * @param tokenMint
10226
- * @param owner owner of the wallets
10227
- * @returns list of accounts with amount on them
10228
- */
10229
- function getTokenAccountsWithBalance(connection, tokenMint, owner) {
10230
- return __awaiter(this, void 0, void 0, function* () {
10231
- const walletsData = yield connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { mint: new PublicKey(tokenMint) });
10232
- const wallets = walletsData.value;
10233
- return wallets.map((wallet) => {
10234
- const tokenInfo = wallet.account.data.parsed;
10235
- return {
10236
- address: wallet.pubkey,
10237
- mint: new PublicKey(tokenInfo.info.mint),
10238
- amount: new BN(tokenInfo.info.tokenAmount.amount),
10239
- decimals: tokenInfo.info.tokenAmount.decimals,
10240
- isInitialized: true,
10241
- isNative: tokenInfo.info.isNative,
10242
- owner: new PublicKey(tokenInfo.info.owner),
10243
- };
10244
- });
10311
+ function assertByteArrayHasEnoughBytesForCodec$1(codecDescription, expected, bytes, offset = 0) {
10312
+ const bytesLength = bytes.length - offset;
10313
+ if (bytesLength < expected) {
10314
+ throw new SolanaError$1(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH$1, {
10315
+ bytesLength,
10316
+ codecDescription,
10317
+ expected
10245
10318
  });
10319
+ }
10246
10320
  }
10247
- /**
10248
- * Builds transaction to transfer&wrap native sol from src wallet to dst wallet
10249
- * @param amount number of lamports to transfer and wrap
10250
- * @param transferFrom source native account
10251
- * @param transferTo destination wallet
10252
- * @returns transaction to transfer&wrap sol
10253
- */
10254
- function buildReplenishWsolBalanceTransaction(amount, transferFrom, transferTo) {
10255
- transferFrom = new PublicKey(transferFrom);
10256
- transferTo = new PublicKey(transferTo);
10257
- const tx = new Transaction();
10258
- tx.add(SystemProgram.transfer({
10259
- fromPubkey: transferFrom,
10260
- toPubkey: transferTo,
10261
- lamports: new BN(amount).toNumber(),
10262
- }));
10263
- tx.add(
10264
- // sync native
10265
- new TransactionInstruction({
10266
- keys: [{ pubkey: transferTo, isSigner: false, isWritable: true }],
10267
- programId: TOKEN_PROGRAM_ID,
10268
- data: buffer.Buffer.from([17]),
10269
- }));
10270
- tx.feePayer = transferFrom;
10271
- return tx;
10321
+
10322
+ // src/add-codec-size-prefix.ts
10323
+ function addEncoderSizePrefix(encoder, prefix) {
10324
+ const write = (value, bytes, offset) => {
10325
+ const encoderBytes = encoder.encode(value);
10326
+ offset = prefix.write(encoderBytes.length, bytes, offset);
10327
+ bytes.set(encoderBytes, offset);
10328
+ return offset + encoderBytes.length;
10329
+ };
10330
+ if (isFixedSize$1(prefix) && isFixedSize$1(encoder)) {
10331
+ return createEncoder$1({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });
10332
+ }
10333
+ const prefixMaxSize = isFixedSize$1(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
10334
+ const encoderMaxSize = isFixedSize$1(encoder) ? encoder.fixedSize : encoder.maxSize ?? null;
10335
+ const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;
10336
+ return createEncoder$1({
10337
+ ...encoder,
10338
+ ...maxSize !== null ? { maxSize } : {},
10339
+ getSizeFromValue: (value) => {
10340
+ const encoderSize = getEncodedSize$1(value, encoder);
10341
+ return getEncodedSize$1(encoderSize, prefix) + encoderSize;
10342
+ },
10343
+ write
10344
+ });
10272
10345
  }
10273
- /**
10274
- * Builds transaction that wraps specified amount of lamports into spl, if account is missing will create it
10275
- * @param amount lamports to wrap, ATA will contain exact amount of lamports
10276
- * @param owner owner of created wallet
10277
- */
10278
- function updateWsolBalance(connection, amount, owner) {
10279
- return __awaiter(this, void 0, void 0, function* () {
10280
- owner = new PublicKey(owner);
10281
- const tx = new Transaction();
10282
- const [wSolATA] = findAssociatedTokenAddress(owner, WRAPPED_SOL_MINT);
10283
- const existingATA = yield getAccountInfo(connection, wSolATA);
10284
- let amountToWrap = new BN(amount);
10285
- if (existingATA === null) {
10286
- tx.add(createAssociatedWalletInstruction(WRAPPED_SOL_MINT, wSolATA, owner, owner));
10287
- }
10288
- else {
10289
- const parsed = parseSplAccount(existingATA.data);
10290
- if (!parsed)
10291
- throw new Error("WSol account exists, but failed to decode its content");
10292
- const parsedAmount = new BN(parsed.amount.toString());
10293
- if (amountToWrap.lte(parsedAmount))
10294
- return null; // don't need to wrap
10295
- amountToWrap = amountToWrap.sub(parsedAmount);
10296
- }
10297
- const replenishTx = buildReplenishWsolBalanceTransaction(amountToWrap, owner, wSolATA);
10298
- tx.add(replenishTx);
10299
- return tx;
10300
- });
10346
+ function addDecoderSizePrefix(decoder, prefix) {
10347
+ const read = (bytes, offset) => {
10348
+ const [bigintSize, decoderOffset] = prefix.read(bytes, offset);
10349
+ const size = Number(bigintSize);
10350
+ offset = decoderOffset;
10351
+ if (offset > 0 || bytes.length > size) {
10352
+ bytes = bytes.slice(offset, offset + size);
10353
+ }
10354
+ assertByteArrayHasEnoughBytesForCodec$1("addDecoderSizePrefix", size, bytes);
10355
+ return [decoder.decode(bytes), offset + size];
10356
+ };
10357
+ if (isFixedSize$1(prefix) && isFixedSize$1(decoder)) {
10358
+ return createDecoder$1({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });
10359
+ }
10360
+ const prefixMaxSize = isFixedSize$1(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
10361
+ const decoderMaxSize = isFixedSize$1(decoder) ? decoder.fixedSize : decoder.maxSize ?? null;
10362
+ const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;
10363
+ return createDecoder$1({ ...decoder, ...maxSize !== null ? { maxSize } : {}, read });
10301
10364
  }
10302
- /**
10303
- * Checks existance of associated wallet for specified token
10304
- * @param mintAccount mint account of SPL-token
10305
- * @param originalWallet account of solana wallet
10306
- * @returns true if account exists
10307
- */
10308
- function checkIfAssociatedWalletExists(connection, mintAccount, originalWallet) {
10309
- return __awaiter(this, void 0, void 0, function* () {
10310
- const [walletAccount] = findAssociatedTokenAddress(originalWallet, mintAccount);
10311
- const accountData = yield getAccountInfo(connection, walletAccount);
10312
- return accountData !== null;
10313
- });
10365
+ function addCodecSizePrefix(codec, prefix) {
10366
+ return combineCodec$1(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));
10314
10367
  }
10315
- function getTransactionAccountsForSimulationDiff(connection, tx) {
10316
- return __awaiter(this, void 0, void 0, function* () {
10317
- var _a, _b;
10318
- const result = new Set();
10319
- if ("version" in tx) {
10320
- const ALTs = tx.message.addressTableLookups.map((alt) => alt.accountKey);
10321
- const fetchedALTs = yield connection.getMultipleAccountsInfo(ALTs);
10322
- const parsedALTs = fetchedALTs
10323
- .map((fetched, i) => fetched
10324
- ? new AddressLookupTableAccount({
10325
- state: AddressLookupTableAccount.deserialize(fetched.data),
10326
- key: ALTs[i],
10327
- })
10328
- : null)
10329
- .filter((x) => x != null);
10330
- const accGetter = tx.message.getAccountKeys({
10331
- addressLookupTableAccounts: parsedALTs,
10332
- });
10333
- const staticWritableOrSignerAccounts = [];
10334
- for (let idx = 0; idx < accGetter.staticAccountKeys.length; idx += 1) {
10335
- if (tx.message.isAccountSigner(idx) || tx.message.isAccountWritable(idx))
10336
- staticWritableOrSignerAccounts.push(accGetter.staticAccountKeys[idx]);
10337
- }
10338
- for (const acc of [
10339
- ...staticWritableOrSignerAccounts,
10340
- ...((_b = (_a = accGetter.accountKeysFromLookups) === null || _a === void 0 ? void 0 : _a.writable) !== null && _b !== void 0 ? _b : []),
10341
- ]) {
10342
- result.add(acc.toBase58());
10343
- }
10344
- }
10345
- else {
10346
- const compiled = tx.compileMessage();
10347
- for (let idx = 0; idx < compiled.accountKeys.length; idx += 1) {
10348
- if (compiled.isAccountSigner(idx) || compiled.isAccountWritable(idx))
10349
- result.add(compiled.staticAccountKeys[idx].toBase58());
10350
- }
10351
- }
10352
- return Array.from(result);
10353
- });
10368
+
10369
+ // src/fix-codec-size.ts
10370
+ function fixEncoderSize$1(encoder, fixedBytes) {
10371
+ return createEncoder$1({
10372
+ fixedSize: fixedBytes,
10373
+ write: (value, bytes, offset) => {
10374
+ const variableByteArray = encoder.encode(value);
10375
+ const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
10376
+ bytes.set(fixedByteArray, offset);
10377
+ return offset + fixedBytes;
10378
+ }
10379
+ });
10354
10380
  }
10355
- function parseMultipleAccounts(accounts) {
10356
- return accounts.map((account) => {
10357
- var _a, _b;
10358
- let parsedSplAccount;
10359
- if (account) {
10360
- const owner = new PublicKey(account.owner);
10361
- if (owner.equals(TOKEN_PROGRAM_ID)) {
10362
- if (account.data instanceof buffer.Buffer) {
10363
- parsedSplAccount = parseSplAccount(account.data);
10364
- }
10365
- else if (account.data instanceof Array) {
10366
- parsedSplAccount = parseSplAccount(buffer.Buffer.from(account.data[0], account.data[1]));
10367
- }
10368
- }
10369
- }
10370
- const parsedAccount = {
10371
- balance: (_a = account === null || account === void 0 ? void 0 : account.lamports) !== null && _a !== void 0 ? _a : 0,
10372
- };
10373
- if (parsedSplAccount) {
10374
- parsedAccount.spl = {
10375
- mint: parsedSplAccount.mint,
10376
- owner: parsedSplAccount.owner,
10377
- balance: (_b = parsedSplAccount.amount) !== null && _b !== void 0 ? _b : BigInt(0),
10378
- };
10379
- }
10380
- return parsedAccount;
10381
- });
10381
+ function fixDecoderSize$1(decoder, fixedBytes) {
10382
+ return createDecoder$1({
10383
+ fixedSize: fixedBytes,
10384
+ read: (bytes, offset) => {
10385
+ assertByteArrayHasEnoughBytesForCodec$1("fixCodecSize", fixedBytes, bytes, offset);
10386
+ if (offset > 0 || bytes.length > fixedBytes) {
10387
+ bytes = bytes.slice(offset, offset + fixedBytes);
10388
+ }
10389
+ if (isFixedSize$1(decoder)) {
10390
+ bytes = fixBytes$1(bytes, decoder.fixedSize);
10391
+ }
10392
+ const [value] = decoder.read(bytes, 0);
10393
+ return [value, offset + fixedBytes];
10394
+ }
10395
+ });
10382
10396
  }
10383
- function getSplDiff(pre, post) {
10384
- var _a, _b, _c, _d, _e, _f;
10385
- const preBalance = (_a = pre === null || pre === void 0 ? void 0 : pre.balance) !== null && _a !== void 0 ? _a : BigInt(0);
10386
- const postBalance = (_b = post === null || post === void 0 ? void 0 : post.balance) !== null && _b !== void 0 ? _b : BigInt(0);
10387
- return {
10388
- mint: (_c = pre === null || pre === void 0 ? void 0 : pre.mint) !== null && _c !== void 0 ? _c : post === null || post === void 0 ? void 0 : post.mint,
10389
- owner: (_d = pre === null || pre === void 0 ? void 0 : pre.owner) !== null && _d !== void 0 ? _d : post === null || post === void 0 ? void 0 : post.owner,
10390
- preBalance: (_e = pre === null || pre === void 0 ? void 0 : pre.balance) !== null && _e !== void 0 ? _e : 0,
10391
- postBalance: (_f = post === null || post === void 0 ? void 0 : post.balance) !== null && _f !== void 0 ? _f : 0,
10392
- diff: postBalance - preBalance,
10393
- };
10397
+ function fixCodecSize$1(codec, fixedBytes) {
10398
+ return combineCodec$1(fixEncoderSize$1(codec, fixedBytes), fixDecoderSize$1(codec, fixedBytes));
10394
10399
  }
10395
- function getTransactionDiff(connection, tx, txAccounts) {
10396
- return __awaiter(this, void 0, void 0, function* () {
10397
- const accountsStrings = txAccounts
10398
- ? txAccounts.map((acc) => acc.toBase58())
10399
- : yield getTransactionAccountsForSimulationDiff(connection, tx);
10400
- const accountsPubKeys = txAccounts !== null && txAccounts !== void 0 ? txAccounts : accountsStrings.map((key) => new PublicKey(key));
10401
- let [accountsInfo, simulatedTx] = yield Promise.all([
10402
- connection.getMultipleAccountsInfo(accountsPubKeys),
10403
- connection.simulateTransaction(tx, {
10404
- replaceRecentBlockhash: true,
10405
- accounts: {
10406
- encoding: "base64",
10407
- addresses: accountsStrings,
10408
- },
10409
- }),
10410
- ]);
10411
- if (simulatedTx.value.err !== null)
10412
- throw new Error(JSON.stringify({
10413
- err: simulatedTx.value.err,
10414
- logs: simulatedTx.value.logs,
10415
- }));
10416
- const simulatesInfo = simulatedTx.value.accounts;
10417
- const preBalances = parseMultipleAccounts(accountsInfo);
10418
- const postBalances = parseMultipleAccounts(simulatesInfo);
10419
- const balancesDiff = accountsPubKeys.reduce((map, pubKey, i) => {
10420
- var _a;
10421
- if ((_a = accountsInfo[i]) === null || _a === void 0 ? void 0 : _a.executable) {
10422
- return map;
10423
- }
10424
- const preBalance = preBalances[i];
10425
- const postBalance = postBalances[i];
10426
- const diff = {
10427
- pubKey: pubKey,
10428
- preBalance: preBalance.balance,
10429
- postBalance: postBalance.balance,
10430
- diff: postBalance.balance - preBalance.balance,
10431
- };
10432
- if (preBalance.spl || postBalance.spl) {
10433
- const splDiff = getSplDiff(preBalance.spl, postBalance.spl);
10434
- if (splDiff.diff) {
10435
- diff.spl = splDiff;
10436
- }
10437
- }
10438
- if (diff.diff || diff.spl) {
10439
- map.set(pubKey.toString(), diff);
10440
- }
10441
- return map;
10442
- }, new Map());
10443
- return balancesDiff;
10400
+
10401
+ // src/assertions.ts
10402
+ function assertNumberIsBetweenForCodec$1(codecDescription, min, max, value) {
10403
+ if (value < min || value > max) {
10404
+ throw new SolanaError$1(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE$1, {
10405
+ codecDescription,
10406
+ max,
10407
+ min,
10408
+ value
10444
10409
  });
10410
+ }
10445
10411
  }
10446
-
10447
- var spl = /*#__PURE__*/Object.freeze({
10448
- __proto__: null,
10449
- get AccountType () { return AccountType$1; },
10450
- getTokenInfo: getTokenInfo,
10451
- createAssociatedWalletInstruction: createAssociatedWalletInstruction,
10452
- parseSplAccount: parseSplAccount,
10453
- isWalletCorrectATA: isWalletCorrectATA,
10454
- getAccountWithType: getAccountWithType,
10455
- getNativeWalletBalance: getNativeWalletBalance,
10456
- getAssocSPLWalletBalance: getAssocSPLWalletBalance,
10457
- getSPLWalletBalance: getSPLWalletBalance,
10458
- getAllTokenAccountsWithBalances: getAllTokenAccountsWithBalances,
10459
- getTokenAccountsWithBalance: getTokenAccountsWithBalance,
10460
- buildReplenishWsolBalanceTransaction: buildReplenishWsolBalanceTransaction,
10461
- updateWsolBalance: updateWsolBalance,
10462
- checkIfAssociatedWalletExists: checkIfAssociatedWalletExists,
10463
- getTransactionAccountsForSimulationDiff: getTransactionAccountsForSimulationDiff,
10464
- parseMultipleAccounts: parseMultipleAccounts,
10465
- getSplDiff: getSplDiff,
10466
- getTransactionDiff: getTransactionDiff
10467
- });
10468
-
10469
- const deBridge = "DEbrdGj3HsRsAzx6uH4MKyREKxVAfBydijLUF3ygsFfh";
10470
- const settings = "DeSetTwWhjZq6Pz9Kfdo1KoS5NqtsM6G8ERbX4SSCSft";
10471
- const dlnSrc = "src5qyZHqTqecJV4aY6Cb6zDZLMDzrDKKezs22MPHr4";
10472
- const dlnDst = "dst5MGcFPoBeREFAA5E3tU5ij8m5uVYwkzkSAbsLbNo";
10473
- const dlnExecutor = "exe59FS5cojZkPJVDFDV8RnXCC7wd6yoBjsUtqH7Zai";
10474
-
10475
- var programs = /*#__PURE__*/Object.freeze({
10476
- __proto__: null,
10477
- deBridge: deBridge,
10478
- settings: settings,
10479
- dlnSrc: dlnSrc,
10480
- dlnDst: dlnDst,
10481
- dlnExecutor: dlnExecutor
10482
- });
10483
-
10484
- /** Address of the SPL Token program */
10485
- new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
10486
- /** Address of the SPL Token 2022 program */
10487
- new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
10488
- /** Address of the SPL Associated Token Account program */
10489
- new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
10490
- /** Address of the special mint for wrapped native SOL in spl-token */
10491
- new PublicKey('So11111111111111111111111111111111111111112');
10492
- /** Address of the special mint for wrapped native SOL in spl-token-2022 */
10493
- new PublicKey('9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP');
10494
-
10495
- /** Instructions defined by the program */
10496
- var TokenInstruction;
10497
- (function (TokenInstruction) {
10498
- TokenInstruction[TokenInstruction["InitializeMint"] = 0] = "InitializeMint";
10499
- TokenInstruction[TokenInstruction["InitializeAccount"] = 1] = "InitializeAccount";
10500
- TokenInstruction[TokenInstruction["InitializeMultisig"] = 2] = "InitializeMultisig";
10501
- TokenInstruction[TokenInstruction["Transfer"] = 3] = "Transfer";
10502
- TokenInstruction[TokenInstruction["Approve"] = 4] = "Approve";
10503
- TokenInstruction[TokenInstruction["Revoke"] = 5] = "Revoke";
10504
- TokenInstruction[TokenInstruction["SetAuthority"] = 6] = "SetAuthority";
10505
- TokenInstruction[TokenInstruction["MintTo"] = 7] = "MintTo";
10506
- TokenInstruction[TokenInstruction["Burn"] = 8] = "Burn";
10507
- TokenInstruction[TokenInstruction["CloseAccount"] = 9] = "CloseAccount";
10508
- TokenInstruction[TokenInstruction["FreezeAccount"] = 10] = "FreezeAccount";
10509
- TokenInstruction[TokenInstruction["ThawAccount"] = 11] = "ThawAccount";
10510
- TokenInstruction[TokenInstruction["TransferChecked"] = 12] = "TransferChecked";
10511
- TokenInstruction[TokenInstruction["ApproveChecked"] = 13] = "ApproveChecked";
10512
- TokenInstruction[TokenInstruction["MintToChecked"] = 14] = "MintToChecked";
10513
- TokenInstruction[TokenInstruction["BurnChecked"] = 15] = "BurnChecked";
10514
- TokenInstruction[TokenInstruction["InitializeAccount2"] = 16] = "InitializeAccount2";
10515
- TokenInstruction[TokenInstruction["SyncNative"] = 17] = "SyncNative";
10516
- TokenInstruction[TokenInstruction["InitializeAccount3"] = 18] = "InitializeAccount3";
10517
- TokenInstruction[TokenInstruction["InitializeMultisig2"] = 19] = "InitializeMultisig2";
10518
- TokenInstruction[TokenInstruction["InitializeMint2"] = 20] = "InitializeMint2";
10519
- TokenInstruction[TokenInstruction["GetAccountDataSize"] = 21] = "GetAccountDataSize";
10520
- TokenInstruction[TokenInstruction["InitializeImmutableOwner"] = 22] = "InitializeImmutableOwner";
10521
- TokenInstruction[TokenInstruction["AmountToUiAmount"] = 23] = "AmountToUiAmount";
10522
- TokenInstruction[TokenInstruction["UiAmountToAmount"] = 24] = "UiAmountToAmount";
10523
- TokenInstruction[TokenInstruction["InitializeMintCloseAuthority"] = 25] = "InitializeMintCloseAuthority";
10524
- TokenInstruction[TokenInstruction["TransferFeeExtension"] = 26] = "TransferFeeExtension";
10525
- TokenInstruction[TokenInstruction["ConfidentialTransferExtension"] = 27] = "ConfidentialTransferExtension";
10526
- TokenInstruction[TokenInstruction["DefaultAccountStateExtension"] = 28] = "DefaultAccountStateExtension";
10527
- TokenInstruction[TokenInstruction["Reallocate"] = 29] = "Reallocate";
10528
- TokenInstruction[TokenInstruction["MemoTransferExtension"] = 30] = "MemoTransferExtension";
10529
- TokenInstruction[TokenInstruction["CreateNativeMint"] = 31] = "CreateNativeMint";
10530
- TokenInstruction[TokenInstruction["InitializeNonTransferableMint"] = 32] = "InitializeNonTransferableMint";
10531
- TokenInstruction[TokenInstruction["InterestBearingMintExtension"] = 33] = "InterestBearingMintExtension";
10532
- TokenInstruction[TokenInstruction["CpiGuardExtension"] = 34] = "CpiGuardExtension";
10533
- TokenInstruction[TokenInstruction["InitializePermanentDelegate"] = 35] = "InitializePermanentDelegate";
10534
- TokenInstruction[TokenInstruction["TransferHookExtension"] = 36] = "TransferHookExtension";
10535
- // ConfidentialTransferFeeExtension = 37,
10536
- // WithdrawalExcessLamports = 38,
10537
- TokenInstruction[TokenInstruction["MetadataPointerExtension"] = 39] = "MetadataPointerExtension";
10538
- TokenInstruction[TokenInstruction["GroupPointerExtension"] = 40] = "GroupPointerExtension";
10539
- TokenInstruction[TokenInstruction["GroupMemberPointerExtension"] = 41] = "GroupMemberPointerExtension";
10540
- // ConfidentialMintBurnExtension = 42,
10541
- TokenInstruction[TokenInstruction["ScaledUiAmountExtension"] = 43] = "ScaledUiAmountExtension";
10542
- TokenInstruction[TokenInstruction["PausableExtension"] = 44] = "PausableExtension";
10543
- })(TokenInstruction || (TokenInstruction = {}));
10544
-
10545
- /** TODO: docs */
10546
- struct$1([
10547
- u8$1('instruction'),
10548
- u64$1('amount'),
10549
- ]);
10550
-
10551
- var AccountType;
10552
- (function (AccountType) {
10553
- AccountType[AccountType["Uninitialized"] = 0] = "Uninitialized";
10554
- AccountType[AccountType["Mint"] = 1] = "Mint";
10555
- AccountType[AccountType["Account"] = 2] = "Account";
10556
- })(AccountType || (AccountType = {}));
10557
-
10558
- /** Buffer layout for de/serializing a multisig */
10559
- const MultisigLayout = struct$1([
10560
- u8$1('m'),
10561
- u8$1('n'),
10562
- bool$1('isInitialized'),
10563
- publicKey$4('signer1'),
10564
- publicKey$4('signer2'),
10565
- publicKey$4('signer3'),
10566
- publicKey$4('signer4'),
10567
- publicKey$4('signer5'),
10568
- publicKey$4('signer6'),
10569
- publicKey$4('signer7'),
10570
- publicKey$4('signer8'),
10571
- publicKey$4('signer9'),
10572
- publicKey$4('signer10'),
10573
- publicKey$4('signer11'),
10574
- ]);
10575
- /** Byte length of a multisig */
10576
- MultisigLayout.span;
10577
-
10578
- /** Token account state as stored by the program */
10579
- var AccountState;
10580
- (function (AccountState) {
10581
- AccountState[AccountState["Uninitialized"] = 0] = "Uninitialized";
10582
- AccountState[AccountState["Initialized"] = 1] = "Initialized";
10583
- AccountState[AccountState["Frozen"] = 2] = "Frozen";
10584
- })(AccountState || (AccountState = {}));
10585
- /** Buffer layout for de/serializing a token account */
10586
- const AccountLayout = struct$1([
10587
- publicKey$4('mint'),
10588
- publicKey$4('owner'),
10589
- u64$1('amount'),
10590
- u32$1('delegateOption'),
10591
- publicKey$4('delegate'),
10592
- u8$1('state'),
10593
- u32$1('isNativeOption'),
10594
- u64$1('isNative'),
10595
- u64$1('delegatedAmount'),
10596
- u32$1('closeAuthorityOption'),
10597
- publicKey$4('closeAuthority'),
10598
- ]);
10599
- /** Byte length of a token account */
10600
- AccountLayout.span;
10601
-
10602
- var CpiGuardInstruction;
10603
- (function (CpiGuardInstruction) {
10604
- CpiGuardInstruction[CpiGuardInstruction["Enable"] = 0] = "Enable";
10605
- CpiGuardInstruction[CpiGuardInstruction["Disable"] = 1] = "Disable";
10606
- })(CpiGuardInstruction || (CpiGuardInstruction = {}));
10607
- /** TODO: docs */
10608
- struct$1([u8$1('instruction'), u8$1('cpiGuardInstruction')]);
10609
-
10610
- /** Buffer layout for de/serializing a CPI Guard extension */
10611
- const CpiGuardLayout = struct$1([bool$1('lockCpi')]);
10612
- CpiGuardLayout.span;
10613
-
10614
- var DefaultAccountStateInstruction;
10615
- (function (DefaultAccountStateInstruction) {
10616
- DefaultAccountStateInstruction[DefaultAccountStateInstruction["Initialize"] = 0] = "Initialize";
10617
- DefaultAccountStateInstruction[DefaultAccountStateInstruction["Update"] = 1] = "Update";
10618
- })(DefaultAccountStateInstruction || (DefaultAccountStateInstruction = {}));
10619
- /** TODO: docs */
10620
- struct$1([
10621
- u8$1('instruction'),
10622
- u8$1('defaultAccountStateInstruction'),
10623
- u8$1('accountState'),
10624
- ]);
10625
-
10626
- /** Buffer layout for de/serializing a transfer fee config extension */
10627
- const DefaultAccountStateLayout = struct$1([u8$1('state')]);
10628
- DefaultAccountStateLayout.span;
10629
-
10630
- // src/codes.ts
10631
- var SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY$1 = 8078e3;
10632
- var SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH$1 = 8078001;
10633
- var SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH$1 = 8078004;
10634
- var SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH$1 = 8078005;
10635
- var SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH$1 = 8078006;
10636
- var SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS$1 = 8078007;
10637
- var SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE$1 = 8078011;
10638
-
10639
- // src/context.ts
10640
- function encodeValue$1(value) {
10641
- if (Array.isArray(value)) {
10642
- const commaSeparatedValues = value.map(encodeValue$1).join(
10643
- "%2C%20"
10644
- /* ", " */
10645
- );
10646
- return "%5B" + commaSeparatedValues + /* "]" */
10647
- "%5D";
10648
- } else if (typeof value === "bigint") {
10649
- return `${value}n`;
10650
- } else {
10651
- return encodeURIComponent(
10652
- String(
10653
- value != null && Object.getPrototypeOf(value) === null ? (
10654
- // Plain objects with no prototype don't have a `toString` method.
10655
- // Convert them before stringifying them.
10656
- { ...value }
10657
- ) : value
10658
- )
10659
- );
10660
- }
10661
- }
10662
- function encodeObjectContextEntry$1([key, value]) {
10663
- return `${key}=${encodeValue$1(value)}`;
10412
+ function isLittleEndian$1(config) {
10413
+ return config?.endian === 1 /* Big */ ? false : true;
10664
10414
  }
10665
- function encodeContextObject$1(context) {
10666
- const searchParamsString = Object.entries(context).map(encodeObjectContextEntry$1).join("&");
10667
- return btoa(searchParamsString);
10415
+ function numberEncoderFactory$1(input) {
10416
+ return createEncoder$1({
10417
+ fixedSize: input.size,
10418
+ write(value, bytes, offset) {
10419
+ if (input.range) {
10420
+ assertNumberIsBetweenForCodec$1(input.name, input.range[0], input.range[1], value);
10421
+ }
10422
+ const arrayBuffer = new ArrayBuffer(input.size);
10423
+ input.set(new DataView(arrayBuffer), value, isLittleEndian$1(input.config));
10424
+ bytes.set(new Uint8Array(arrayBuffer), offset);
10425
+ return offset + input.size;
10426
+ }
10427
+ });
10668
10428
  }
10669
- function getErrorMessage$1(code, context = {}) {
10670
- {
10671
- let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;
10672
- if (Object.keys(context).length) {
10673
- decodingAdviceMessage += ` '${encodeContextObject$1(context)}'`;
10429
+ function numberDecoderFactory$1(input) {
10430
+ return createDecoder$1({
10431
+ fixedSize: input.size,
10432
+ read(bytes, offset = 0) {
10433
+ assertByteArrayIsNotEmptyForCodec$1(input.name, bytes, offset);
10434
+ assertByteArrayHasEnoughBytesForCodec$1(input.name, input.size, bytes, offset);
10435
+ const view = new DataView(toArrayBuffer$1(bytes, offset, input.size));
10436
+ return [input.get(view, isLittleEndian$1(input.config)), offset + input.size];
10674
10437
  }
10675
- return `${decodingAdviceMessage}\``;
10676
- }
10677
- }
10678
- var SolanaError$1 = class extends Error {
10679
- cause = this.cause;
10680
- context;
10681
- constructor(...[code, contextAndErrorOptions]) {
10682
- let context;
10683
- let errorOptions;
10684
- if (contextAndErrorOptions) {
10685
- const { cause, ...contextRest } = contextAndErrorOptions;
10686
- if (cause) {
10687
- errorOptions = { cause };
10688
- }
10689
- if (Object.keys(contextRest).length > 0) {
10690
- context = contextRest;
10691
- }
10692
- }
10693
- const message = getErrorMessage$1(code, context);
10694
- super(message, errorOptions);
10695
- this.context = {
10696
- __code: code,
10697
- ...context
10698
- };
10699
- this.name = "SolanaError";
10700
- }
10701
- };
10702
-
10703
- var padBytes$1 = (bytes, length) => {
10704
- if (bytes.length >= length) return bytes;
10705
- const paddedBytes = new Uint8Array(length).fill(0);
10706
- paddedBytes.set(bytes);
10707
- return paddedBytes;
10708
- };
10709
- var fixBytes$1 = (bytes, length) => padBytes$1(bytes.length <= length ? bytes : bytes.slice(0, length), length);
10710
- function getEncodedSize$1(value, encoder) {
10711
- return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
10712
- }
10713
- function createEncoder$1(encoder) {
10714
- return Object.freeze({
10715
- ...encoder,
10716
- encode: (value) => {
10717
- const bytes = new Uint8Array(getEncodedSize$1(value, encoder));
10718
- encoder.write(value, bytes, 0);
10719
- return bytes;
10720
- }
10721
- });
10722
- }
10723
- function createDecoder$1(decoder) {
10724
- return Object.freeze({
10725
- ...decoder,
10726
- decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
10727
- });
10728
- }
10729
- function isFixedSize$1(codec) {
10730
- return "fixedSize" in codec && typeof codec.fixedSize === "number";
10731
- }
10732
- function combineCodec$1(encoder, decoder) {
10733
- if (isFixedSize$1(encoder) !== isFixedSize$1(decoder)) {
10734
- throw new SolanaError$1(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH$1);
10735
- }
10736
- if (isFixedSize$1(encoder) && isFixedSize$1(decoder) && encoder.fixedSize !== decoder.fixedSize) {
10737
- throw new SolanaError$1(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH$1, {
10738
- decoderFixedSize: decoder.fixedSize,
10739
- encoderFixedSize: encoder.fixedSize
10740
- });
10741
- }
10742
- if (!isFixedSize$1(encoder) && !isFixedSize$1(decoder) && encoder.maxSize !== decoder.maxSize) {
10743
- throw new SolanaError$1(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH$1, {
10744
- decoderMaxSize: decoder.maxSize,
10745
- encoderMaxSize: encoder.maxSize
10746
- });
10747
- }
10748
- return {
10749
- ...decoder,
10750
- ...encoder,
10751
- decode: decoder.decode,
10752
- encode: encoder.encode,
10753
- read: decoder.read,
10754
- write: encoder.write
10755
- };
10756
- }
10757
- function assertByteArrayIsNotEmptyForCodec$1(codecDescription, bytes, offset = 0) {
10758
- if (bytes.length - offset <= 0) {
10759
- throw new SolanaError$1(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY$1, {
10760
- codecDescription
10761
- });
10762
- }
10763
- }
10764
- function assertByteArrayHasEnoughBytesForCodec$1(codecDescription, expected, bytes, offset = 0) {
10765
- const bytesLength = bytes.length - offset;
10766
- if (bytesLength < expected) {
10767
- throw new SolanaError$1(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH$1, {
10768
- bytesLength,
10769
- codecDescription,
10770
- expected
10771
- });
10772
- }
10773
- }
10774
-
10775
- // src/add-codec-size-prefix.ts
10776
- function addEncoderSizePrefix(encoder, prefix) {
10777
- const write = (value, bytes, offset) => {
10778
- const encoderBytes = encoder.encode(value);
10779
- offset = prefix.write(encoderBytes.length, bytes, offset);
10780
- bytes.set(encoderBytes, offset);
10781
- return offset + encoderBytes.length;
10782
- };
10783
- if (isFixedSize$1(prefix) && isFixedSize$1(encoder)) {
10784
- return createEncoder$1({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });
10785
- }
10786
- const prefixMaxSize = isFixedSize$1(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
10787
- const encoderMaxSize = isFixedSize$1(encoder) ? encoder.fixedSize : encoder.maxSize ?? null;
10788
- const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;
10789
- return createEncoder$1({
10790
- ...encoder,
10791
- ...maxSize !== null ? { maxSize } : {},
10792
- getSizeFromValue: (value) => {
10793
- const encoderSize = getEncodedSize$1(value, encoder);
10794
- return getEncodedSize$1(encoderSize, prefix) + encoderSize;
10795
- },
10796
- write
10797
- });
10798
- }
10799
- function addDecoderSizePrefix(decoder, prefix) {
10800
- const read = (bytes, offset) => {
10801
- const [bigintSize, decoderOffset] = prefix.read(bytes, offset);
10802
- const size = Number(bigintSize);
10803
- offset = decoderOffset;
10804
- if (offset > 0 || bytes.length > size) {
10805
- bytes = bytes.slice(offset, offset + size);
10806
- }
10807
- assertByteArrayHasEnoughBytesForCodec$1("addDecoderSizePrefix", size, bytes);
10808
- return [decoder.decode(bytes), offset + size];
10809
- };
10810
- if (isFixedSize$1(prefix) && isFixedSize$1(decoder)) {
10811
- return createDecoder$1({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });
10812
- }
10813
- const prefixMaxSize = isFixedSize$1(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
10814
- const decoderMaxSize = isFixedSize$1(decoder) ? decoder.fixedSize : decoder.maxSize ?? null;
10815
- const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;
10816
- return createDecoder$1({ ...decoder, ...maxSize !== null ? { maxSize } : {}, read });
10817
- }
10818
- function addCodecSizePrefix(codec, prefix) {
10819
- return combineCodec$1(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));
10820
- }
10821
-
10822
- // src/fix-codec-size.ts
10823
- function fixEncoderSize$1(encoder, fixedBytes) {
10824
- return createEncoder$1({
10825
- fixedSize: fixedBytes,
10826
- write: (value, bytes, offset) => {
10827
- const variableByteArray = encoder.encode(value);
10828
- const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
10829
- bytes.set(fixedByteArray, offset);
10830
- return offset + fixedBytes;
10831
- }
10832
- });
10833
- }
10834
- function fixDecoderSize$1(decoder, fixedBytes) {
10835
- return createDecoder$1({
10836
- fixedSize: fixedBytes,
10837
- read: (bytes, offset) => {
10838
- assertByteArrayHasEnoughBytesForCodec$1("fixCodecSize", fixedBytes, bytes, offset);
10839
- if (offset > 0 || bytes.length > fixedBytes) {
10840
- bytes = bytes.slice(offset, offset + fixedBytes);
10841
- }
10842
- if (isFixedSize$1(decoder)) {
10843
- bytes = fixBytes$1(bytes, decoder.fixedSize);
10844
- }
10845
- const [value] = decoder.read(bytes, 0);
10846
- return [value, offset + fixedBytes];
10847
- }
10848
- });
10849
- }
10850
- function fixCodecSize$1(codec, fixedBytes) {
10851
- return combineCodec$1(fixEncoderSize$1(codec, fixedBytes), fixDecoderSize$1(codec, fixedBytes));
10852
- }
10853
-
10854
- // src/assertions.ts
10855
- function assertNumberIsBetweenForCodec$1(codecDescription, min, max, value) {
10856
- if (value < min || value > max) {
10857
- throw new SolanaError$1(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE$1, {
10858
- codecDescription,
10859
- max,
10860
- min,
10861
- value
10862
- });
10863
- }
10864
- }
10865
- function isLittleEndian$1(config) {
10866
- return config?.endian === 1 /* Big */ ? false : true;
10867
- }
10868
- function numberEncoderFactory$1(input) {
10869
- return createEncoder$1({
10870
- fixedSize: input.size,
10871
- write(value, bytes, offset) {
10872
- if (input.range) {
10873
- assertNumberIsBetweenForCodec$1(input.name, input.range[0], input.range[1], value);
10874
- }
10875
- const arrayBuffer = new ArrayBuffer(input.size);
10876
- input.set(new DataView(arrayBuffer), value, isLittleEndian$1(input.config));
10877
- bytes.set(new Uint8Array(arrayBuffer), offset);
10878
- return offset + input.size;
10879
- }
10880
- });
10881
- }
10882
- function numberDecoderFactory$1(input) {
10883
- return createDecoder$1({
10884
- fixedSize: input.size,
10885
- read(bytes, offset = 0) {
10886
- assertByteArrayIsNotEmptyForCodec$1(input.name, bytes, offset);
10887
- assertByteArrayHasEnoughBytesForCodec$1(input.name, input.size, bytes, offset);
10888
- const view = new DataView(toArrayBuffer$1(bytes, offset, input.size));
10889
- return [input.get(view, isLittleEndian$1(input.config)), offset + input.size];
10890
- }
10891
- });
10438
+ });
10892
10439
  }
10893
10440
  function toArrayBuffer$1(bytes, offset, length) {
10894
10441
  const bytesOffset = bytes.byteOffset + (offset ?? 0);
@@ -11206,6 +10753,20 @@ const MetadataPointerLayout = struct$1([
11206
10753
  publicKey$4('metadataAddress'),
11207
10754
  ]);
11208
10755
  MetadataPointerLayout.span;
10756
+ function getMetadataPointerState(mint) {
10757
+ const extensionData = getExtensionData(ExtensionType.MetadataPointer, mint.tlvData);
10758
+ if (extensionData !== null) {
10759
+ const { authority, metadataAddress } = MetadataPointerLayout.decode(extensionData);
10760
+ // Explicitly set None/Zero keys to null
10761
+ return {
10762
+ authority: authority.equals(PublicKey.default) ? null : authority,
10763
+ metadataAddress: metadataAddress.equals(PublicKey.default) ? null : metadataAddress,
10764
+ };
10765
+ }
10766
+ else {
10767
+ return null;
10768
+ }
10769
+ }
11209
10770
 
11210
10771
  /** Buffer layout for de/serializing a mint */
11211
10772
  const MintCloseAuthorityLayout = struct$1([publicKey$4('closeAuthority')]);
@@ -11446,6 +11007,35 @@ var ExtensionType;
11446
11007
  ExtensionType[ExtensionType["PausableConfig"] = 26] = "PausableConfig";
11447
11008
  ExtensionType[ExtensionType["PausableAccount"] = 27] = "PausableAccount";
11448
11009
  })(ExtensionType || (ExtensionType = {}));
11010
+ const TYPE_SIZE = 2;
11011
+ const LENGTH_SIZE = 2;
11012
+ function addTypeAndLengthToLen(len) {
11013
+ return len + TYPE_SIZE + LENGTH_SIZE;
11014
+ }
11015
+ function getExtensionData(extension, tlvData) {
11016
+ let extensionTypeIndex = 0;
11017
+ while (addTypeAndLengthToLen(extensionTypeIndex) <= tlvData.length) {
11018
+ const entryType = tlvData.readUInt16LE(extensionTypeIndex);
11019
+ const entryLength = tlvData.readUInt16LE(extensionTypeIndex + TYPE_SIZE);
11020
+ const typeIndex = addTypeAndLengthToLen(extensionTypeIndex);
11021
+ if (entryType == extension) {
11022
+ return tlvData.slice(typeIndex, typeIndex + entryLength);
11023
+ }
11024
+ extensionTypeIndex = typeIndex + entryLength;
11025
+ }
11026
+ return null;
11027
+ }
11028
+ function getExtensionTypes(tlvData) {
11029
+ const extensionTypes = [];
11030
+ let extensionTypeIndex = 0;
11031
+ while (extensionTypeIndex < tlvData.length) {
11032
+ const entryType = tlvData.readUInt16LE(extensionTypeIndex);
11033
+ extensionTypes.push(entryType);
11034
+ const entryLength = tlvData.readUInt16LE(extensionTypeIndex + TYPE_SIZE);
11035
+ extensionTypeIndex += addTypeAndLengthToLen(entryLength);
11036
+ }
11037
+ return extensionTypes;
11038
+ }
11449
11039
 
11450
11040
  /** Buffer layout for de/serializing a mint */
11451
11041
  const MintLayout = struct$1([
@@ -11458,7 +11048,46 @@ const MintLayout = struct$1([
11458
11048
  publicKey$4('freezeAuthority'),
11459
11049
  ]);
11460
11050
  /** Byte length of a mint */
11461
- MintLayout.span;
11051
+ const MINT_SIZE = MintLayout.span;
11052
+ /**
11053
+ * Unpack a mint
11054
+ *
11055
+ * @param address Mint account
11056
+ * @param info Mint account data
11057
+ * @param programId SPL Token program account
11058
+ *
11059
+ * @return Unpacked mint
11060
+ */
11061
+ function unpackMint(address, info, programId = TOKEN_PROGRAM_ID) {
11062
+ if (!info)
11063
+ throw new TokenAccountNotFoundError();
11064
+ if (!info.owner.equals(programId))
11065
+ throw new TokenInvalidAccountOwnerError();
11066
+ if (info.data.length < MINT_SIZE)
11067
+ throw new TokenInvalidAccountSizeError();
11068
+ const rawMint = MintLayout.decode(info.data.slice(0, MINT_SIZE));
11069
+ let tlvData = Buffer.alloc(0);
11070
+ if (info.data.length > MINT_SIZE) {
11071
+ if (info.data.length <= ACCOUNT_SIZE)
11072
+ throw new TokenInvalidAccountSizeError();
11073
+ if (info.data.length === MULTISIG_SIZE)
11074
+ throw new TokenInvalidAccountSizeError();
11075
+ if (info.data[ACCOUNT_SIZE] != AccountType$1.Mint)
11076
+ throw new TokenInvalidMintError();
11077
+ tlvData = info.data.slice(ACCOUNT_SIZE + ACCOUNT_TYPE_SIZE);
11078
+ }
11079
+ return {
11080
+ address,
11081
+ mintAuthority: rawMint.mintAuthorityOption ? rawMint.mintAuthority : null,
11082
+ supply: rawMint.supply,
11083
+ decimals: rawMint.decimals,
11084
+ isInitialized: rawMint.isInitialized,
11085
+ freezeAuthority: rawMint.freezeAuthorityOption ? rawMint.freezeAuthority : null,
11086
+ tlvData,
11087
+ };
11088
+ }
11089
+
11090
+ new PublicKey('SysvarC1ock11111111111111111111111111111111');
11462
11091
 
11463
11092
  /** TODO: docs */
11464
11093
  struct$1([u8$1('instruction'), u64$1('amount')]);
@@ -11650,46 +11279,600 @@ Buffer.from([112, 132, 90, 90, 11, 88, 157, 87]);
11650
11279
  function getStringCodec() {
11651
11280
  return addCodecSizePrefix(getUtf8Codec$1(), getU32Codec());
11652
11281
  }
11653
- getStructCodec$1([
11654
- ['updateAuthority', fixCodecSize$1(getBytesCodec$1(), 32)],
11655
- ['mint', fixCodecSize$1(getBytesCodec$1(), 32)],
11656
- ['name', getStringCodec()],
11657
- ['symbol', getStringCodec()],
11658
- ['uri', getStringCodec()],
11659
- ['additionalMetadata', getArrayCodec$1(getTupleCodec$1([getStringCodec(), getStringCodec()]))],
11660
- ]);
11661
-
11662
- struct$1([
11663
- u8$1('instruction'),
11664
- publicKey$4('owner'),
11665
- ]);
11666
-
11667
- struct$1([
11668
- u8$1('instruction'),
11669
- publicKey$4('owner'),
11670
- ]);
11671
-
11672
- /** The struct that represents the instruction data as it is read by the program */
11673
- struct$1([
11674
- u8$1('instruction'),
11675
- ]);
11282
+ const tokenMetadataCodec = getStructCodec$1([
11283
+ ['updateAuthority', fixCodecSize$1(getBytesCodec$1(), 32)],
11284
+ ['mint', fixCodecSize$1(getBytesCodec$1(), 32)],
11285
+ ['name', getStringCodec()],
11286
+ ['symbol', getStringCodec()],
11287
+ ['uri', getStringCodec()],
11288
+ ['additionalMetadata', getArrayCodec$1(getTupleCodec$1([getStringCodec(), getStringCodec()]))],
11289
+ ]);
11290
+ // Checks if all elements in the array are 0
11291
+ function isNonePubkey(buffer) {
11292
+ for (let i = 0; i < buffer.length; i++) {
11293
+ if (buffer[i] !== 0) {
11294
+ return false;
11295
+ }
11296
+ }
11297
+ return true;
11298
+ }
11299
+ // unpack byte slab into TokenMetadata
11300
+ function unpack(buffer) {
11301
+ const data = tokenMetadataCodec.decode(buffer);
11302
+ return isNonePubkey(data.updateAuthority)
11303
+ ? {
11304
+ mint: new PublicKey(data.mint),
11305
+ name: data.name,
11306
+ symbol: data.symbol,
11307
+ uri: data.uri,
11308
+ additionalMetadata: data.additionalMetadata,
11309
+ }
11310
+ : {
11311
+ updateAuthority: new PublicKey(data.updateAuthority),
11312
+ mint: new PublicKey(data.mint),
11313
+ name: data.name,
11314
+ symbol: data.symbol,
11315
+ uri: data.uri,
11316
+ additionalMetadata: data.additionalMetadata,
11317
+ };
11318
+ }
11319
+
11320
+ struct$1([
11321
+ u8$1('instruction'),
11322
+ publicKey$4('owner'),
11323
+ ]);
11324
+
11325
+ struct$1([
11326
+ u8$1('instruction'),
11327
+ publicKey$4('owner'),
11328
+ ]);
11329
+
11330
+ /** The struct that represents the instruction data as it is read by the program */
11331
+ struct$1([
11332
+ u8$1('instruction'),
11333
+ ]);
11334
+
11335
+ /** TODO: docs */
11336
+ struct$1([
11337
+ u8$1('instruction'),
11338
+ new COptionPublicKeyLayout('closeAuthority'),
11339
+ ]);
11340
+
11341
+ /** The struct that represents the instruction data as it is read by the program */
11342
+ struct$1([
11343
+ u8$1('instruction'),
11344
+ ]);
11345
+
11346
+ /** TODO: docs */
11347
+ struct$1([
11348
+ u8$1('instruction'),
11349
+ publicKey$4('delegate'),
11350
+ ]);
11351
+
11352
+ var AccountState;
11353
+ (function (AccountState) {
11354
+ AccountState[AccountState["Uninitialized"] = 0] = "Uninitialized";
11355
+ AccountState[AccountState["Initialized"] = 1] = "Initialized";
11356
+ AccountState[AccountState["Frozen"] = 2] = "Frozen";
11357
+ })(AccountState || (AccountState = {}));
11358
+ const AccountLayout = struct$1([
11359
+ publicKey$4("mint"),
11360
+ publicKey$4("owner"),
11361
+ u64$1("amount"),
11362
+ u32$1("delegateOption"),
11363
+ publicKey$4("delegate"),
11364
+ u8$1("state"),
11365
+ u32$1("isNativeOption"),
11366
+ u64$1("isNative"),
11367
+ u64$1("delegatedAmount"),
11368
+ u32$1("closeAuthorityOption"),
11369
+ publicKey$4("closeAuthority"),
11370
+ ]);
11371
+ var AccountType;
11372
+ (function (AccountType) {
11373
+ AccountType[AccountType["System"] = 0] = "System";
11374
+ AccountType[AccountType["Token"] = 1] = "Token";
11375
+ AccountType[AccountType["CorrectATA"] = 2] = "CorrectATA";
11376
+ AccountType[AccountType["Unknown"] = 3] = "Unknown";
11377
+ AccountType[AccountType["NotExists"] = 4] = "NotExists";
11378
+ })(AccountType || (AccountType = {}));
11379
+ /**
11380
+ * Get name, symbol and decimals for provided token
11381
+ * @param connection solana web3 connection
11382
+ * @param tokenAddress address to get metaplex info for
11383
+ * @returns
11384
+ */
11385
+ function getTokenInfo(connection, tokenAddress) {
11386
+ return __awaiter(this, void 0, void 0, function* () {
11387
+ var _a;
11388
+ const tokenMetaProgramId = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
11389
+ const findMetaplexMetadataPda = (tokenMint) => PublicKey.findProgramAddressSync([
11390
+ buffer.Buffer.from("metadata", "utf-8"),
11391
+ tokenMetaProgramId.toBuffer(),
11392
+ tokenMint.toBuffer(),
11393
+ ], tokenMetaProgramId)[0];
11394
+ const decodeMetaplexMetadataPartial = (data) => {
11395
+ const rawName = data.subarray(65 + 4, 65 + 36); // omit first 4 bytes, size is already hardcoded
11396
+ const rawSymbol = data.subarray(101 + 4, 115); // omit first 4 bytes, size is already hardcoded
11397
+ const rawUri = data.subarray(115 + 4, 204); // omit first 4 bytes, size is already hardcoded
11398
+ return {
11399
+ uri: rawUri.toString("utf-8").replace(/\u0000/g, ""),
11400
+ symbol: rawSymbol.toString("utf-8").replace(/\u0000/g, ""),
11401
+ name: rawName.toString("utf-8").replace(/\u0000/g, ""),
11402
+ };
11403
+ };
11404
+ const pda = findMetaplexMetadataPda(tokenAddress);
11405
+ const [tokenAccount, pdaAccount] = yield connection.getMultipleAccountsInfo([
11406
+ tokenAddress,
11407
+ pda,
11408
+ ]);
11409
+ if (tokenAccount === null) {
11410
+ return null;
11411
+ }
11412
+ const mint2022 = unpackMint(tokenAddress, tokenAccount, tokenAccount.owner);
11413
+ const extTypes = getExtensionTypes((_a = mint2022.tlvData) !== null && _a !== void 0 ? _a : buffer.Buffer.alloc(0));
11414
+ const tokenMetaBuf = extTypes.includes(ExtensionType.TokenMetadata)
11415
+ ? getExtensionData(ExtensionType.TokenMetadata, mint2022.tlvData)
11416
+ : null;
11417
+ if (tokenMetaBuf) {
11418
+ const meta = unpack(tokenMetaBuf);
11419
+ return {
11420
+ address: tokenAddress,
11421
+ decimals: mint2022.decimals,
11422
+ name: meta.name,
11423
+ symbol: meta.symbol,
11424
+ json: meta.uri,
11425
+ };
11426
+ }
11427
+ if (extTypes.includes(ExtensionType.MetadataPointer)) {
11428
+ const mpState = getMetadataPointerState(mint2022);
11429
+ if ((mpState === null || mpState === void 0 ? void 0 : mpState.metadataAddress) &&
11430
+ mpState.metadataAddress.equals(tokenAddress)) {
11431
+ const inlineMetaBuf = getExtensionData(ExtensionType.TokenMetadata, mint2022.tlvData);
11432
+ if (inlineMetaBuf) {
11433
+ const meta = unpack(inlineMetaBuf);
11434
+ return {
11435
+ address: tokenAddress,
11436
+ decimals: mint2022.decimals,
11437
+ name: meta.name,
11438
+ symbol: meta.symbol,
11439
+ json: meta.uri,
11440
+ };
11441
+ }
11442
+ }
11443
+ }
11444
+ if (pdaAccount === null || (pdaAccount === null || pdaAccount === void 0 ? void 0 : pdaAccount.lamports) === 0) {
11445
+ return null;
11446
+ }
11447
+ // parse token account
11448
+ // mint_authority - coption(pubkey) = 4 or 36
11449
+ // supply - u64 = 8
11450
+ // decimals - u8
11451
+ let decimalsOffset = 12;
11452
+ if (tokenAccount.data[0] === 1)
11453
+ decimalsOffset += 32;
11454
+ const decimals = tokenAccount.data[decimalsOffset];
11455
+ const { name, symbol, uri } = decodeMetaplexMetadataPartial(pdaAccount.data);
11456
+ return {
11457
+ address: tokenAddress,
11458
+ decimals,
11459
+ name,
11460
+ symbol,
11461
+ json: uri,
11462
+ };
11463
+ });
11464
+ }
11465
+ /**
11466
+ * Builds instruction for creation of associated wallet for specified token
11467
+ * @param tokenMint mint account of SPL-token
11468
+ * @param associatedAccount associated account address
11469
+ * @param owner owner of the associated account
11470
+ * @param payer who pays for account creation
11471
+ */
11472
+ function createAssociatedWalletInstruction(tokenMint, associatedAccount, owner, payer, associatedTokenProramId) {
11473
+ tokenMint = new PublicKey(tokenMint);
11474
+ payer = new PublicKey(payer);
11475
+ owner = new PublicKey(owner);
11476
+ return new TransactionInstruction({
11477
+ programId: associatedTokenProramId || ASSOCIATED_TOKEN_PROGRAM_ID,
11478
+ data: buffer.Buffer.from([1]),
11479
+ keys: [
11480
+ {
11481
+ pubkey: payer,
11482
+ isSigner: true,
11483
+ isWritable: true,
11484
+ },
11485
+ {
11486
+ pubkey: associatedAccount,
11487
+ isSigner: false,
11488
+ isWritable: true,
11489
+ },
11490
+ {
11491
+ pubkey: owner,
11492
+ isSigner: false,
11493
+ isWritable: false,
11494
+ },
11495
+ {
11496
+ pubkey: tokenMint,
11497
+ isSigner: false,
11498
+ isWritable: false,
11499
+ },
11500
+ {
11501
+ pubkey: SystemProgram.programId,
11502
+ isSigner: false,
11503
+ isWritable: false,
11504
+ },
11505
+ {
11506
+ pubkey: TOKEN_PROGRAM_ID$1,
11507
+ isSigner: false,
11508
+ isWritable: false,
11509
+ },
11510
+ ],
11511
+ });
11512
+ }
11513
+ function parseSplAccount(dataOrInfo) {
11514
+ if (dataOrInfo === null) {
11515
+ return null;
11516
+ }
11517
+ const data = "executable" in dataOrInfo ? dataOrInfo.data : dataOrInfo;
11518
+ data.subarray(0, 165); // only use static part
11519
+ // if (data.length === 82) return null; // token mint
11520
+ try {
11521
+ return AccountLayout.decode(data);
11522
+ }
11523
+ catch (e) {
11524
+ console.error(e);
11525
+ }
11526
+ return null;
11527
+ }
11528
+ function isWalletCorrectATA(walletAddress, data) {
11529
+ const decoded = parseSplAccount(data);
11530
+ if (!decoded)
11531
+ return false;
11532
+ const [realAta] = findAssociatedTokenAddress(decoded.owner, decoded.mint);
11533
+ return realAta.equals(new PublicKey(walletAddress));
11534
+ }
11535
+ /**
11536
+ * Requests account from blockchain and returns result with account type
11537
+ * @param account address of account
11538
+ * @returns account info and account type
11539
+ */
11540
+ function getAccountWithType(connection, account) {
11541
+ return __awaiter(this, void 0, void 0, function* () {
11542
+ account = new PublicKey(account);
11543
+ const accountData = yield getAccountInfo(connection, account);
11544
+ if (!accountData)
11545
+ return [null, AccountType.NotExists];
11546
+ if (accountData.owner.equals(TOKEN_PROGRAM_ID$1)) {
11547
+ return isWalletCorrectATA(account, accountData.data)
11548
+ ? [accountData, AccountType.CorrectATA]
11549
+ : [accountData, AccountType.Token];
11550
+ }
11551
+ if (accountData.owner.equals(SystemProgram.programId))
11552
+ return [accountData, AccountType.System];
11553
+ return [accountData, AccountType.Unknown];
11554
+ });
11555
+ }
11556
+ /**
11557
+ * Returns balance of specified wallet in native tokens
11558
+ * @param wallet wallet to inspect
11559
+ */
11560
+ function getNativeWalletBalance(connection, wallet) {
11561
+ return __awaiter(this, void 0, void 0, function* () {
11562
+ wallet = new PublicKey(wallet);
11563
+ const result = yield connection.getBalance(wallet);
11564
+ return new BN(result.toString());
11565
+ });
11566
+ }
11567
+ /**
11568
+ * Returns balance of associated wallet in SPL-tokens
11569
+ * @param originalWallet native tokens wallet address
11570
+ * @param tokenMint mint of SPL-Token
11571
+ */
11572
+ function getAssocSPLWalletBalance(connection, originalWallet, tokenMint) {
11573
+ return __awaiter(this, void 0, void 0, function* () {
11574
+ originalWallet = new PublicKey(originalWallet);
11575
+ tokenMint = new PublicKey(tokenMint);
11576
+ const [wallet] = findAssociatedTokenAddress(originalWallet, tokenMint);
11577
+ const result = yield connection.getTokenAccountBalance(wallet, "finalized");
11578
+ return new BN(result.value.amount);
11579
+ });
11580
+ }
11581
+ /**
11582
+ * Returns balance of specified wallet in SPL-tokens
11583
+ * @param wallet spl-tokens wallet address
11584
+ */
11585
+ function getSPLWalletBalance(connection, wallet) {
11586
+ return __awaiter(this, void 0, void 0, function* () {
11587
+ wallet = new PublicKey(wallet);
11588
+ const result = yield connection.getTokenAccountBalance(wallet, "finalized");
11589
+ return new BN(result.value.amount);
11590
+ });
11591
+ }
11592
+ /**
11593
+ * Gets list of user's SPL-token accounts
11594
+ * @param owner owner of the SPL wallets
11595
+ * @returns list of accounts with amount on them
11596
+ */
11597
+ function getAllTokenAccountsWithBalances(connection, owner) {
11598
+ return __awaiter(this, void 0, void 0, function* () {
11599
+ const walletsData = yield connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { programId: TOKEN_PROGRAM_ID$1 });
11600
+ const wallets = walletsData.value;
11601
+ return wallets.map((wallet) => {
11602
+ const tokenInfo = wallet.account.data.parsed;
11603
+ return {
11604
+ address: wallet.pubkey,
11605
+ mint: new PublicKey(tokenInfo.info.mint),
11606
+ amount: new BN(tokenInfo.info.tokenAmount.amount),
11607
+ decimals: tokenInfo.info.tokenAmount.decimals,
11608
+ isInitialized: true,
11609
+ isNative: tokenInfo.info.isNative,
11610
+ owner: new PublicKey(tokenInfo.info.owner),
11611
+ };
11612
+ });
11613
+ });
11614
+ }
11615
+ /**
11616
+ * Gets list of user's tokenMint token accounts
11617
+ * @param tokenMint
11618
+ * @param owner owner of the wallets
11619
+ * @returns list of accounts with amount on them
11620
+ */
11621
+ function getTokenAccountsWithBalance(connection, tokenMint, owner) {
11622
+ return __awaiter(this, void 0, void 0, function* () {
11623
+ const walletsData = yield connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { mint: new PublicKey(tokenMint) });
11624
+ const wallets = walletsData.value;
11625
+ return wallets.map((wallet) => {
11626
+ const tokenInfo = wallet.account.data.parsed;
11627
+ return {
11628
+ address: wallet.pubkey,
11629
+ mint: new PublicKey(tokenInfo.info.mint),
11630
+ amount: new BN(tokenInfo.info.tokenAmount.amount),
11631
+ decimals: tokenInfo.info.tokenAmount.decimals,
11632
+ isInitialized: true,
11633
+ isNative: tokenInfo.info.isNative,
11634
+ owner: new PublicKey(tokenInfo.info.owner),
11635
+ };
11636
+ });
11637
+ });
11638
+ }
11639
+ /**
11640
+ * Builds transaction to transfer&wrap native sol from src wallet to dst wallet
11641
+ * @param amount number of lamports to transfer and wrap
11642
+ * @param transferFrom source native account
11643
+ * @param transferTo destination wallet
11644
+ * @returns transaction to transfer&wrap sol
11645
+ */
11646
+ function buildReplenishWsolBalanceTransaction(amount, transferFrom, transferTo) {
11647
+ transferFrom = new PublicKey(transferFrom);
11648
+ transferTo = new PublicKey(transferTo);
11649
+ const tx = new Transaction();
11650
+ tx.add(SystemProgram.transfer({
11651
+ fromPubkey: transferFrom,
11652
+ toPubkey: transferTo,
11653
+ lamports: new BN(amount).toNumber(),
11654
+ }));
11655
+ tx.add(
11656
+ // sync native
11657
+ new TransactionInstruction({
11658
+ keys: [{ pubkey: transferTo, isSigner: false, isWritable: true }],
11659
+ programId: TOKEN_PROGRAM_ID$1,
11660
+ data: buffer.Buffer.from([17]),
11661
+ }));
11662
+ tx.feePayer = transferFrom;
11663
+ return tx;
11664
+ }
11665
+ /**
11666
+ * Builds transaction that wraps specified amount of lamports into spl, if account is missing will create it
11667
+ * @param amount lamports to wrap, ATA will contain exact amount of lamports
11668
+ * @param owner owner of created wallet
11669
+ */
11670
+ function updateWsolBalance(connection, amount, owner) {
11671
+ return __awaiter(this, void 0, void 0, function* () {
11672
+ owner = new PublicKey(owner);
11673
+ const tx = new Transaction();
11674
+ const [wSolATA] = findAssociatedTokenAddress(owner, WRAPPED_SOL_MINT);
11675
+ const existingATA = yield getAccountInfo(connection, wSolATA);
11676
+ let amountToWrap = new BN(amount);
11677
+ if (existingATA === null) {
11678
+ tx.add(createAssociatedWalletInstruction(WRAPPED_SOL_MINT, wSolATA, owner, owner));
11679
+ }
11680
+ else {
11681
+ const parsed = parseSplAccount(existingATA.data);
11682
+ if (!parsed)
11683
+ throw new Error("WSol account exists, but failed to decode its content");
11684
+ const parsedAmount = new BN(parsed.amount.toString());
11685
+ if (amountToWrap.lte(parsedAmount))
11686
+ return null; // don't need to wrap
11687
+ amountToWrap = amountToWrap.sub(parsedAmount);
11688
+ }
11689
+ const replenishTx = buildReplenishWsolBalanceTransaction(amountToWrap, owner, wSolATA);
11690
+ tx.add(replenishTx);
11691
+ return tx;
11692
+ });
11693
+ }
11694
+ /**
11695
+ * Checks existance of associated wallet for specified token
11696
+ * @param mintAccount mint account of SPL-token
11697
+ * @param originalWallet account of solana wallet
11698
+ * @returns true if account exists
11699
+ */
11700
+ function checkIfAssociatedWalletExists(connection, mintAccount, originalWallet) {
11701
+ return __awaiter(this, void 0, void 0, function* () {
11702
+ const [walletAccount] = findAssociatedTokenAddress(originalWallet, mintAccount);
11703
+ const accountData = yield getAccountInfo(connection, walletAccount);
11704
+ return accountData !== null;
11705
+ });
11706
+ }
11707
+ function getTransactionAccountsForSimulationDiff(connection, tx) {
11708
+ return __awaiter(this, void 0, void 0, function* () {
11709
+ var _a, _b;
11710
+ const result = new Set();
11711
+ if ("version" in tx) {
11712
+ const ALTs = tx.message.addressTableLookups.map((alt) => alt.accountKey);
11713
+ const fetchedALTs = yield connection.getMultipleAccountsInfo(ALTs);
11714
+ const parsedALTs = fetchedALTs
11715
+ .map((fetched, i) => fetched
11716
+ ? new AddressLookupTableAccount({
11717
+ state: AddressLookupTableAccount.deserialize(fetched.data),
11718
+ key: ALTs[i],
11719
+ })
11720
+ : null)
11721
+ .filter((x) => x != null);
11722
+ const accGetter = tx.message.getAccountKeys({
11723
+ addressLookupTableAccounts: parsedALTs,
11724
+ });
11725
+ const staticWritableOrSignerAccounts = [];
11726
+ for (let idx = 0; idx < accGetter.staticAccountKeys.length; idx += 1) {
11727
+ if (tx.message.isAccountSigner(idx) || tx.message.isAccountWritable(idx))
11728
+ staticWritableOrSignerAccounts.push(accGetter.staticAccountKeys[idx]);
11729
+ }
11730
+ for (const acc of [
11731
+ ...staticWritableOrSignerAccounts,
11732
+ ...((_b = (_a = accGetter.accountKeysFromLookups) === null || _a === void 0 ? void 0 : _a.writable) !== null && _b !== void 0 ? _b : []),
11733
+ ]) {
11734
+ result.add(acc.toBase58());
11735
+ }
11736
+ }
11737
+ else {
11738
+ const compiled = tx.compileMessage();
11739
+ for (let idx = 0; idx < compiled.accountKeys.length; idx += 1) {
11740
+ if (compiled.isAccountSigner(idx) || compiled.isAccountWritable(idx))
11741
+ result.add(compiled.staticAccountKeys[idx].toBase58());
11742
+ }
11743
+ }
11744
+ return Array.from(result);
11745
+ });
11746
+ }
11747
+ function parseMultipleAccounts(accounts) {
11748
+ return accounts.map((account) => {
11749
+ var _a, _b;
11750
+ let parsedSplAccount;
11751
+ if (account) {
11752
+ const owner = new PublicKey(account.owner);
11753
+ if (owner.equals(TOKEN_PROGRAM_ID$1) ||
11754
+ owner.equals(TOKEN_2022_PROGRAM_ID)) {
11755
+ if (account.data instanceof buffer.Buffer) {
11756
+ parsedSplAccount = parseSplAccount(account.data);
11757
+ }
11758
+ else if (account.data instanceof Array) {
11759
+ parsedSplAccount = parseSplAccount(buffer.Buffer.from(account.data[0], account.data[1]));
11760
+ }
11761
+ }
11762
+ }
11763
+ const parsedAccount = {
11764
+ balance: (_a = account === null || account === void 0 ? void 0 : account.lamports) !== null && _a !== void 0 ? _a : 0,
11765
+ };
11766
+ if (parsedSplAccount) {
11767
+ parsedAccount.spl = {
11768
+ mint: parsedSplAccount.mint,
11769
+ owner: parsedSplAccount.owner,
11770
+ balance: (_b = parsedSplAccount.amount) !== null && _b !== void 0 ? _b : BigInt(0),
11771
+ };
11772
+ }
11773
+ return parsedAccount;
11774
+ });
11775
+ }
11776
+ function getSplDiff(pre, post) {
11777
+ var _a, _b, _c, _d, _e, _f;
11778
+ const preBalance = (_a = pre === null || pre === void 0 ? void 0 : pre.balance) !== null && _a !== void 0 ? _a : BigInt(0);
11779
+ const postBalance = (_b = post === null || post === void 0 ? void 0 : post.balance) !== null && _b !== void 0 ? _b : BigInt(0);
11780
+ return {
11781
+ mint: (_c = pre === null || pre === void 0 ? void 0 : pre.mint) !== null && _c !== void 0 ? _c : post === null || post === void 0 ? void 0 : post.mint,
11782
+ owner: (_d = pre === null || pre === void 0 ? void 0 : pre.owner) !== null && _d !== void 0 ? _d : post === null || post === void 0 ? void 0 : post.owner,
11783
+ preBalance: (_e = pre === null || pre === void 0 ? void 0 : pre.balance) !== null && _e !== void 0 ? _e : 0,
11784
+ postBalance: (_f = post === null || post === void 0 ? void 0 : post.balance) !== null && _f !== void 0 ? _f : 0,
11785
+ diff: postBalance - preBalance,
11786
+ };
11787
+ }
11788
+ function getTransactionDiff(connection, tx, txAccounts) {
11789
+ return __awaiter(this, void 0, void 0, function* () {
11790
+ const accountsStrings = txAccounts
11791
+ ? txAccounts.map((acc) => acc.toBase58())
11792
+ : yield getTransactionAccountsForSimulationDiff(connection, tx);
11793
+ const accountsPubKeys = txAccounts !== null && txAccounts !== void 0 ? txAccounts : accountsStrings.map((key) => new PublicKey(key));
11794
+ let [accountsInfo, simulatedTx] = yield Promise.all([
11795
+ connection.getMultipleAccountsInfo(accountsPubKeys),
11796
+ connection.simulateTransaction(tx, {
11797
+ replaceRecentBlockhash: true,
11798
+ accounts: {
11799
+ encoding: "base64",
11800
+ addresses: accountsStrings,
11801
+ },
11802
+ }),
11803
+ ]);
11804
+ if (simulatedTx.value.err !== null)
11805
+ throw new Error(JSON.stringify({
11806
+ err: simulatedTx.value.err,
11807
+ logs: simulatedTx.value.logs,
11808
+ }));
11809
+ const simulatesInfo = simulatedTx.value.accounts;
11810
+ const preBalances = parseMultipleAccounts(accountsInfo);
11811
+ const postBalances = parseMultipleAccounts(simulatesInfo);
11812
+ const balancesDiff = accountsPubKeys.reduce((map, pubKey, i) => {
11813
+ var _a;
11814
+ if ((_a = accountsInfo[i]) === null || _a === void 0 ? void 0 : _a.executable) {
11815
+ return map;
11816
+ }
11817
+ const preBalance = preBalances[i];
11818
+ const postBalance = postBalances[i];
11819
+ const diff = {
11820
+ pubKey: pubKey,
11821
+ preBalance: preBalance.balance,
11822
+ postBalance: postBalance.balance,
11823
+ diff: postBalance.balance - preBalance.balance,
11824
+ };
11825
+ if (preBalance.spl || postBalance.spl) {
11826
+ const splDiff = getSplDiff(preBalance.spl, postBalance.spl);
11827
+ if (splDiff.diff) {
11828
+ diff.spl = splDiff;
11829
+ }
11830
+ }
11831
+ if (diff.diff || diff.spl) {
11832
+ map.set(pubKey.toString(), diff);
11833
+ }
11834
+ return map;
11835
+ }, new Map());
11836
+ return balancesDiff;
11837
+ });
11838
+ }
11676
11839
 
11677
- /** TODO: docs */
11678
- struct$1([
11679
- u8$1('instruction'),
11680
- new COptionPublicKeyLayout('closeAuthority'),
11681
- ]);
11840
+ var spl = /*#__PURE__*/Object.freeze({
11841
+ __proto__: null,
11842
+ get AccountType () { return AccountType; },
11843
+ getTokenInfo: getTokenInfo,
11844
+ createAssociatedWalletInstruction: createAssociatedWalletInstruction,
11845
+ parseSplAccount: parseSplAccount,
11846
+ isWalletCorrectATA: isWalletCorrectATA,
11847
+ getAccountWithType: getAccountWithType,
11848
+ getNativeWalletBalance: getNativeWalletBalance,
11849
+ getAssocSPLWalletBalance: getAssocSPLWalletBalance,
11850
+ getSPLWalletBalance: getSPLWalletBalance,
11851
+ getAllTokenAccountsWithBalances: getAllTokenAccountsWithBalances,
11852
+ getTokenAccountsWithBalance: getTokenAccountsWithBalance,
11853
+ buildReplenishWsolBalanceTransaction: buildReplenishWsolBalanceTransaction,
11854
+ updateWsolBalance: updateWsolBalance,
11855
+ checkIfAssociatedWalletExists: checkIfAssociatedWalletExists,
11856
+ getTransactionAccountsForSimulationDiff: getTransactionAccountsForSimulationDiff,
11857
+ parseMultipleAccounts: parseMultipleAccounts,
11858
+ getSplDiff: getSplDiff,
11859
+ getTransactionDiff: getTransactionDiff
11860
+ });
11682
11861
 
11683
- /** The struct that represents the instruction data as it is read by the program */
11684
- struct$1([
11685
- u8$1('instruction'),
11686
- ]);
11862
+ const deBridge = "DEbrdGj3HsRsAzx6uH4MKyREKxVAfBydijLUF3ygsFfh";
11863
+ const settings = "DeSetTwWhjZq6Pz9Kfdo1KoS5NqtsM6G8ERbX4SSCSft";
11864
+ const dlnSrc = "src5qyZHqTqecJV4aY6Cb6zDZLMDzrDKKezs22MPHr4";
11865
+ const dlnDst = "dst5MGcFPoBeREFAA5E3tU5ij8m5uVYwkzkSAbsLbNo";
11866
+ const dlnExecutor = "exe59FS5cojZkPJVDFDV8RnXCC7wd6yoBjsUtqH7Zai";
11687
11867
 
11688
- /** TODO: docs */
11689
- struct$1([
11690
- u8$1('instruction'),
11691
- publicKey$4('delegate'),
11692
- ]);
11868
+ var programs = /*#__PURE__*/Object.freeze({
11869
+ __proto__: null,
11870
+ deBridge: deBridge,
11871
+ settings: settings,
11872
+ dlnSrc: dlnSrc,
11873
+ dlnDst: dlnDst,
11874
+ dlnExecutor: dlnExecutor
11875
+ });
11693
11876
 
11694
11877
  var safeBuffer = {exports: {}};
11695
11878
 
@@ -28953,7 +29136,7 @@ function simulateTransaction(connection, tx, simulateConfig) {
28953
29136
  for (const [idx, simulatedAccountInfo] of ((_c = result.value.accounts) !== null && _c !== void 0 ? _c : []).entries()) {
28954
29137
  const accountAddress = addressesToGetDiffFor[idx];
28955
29138
  const oldAccountData = (_d = accountsToFetch.at(idx)) !== null && _d !== void 0 ? _d : null;
28956
- const oldParsedMaybeSpl = (oldAccountData === null || oldAccountData === void 0 ? void 0 : oldAccountData.owner.equals(TOKEN_PROGRAM_ID))
29139
+ const oldParsedMaybeSpl = (oldAccountData === null || oldAccountData === void 0 ? void 0 : oldAccountData.owner.equals(TOKEN_PROGRAM_ID$1))
28957
29140
  ? parseSplAccount(oldAccountData)
28958
29141
  : null;
28959
29142
  const oldSolValue = (_e = oldAccountData === null || oldAccountData === void 0 ? void 0 : oldAccountData.lamports) !== null && _e !== void 0 ? _e : 0;
@@ -28970,7 +29153,7 @@ function simulateTransaction(connection, tx, simulateConfig) {
28970
29153
  if (encoding !== "base64")
28971
29154
  throw new Error("Expected bs64 account data");
28972
29155
  const artificialAccountInfo = Object.assign(Object.assign({}, simulatedAccountInfo), { owner: new PublicKey(simulatedAccountInfo.owner), data: Buffer.from(rawData, "base64") });
28973
- newParsedMaybeSpl = artificialAccountInfo.owner.equals(TOKEN_PROGRAM_ID)
29156
+ newParsedMaybeSpl = artificialAccountInfo.owner.equals(TOKEN_PROGRAM_ID$1)
28974
29157
  ? parseSplAccount(artificialAccountInfo)
28975
29158
  : null;
28976
29159
  }
@@ -29084,5 +29267,5 @@ var transaction = /*#__PURE__*/Object.freeze({
29084
29267
  getErrorData: getErrorData
29085
29268
  });
29086
29269
 
29087
- export { ASSOCIATED_TOKEN_PROGRAM_ID, DeBridgeResolver, TOKEN_2022_PROGRAM_ID, TOKEN_METADATA_PROGRAM_ID, TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT, constants$1 as constants, crypto$1 as crypto, dlnDstResolver, dlnSrcResolver, findAssociatedTokenAddress, findAssociatedTokenAddressSync, getTokenMetadataAddress, helpers, interfaces, programs, spl, transaction as txs };
29270
+ export { ASSOCIATED_TOKEN_PROGRAM_ID, DeBridgeResolver, TOKEN_2022_PROGRAM_ID, TOKEN_METADATA_PROGRAM_ID, TOKEN_PROGRAM_ID$1 as TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT, constants$1 as constants, crypto$1 as crypto, dlnDstResolver, dlnSrcResolver, findAssociatedTokenAddress, findAssociatedTokenAddressSync, getTokenMetadataAddress, helpers, interfaces, programs, spl, transaction as txs };
29088
29271
  //# sourceMappingURL=index.js.map