@solana-program/token-wrap 0.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,898 @@
1
+ import { getProgramDerivedAddress, getUtf8Encoder, getAddressEncoder, getStructEncoder, getStructDecoder, getAddressDecoder, combineCodec, decodeAccount, assertAccountExists, fetchEncodedAccount, assertAccountsExist, fetchEncodedAccounts, containsBytes, getU8Encoder, isProgramError, transformEncoder, getBooleanEncoder, getU8Decoder, getBooleanDecoder, getU64Encoder, getU64Decoder, AccountRole, assertTransactionIsFullySigned, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, upgradeRoleToSigner, isTransactionSigner as isTransactionSigner$1 } from '@solana/kit';
2
+ import { getMintSize, findAssociatedTokenPda, fetchMaybeToken, getCreateAssociatedTokenInstruction, getTokenDecoder } from '@solana-program/token-2022';
3
+ import { getTransferSolInstruction } from '@solana-program/system';
4
+ import '@solana-program/token';
5
+
6
+ // src/generated/accounts/backpointer.ts
7
+ async function findBackpointerPda(seeds, config = {}) {
8
+ const {
9
+ programAddress = "TwRapQCDhWkZRrDaHfZGuHxkZ91gHDRkyuzNqeU5MgR"
10
+ } = config;
11
+ return await getProgramDerivedAddress({
12
+ programAddress,
13
+ seeds: [
14
+ getUtf8Encoder().encode("backpointer"),
15
+ getAddressEncoder().encode(seeds.wrappedMint)
16
+ ]
17
+ });
18
+ }
19
+ async function findWrappedMintPda(seeds, config = {}) {
20
+ const {
21
+ programAddress = "TwRapQCDhWkZRrDaHfZGuHxkZ91gHDRkyuzNqeU5MgR"
22
+ } = config;
23
+ return await getProgramDerivedAddress({
24
+ programAddress,
25
+ seeds: [
26
+ getUtf8Encoder().encode("mint"),
27
+ getAddressEncoder().encode(seeds.unwrappedMint),
28
+ getAddressEncoder().encode(seeds.wrappedTokenProgram)
29
+ ]
30
+ });
31
+ }
32
+ async function findWrappedMintAuthorityPda(seeds, config = {}) {
33
+ const {
34
+ programAddress = "TwRapQCDhWkZRrDaHfZGuHxkZ91gHDRkyuzNqeU5MgR"
35
+ } = config;
36
+ return await getProgramDerivedAddress({
37
+ programAddress,
38
+ seeds: [
39
+ getUtf8Encoder().encode("authority"),
40
+ getAddressEncoder().encode(seeds.wrappedMint)
41
+ ]
42
+ });
43
+ }
44
+
45
+ // src/generated/accounts/backpointer.ts
46
+ function getBackpointerEncoder() {
47
+ return getStructEncoder([["unwrappedMint", getAddressEncoder()]]);
48
+ }
49
+ function getBackpointerDecoder() {
50
+ return getStructDecoder([["unwrappedMint", getAddressDecoder()]]);
51
+ }
52
+ function getBackpointerCodec() {
53
+ return combineCodec(getBackpointerEncoder(), getBackpointerDecoder());
54
+ }
55
+ function decodeBackpointer(encodedAccount) {
56
+ return decodeAccount(
57
+ encodedAccount,
58
+ getBackpointerDecoder()
59
+ );
60
+ }
61
+ async function fetchBackpointer(rpc, address, config) {
62
+ const maybeAccount = await fetchMaybeBackpointer(rpc, address, config);
63
+ assertAccountExists(maybeAccount);
64
+ return maybeAccount;
65
+ }
66
+ async function fetchMaybeBackpointer(rpc, address, config) {
67
+ const maybeAccount = await fetchEncodedAccount(rpc, address, config);
68
+ return decodeBackpointer(maybeAccount);
69
+ }
70
+ async function fetchAllBackpointer(rpc, addresses, config) {
71
+ const maybeAccounts = await fetchAllMaybeBackpointer(rpc, addresses, config);
72
+ assertAccountsExist(maybeAccounts);
73
+ return maybeAccounts;
74
+ }
75
+ async function fetchAllMaybeBackpointer(rpc, addresses, config) {
76
+ const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);
77
+ return maybeAccounts.map((maybeAccount) => decodeBackpointer(maybeAccount));
78
+ }
79
+ function getBackpointerSize() {
80
+ return 32;
81
+ }
82
+ async function fetchBackpointerFromSeeds(rpc, seeds, config = {}) {
83
+ const maybeAccount = await fetchMaybeBackpointerFromSeeds(rpc, seeds, config);
84
+ assertAccountExists(maybeAccount);
85
+ return maybeAccount;
86
+ }
87
+ async function fetchMaybeBackpointerFromSeeds(rpc, seeds, config = {}) {
88
+ const { programAddress, ...fetchConfig } = config;
89
+ const [address] = await findBackpointerPda(seeds, { programAddress });
90
+ return await fetchMaybeBackpointer(rpc, address, fetchConfig);
91
+ }
92
+ var TOKEN_WRAP_PROGRAM_ADDRESS = "TwRapQCDhWkZRrDaHfZGuHxkZ91gHDRkyuzNqeU5MgR";
93
+ var TokenWrapAccount = /* @__PURE__ */ ((TokenWrapAccount2) => {
94
+ TokenWrapAccount2[TokenWrapAccount2["Backpointer"] = 0] = "Backpointer";
95
+ return TokenWrapAccount2;
96
+ })(TokenWrapAccount || {});
97
+ var TokenWrapInstruction = /* @__PURE__ */ ((TokenWrapInstruction2) => {
98
+ TokenWrapInstruction2[TokenWrapInstruction2["CreateMint"] = 0] = "CreateMint";
99
+ TokenWrapInstruction2[TokenWrapInstruction2["Wrap"] = 1] = "Wrap";
100
+ TokenWrapInstruction2[TokenWrapInstruction2["Unwrap"] = 2] = "Unwrap";
101
+ return TokenWrapInstruction2;
102
+ })(TokenWrapInstruction || {});
103
+ function identifyTokenWrapInstruction(instruction) {
104
+ const data = "data" in instruction ? instruction.data : instruction;
105
+ if (containsBytes(data, getU8Encoder().encode(0), 0)) {
106
+ return 0 /* CreateMint */;
107
+ }
108
+ if (containsBytes(data, getU8Encoder().encode(1), 0)) {
109
+ return 1 /* Wrap */;
110
+ }
111
+ if (containsBytes(data, getU8Encoder().encode(2), 0)) {
112
+ return 2 /* Unwrap */;
113
+ }
114
+ throw new Error(
115
+ "The provided instruction could not be identified as a tokenWrap instruction."
116
+ );
117
+ }
118
+
119
+ // src/generated/errors/tokenWrap.ts
120
+ var TOKEN_WRAP_ERROR__WRAPPED_MINT_MISMATCH = 0;
121
+ var TOKEN_WRAP_ERROR__BACKPOINTER_MISMATCH = 1;
122
+ var TOKEN_WRAP_ERROR__ZERO_WRAP_AMOUNT = 2;
123
+ var TOKEN_WRAP_ERROR__MINT_AUTHORITY_MISMATCH = 3;
124
+ var TOKEN_WRAP_ERROR__ESCROW_OWNER_MISMATCH = 4;
125
+ var TOKEN_WRAP_ERROR__INVALID_WRAPPED_MINT_OWNER = 5;
126
+ var TOKEN_WRAP_ERROR__INVALID_BACKPOINTER_OWNER = 6;
127
+ var TOKEN_WRAP_ERROR__ESCROW_MISMATCH = 7;
128
+ var tokenWrapErrorMessages;
129
+ if (process.env.NODE_ENV !== "production") {
130
+ tokenWrapErrorMessages = {
131
+ [TOKEN_WRAP_ERROR__BACKPOINTER_MISMATCH]: `Wrapped backpointer account address does not match expected PDA`,
132
+ [TOKEN_WRAP_ERROR__ESCROW_MISMATCH]: `Escrow account address does not match expected ATA`,
133
+ [TOKEN_WRAP_ERROR__ESCROW_OWNER_MISMATCH]: `Unwrapped escrow token owner is not set to expected PDA`,
134
+ [TOKEN_WRAP_ERROR__INVALID_BACKPOINTER_OWNER]: `Wrapped backpointer account owner is not the expected token wrap program`,
135
+ [TOKEN_WRAP_ERROR__INVALID_WRAPPED_MINT_OWNER]: `Wrapped mint account owner is not the expected token program`,
136
+ [TOKEN_WRAP_ERROR__MINT_AUTHORITY_MISMATCH]: `Wrapped mint authority does not match expected PDA`,
137
+ [TOKEN_WRAP_ERROR__WRAPPED_MINT_MISMATCH]: `Wrapped mint account address does not match expected PDA`,
138
+ [TOKEN_WRAP_ERROR__ZERO_WRAP_AMOUNT]: `Wrap amount should be positive`
139
+ };
140
+ }
141
+ function getTokenWrapErrorMessage(code) {
142
+ if (process.env.NODE_ENV !== "production") {
143
+ return tokenWrapErrorMessages[code];
144
+ }
145
+ return "Error message not available in production bundles.";
146
+ }
147
+ function isTokenWrapError(error, transactionMessage, code) {
148
+ return isProgramError(
149
+ error,
150
+ transactionMessage,
151
+ TOKEN_WRAP_PROGRAM_ADDRESS,
152
+ code
153
+ );
154
+ }
155
+ function expectAddress(value) {
156
+ if (!value) {
157
+ throw new Error("Expected a Address.");
158
+ }
159
+ if (typeof value === "object" && "address" in value) {
160
+ return value.address;
161
+ }
162
+ if (Array.isArray(value)) {
163
+ return value[0];
164
+ }
165
+ return value;
166
+ }
167
+ function getAccountMetaFactory(programAddress, optionalAccountStrategy) {
168
+ return (account) => {
169
+ if (!account.value) {
170
+ return Object.freeze({
171
+ address: programAddress,
172
+ role: AccountRole.READONLY
173
+ });
174
+ }
175
+ const writableRole = account.isWritable ? AccountRole.WRITABLE : AccountRole.READONLY;
176
+ return Object.freeze({
177
+ address: expectAddress(account.value),
178
+ role: isTransactionSigner(account.value) ? upgradeRoleToSigner(writableRole) : writableRole,
179
+ ...isTransactionSigner(account.value) ? { signer: account.value } : {}
180
+ });
181
+ };
182
+ }
183
+ function isTransactionSigner(value) {
184
+ return !!value && typeof value === "object" && "address" in value && isTransactionSigner$1(value);
185
+ }
186
+
187
+ // src/generated/instructions/createMint.ts
188
+ var CREATE_MINT_DISCRIMINATOR = 0;
189
+ function getCreateMintDiscriminatorBytes() {
190
+ return getU8Encoder().encode(CREATE_MINT_DISCRIMINATOR);
191
+ }
192
+ function getCreateMintInstructionDataEncoder() {
193
+ return transformEncoder(
194
+ getStructEncoder([
195
+ ["discriminator", getU8Encoder()],
196
+ ["idempotent", getBooleanEncoder()]
197
+ ]),
198
+ (value) => ({
199
+ ...value,
200
+ discriminator: CREATE_MINT_DISCRIMINATOR,
201
+ idempotent: value.idempotent ?? false
202
+ })
203
+ );
204
+ }
205
+ function getCreateMintInstructionDataDecoder() {
206
+ return getStructDecoder([
207
+ ["discriminator", getU8Decoder()],
208
+ ["idempotent", getBooleanDecoder()]
209
+ ]);
210
+ }
211
+ function getCreateMintInstructionDataCodec() {
212
+ return combineCodec(
213
+ getCreateMintInstructionDataEncoder(),
214
+ getCreateMintInstructionDataDecoder()
215
+ );
216
+ }
217
+ function getCreateMintInstruction(input, config) {
218
+ const programAddress = config?.programAddress ?? TOKEN_WRAP_PROGRAM_ADDRESS;
219
+ const originalAccounts = {
220
+ wrappedMint: { value: input.wrappedMint ?? null, isWritable: true },
221
+ backpointer: { value: input.backpointer ?? null, isWritable: true },
222
+ unwrappedMint: { value: input.unwrappedMint ?? null, isWritable: false },
223
+ systemProgram: { value: input.systemProgram ?? null, isWritable: false },
224
+ wrappedTokenProgram: {
225
+ value: input.wrappedTokenProgram ?? null,
226
+ isWritable: false
227
+ }
228
+ };
229
+ const accounts = originalAccounts;
230
+ const args = { ...input };
231
+ if (!accounts.systemProgram.value) {
232
+ accounts.systemProgram.value = "11111111111111111111111111111111";
233
+ }
234
+ const getAccountMeta = getAccountMetaFactory(programAddress);
235
+ const instruction = {
236
+ accounts: [
237
+ getAccountMeta(accounts.wrappedMint),
238
+ getAccountMeta(accounts.backpointer),
239
+ getAccountMeta(accounts.unwrappedMint),
240
+ getAccountMeta(accounts.systemProgram),
241
+ getAccountMeta(accounts.wrappedTokenProgram)
242
+ ],
243
+ programAddress,
244
+ data: getCreateMintInstructionDataEncoder().encode(
245
+ args
246
+ )
247
+ };
248
+ return instruction;
249
+ }
250
+ function parseCreateMintInstruction(instruction) {
251
+ if (instruction.accounts.length < 5) {
252
+ throw new Error("Not enough accounts");
253
+ }
254
+ let accountIndex = 0;
255
+ const getNextAccount = () => {
256
+ const accountMeta = instruction.accounts[accountIndex];
257
+ accountIndex += 1;
258
+ return accountMeta;
259
+ };
260
+ const getNextOptionalAccount = () => {
261
+ const accountMeta = getNextAccount();
262
+ return accountMeta.address === TOKEN_WRAP_PROGRAM_ADDRESS ? void 0 : accountMeta;
263
+ };
264
+ return {
265
+ programAddress: instruction.programAddress,
266
+ accounts: {
267
+ wrappedMint: getNextAccount(),
268
+ backpointer: getNextAccount(),
269
+ unwrappedMint: getNextAccount(),
270
+ systemProgram: getNextOptionalAccount(),
271
+ wrappedTokenProgram: getNextAccount()
272
+ },
273
+ data: getCreateMintInstructionDataDecoder().decode(instruction.data)
274
+ };
275
+ }
276
+ var UNWRAP_DISCRIMINATOR = 2;
277
+ function getUnwrapDiscriminatorBytes() {
278
+ return getU8Encoder().encode(UNWRAP_DISCRIMINATOR);
279
+ }
280
+ function getUnwrapInstructionDataEncoder() {
281
+ return transformEncoder(
282
+ getStructEncoder([
283
+ ["discriminator", getU8Encoder()],
284
+ ["amount", getU64Encoder()]
285
+ ]),
286
+ (value) => ({ ...value, discriminator: UNWRAP_DISCRIMINATOR })
287
+ );
288
+ }
289
+ function getUnwrapInstructionDataDecoder() {
290
+ return getStructDecoder([
291
+ ["discriminator", getU8Decoder()],
292
+ ["amount", getU64Decoder()]
293
+ ]);
294
+ }
295
+ function getUnwrapInstructionDataCodec() {
296
+ return combineCodec(
297
+ getUnwrapInstructionDataEncoder(),
298
+ getUnwrapInstructionDataDecoder()
299
+ );
300
+ }
301
+ function getUnwrapInstruction(input, config) {
302
+ const programAddress = config?.programAddress ?? TOKEN_WRAP_PROGRAM_ADDRESS;
303
+ const originalAccounts = {
304
+ unwrappedEscrow: { value: input.unwrappedEscrow ?? null, isWritable: true },
305
+ recipientUnwrappedToken: {
306
+ value: input.recipientUnwrappedToken ?? null,
307
+ isWritable: true
308
+ },
309
+ wrappedMintAuthority: {
310
+ value: input.wrappedMintAuthority ?? null,
311
+ isWritable: false
312
+ },
313
+ unwrappedMint: { value: input.unwrappedMint ?? null, isWritable: false },
314
+ wrappedTokenProgram: {
315
+ value: input.wrappedTokenProgram ?? null,
316
+ isWritable: false
317
+ },
318
+ unwrappedTokenProgram: {
319
+ value: input.unwrappedTokenProgram ?? null,
320
+ isWritable: false
321
+ },
322
+ wrappedTokenAccount: {
323
+ value: input.wrappedTokenAccount ?? null,
324
+ isWritable: true
325
+ },
326
+ wrappedMint: { value: input.wrappedMint ?? null, isWritable: true },
327
+ transferAuthority: {
328
+ value: input.transferAuthority ?? null,
329
+ isWritable: false
330
+ }
331
+ };
332
+ const accounts = originalAccounts;
333
+ const args = { ...input };
334
+ const remainingAccounts = (args.multiSigners ?? []).map(
335
+ (signer) => ({
336
+ address: signer.address,
337
+ role: AccountRole.READONLY_SIGNER,
338
+ signer
339
+ })
340
+ );
341
+ const getAccountMeta = getAccountMetaFactory(programAddress);
342
+ const instruction = {
343
+ accounts: [
344
+ getAccountMeta(accounts.unwrappedEscrow),
345
+ getAccountMeta(accounts.recipientUnwrappedToken),
346
+ getAccountMeta(accounts.wrappedMintAuthority),
347
+ getAccountMeta(accounts.unwrappedMint),
348
+ getAccountMeta(accounts.wrappedTokenProgram),
349
+ getAccountMeta(accounts.unwrappedTokenProgram),
350
+ getAccountMeta(accounts.wrappedTokenAccount),
351
+ getAccountMeta(accounts.wrappedMint),
352
+ getAccountMeta(accounts.transferAuthority),
353
+ ...remainingAccounts
354
+ ],
355
+ programAddress,
356
+ data: getUnwrapInstructionDataEncoder().encode(
357
+ args
358
+ )
359
+ };
360
+ return instruction;
361
+ }
362
+ function parseUnwrapInstruction(instruction) {
363
+ if (instruction.accounts.length < 9) {
364
+ throw new Error("Not enough accounts");
365
+ }
366
+ let accountIndex = 0;
367
+ const getNextAccount = () => {
368
+ const accountMeta = instruction.accounts[accountIndex];
369
+ accountIndex += 1;
370
+ return accountMeta;
371
+ };
372
+ return {
373
+ programAddress: instruction.programAddress,
374
+ accounts: {
375
+ unwrappedEscrow: getNextAccount(),
376
+ recipientUnwrappedToken: getNextAccount(),
377
+ wrappedMintAuthority: getNextAccount(),
378
+ unwrappedMint: getNextAccount(),
379
+ wrappedTokenProgram: getNextAccount(),
380
+ unwrappedTokenProgram: getNextAccount(),
381
+ wrappedTokenAccount: getNextAccount(),
382
+ wrappedMint: getNextAccount(),
383
+ transferAuthority: getNextAccount()
384
+ },
385
+ data: getUnwrapInstructionDataDecoder().decode(instruction.data)
386
+ };
387
+ }
388
+ var WRAP_DISCRIMINATOR = 1;
389
+ function getWrapDiscriminatorBytes() {
390
+ return getU8Encoder().encode(WRAP_DISCRIMINATOR);
391
+ }
392
+ function getWrapInstructionDataEncoder() {
393
+ return transformEncoder(
394
+ getStructEncoder([
395
+ ["discriminator", getU8Encoder()],
396
+ ["amount", getU64Encoder()]
397
+ ]),
398
+ (value) => ({ ...value, discriminator: WRAP_DISCRIMINATOR })
399
+ );
400
+ }
401
+ function getWrapInstructionDataDecoder() {
402
+ return getStructDecoder([
403
+ ["discriminator", getU8Decoder()],
404
+ ["amount", getU64Decoder()]
405
+ ]);
406
+ }
407
+ function getWrapInstructionDataCodec() {
408
+ return combineCodec(
409
+ getWrapInstructionDataEncoder(),
410
+ getWrapInstructionDataDecoder()
411
+ );
412
+ }
413
+ function getWrapInstruction(input, config) {
414
+ const programAddress = config?.programAddress ?? TOKEN_WRAP_PROGRAM_ADDRESS;
415
+ const originalAccounts = {
416
+ recipientWrappedTokenAccount: {
417
+ value: input.recipientWrappedTokenAccount ?? null,
418
+ isWritable: true
419
+ },
420
+ wrappedMint: { value: input.wrappedMint ?? null, isWritable: true },
421
+ wrappedMintAuthority: {
422
+ value: input.wrappedMintAuthority ?? null,
423
+ isWritable: false
424
+ },
425
+ unwrappedTokenProgram: {
426
+ value: input.unwrappedTokenProgram ?? null,
427
+ isWritable: false
428
+ },
429
+ wrappedTokenProgram: {
430
+ value: input.wrappedTokenProgram ?? null,
431
+ isWritable: false
432
+ },
433
+ unwrappedTokenAccount: {
434
+ value: input.unwrappedTokenAccount ?? null,
435
+ isWritable: true
436
+ },
437
+ unwrappedMint: { value: input.unwrappedMint ?? null, isWritable: false },
438
+ unwrappedEscrow: { value: input.unwrappedEscrow ?? null, isWritable: true },
439
+ transferAuthority: {
440
+ value: input.transferAuthority ?? null,
441
+ isWritable: false
442
+ }
443
+ };
444
+ const accounts = originalAccounts;
445
+ const args = { ...input };
446
+ const remainingAccounts = (args.multiSigners ?? []).map(
447
+ (signer) => ({
448
+ address: signer.address,
449
+ role: AccountRole.READONLY_SIGNER,
450
+ signer
451
+ })
452
+ );
453
+ const getAccountMeta = getAccountMetaFactory(programAddress);
454
+ const instruction = {
455
+ accounts: [
456
+ getAccountMeta(accounts.recipientWrappedTokenAccount),
457
+ getAccountMeta(accounts.wrappedMint),
458
+ getAccountMeta(accounts.wrappedMintAuthority),
459
+ getAccountMeta(accounts.unwrappedTokenProgram),
460
+ getAccountMeta(accounts.wrappedTokenProgram),
461
+ getAccountMeta(accounts.unwrappedTokenAccount),
462
+ getAccountMeta(accounts.unwrappedMint),
463
+ getAccountMeta(accounts.unwrappedEscrow),
464
+ getAccountMeta(accounts.transferAuthority),
465
+ ...remainingAccounts
466
+ ],
467
+ programAddress,
468
+ data: getWrapInstructionDataEncoder().encode(
469
+ args
470
+ )
471
+ };
472
+ return instruction;
473
+ }
474
+ function parseWrapInstruction(instruction) {
475
+ if (instruction.accounts.length < 9) {
476
+ throw new Error("Not enough accounts");
477
+ }
478
+ let accountIndex = 0;
479
+ const getNextAccount = () => {
480
+ const accountMeta = instruction.accounts[accountIndex];
481
+ accountIndex += 1;
482
+ return accountMeta;
483
+ };
484
+ return {
485
+ programAddress: instruction.programAddress,
486
+ accounts: {
487
+ recipientWrappedTokenAccount: getNextAccount(),
488
+ wrappedMint: getNextAccount(),
489
+ wrappedMintAuthority: getNextAccount(),
490
+ unwrappedTokenProgram: getNextAccount(),
491
+ wrappedTokenProgram: getNextAccount(),
492
+ unwrappedTokenAccount: getNextAccount(),
493
+ unwrappedMint: getNextAccount(),
494
+ unwrappedEscrow: getNextAccount(),
495
+ transferAuthority: getNextAccount()
496
+ },
497
+ data: getWrapInstructionDataDecoder().decode(instruction.data)
498
+ };
499
+ }
500
+ async function createMint({
501
+ rpc,
502
+ unwrappedMint,
503
+ wrappedTokenProgram,
504
+ payer,
505
+ idempotent = false
506
+ }) {
507
+ const [wrappedMint] = await findWrappedMintPda({
508
+ unwrappedMint,
509
+ wrappedTokenProgram
510
+ });
511
+ const [backpointer] = await findBackpointerPda({ wrappedMint });
512
+ const instructions = [];
513
+ let fundedWrappedMintLamports = 0n;
514
+ const mintSize = BigInt(getMintSize());
515
+ const [wrappedMintAccount, wrappedMintRent] = await Promise.all([
516
+ fetchEncodedAccount(rpc, wrappedMint),
517
+ rpc.getMinimumBalanceForRentExemption(mintSize).send()
518
+ ]);
519
+ const wrappedMintLamports = wrappedMintAccount.exists ? wrappedMintAccount.lamports : 0n;
520
+ if (wrappedMintLamports < wrappedMintRent) {
521
+ fundedWrappedMintLamports = wrappedMintRent - wrappedMintLamports;
522
+ instructions.push(
523
+ getTransferSolInstruction({
524
+ source: payer,
525
+ destination: wrappedMint,
526
+ amount: fundedWrappedMintLamports
527
+ })
528
+ );
529
+ }
530
+ let fundedBackpointerLamports = 0n;
531
+ const backpointerSize = BigInt(getBackpointerSize());
532
+ const [backpointerAccount, backpointerRent] = await Promise.all([
533
+ fetchEncodedAccount(rpc, backpointer),
534
+ rpc.getMinimumBalanceForRentExemption(backpointerSize).send()
535
+ ]);
536
+ const backpointerLamports = backpointerAccount.exists ? backpointerAccount.lamports : 0n;
537
+ if (backpointerLamports < backpointerRent) {
538
+ fundedBackpointerLamports = backpointerRent - backpointerLamports;
539
+ instructions.push(
540
+ getTransferSolInstruction({
541
+ source: payer,
542
+ destination: backpointer,
543
+ amount: fundedBackpointerLamports
544
+ })
545
+ );
546
+ }
547
+ instructions.push(
548
+ getCreateMintInstruction({
549
+ wrappedMint,
550
+ backpointer,
551
+ unwrappedMint,
552
+ wrappedTokenProgram,
553
+ idempotent
554
+ })
555
+ );
556
+ return {
557
+ wrappedMint,
558
+ backpointer,
559
+ ixs: instructions,
560
+ fundedWrappedMintLamports,
561
+ fundedBackpointerLamports
562
+ };
563
+ }
564
+ async function createEscrowAccount({
565
+ rpc,
566
+ payer,
567
+ unwrappedMint,
568
+ wrappedTokenProgram
569
+ }) {
570
+ const [wrappedMint] = await findWrappedMintPda({ unwrappedMint, wrappedTokenProgram });
571
+ const [wrappedMintAuthority] = await findWrappedMintAuthorityPda({ wrappedMint });
572
+ const unwrappedTokenProgram = await getOwnerFromAccount(rpc, unwrappedMint);
573
+ const [escrowAta] = await findAssociatedTokenPda({
574
+ owner: wrappedMintAuthority,
575
+ mint: unwrappedMint,
576
+ tokenProgram: unwrappedTokenProgram
577
+ });
578
+ const escrowResult = await fetchMaybeToken(rpc, escrowAta);
579
+ if (escrowResult.exists) {
580
+ return { kind: "already_exists", account: escrowResult };
581
+ }
582
+ const ix = getCreateAssociatedTokenInstruction({
583
+ payer,
584
+ owner: wrappedMintAuthority,
585
+ mint: unwrappedMint,
586
+ ata: escrowAta,
587
+ tokenProgram: unwrappedTokenProgram
588
+ });
589
+ return { address: escrowAta, ixs: [ix], kind: "instructions_to_create" };
590
+ }
591
+ async function getOwnerFromAccount(rpc, accountAddress) {
592
+ const accountInfo = await rpc.getAccountInfo(accountAddress, { encoding: "base64" }).send();
593
+ if (!accountInfo.value) {
594
+ throw new Error(`Account ${accountAddress} not found.`);
595
+ }
596
+ return accountInfo.value.owner;
597
+ }
598
+ async function getMintFromTokenAccount(rpc, tokenAccountAddress) {
599
+ const account = await fetchEncodedAccount(rpc, tokenAccountAddress);
600
+ if (!account.exists) {
601
+ throw new Error(`Unwrapped token account ${tokenAccountAddress} not found.`);
602
+ }
603
+ return getTokenDecoder().decode(account.data).mint;
604
+ }
605
+ function messageBytesEqual(results) {
606
+ if (results.length === 1) {
607
+ return true;
608
+ }
609
+ const reference = results[0];
610
+ if (!reference) throw new Error("No transactions in input");
611
+ return results.every(
612
+ (c) => reference.messageBytes.length === c.messageBytes.length && containsBytes(reference.messageBytes, c.messageBytes, 0)
613
+ );
614
+ }
615
+ function combineSignatures(signedTxs) {
616
+ const firstSignedTx = signedTxs[0];
617
+ if (!firstSignedTx) {
618
+ throw new Error("No signed transactions provided");
619
+ }
620
+ const allSignatures = {};
621
+ for (const pubkey of Object.keys(firstSignedTx.signatures)) {
622
+ allSignatures[pubkey] = null;
623
+ }
624
+ for (const signedTx of signedTxs) {
625
+ for (const [address, signature] of Object.entries(signedTx.signatures)) {
626
+ if (signature) {
627
+ allSignatures[address] = signature;
628
+ }
629
+ }
630
+ }
631
+ const missingSigners = [];
632
+ for (const [pubkey, signature] of Object.entries(allSignatures)) {
633
+ if (signature === null) {
634
+ missingSigners.push(pubkey);
635
+ }
636
+ }
637
+ if (missingSigners.length > 0) {
638
+ throw new Error(`Missing signatures for: ${missingSigners.join(", ")}`);
639
+ }
640
+ return allSignatures;
641
+ }
642
+ function combinedMultisigTx({
643
+ signedTxs,
644
+ blockhash
645
+ }) {
646
+ const messagesEqual = messageBytesEqual(signedTxs);
647
+ if (!messagesEqual) throw new Error("Messages are not all the same");
648
+ if (!signedTxs[0]) throw new Error("No signed transactions provided");
649
+ const tx = {
650
+ messageBytes: signedTxs[0].messageBytes,
651
+ signatures: combineSignatures(signedTxs),
652
+ lifetimeConstraint: blockhash
653
+ };
654
+ assertTransactionIsFullySigned(tx);
655
+ return tx;
656
+ }
657
+ async function multisigOfflineSignWrap(args) {
658
+ const wrapIx = await buildWrapIx(args);
659
+ return pipe(
660
+ createTransactionMessage({ version: 0 }),
661
+ (tx) => setTransactionMessageFeePayerSigner(args.payer, tx),
662
+ (tx) => setTransactionMessageLifetimeUsingBlockhash(args.blockhash, tx),
663
+ (tx) => appendTransactionMessageInstructions([wrapIx], tx)
664
+ );
665
+ }
666
+ async function singleSignerWrap({
667
+ rpc,
668
+ payer,
669
+ unwrappedTokenAccount,
670
+ wrappedTokenProgram,
671
+ amount,
672
+ transferAuthority: inputTransferAuthority,
673
+ unwrappedMint: inputUnwrappedMint,
674
+ recipientWrappedTokenAccount: inputRecipientTokenAccount,
675
+ unwrappedTokenProgram: inputUnwrappedTokenProgram
676
+ }) {
677
+ const {
678
+ unwrappedMint,
679
+ unwrappedTokenProgram,
680
+ wrappedMint,
681
+ wrappedMintAuthority,
682
+ recipientWrappedTokenAccount,
683
+ transferAuthority,
684
+ unwrappedEscrow
685
+ } = await resolveAddrs({
686
+ rpc,
687
+ payer,
688
+ inputTransferAuthority,
689
+ inputUnwrappedMint,
690
+ unwrappedTokenAccount,
691
+ inputUnwrappedTokenProgram,
692
+ wrappedTokenProgram,
693
+ inputRecipientTokenAccount
694
+ });
695
+ const ix = await buildWrapIx({
696
+ unwrappedTokenAccount,
697
+ wrappedTokenProgram,
698
+ amount,
699
+ transferAuthority,
700
+ unwrappedMint,
701
+ wrappedMint,
702
+ wrappedMintAuthority,
703
+ recipientWrappedTokenAccount,
704
+ unwrappedTokenProgram
705
+ });
706
+ return {
707
+ ixs: [ix],
708
+ recipientWrappedTokenAccount,
709
+ escrowAccount: unwrappedEscrow,
710
+ amount: BigInt(amount)
711
+ };
712
+ }
713
+ async function resolveAddrs({
714
+ rpc,
715
+ payer,
716
+ unwrappedTokenAccount,
717
+ wrappedTokenProgram,
718
+ inputTransferAuthority,
719
+ inputUnwrappedMint,
720
+ inputRecipientTokenAccount,
721
+ inputUnwrappedTokenProgram
722
+ }) {
723
+ const unwrappedMint = inputUnwrappedMint ?? await getMintFromTokenAccount(rpc, unwrappedTokenAccount);
724
+ const unwrappedTokenProgram = inputUnwrappedTokenProgram ?? await getOwnerFromAccount(rpc, unwrappedTokenAccount);
725
+ const [wrappedMint] = await findWrappedMintPda({ unwrappedMint, wrappedTokenProgram });
726
+ const [wrappedMintAuthority] = await findWrappedMintAuthorityPda({ wrappedMint });
727
+ const recipientWrappedTokenAccount = inputRecipientTokenAccount ?? (await findAssociatedTokenPda({
728
+ owner: payer.address,
729
+ mint: wrappedMint,
730
+ tokenProgram: wrappedTokenProgram
731
+ }))[0];
732
+ const [unwrappedEscrow] = await findAssociatedTokenPda({
733
+ owner: wrappedMintAuthority,
734
+ mint: unwrappedMint,
735
+ tokenProgram: unwrappedTokenProgram
736
+ });
737
+ const transferAuthority = inputTransferAuthority ?? payer;
738
+ return {
739
+ unwrappedEscrow,
740
+ transferAuthority,
741
+ unwrappedMint,
742
+ unwrappedTokenProgram,
743
+ wrappedMint,
744
+ wrappedMintAuthority,
745
+ recipientWrappedTokenAccount
746
+ };
747
+ }
748
+ async function buildWrapIx({
749
+ unwrappedTokenAccount,
750
+ wrappedTokenProgram,
751
+ amount,
752
+ transferAuthority,
753
+ unwrappedMint,
754
+ recipientWrappedTokenAccount,
755
+ unwrappedTokenProgram,
756
+ wrappedMint,
757
+ wrappedMintAuthority,
758
+ multiSigners = []
759
+ }) {
760
+ const [unwrappedEscrow] = await findAssociatedTokenPda({
761
+ owner: wrappedMintAuthority,
762
+ mint: unwrappedMint,
763
+ tokenProgram: unwrappedTokenProgram
764
+ });
765
+ const wrapInstructionInput = {
766
+ recipientWrappedTokenAccount,
767
+ wrappedMint,
768
+ wrappedMintAuthority,
769
+ unwrappedTokenProgram,
770
+ wrappedTokenProgram,
771
+ unwrappedTokenAccount,
772
+ unwrappedMint,
773
+ unwrappedEscrow,
774
+ transferAuthority,
775
+ amount: BigInt(amount),
776
+ multiSigners
777
+ };
778
+ return getWrapInstruction(wrapInstructionInput);
779
+ }
780
+ async function resolveUnwrapAddrs({
781
+ rpc,
782
+ payer,
783
+ wrappedTokenAccount,
784
+ recipientUnwrappedToken,
785
+ inputUnwrappedMint,
786
+ inputTransferAuthority,
787
+ inputWrappedTokenProgram,
788
+ inputUnwrappedTokenProgram
789
+ }) {
790
+ const wrappedTokenProgram = inputWrappedTokenProgram ?? await getOwnerFromAccount(rpc, wrappedTokenAccount);
791
+ const unwrappedTokenProgram = inputUnwrappedTokenProgram ?? await getOwnerFromAccount(rpc, recipientUnwrappedToken);
792
+ const unwrappedMint = inputUnwrappedMint ?? await getMintFromTokenAccount(rpc, recipientUnwrappedToken);
793
+ const wrappedAccountInfo = await fetchEncodedAccount(rpc, wrappedTokenAccount);
794
+ if (!wrappedAccountInfo.exists) {
795
+ throw new Error(`Wrapped token account ${wrappedTokenAccount} not found.`);
796
+ }
797
+ const wrappedMint = getTokenDecoder().decode(wrappedAccountInfo.data).mint;
798
+ const [wrappedMintAuthority] = await findWrappedMintAuthorityPda({ wrappedMint });
799
+ const transferAuthority = inputTransferAuthority ?? payer;
800
+ return {
801
+ unwrappedMint,
802
+ wrappedMint,
803
+ wrappedMintAuthority,
804
+ transferAuthority,
805
+ wrappedTokenProgram,
806
+ unwrappedTokenProgram
807
+ };
808
+ }
809
+ async function buildUnwrapTransaction({
810
+ recipientUnwrappedToken,
811
+ wrappedMintAuthority,
812
+ unwrappedMint,
813
+ wrappedTokenProgram,
814
+ unwrappedTokenProgram,
815
+ wrappedTokenAccount,
816
+ wrappedMint,
817
+ transferAuthority,
818
+ amount,
819
+ multiSigners = []
820
+ }) {
821
+ const [unwrappedEscrow] = await findAssociatedTokenPda({
822
+ owner: wrappedMintAuthority,
823
+ mint: unwrappedMint,
824
+ tokenProgram: unwrappedTokenProgram
825
+ });
826
+ const unwrapInstructionInput = {
827
+ unwrappedEscrow,
828
+ recipientUnwrappedToken,
829
+ wrappedMintAuthority,
830
+ unwrappedMint,
831
+ wrappedTokenProgram,
832
+ unwrappedTokenProgram,
833
+ wrappedTokenAccount,
834
+ wrappedMint,
835
+ transferAuthority,
836
+ amount: BigInt(amount),
837
+ multiSigners
838
+ };
839
+ return getUnwrapInstruction(unwrapInstructionInput);
840
+ }
841
+ async function singleSignerUnwrap({
842
+ rpc,
843
+ payer,
844
+ wrappedTokenAccount,
845
+ amount,
846
+ recipientUnwrappedToken,
847
+ transferAuthority: inputTransferAuthority,
848
+ unwrappedMint: inputUnwrappedMint,
849
+ wrappedTokenProgram: inputWrappedTokenProgram,
850
+ unwrappedTokenProgram: inputUnwrappedTokenProgram
851
+ }) {
852
+ const {
853
+ wrappedMint,
854
+ wrappedMintAuthority,
855
+ transferAuthority,
856
+ unwrappedTokenProgram,
857
+ unwrappedMint,
858
+ wrappedTokenProgram
859
+ } = await resolveUnwrapAddrs({
860
+ rpc,
861
+ payer,
862
+ wrappedTokenAccount,
863
+ recipientUnwrappedToken,
864
+ inputUnwrappedMint,
865
+ inputTransferAuthority,
866
+ inputWrappedTokenProgram,
867
+ inputUnwrappedTokenProgram
868
+ });
869
+ const ix = await buildUnwrapTransaction({
870
+ recipientUnwrappedToken,
871
+ wrappedMintAuthority,
872
+ unwrappedMint,
873
+ wrappedTokenProgram,
874
+ unwrappedTokenProgram,
875
+ wrappedTokenAccount,
876
+ wrappedMint,
877
+ transferAuthority,
878
+ amount
879
+ });
880
+ return {
881
+ recipientUnwrappedToken,
882
+ amount: BigInt(amount),
883
+ ixs: [ix]
884
+ };
885
+ }
886
+ async function multisigOfflineSignUnwrap(args) {
887
+ const unwrapIx = await buildUnwrapTransaction(args);
888
+ return pipe(
889
+ createTransactionMessage({ version: 0 }),
890
+ (tx) => setTransactionMessageFeePayerSigner(args.payer, tx),
891
+ (tx) => setTransactionMessageLifetimeUsingBlockhash(args.blockhash, tx),
892
+ (tx) => appendTransactionMessageInstructions([unwrapIx], tx)
893
+ );
894
+ }
895
+
896
+ export { CREATE_MINT_DISCRIMINATOR, TOKEN_WRAP_ERROR__BACKPOINTER_MISMATCH, TOKEN_WRAP_ERROR__ESCROW_MISMATCH, TOKEN_WRAP_ERROR__ESCROW_OWNER_MISMATCH, TOKEN_WRAP_ERROR__INVALID_BACKPOINTER_OWNER, TOKEN_WRAP_ERROR__INVALID_WRAPPED_MINT_OWNER, TOKEN_WRAP_ERROR__MINT_AUTHORITY_MISMATCH, TOKEN_WRAP_ERROR__WRAPPED_MINT_MISMATCH, TOKEN_WRAP_ERROR__ZERO_WRAP_AMOUNT, TOKEN_WRAP_PROGRAM_ADDRESS, TokenWrapAccount, TokenWrapInstruction, UNWRAP_DISCRIMINATOR, WRAP_DISCRIMINATOR, combinedMultisigTx, createEscrowAccount, createMint, decodeBackpointer, fetchAllBackpointer, fetchAllMaybeBackpointer, fetchBackpointer, fetchBackpointerFromSeeds, fetchMaybeBackpointer, fetchMaybeBackpointerFromSeeds, findBackpointerPda, findWrappedMintAuthorityPda, findWrappedMintPda, getBackpointerCodec, getBackpointerDecoder, getBackpointerEncoder, getBackpointerSize, getCreateMintDiscriminatorBytes, getCreateMintInstruction, getCreateMintInstructionDataCodec, getCreateMintInstructionDataDecoder, getCreateMintInstructionDataEncoder, getTokenWrapErrorMessage, getUnwrapDiscriminatorBytes, getUnwrapInstruction, getUnwrapInstructionDataCodec, getUnwrapInstructionDataDecoder, getUnwrapInstructionDataEncoder, getWrapDiscriminatorBytes, getWrapInstruction, getWrapInstructionDataCodec, getWrapInstructionDataDecoder, getWrapInstructionDataEncoder, identifyTokenWrapInstruction, isTokenWrapError, multisigOfflineSignUnwrap, multisigOfflineSignWrap, parseCreateMintInstruction, parseUnwrapInstruction, parseWrapInstruction, singleSignerUnwrap, singleSignerWrap };
897
+ //# sourceMappingURL=index.mjs.map
898
+ //# sourceMappingURL=index.mjs.map