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