-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathget-or-create-ata-interface.ts
More file actions
433 lines (403 loc) · 13.1 KB
/
get-or-create-ata-interface.ts
File metadata and controls
433 lines (403 loc) · 13.1 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import {
Rpc,
LIGHT_TOKEN_PROGRAM_ID,
buildAndSignTx,
sendAndConfirmTx,
assertBetaEnabled,
} from '@lightprotocol/stateless.js';
import {
getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID,
TokenAccountNotFoundError,
TokenInvalidAccountOwnerError,
TokenInvalidMintError,
TokenInvalidOwnerError,
} from '@solana/spl-token';
import type {
Commitment,
ConfirmOptions,
PublicKey,
Signer,
} from '@solana/web3.js';
import {
sendAndConfirmTransaction,
Transaction,
ComputeBudgetProgram,
} from '@solana/web3.js';
import {
createAssociatedTokenAccountInterfaceInstruction,
createAssociatedTokenAccountInterfaceIdempotentInstruction,
} from '../instructions/create-ata-interface';
import {
getAccountInterface,
getAtaInterface,
AccountInterface,
TokenAccountSourceType,
} from '../get-account-interface';
import { getAtaProgramId } from '../ata-utils';
import { loadAta } from './load-ata';
/**
* Retrieve the associated token account, or create it if it doesn't exist.
*
* @param rpc Connection to use
* @param payer Payer of the transaction and initialization
* fees.
* @param mint Mint associated with the account to set or
* verify.
* @param owner Owner of the account. Pass Signer to
* auto-load compressed light-tokens (cold balance), or
* PublicKey for read-only.
* @param allowOwnerOffCurve Allow the owner account to be a PDA (Program
* Derived Address).
* @param commitment Desired level of commitment for querying the
* state.
* @param confirmOptions Options for confirming the transaction
* @param programId Token program ID (defaults to
* LIGHT_TOKEN_PROGRAM_ID)
* @param associatedTokenProgramId Associated token program ID (auto-derived if
* not provided)
*
* @returns AccountInterface with aggregated balance and source breakdown
*/
export async function getOrCreateAtaInterface(
rpc: Rpc,
payer: Signer,
mint: PublicKey,
owner: PublicKey | Signer,
allowOwnerOffCurve = false,
commitment?: Commitment,
confirmOptions?: ConfirmOptions,
programId = LIGHT_TOKEN_PROGRAM_ID,
associatedTokenProgramId = getAtaProgramId(programId),
): Promise<AccountInterface> {
assertBetaEnabled();
return _getOrCreateAtaInterface(
rpc,
payer,
mint,
owner,
allowOwnerOffCurve,
commitment,
confirmOptions,
programId,
associatedTokenProgramId,
false, // wrap=false for standard path
);
}
/** @internal */
function isSigner(owner: PublicKey | Signer): owner is Signer {
// Check for both publicKey and secretKey properties
// A proper Signer (like Keypair) has secretKey as Uint8Array
if (!('publicKey' in owner) || !('secretKey' in owner)) {
return false;
}
// Verify secretKey is actually present and is a Uint8Array
const signer = owner as Signer;
return (
signer.secretKey instanceof Uint8Array && signer.secretKey.length > 0
);
}
/** @internal */
function getOwnerPublicKey(owner: PublicKey | Signer): PublicKey {
return isSigner(owner) ? owner.publicKey : owner;
}
/**
* @internal
* Internal implementation with wrap parameter.
*/
export async function _getOrCreateAtaInterface(
rpc: Rpc,
payer: Signer,
mint: PublicKey,
owner: PublicKey | Signer,
allowOwnerOffCurve: boolean,
commitment: Commitment | undefined,
confirmOptions: ConfirmOptions | undefined,
programId: PublicKey,
associatedTokenProgramId: PublicKey,
wrap: boolean,
): Promise<AccountInterface> {
const ownerPubkey = getOwnerPublicKey(owner);
const associatedToken = getAssociatedTokenAddressSync(
mint,
ownerPubkey,
allowOwnerOffCurve,
programId,
associatedTokenProgramId,
);
// For light-token, use getAtaInterface which properly aggregates hot+cold balances
// When wrap=true (unified path), also includes SPL/T22 balances
if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) {
return getOrCreateCTokenAta(
rpc,
payer,
mint,
owner,
associatedToken,
commitment,
confirmOptions,
wrap,
allowOwnerOffCurve,
);
}
// For SPL/T22, use standard address-based lookup
return getOrCreateSplAta(
rpc,
payer,
mint,
ownerPubkey,
associatedToken,
programId,
associatedTokenProgramId,
commitment,
confirmOptions,
);
}
/**
* Get or create light-token associated token account with proper compressed balance handling.
*
* Like SPL's getOrCreateAssociatedTokenAccount, this is a write operation:
* 1. Creates hot associated token account if it doesn't exist
* 2. If owner is Signer: loads compressed light-tokens (cold balance) into light-token associated token account
* 3. When wrap=true and owner is Signer: also wraps SPL/T22 tokens
*
* After this call (with Signer owner), all tokens are in the hot associated token account and ready
* to use.
*
* @internal
*/
async function getOrCreateCTokenAta(
rpc: Rpc,
payer: Signer,
mint: PublicKey,
owner: PublicKey | Signer,
associatedToken: PublicKey,
commitment?: Commitment,
confirmOptions?: ConfirmOptions,
wrap = false,
allowOwnerOffCurve = false,
): Promise<AccountInterface> {
const ownerPubkey = getOwnerPublicKey(owner);
const ownerIsSigner = isSigner(owner);
let accountInterface: AccountInterface;
let hasHotAccount = false;
try {
// Use getAtaInterface which properly fetches by owner+mint and aggregates
// hot+cold balances. When wrap=true, also includes SPL/T22 balances.
accountInterface = await getAtaInterface(
rpc,
associatedToken,
ownerPubkey,
mint,
commitment,
LIGHT_TOKEN_PROGRAM_ID,
wrap,
allowOwnerOffCurve,
);
// Check if we have a hot account
hasHotAccount =
accountInterface._sources?.some(
s => s.type === TokenAccountSourceType.CTokenHot,
) ?? false;
} catch (error: unknown) {
if (
error instanceof TokenAccountNotFoundError ||
error instanceof TokenInvalidAccountOwnerError
) {
// No account found (neither hot nor cold), create hot associated token account
await createCTokenAtaIdempotent(
rpc,
payer,
mint,
ownerPubkey,
associatedToken,
confirmOptions,
);
// Fetch the newly created account
accountInterface = await getAtaInterface(
rpc,
associatedToken,
ownerPubkey,
mint,
commitment,
LIGHT_TOKEN_PROGRAM_ID,
wrap,
allowOwnerOffCurve,
);
hasHotAccount = true;
} else {
throw error;
}
}
// If we only have cold balance (no hot associated token account), create the hot associated token account first
if (!hasHotAccount) {
await createCTokenAtaIdempotent(
rpc,
payer,
mint,
ownerPubkey,
associatedToken,
confirmOptions,
);
}
// Only auto-load if owner is a Signer (we can sign the load transaction)
// Use direct type guard in the if condition for proper type narrowing
if (isSigner(owner)) {
// Check if we need to load tokens into the hot associated token account
// Load if: cold balance exists, or (wrap=true and SPL/T22 balance exists)
const sources = accountInterface._sources ?? [];
const hasCold = sources.some(
s =>
s.type === TokenAccountSourceType.CTokenCold &&
s.amount > BigInt(0),
);
const hasSplToWrap =
wrap &&
sources.some(
s =>
(s.type === TokenAccountSourceType.Spl ||
s.type === TokenAccountSourceType.Token2022) &&
s.amount > BigInt(0),
);
if (hasCold || hasSplToWrap) {
// Verify owner is a valid Signer before loading
if (
!(owner.secretKey instanceof Uint8Array) ||
owner.secretKey.length === 0
) {
throw new Error(
'Owner must be a valid Signer with secretKey to auto-load',
);
}
// Load all tokens into hot associated token account (decompress cold, wrap SPL/T22 if
// wrap=true)
await loadAta(
rpc,
associatedToken,
owner, // TypeScript now knows owner is Signer
mint,
payer,
confirmOptions,
undefined,
wrap,
);
// Re-fetch the updated account state
accountInterface = await getAtaInterface(
rpc,
associatedToken,
ownerPubkey,
mint,
commitment,
LIGHT_TOKEN_PROGRAM_ID,
wrap,
allowOwnerOffCurve,
);
}
}
const account = accountInterface.parsed;
if (!account.mint.equals(mint)) throw new TokenInvalidMintError();
if (!account.owner.equals(ownerPubkey)) throw new TokenInvalidOwnerError();
return accountInterface;
}
/**
* Create light-token associated token account idempotently.
* @internal
*/
async function createCTokenAtaIdempotent(
rpc: Rpc,
payer: Signer,
mint: PublicKey,
owner: PublicKey,
associatedToken: PublicKey,
confirmOptions?: ConfirmOptions,
): Promise<void> {
try {
const ix = createAssociatedTokenAccountInterfaceIdempotentInstruction(
payer.publicKey,
associatedToken,
owner,
mint,
LIGHT_TOKEN_PROGRAM_ID,
);
const { blockhash } = await rpc.getLatestBlockhash();
const tx = buildAndSignTx(
[ComputeBudgetProgram.setComputeUnitLimit({ units: 200_000 }), ix],
payer,
blockhash,
[],
);
await sendAndConfirmTx(rpc, tx, confirmOptions);
} catch {
// Ignore errors - associated token account may already exist
}
}
/**
* Get or create SPL/T22 associated token account.
* @internal
*/
async function getOrCreateSplAta(
rpc: Rpc,
payer: Signer,
mint: PublicKey,
owner: PublicKey,
associatedToken: PublicKey,
programId: PublicKey,
associatedTokenProgramId: PublicKey,
commitment?: Commitment,
confirmOptions?: ConfirmOptions,
): Promise<AccountInterface> {
let accountInterface: AccountInterface;
try {
accountInterface = await getAccountInterface(
rpc,
associatedToken,
commitment,
programId,
);
} catch (error: unknown) {
// TokenAccountNotFoundError can be possible if the associated address
// has already received some lamports, becoming a system account.
if (
error instanceof TokenAccountNotFoundError ||
error instanceof TokenInvalidAccountOwnerError
) {
// As this isn't atomic, it's possible others can create associated
// accounts meanwhile.
try {
const transaction = new Transaction().add(
createAssociatedTokenAccountInterfaceInstruction(
payer.publicKey,
associatedToken,
owner,
mint,
programId,
associatedTokenProgramId,
),
);
await sendAndConfirmTransaction(
rpc,
transaction,
[payer],
confirmOptions,
);
} catch {
// Ignore all errors; for now there is no API-compatible way to
// selectively ignore the expected instruction error if the
// associated account exists already.
}
// Now this should always succeed
accountInterface = await getAccountInterface(
rpc,
associatedToken,
commitment,
programId,
);
} else {
throw error;
}
}
const account = accountInterface.parsed;
if (!account.mint.equals(mint)) throw new TokenInvalidMintError();
if (!account.owner.equals(owner)) throw new TokenInvalidOwnerError();
return accountInterface;
}