-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathdecompress-interface.ts
More file actions
214 lines (194 loc) · 6.71 KB
/
decompress-interface.ts
File metadata and controls
214 lines (194 loc) · 6.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import {
ConfirmOptions,
PublicKey,
Signer,
TransactionSignature,
ComputeBudgetProgram,
} from '@solana/web3.js';
import {
Rpc,
buildAndSignTx,
sendAndConfirmTx,
dedupeSigner,
ParsedTokenAccount,
assertBetaEnabled,
} from '@lightprotocol/stateless.js';
import { assertV2Only } from '../assert-v2-only';
import {
createAssociatedTokenAccountIdempotentInstruction,
getAssociatedTokenAddress,
getMint,
} from '@solana/spl-token';
import BN from 'bn.js';
import { createDecompressInterfaceInstruction } from '../instructions/create-decompress-interface-instruction';
import { createAssociatedTokenAccountInterfaceIdempotentInstruction } from '../instructions/create-ata-interface';
import { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';
import { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';
import { SplInterfaceInfo } from '../../utils/get-token-pool-infos';
/**
* Decompress compressed (cold) tokens to an on-chain token account.
*
* For unified loading, use {@link loadAta} instead.
*
* @param rpc RPC connection
* @param payer Fee payer (signer)
* @param owner Owner of the compressed tokens (signer)
* @param mint Mint address
* @param amount Amount to decompress (defaults to all)
* @param destinationAta Destination token account address
* @param destinationOwner Owner of the destination ATA
* @param splInterfaceInfo SPL interface info for SPL/T22 destinations
* @param confirmOptions Confirm options
* @returns Transaction signature, null if nothing to load.
*/
export async function decompressInterface(
rpc: Rpc,
payer: Signer,
owner: Signer,
mint: PublicKey,
amount?: number | bigint | BN,
destinationAta?: PublicKey,
destinationOwner?: PublicKey,
splInterfaceInfo?: SplInterfaceInfo,
confirmOptions?: ConfirmOptions,
): Promise<TransactionSignature | null> {
assertBetaEnabled();
// Determine if this is SPL or light-token destination
const isSplDestination = splInterfaceInfo !== undefined;
// Get compressed token accounts
const compressedResult = await rpc.getCompressedTokenAccountsByOwner(
owner.publicKey,
{ mint },
);
const compressedAccounts = compressedResult.items;
if (compressedAccounts.length === 0) {
return null; // Nothing to decompress
}
// v3 interface only supports V2 trees
assertV2Only(compressedAccounts);
// Calculate total and determine amount
const totalBalance = compressedAccounts.reduce(
(sum, acc) => sum + BigInt(acc.parsed.amount.toString()),
BigInt(0),
);
const decompressAmount = amount ? BigInt(amount.toString()) : totalBalance;
if (decompressAmount > totalBalance) {
throw new Error(
`Insufficient compressed balance. Requested: ${decompressAmount}, Available: ${totalBalance}`,
);
}
// Select minimum accounts needed for the amount
const accountsToUse: ParsedTokenAccount[] = [];
let accumulatedAmount = BigInt(0);
for (const acc of compressedAccounts) {
if (accumulatedAmount >= decompressAmount) break;
accountsToUse.push(acc);
accumulatedAmount += BigInt(acc.parsed.amount.toString());
}
// Get validity proof
const validityProof = await rpc.getValidityProofV0(
accountsToUse.map(acc => ({
hash: acc.compressedAccount.hash,
tree: acc.compressedAccount.treeInfo.tree,
queue: acc.compressedAccount.treeInfo.queue,
})),
);
// Determine destination ATA based on token program
const ataOwner = destinationOwner ?? owner.publicKey;
let destinationAtaAddress: PublicKey;
if (isSplDestination) {
// SPL destination - use SPL ATA
destinationAtaAddress =
destinationAta ??
(await getAssociatedTokenAddress(
mint,
ataOwner,
false,
splInterfaceInfo.tokenProgram,
));
} else {
// light-token destination - use light-token ATA
destinationAtaAddress =
destinationAta ??
getAssociatedTokenAddressInterface(mint, ataOwner);
}
// Build instructions
const instructions = [];
// Create ATA if needed (idempotent)
const ataInfo = await rpc.getAccountInfo(destinationAtaAddress);
if (!ataInfo) {
if (isSplDestination) {
// Create SPL ATA
instructions.push(
createAssociatedTokenAccountIdempotentInstruction(
payer.publicKey,
destinationAtaAddress,
ataOwner,
mint,
splInterfaceInfo.tokenProgram,
),
);
} else {
// Create light-token ATA
instructions.push(
createAssociatedTokenAccountInterfaceIdempotentInstruction(
payer.publicKey,
destinationAtaAddress,
ataOwner,
mint,
CTOKEN_PROGRAM_ID,
),
);
}
}
// Calculate compute units
const hasValidityProof = validityProof.compressedProof !== null;
let computeUnits = 50_000; // Base
if (hasValidityProof) {
computeUnits += 100_000;
}
for (const acc of accountsToUse) {
const proveByIndex = acc.compressedAccount.proveByIndex ?? false;
computeUnits += proveByIndex ? 10_000 : 30_000;
}
// SPL decompression needs extra compute for pool operations
if (isSplDestination) {
computeUnits += 50_000;
}
// Fetch decimals for SPL destinations
let decimals = 0;
if (isSplDestination) {
const mintInfo = await getMint(
rpc,
mint,
undefined,
splInterfaceInfo.tokenProgram,
);
decimals = mintInfo.decimals;
}
// Add decompressInterface instruction
instructions.push(
createDecompressInterfaceInstruction(
payer.publicKey,
accountsToUse,
destinationAtaAddress,
decompressAmount,
validityProof,
splInterfaceInfo,
decimals,
),
);
// Build and send
const { blockhash } = await rpc.getLatestBlockhash();
const additionalSigners = dedupeSigner(payer, [owner]);
const tx = buildAndSignTx(
[
ComputeBudgetProgram.setComputeUnitLimit({ units: computeUnits }),
...instructions,
],
payer,
blockhash,
additionalSigners,
);
return sendAndConfirmTx(rpc, tx, confirmOptions);
}