@solana-program/token-wrap 0.0.0 → 1.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,990 @@
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
+ var token = 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 tokenWrapErrorMessages;
130
+ if (process.env.NODE_ENV !== "production") {
131
+ tokenWrapErrorMessages = {
132
+ [TOKEN_WRAP_ERROR__BACKPOINTER_MISMATCH]: `Wrapped backpointer account address does not match expected PDA`,
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 kit.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: kit.AccountRole.READONLY
173
+ });
174
+ }
175
+ const writableRole = account.isWritable ? kit.AccountRole.WRITABLE : kit.AccountRole.READONLY;
176
+ return Object.freeze({
177
+ address: expectAddress(account.value),
178
+ role: isTransactionSigner(account.value) ? kit.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 && kit.isTransactionSigner(value);
185
+ }
186
+
187
+ // src/generated/instructions/createMint.ts
188
+ var CREATE_MINT_DISCRIMINATOR = 0;
189
+ function getCreateMintDiscriminatorBytes() {
190
+ return kit.getU8Encoder().encode(CREATE_MINT_DISCRIMINATOR);
191
+ }
192
+ function getCreateMintInstructionDataEncoder() {
193
+ return kit.transformEncoder(
194
+ kit.getStructEncoder([
195
+ ["discriminator", kit.getU8Encoder()],
196
+ ["idempotent", kit.getBooleanEncoder()]
197
+ ]),
198
+ (value) => ({
199
+ ...value,
200
+ discriminator: CREATE_MINT_DISCRIMINATOR,
201
+ idempotent: value.idempotent ?? false
202
+ })
203
+ );
204
+ }
205
+ function getCreateMintInstructionDataDecoder() {
206
+ return kit.getStructDecoder([
207
+ ["discriminator", kit.getU8Decoder()],
208
+ ["idempotent", kit.getBooleanDecoder()]
209
+ ]);
210
+ }
211
+ function getCreateMintInstructionDataCodec() {
212
+ return kit.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 kit.getU8Encoder().encode(UNWRAP_DISCRIMINATOR);
279
+ }
280
+ function getUnwrapInstructionDataEncoder() {
281
+ return kit.transformEncoder(
282
+ kit.getStructEncoder([
283
+ ["discriminator", kit.getU8Encoder()],
284
+ ["amount", kit.getU64Encoder()]
285
+ ]),
286
+ (value) => ({ ...value, discriminator: UNWRAP_DISCRIMINATOR })
287
+ );
288
+ }
289
+ function getUnwrapInstructionDataDecoder() {
290
+ return kit.getStructDecoder([
291
+ ["discriminator", kit.getU8Decoder()],
292
+ ["amount", kit.getU64Decoder()]
293
+ ]);
294
+ }
295
+ function getUnwrapInstructionDataCodec() {
296
+ return kit.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: kit.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 kit.getU8Encoder().encode(WRAP_DISCRIMINATOR);
391
+ }
392
+ function getWrapInstructionDataEncoder() {
393
+ return kit.transformEncoder(
394
+ kit.getStructEncoder([
395
+ ["discriminator", kit.getU8Encoder()],
396
+ ["amount", kit.getU64Encoder()]
397
+ ]),
398
+ (value) => ({ ...value, discriminator: WRAP_DISCRIMINATOR })
399
+ );
400
+ }
401
+ function getWrapInstructionDataDecoder() {
402
+ return kit.getStructDecoder([
403
+ ["discriminator", kit.getU8Decoder()],
404
+ ["amount", kit.getU64Decoder()]
405
+ ]);
406
+ }
407
+ function getWrapInstructionDataCodec() {
408
+ return kit.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: kit.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 createMintTx({
501
+ rpc,
502
+ blockhash,
503
+ unwrappedMint,
504
+ wrappedTokenProgram,
505
+ payer,
506
+ idempotent = false
507
+ }) {
508
+ const [wrappedMint] = await findWrappedMintPda({
509
+ unwrappedMint,
510
+ wrappedTokenProgram
511
+ });
512
+ const [backpointer] = await findBackpointerPda({ wrappedMint });
513
+ const instructions = [];
514
+ let fundedWrappedMintLamports = 0n;
515
+ const mintSize = BigInt(token2022.getMintSize());
516
+ const [wrappedMintAccount, wrappedMintRent] = await Promise.all([
517
+ kit.fetchEncodedAccount(rpc, wrappedMint),
518
+ rpc.getMinimumBalanceForRentExemption(mintSize).send()
519
+ ]);
520
+ const wrappedMintLamports = wrappedMintAccount.exists ? wrappedMintAccount.lamports : 0n;
521
+ if (wrappedMintLamports < wrappedMintRent) {
522
+ fundedWrappedMintLamports = wrappedMintRent - wrappedMintLamports;
523
+ instructions.push(
524
+ system.getTransferSolInstruction({
525
+ source: payer,
526
+ destination: wrappedMint,
527
+ amount: fundedWrappedMintLamports
528
+ })
529
+ );
530
+ }
531
+ let fundedBackpointerLamports = 0n;
532
+ const backpointerSize = BigInt(getBackpointerSize());
533
+ const [backpointerAccount, backpointerRent] = await Promise.all([
534
+ kit.fetchEncodedAccount(rpc, backpointer),
535
+ rpc.getMinimumBalanceForRentExemption(backpointerSize).send()
536
+ ]);
537
+ const backpointerLamports = backpointerAccount.exists ? backpointerAccount.lamports : 0n;
538
+ if (backpointerLamports < backpointerRent) {
539
+ fundedBackpointerLamports = backpointerRent - backpointerLamports;
540
+ instructions.push(
541
+ system.getTransferSolInstruction({
542
+ source: payer,
543
+ destination: backpointer,
544
+ amount: fundedBackpointerLamports
545
+ })
546
+ );
547
+ }
548
+ instructions.push(
549
+ getCreateMintInstruction({
550
+ wrappedMint,
551
+ backpointer,
552
+ unwrappedMint,
553
+ wrappedTokenProgram,
554
+ idempotent
555
+ })
556
+ );
557
+ const tx = kit.pipe(
558
+ kit.createTransactionMessage({ version: 0 }),
559
+ (tx2) => kit.setTransactionMessageFeePayerSigner(payer, tx2),
560
+ (tx2) => kit.setTransactionMessageLifetimeUsingBlockhash(blockhash, tx2),
561
+ (tx2) => kit.appendTransactionMessageInstructions(instructions, tx2)
562
+ );
563
+ return {
564
+ wrappedMint,
565
+ backpointer,
566
+ tx,
567
+ fundedWrappedMintLamports,
568
+ fundedBackpointerLamports
569
+ };
570
+ }
571
+ function getInitializeTokenFn(tokenProgram) {
572
+ if (tokenProgram === token.TOKEN_PROGRAM_ADDRESS) return token.getInitializeAccountInstruction;
573
+ if (tokenProgram === token2022.TOKEN_2022_PROGRAM_ADDRESS) return token2022.getInitializeAccountInstruction;
574
+ throw new Error(`${tokenProgram} is not a valid token program.`);
575
+ }
576
+ async function createTokenAccountTx({
577
+ rpc,
578
+ blockhash,
579
+ payer,
580
+ mint,
581
+ owner,
582
+ tokenProgram
583
+ }) {
584
+ const [keyPair, lamports] = await Promise.all([
585
+ kit.generateKeyPairSigner(),
586
+ rpc.getMinimumBalanceForRentExemption(165n).send()
587
+ ]);
588
+ const createAccountIx = system.getCreateAccountInstruction({
589
+ payer,
590
+ newAccount: keyPair,
591
+ lamports,
592
+ space: 165,
593
+ programAddress: tokenProgram
594
+ });
595
+ const initializeAccountIx = getInitializeTokenFn(tokenProgram)({
596
+ account: keyPair.address,
597
+ mint,
598
+ owner
599
+ });
600
+ const tx = kit.pipe(
601
+ kit.createTransactionMessage({ version: 0 }),
602
+ (tx2) => kit.setTransactionMessageFeePayerSigner(payer, tx2),
603
+ (tx2) => kit.setTransactionMessageLifetimeUsingBlockhash(blockhash, tx2),
604
+ (tx2) => kit.appendTransactionMessageInstructions([createAccountIx, initializeAccountIx], tx2)
605
+ );
606
+ return {
607
+ tx,
608
+ keyPair
609
+ };
610
+ }
611
+ async function createEscrowAccountTx({
612
+ rpc,
613
+ blockhash,
614
+ payer,
615
+ unwrappedMint,
616
+ wrappedTokenProgram
617
+ }) {
618
+ const [wrappedMint] = await findWrappedMintPda({ unwrappedMint, wrappedTokenProgram });
619
+ const [wrappedMintAuthority] = await findWrappedMintAuthorityPda({ wrappedMint });
620
+ const unwrappedTokenProgram = await getOwnerFromAccount(rpc, unwrappedMint);
621
+ return createTokenAccountTx({
622
+ rpc,
623
+ blockhash,
624
+ payer,
625
+ mint: unwrappedMint,
626
+ owner: wrappedMintAuthority,
627
+ tokenProgram: unwrappedTokenProgram
628
+ });
629
+ }
630
+ async function getOwnerFromAccount(rpc, accountAddress) {
631
+ const accountInfo = await rpc.getAccountInfo(accountAddress, { encoding: "base64" }).send();
632
+ if (!accountInfo.value) {
633
+ throw new Error(`Account ${accountAddress} not found.`);
634
+ }
635
+ return accountInfo.value.owner;
636
+ }
637
+ async function getMintFromTokenAccount(rpc, tokenAccountAddress) {
638
+ const account = await kit.fetchEncodedAccount(rpc, tokenAccountAddress);
639
+ if (!account.exists) {
640
+ throw new Error(`Unwrapped token account ${tokenAccountAddress} not found.`);
641
+ }
642
+ return token2022.getTokenDecoder().decode(account.data).mint;
643
+ }
644
+ function messageBytesEqual(results) {
645
+ if (results.length === 1) {
646
+ return true;
647
+ }
648
+ const reference = results[0];
649
+ if (!reference) throw new Error("No transactions in input");
650
+ return results.every(
651
+ (c) => reference.messageBytes.length === c.messageBytes.length && kit.containsBytes(reference.messageBytes, c.messageBytes, 0)
652
+ );
653
+ }
654
+ function combineSignatures(signedTxs) {
655
+ const firstSignedTx = signedTxs[0];
656
+ if (!firstSignedTx) {
657
+ throw new Error("No signed transactions provided");
658
+ }
659
+ const allSignatures = {};
660
+ for (const pubkey of Object.keys(firstSignedTx.signatures)) {
661
+ allSignatures[pubkey] = null;
662
+ }
663
+ for (const signedTx of signedTxs) {
664
+ for (const [address, signature] of Object.entries(signedTx.signatures)) {
665
+ if (signature) {
666
+ allSignatures[address] = signature;
667
+ }
668
+ }
669
+ }
670
+ const missingSigners = [];
671
+ for (const [pubkey, signature] of Object.entries(allSignatures)) {
672
+ if (signature === null) {
673
+ missingSigners.push(pubkey);
674
+ }
675
+ }
676
+ if (missingSigners.length > 0) {
677
+ throw new Error(`Missing signatures for: ${missingSigners.join(", ")}`);
678
+ }
679
+ return allSignatures;
680
+ }
681
+ function combinedMultisigTx({
682
+ signedTxs,
683
+ blockhash
684
+ }) {
685
+ const messagesEqual = messageBytesEqual(signedTxs);
686
+ if (!messagesEqual) throw new Error("Messages are not all the same");
687
+ if (!signedTxs[0]) throw new Error("No signed transactions provided");
688
+ const tx = {
689
+ messageBytes: signedTxs[0].messageBytes,
690
+ signatures: combineSignatures(signedTxs),
691
+ lifetimeConstraint: blockhash
692
+ };
693
+ kit.assertTransactionIsFullySigned(tx);
694
+ return tx;
695
+ }
696
+ function multisigOfflineSignWrapTx(args) {
697
+ return buildWrapTransaction(args);
698
+ }
699
+ async function singleSignerWrapTx({
700
+ rpc,
701
+ blockhash,
702
+ payer,
703
+ unwrappedTokenAccount,
704
+ escrowAccount,
705
+ wrappedTokenProgram,
706
+ amount,
707
+ transferAuthority: inputTransferAuthority,
708
+ unwrappedMint: inputUnwrappedMint,
709
+ recipientWrappedTokenAccount: inputRecipientTokenAccount,
710
+ unwrappedTokenProgram: inputUnwrappedTokenProgram
711
+ }) {
712
+ const {
713
+ unwrappedMint,
714
+ unwrappedTokenProgram,
715
+ wrappedMint,
716
+ wrappedMintAuthority,
717
+ recipientWrappedTokenAccount,
718
+ transferAuthority
719
+ } = await resolveAddrs({
720
+ rpc,
721
+ payer,
722
+ inputTransferAuthority,
723
+ inputUnwrappedMint,
724
+ unwrappedTokenAccount,
725
+ inputUnwrappedTokenProgram,
726
+ wrappedTokenProgram,
727
+ inputRecipientTokenAccount
728
+ });
729
+ const tx = buildWrapTransaction({
730
+ blockhash,
731
+ payer,
732
+ unwrappedTokenAccount,
733
+ escrowAccount,
734
+ wrappedTokenProgram,
735
+ amount,
736
+ transferAuthority,
737
+ unwrappedMint,
738
+ wrappedMint,
739
+ wrappedMintAuthority,
740
+ recipientWrappedTokenAccount,
741
+ unwrappedTokenProgram
742
+ });
743
+ return {
744
+ tx,
745
+ recipientWrappedTokenAccount,
746
+ escrowAccount,
747
+ amount: BigInt(amount)
748
+ };
749
+ }
750
+ async function resolveAddrs({
751
+ rpc,
752
+ payer,
753
+ unwrappedTokenAccount,
754
+ wrappedTokenProgram,
755
+ inputTransferAuthority,
756
+ inputUnwrappedMint,
757
+ inputRecipientTokenAccount,
758
+ inputUnwrappedTokenProgram
759
+ }) {
760
+ const unwrappedMint = inputUnwrappedMint ?? await getMintFromTokenAccount(rpc, unwrappedTokenAccount);
761
+ const unwrappedTokenProgram = inputUnwrappedTokenProgram ?? await getOwnerFromAccount(rpc, unwrappedTokenAccount);
762
+ const [wrappedMint] = await findWrappedMintPda({ unwrappedMint, wrappedTokenProgram });
763
+ const [wrappedMintAuthority] = await findWrappedMintAuthorityPda({ wrappedMint });
764
+ const recipientWrappedTokenAccount = inputRecipientTokenAccount ?? (await token2022.findAssociatedTokenPda({
765
+ owner: payer.address,
766
+ mint: wrappedMint,
767
+ tokenProgram: wrappedTokenProgram
768
+ }))[0];
769
+ const transferAuthority = inputTransferAuthority ?? payer;
770
+ return {
771
+ transferAuthority,
772
+ unwrappedMint,
773
+ unwrappedTokenProgram,
774
+ wrappedMint,
775
+ wrappedMintAuthority,
776
+ recipientWrappedTokenAccount
777
+ };
778
+ }
779
+ function buildWrapTransaction({
780
+ payer,
781
+ unwrappedTokenAccount,
782
+ escrowAccount,
783
+ wrappedTokenProgram,
784
+ amount,
785
+ transferAuthority,
786
+ unwrappedMint,
787
+ recipientWrappedTokenAccount,
788
+ unwrappedTokenProgram,
789
+ wrappedMint,
790
+ wrappedMintAuthority,
791
+ blockhash,
792
+ multiSigners = []
793
+ }) {
794
+ const wrapInstructionInput = {
795
+ recipientWrappedTokenAccount,
796
+ wrappedMint,
797
+ wrappedMintAuthority,
798
+ unwrappedTokenProgram,
799
+ wrappedTokenProgram,
800
+ unwrappedTokenAccount,
801
+ unwrappedMint,
802
+ unwrappedEscrow: escrowAccount,
803
+ transferAuthority,
804
+ amount: BigInt(amount),
805
+ multiSigners
806
+ };
807
+ const wrapInstruction = getWrapInstruction(wrapInstructionInput);
808
+ return kit.pipe(
809
+ kit.createTransactionMessage({ version: 0 }),
810
+ (tx) => kit.setTransactionMessageFeePayerSigner(payer, tx),
811
+ (tx) => kit.setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),
812
+ (tx) => kit.appendTransactionMessageInstructions([wrapInstruction], tx)
813
+ );
814
+ }
815
+ async function resolveUnwrapAddrs({
816
+ rpc,
817
+ payer,
818
+ wrappedTokenAccount,
819
+ unwrappedEscrow,
820
+ inputUnwrappedMint,
821
+ inputTransferAuthority,
822
+ inputWrappedTokenProgram,
823
+ inputUnwrappedTokenProgram
824
+ }) {
825
+ const wrappedTokenProgram = inputWrappedTokenProgram ?? await getOwnerFromAccount(rpc, wrappedTokenAccount);
826
+ const unwrappedTokenProgram = inputUnwrappedTokenProgram ?? await getOwnerFromAccount(rpc, unwrappedEscrow);
827
+ const unwrappedMint = inputUnwrappedMint ?? await getMintFromTokenAccount(rpc, unwrappedEscrow);
828
+ const wrappedAccountInfo = await kit.fetchEncodedAccount(rpc, wrappedTokenAccount);
829
+ if (!wrappedAccountInfo.exists) {
830
+ throw new Error(`Wrapped token account ${wrappedTokenAccount} not found.`);
831
+ }
832
+ const wrappedMint = token2022.getTokenDecoder().decode(wrappedAccountInfo.data).mint;
833
+ const [wrappedMintAuthority] = await findWrappedMintAuthorityPda({ wrappedMint });
834
+ const transferAuthority = inputTransferAuthority ?? payer;
835
+ return {
836
+ unwrappedMint,
837
+ wrappedMint,
838
+ wrappedMintAuthority,
839
+ transferAuthority,
840
+ wrappedTokenProgram,
841
+ unwrappedTokenProgram
842
+ };
843
+ }
844
+ function buildUnwrapTransaction({
845
+ payer,
846
+ unwrappedEscrow,
847
+ recipientUnwrappedToken,
848
+ wrappedMintAuthority,
849
+ unwrappedMint,
850
+ wrappedTokenProgram,
851
+ unwrappedTokenProgram,
852
+ wrappedTokenAccount,
853
+ wrappedMint,
854
+ transferAuthority,
855
+ amount,
856
+ blockhash,
857
+ multiSigners = []
858
+ }) {
859
+ const unwrapInstructionInput = {
860
+ unwrappedEscrow,
861
+ recipientUnwrappedToken,
862
+ wrappedMintAuthority,
863
+ unwrappedMint,
864
+ wrappedTokenProgram,
865
+ unwrappedTokenProgram,
866
+ wrappedTokenAccount,
867
+ wrappedMint,
868
+ transferAuthority,
869
+ amount: BigInt(amount),
870
+ multiSigners
871
+ };
872
+ const unwrapInstruction = getUnwrapInstruction(unwrapInstructionInput);
873
+ return kit.pipe(
874
+ kit.createTransactionMessage({ version: 0 }),
875
+ (tx) => kit.setTransactionMessageFeePayerSigner(payer, tx),
876
+ (tx) => kit.setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),
877
+ (tx) => kit.appendTransactionMessageInstructions([unwrapInstruction], tx)
878
+ );
879
+ }
880
+ async function singleSignerUnwrapTx({
881
+ rpc,
882
+ blockhash,
883
+ payer,
884
+ wrappedTokenAccount,
885
+ unwrappedEscrow,
886
+ amount,
887
+ recipientUnwrappedToken,
888
+ transferAuthority: inputTransferAuthority,
889
+ unwrappedMint: inputUnwrappedMint,
890
+ wrappedTokenProgram: inputWrappedTokenProgram,
891
+ unwrappedTokenProgram: inputUnwrappedTokenProgram
892
+ }) {
893
+ const {
894
+ wrappedMint,
895
+ wrappedMintAuthority,
896
+ transferAuthority,
897
+ unwrappedTokenProgram,
898
+ unwrappedMint,
899
+ wrappedTokenProgram
900
+ } = await resolveUnwrapAddrs({
901
+ rpc,
902
+ payer,
903
+ wrappedTokenAccount,
904
+ unwrappedEscrow,
905
+ inputUnwrappedMint,
906
+ inputTransferAuthority,
907
+ inputWrappedTokenProgram,
908
+ inputUnwrappedTokenProgram
909
+ });
910
+ const tx = buildUnwrapTransaction({
911
+ payer,
912
+ unwrappedEscrow,
913
+ recipientUnwrappedToken,
914
+ wrappedMintAuthority,
915
+ unwrappedMint,
916
+ wrappedTokenProgram,
917
+ unwrappedTokenProgram,
918
+ wrappedTokenAccount,
919
+ wrappedMint,
920
+ transferAuthority,
921
+ amount,
922
+ blockhash
923
+ });
924
+ return {
925
+ recipientUnwrappedToken,
926
+ amount: BigInt(amount),
927
+ tx
928
+ };
929
+ }
930
+ function multisigOfflineSignUnwrap(args) {
931
+ return buildUnwrapTransaction(args);
932
+ }
933
+
934
+ exports.CREATE_MINT_DISCRIMINATOR = CREATE_MINT_DISCRIMINATOR;
935
+ exports.TOKEN_WRAP_ERROR__BACKPOINTER_MISMATCH = TOKEN_WRAP_ERROR__BACKPOINTER_MISMATCH;
936
+ exports.TOKEN_WRAP_ERROR__ESCROW_OWNER_MISMATCH = TOKEN_WRAP_ERROR__ESCROW_OWNER_MISMATCH;
937
+ exports.TOKEN_WRAP_ERROR__INVALID_BACKPOINTER_OWNER = TOKEN_WRAP_ERROR__INVALID_BACKPOINTER_OWNER;
938
+ exports.TOKEN_WRAP_ERROR__INVALID_WRAPPED_MINT_OWNER = TOKEN_WRAP_ERROR__INVALID_WRAPPED_MINT_OWNER;
939
+ exports.TOKEN_WRAP_ERROR__MINT_AUTHORITY_MISMATCH = TOKEN_WRAP_ERROR__MINT_AUTHORITY_MISMATCH;
940
+ exports.TOKEN_WRAP_ERROR__WRAPPED_MINT_MISMATCH = TOKEN_WRAP_ERROR__WRAPPED_MINT_MISMATCH;
941
+ exports.TOKEN_WRAP_ERROR__ZERO_WRAP_AMOUNT = TOKEN_WRAP_ERROR__ZERO_WRAP_AMOUNT;
942
+ exports.TOKEN_WRAP_PROGRAM_ADDRESS = TOKEN_WRAP_PROGRAM_ADDRESS;
943
+ exports.TokenWrapAccount = TokenWrapAccount;
944
+ exports.TokenWrapInstruction = TokenWrapInstruction;
945
+ exports.UNWRAP_DISCRIMINATOR = UNWRAP_DISCRIMINATOR;
946
+ exports.WRAP_DISCRIMINATOR = WRAP_DISCRIMINATOR;
947
+ exports.combinedMultisigTx = combinedMultisigTx;
948
+ exports.createEscrowAccountTx = createEscrowAccountTx;
949
+ exports.createMintTx = createMintTx;
950
+ exports.decodeBackpointer = decodeBackpointer;
951
+ exports.fetchAllBackpointer = fetchAllBackpointer;
952
+ exports.fetchAllMaybeBackpointer = fetchAllMaybeBackpointer;
953
+ exports.fetchBackpointer = fetchBackpointer;
954
+ exports.fetchBackpointerFromSeeds = fetchBackpointerFromSeeds;
955
+ exports.fetchMaybeBackpointer = fetchMaybeBackpointer;
956
+ exports.fetchMaybeBackpointerFromSeeds = fetchMaybeBackpointerFromSeeds;
957
+ exports.findBackpointerPda = findBackpointerPda;
958
+ exports.findWrappedMintAuthorityPda = findWrappedMintAuthorityPda;
959
+ exports.findWrappedMintPda = findWrappedMintPda;
960
+ exports.getBackpointerCodec = getBackpointerCodec;
961
+ exports.getBackpointerDecoder = getBackpointerDecoder;
962
+ exports.getBackpointerEncoder = getBackpointerEncoder;
963
+ exports.getBackpointerSize = getBackpointerSize;
964
+ exports.getCreateMintDiscriminatorBytes = getCreateMintDiscriminatorBytes;
965
+ exports.getCreateMintInstruction = getCreateMintInstruction;
966
+ exports.getCreateMintInstructionDataCodec = getCreateMintInstructionDataCodec;
967
+ exports.getCreateMintInstructionDataDecoder = getCreateMintInstructionDataDecoder;
968
+ exports.getCreateMintInstructionDataEncoder = getCreateMintInstructionDataEncoder;
969
+ exports.getTokenWrapErrorMessage = getTokenWrapErrorMessage;
970
+ exports.getUnwrapDiscriminatorBytes = getUnwrapDiscriminatorBytes;
971
+ exports.getUnwrapInstruction = getUnwrapInstruction;
972
+ exports.getUnwrapInstructionDataCodec = getUnwrapInstructionDataCodec;
973
+ exports.getUnwrapInstructionDataDecoder = getUnwrapInstructionDataDecoder;
974
+ exports.getUnwrapInstructionDataEncoder = getUnwrapInstructionDataEncoder;
975
+ exports.getWrapDiscriminatorBytes = getWrapDiscriminatorBytes;
976
+ exports.getWrapInstruction = getWrapInstruction;
977
+ exports.getWrapInstructionDataCodec = getWrapInstructionDataCodec;
978
+ exports.getWrapInstructionDataDecoder = getWrapInstructionDataDecoder;
979
+ exports.getWrapInstructionDataEncoder = getWrapInstructionDataEncoder;
980
+ exports.identifyTokenWrapInstruction = identifyTokenWrapInstruction;
981
+ exports.isTokenWrapError = isTokenWrapError;
982
+ exports.multisigOfflineSignUnwrap = multisigOfflineSignUnwrap;
983
+ exports.multisigOfflineSignWrapTx = multisigOfflineSignWrapTx;
984
+ exports.parseCreateMintInstruction = parseCreateMintInstruction;
985
+ exports.parseUnwrapInstruction = parseUnwrapInstruction;
986
+ exports.parseWrapInstruction = parseWrapInstruction;
987
+ exports.singleSignerUnwrapTx = singleSignerUnwrapTx;
988
+ exports.singleSignerWrapTx = singleSignerWrapTx;
989
+ //# sourceMappingURL=index.js.map
990
+ //# sourceMappingURL=index.js.map