This repository was archived by the owner on Jul 23, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathtoken-entangler-cli.ts
More file actions
520 lines (473 loc) · 14.4 KB
/
Copy pathtoken-entangler-cli.ts
File metadata and controls
520 lines (473 loc) · 14.4 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import { program } from 'commander';
import log from 'loglevel';
import {
getAtaForMint,
getMasterEdition,
getMetadata,
getTokenAmount,
getTokenEntanglement,
getTokenEntanglementEscrows,
loadTokenEntanglementProgream,
loadWalletKey,
} from './helpers/accounts';
import { BN, web3, Program } from '@project-serum/anchor';
import { TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT } from './helpers/constants';
import { ASSOCIATED_TOKEN_PROGRAM_ID, Token } from '@solana/spl-token';
import { getPriceWithMantissa } from './helpers/various';
import { sendTransactionWithRetryWithKeypair } from './helpers/transactions';
import { decodeMetadata, Metadata } from './helpers/schema';
program.version('0.0.1');
log.setLevel('info');
export const getEpKeyFromArgs = async (
anchorProgram: Program,
mintA: web3.PublicKey | null,
mintB: web3.PublicKey | null,
entangledPair: string | undefined,
): Promise<web3.PublicKey> => {
let epKey;
if (!entangledPair) {
log.info('No entangled pair detected, generating from mint arguments.');
epKey = (await getTokenEntanglement(mintA, mintB))[0];
const obj = await anchorProgram.provider.connection.getAccountInfo(epKey);
if (!obj) {
epKey = (await getTokenEntanglement(mintB, mintA))[0];
}
} else {
epKey = new web3.PublicKey(entangledPair);
}
return epKey;
};
programCommand('show')
.option(
'-ep, --entangled-pair <string>',
'Optional. Overrides mint arguments.',
)
.option('-ma, --mint-a <string>', 'mint a')
.option('-mb, --mint-b <string>', 'mint b')
.action(async (directory, cmd) => {
const { keypair, env, entangledPair, mintA, mintB } = cmd.opts();
const walletKeyPair = loadWalletKey(keypair);
const anchorProgram = await loadTokenEntanglementProgream(
walletKeyPair,
env,
);
const epKey = await getEpKeyFromArgs(
anchorProgram,
mintA ? new web3.PublicKey(mintA) : null,
mintB ? new web3.PublicKey(mintB) : null,
entangledPair,
);
const epObj = await anchorProgram.account.entangledPair.fetch(epKey);
log.info('-----');
log.info('Entangled Pair:', epKey.toBase58());
//@ts-ignore
log.info('Mint:', epObj.treasuryMint.toBase58());
//@ts-ignore
log.info('Authority:', epObj.authority.toBase58());
//@ts-ignore
log.info('Mint A:', epObj.mintA.toBase58());
//@ts-ignore
log.info('Mint B:', epObj.mintB.toBase58());
//@ts-ignore
log.info('Token A Escrow:', epObj.tokenAEscrow.toBase58());
//@ts-ignore
log.info('Token B Escrow:', epObj.tokenBEscrow.toBase58());
//@ts-ignore
log.info('Price:', epObj.price.toNumber());
//@ts-ignore
log.info('Paid At Least Once:', epObj.paid);
//@ts-ignore
log.info('Pays Every Time:', epObj.paysEveryTime);
//@ts-ignore
log.info('Bump:', epObj.bump);
});
programCommand('create_entanglement')
.option(
'-tm, --treasury-mint <string>',
'Mint address of treasury. If not used, default to SOL.',
)
.option('-a, --authority <string>', 'Authority, defaults to keypair')
.option('-p, --price <string>', 'Price for a swap')
.option(
'-pet, --pays-every-time <string>',
'If true, the user must pay the swapping fee each swap',
)
.option(
'-ma, --mint-a <string>',
'Mint a. You do not even need to own this token to create this entanglement.',
)
.option(
'-mb, --mint-b <string>',
'Mint b. This token will be removed from your token account right now.',
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.action(async (directory, cmd) => {
const {
keypair,
env,
price,
paysEveryTime,
mintA,
mintB,
treasuryMint,
authority,
} = cmd.opts();
const priceNumber = parseFloat(price);
const walletKeyPair = loadWalletKey(keypair);
const anchorProgram = await loadTokenEntanglementProgream(
walletKeyPair,
env,
);
let authorityKey: web3.PublicKey, tMintKey: web3.PublicKey;
if (!authority) {
log.info('No authority detected, using keypair');
authorityKey = walletKeyPair.publicKey;
} else {
authorityKey = new web3.PublicKey(authority);
}
const mintAKey = new web3.PublicKey(mintA);
const mintBKey = new web3.PublicKey(mintB);
if (!treasuryMint) {
log.info('No treasury mint detected, using SOL.');
tMintKey = WRAPPED_SOL_MINT;
} else {
tMintKey = new web3.PublicKey(treasuryMint);
}
const [entangledPair, bump] = await getTokenEntanglement(
mintAKey,
mintBKey,
);
const [reverseEntangledPair, reverseBump] = await getTokenEntanglement(
mintBKey,
mintAKey,
);
const [tokenAEscrow, tokenABump, tokenBEscrow, tokenBBump] =
await getTokenEntanglementEscrows(mintAKey, mintBKey);
const priceAdjusted = new BN(
await getPriceWithMantissa(
priceNumber,
tMintKey,
walletKeyPair,
anchorProgram,
),
);
const ata = (await getAtaForMint(mintBKey, walletKeyPair.publicKey))[0];
const transferAuthority = web3.Keypair.generate();
const signers = [transferAuthority];
const instruction = await anchorProgram.instruction.createEntangledPair(
bump,
reverseBump,
tokenABump,
tokenBBump,
priceAdjusted,
paysEveryTime == 'true',
{
accounts: {
treasuryMint: tMintKey,
payer: walletKeyPair.publicKey,
transferAuthority: transferAuthority.publicKey,
authority: authorityKey,
mintA: mintAKey,
metadataA: await getMetadata(mintAKey),
editionA: await getMasterEdition(mintAKey),
mintB: mintBKey,
metadataB: await getMetadata(mintBKey),
editionB: await getMasterEdition(mintBKey),
tokenB: ata,
tokenAEscrow,
tokenBEscrow,
entangledPair,
reverseEntangledPair,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: web3.SystemProgram.programId,
rent: web3.SYSVAR_RENT_PUBKEY,
},
},
);
const instructions = [
Token.createApproveInstruction(
TOKEN_PROGRAM_ID,
ata,
transferAuthority.publicKey,
walletKeyPair.publicKey,
[],
1,
),
instruction,
Token.createRevokeInstruction(
TOKEN_PROGRAM_ID,
ata,
walletKeyPair.publicKey,
[],
),
];
await sendTransactionWithRetryWithKeypair(
anchorProgram.provider.connection,
walletKeyPair,
instructions,
signers,
'max',
);
log.info('Created entanglement', entangledPair.toBase58());
});
programCommand('swap')
.option(
'-ep, --entangled-pair <string>',
'Optional. Overrides mint arguments.',
)
.option(
'-ma, --mint-a <string>',
'Mint a. You do not even need to own this token to create this entanglement.',
)
.option(
'-mb, --mint-b <string>',
'Mint b. This token will be removed from your token account right now.',
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.action(async (directory, cmd) => {
const { keypair, env, mintA, mintB, entangledPair } = cmd.opts();
const walletKeyPair = loadWalletKey(keypair);
const anchorProgram = await loadTokenEntanglementProgream(
walletKeyPair,
env,
);
const epKey = await getEpKeyFromArgs(
anchorProgram,
mintA ? new web3.PublicKey(mintA) : null,
mintB ? new web3.PublicKey(mintB) : null,
entangledPair,
);
const epObj = await anchorProgram.account.entangledPair.fetch(epKey);
//@ts-ignore
const mintAKey = epObj.mintA;
//@ts-ignore
const mintBKey = epObj.mintB;
const aAta = (await getAtaForMint(mintAKey, walletKeyPair.publicKey))[0];
const bAta = (await getAtaForMint(mintBKey, walletKeyPair.publicKey))[0];
const currABal = await getTokenAmount(anchorProgram, aAta, mintAKey);
const token = currABal == 1 ? aAta : bAta,
replacementToken = currABal == 1 ? bAta : aAta;
const tokenMint = currABal == 1 ? mintAKey : mintBKey,
replacementTokenMint = currABal == 1 ? mintBKey : mintAKey;
const result = await getTokenEntanglementEscrows(mintAKey, mintBKey);
const tokenAEscrow = result[0];
const tokenBEscrow = result[2];
const transferAuthority = web3.Keypair.generate();
const paymentTransferAuthority = web3.Keypair.generate();
const replacementTokenMetadata = await getMetadata(replacementTokenMint);
const signers = [transferAuthority];
//@ts-ignore
const isNative = epObj.treasuryMint.equals(WRAPPED_SOL_MINT);
//@ts-ignore
const paymentAccount = isNative
? walletKeyPair.publicKey
: (await getAtaForMint(epObj.treasuryMint, walletKeyPair.publicKey))[0];
if (!isNative) signers.push(paymentTransferAuthority);
const remainingAccounts = [];
const metadataObj = await anchorProgram.provider.connection.getAccountInfo(
replacementTokenMetadata,
);
const metadataDecoded: Metadata = decodeMetadata(
Buffer.from(metadataObj.data),
);
for (let i = 0; i < metadataDecoded.data.creators.length; i++) {
remainingAccounts.push({
pubkey: new web3.PublicKey(metadataDecoded.data.creators[i].address),
isWritable: true,
isSigner: false,
});
if (!isNative) {
remainingAccounts.push({
pubkey: (
await getAtaForMint(
//@ts-ignore
epObj.treasuryMint,
remainingAccounts[remainingAccounts.length - 1].pubkey,
)
)[0],
isWritable: true,
isSigner: false,
});
}
}
const instruction = await anchorProgram.instruction.swap({
accounts: {
//@ts-ignore
treasuryMint: epObj.treasuryMint,
payer: walletKeyPair.publicKey,
paymentAccount,
transferAuthority: transferAuthority.publicKey,
paymentTransferAuthority: paymentTransferAuthority.publicKey,
token,
tokenMint,
replacementTokenMetadata,
replacementToken,
replacementTokenMint,
tokenAEscrow,
tokenBEscrow,
entangledPair: epKey,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: web3.SystemProgram.programId,
ataProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
rent: web3.SYSVAR_RENT_PUBKEY,
},
remainingAccounts,
});
if (!isNative) {
instruction.keys
.filter(k => k.pubkey.equals(paymentTransferAuthority.publicKey))
.map(k => (k.isSigner = true));
}
const instructions = [
Token.createApproveInstruction(
TOKEN_PROGRAM_ID,
token,
transferAuthority.publicKey,
walletKeyPair.publicKey,
[],
1,
),
...(!isNative
? [
Token.createApproveInstruction(
TOKEN_PROGRAM_ID,
paymentAccount,
paymentTransferAuthority.publicKey,
walletKeyPair.publicKey,
[],
//@ts-ignore
epObj.price.toNumber(),
),
]
: []),
instruction,
Token.createRevokeInstruction(
TOKEN_PROGRAM_ID,
token,
walletKeyPair.publicKey,
[],
),
...(!isNative
? [
Token.createRevokeInstruction(
TOKEN_PROGRAM_ID,
paymentAccount,
walletKeyPair.publicKey,
[],
),
]
: []),
];
await sendTransactionWithRetryWithKeypair(
anchorProgram.provider.connection,
walletKeyPair,
instructions,
signers,
'max',
);
log.info(
'Swapped',
tokenMint.toBase58(),
'mint for',
replacementTokenMint.toBase58(),
' with entangled pair ',
epKey.toBase58(),
);
});
programCommand('update_entanglement')
.option(
'-ep, --entangled-pair <string>',
'Optional. Overrides mint arguments.',
)
.option('-na, --new-authority <string>', 'Authority, defaults to keypair')
.option('-p, --price <string>', 'Price for a swap')
.option(
'-pet, --pays-every-time <string>',
'If true, the user must pay the swapping fee each swap',
)
.option(
'-ma, --mint-a <string>',
'Mint a. You do not even need to own this token to create this entanglement.',
)
.option(
'-mb, --mint-b <string>',
'Mint b. This token will be removed from your token account right now.',
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.action(async (directory, cmd) => {
const {
keypair,
env,
price,
paysEveryTime,
mintA,
mintB,
entangledPair,
newAuthority,
} = cmd.opts();
const walletKeyPair = loadWalletKey(keypair);
const anchorProgram = await loadTokenEntanglementProgream(
walletKeyPair,
env,
);
const epKey = await getEpKeyFromArgs(
anchorProgram,
mintA ? new web3.PublicKey(mintA) : null,
mintB ? new web3.PublicKey(mintB) : null,
entangledPair,
);
const epObj = await anchorProgram.account.entangledPair.fetch(epKey);
//@ts-ignore
const authorityKey = new web3.PublicKey(
newAuthority ? newAuthority : epObj.authority,
);
const priceAdjusted = price
? new BN(
await getPriceWithMantissa(
parseFloat(price),
//@ts-ignore
epObj.treasuryMint,
walletKeyPair,
anchorProgram,
),
)
: //@ts-ignore
epObj.price;
await anchorProgram.rpc.updateEntangledPair(
priceAdjusted,
paysEveryTime == 'true',
{
accounts: {
newAuthority: authorityKey,
//@ts-ignore
authority: epObj.authority,
entangledPair: epKey,
},
},
);
log.info('Updated entanglement', epKey.toBase58());
});
function programCommand(name: string) {
return program
.command(name)
.option(
'-e, --env <string>',
'Solana cluster env name',
'devnet', //mainnet-beta, testnet, devnet
)
.option(
'-k, --keypair <path>',
`Solana wallet location`,
'--keypair not provided',
)
.option('-l, --log-level <string>', 'log level', setLogLevel);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function setLogLevel(value, prev) {
if (value === undefined || value === null) {
return;
}
log.info('setting the log value to: ' + value);
log.setLevel(value);
}
program.parse(process.argv);