-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathScope.ts
610 lines (571 loc) · 18.9 KB
/
Scope.ts
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
import {
AccountMeta,
Connection,
Keypair,
PublicKey,
SystemProgram,
SYSVAR_INSTRUCTIONS_PUBKEY,
Transaction,
} from '@solana/web3.js';
import Decimal from 'decimal.js';
import { Configuration, OracleMappings, OraclePrices } from './accounts';
import { OracleType, OracleTypeKind, Price } from './types';
import { SCOPE_DEVNET_CONFIG, SCOPE_LOCALNET_CONFIG, SCOPE_MAINNET_CONFIG, ScopeConfig, U16_MAX } from './constants';
import * as ScopeIx from './instructions';
import { AnchorProvider, Wallet } from '@coral-xyz/anchor';
import {
getConfigurationPda,
ORACLE_MAPPINGS_LEN,
TOKEN_METADATAS_LEN,
ORACLE_PRICES_LEN,
ORACLE_TWAPS_LEN,
getJlpMintPda,
JLP_PROGRAM_ID,
getMintsToScopeChainPda,
} from './utils';
import { FeedParam, PricesParam, validateFeedParam, validatePricesParam } from './model';
import { GlobalConfig, WhirlpoolStrategy } from './@codegen/kamino/accounts';
import { Custody, Pool } from './@codegen/jupiter-perps/accounts';
export type ScopeDatedPrice = {
price: Decimal;
timestamp: Decimal;
};
export class Scope {
private readonly _connection: Connection;
private readonly _config: ScopeConfig;
/**
* Create a new instance of the Scope SDK class.
* @param cluster Name of the Solana cluster
* @param connection Connection to the Solana cluster
*/
constructor(cluster: 'localnet' | 'devnet' | 'mainnet-beta', connection: Connection) {
this._connection = connection;
switch (cluster) {
case 'localnet':
this._config = SCOPE_LOCALNET_CONFIG;
break;
case 'devnet':
this._config = SCOPE_DEVNET_CONFIG;
break;
case 'mainnet-beta': {
this._config = SCOPE_MAINNET_CONFIG;
break;
}
default: {
throw Error('Invalid cluster');
}
}
}
private static priceToDecimal(price: Price) {
return new Decimal(price.value.toString()).mul(new Decimal(10).pow(new Decimal(-price.exp.toString())));
}
/**
* Get the deserialised OraclePrices account for a given feed
* @param feed - either the feed PDA seed or the configuration account address
* @returns OraclePrices
*/
async getOraclePrices(feed?: PricesParam): Promise<OraclePrices> {
validatePricesParam(feed);
let oraclePrices: PublicKey;
if (feed?.feed || feed?.config) {
const [, configAccount] = await this.getFeedConfiguration(feed);
oraclePrices = configAccount.oraclePrices;
} else if (feed?.prices) {
oraclePrices = feed.prices;
} else {
oraclePrices = this._config.oraclePrices;
}
const prices = await OraclePrices.fetch(this._connection, oraclePrices, this._config.programId);
if (!prices) {
throw Error(`Could not get scope oracle prices`);
}
return prices;
}
/**
* Get the deserialised OraclePrices accounts for a given `OraclePrices` account pubkeys
* Optimised to filter duplicate keys from the network request but returns the same size response as requested in the same order
* @throws Error if any of the accounts cannot be fetched
* @param prices - public keys of the `OraclePrices` accounts
* @returns [PublicKey, OraclePrices][]
*/
async getMultipleOraclePrices(prices: PublicKey[]): Promise<[PublicKey, OraclePrices][]> {
const priceStrings = prices.map((price) => price.toBase58());
const uniqueScopePrices = [...new Set(priceStrings)].map((value) => new PublicKey(value));
if (uniqueScopePrices.length === 1) {
return [[uniqueScopePrices[0], await this.getOraclePrices({ prices: uniqueScopePrices[0] })]];
}
const oraclePrices = await OraclePrices.fetchMultiple(this._connection, uniqueScopePrices, this._config.programId);
const oraclePricesMap: Record<string, OraclePrices> = oraclePrices
.map((price, i) => {
if (price === null) {
throw Error(`Could not get scope oracle prices for ${uniqueScopePrices[i].toBase58()}`);
}
return price;
})
.reduce((map, price, i) => {
map[uniqueScopePrices[i].toBase58()] = price;
return map;
}, {});
return prices.map((price) => [price, oraclePricesMap[price.toBase58()]]);
}
/**
* Get the deserialised Configuration account for a given feed
* @param feedParam - either the feed PDA seed or the configuration account address
* @returns [configuration account address, deserialised configuration]
*/
async getFeedConfiguration(feedParam?: FeedParam): Promise<[PublicKey, Configuration]> {
validateFeedParam(feedParam);
const { feed, config } = feedParam || {};
let configPubkey: PublicKey;
if (feed) {
configPubkey = getConfigurationPda(feed);
} else if (config) {
configPubkey = config;
} else {
configPubkey = this._config.configurationAccount;
}
const configAccount = await Configuration.fetch(this._connection, configPubkey, this._config.programId);
if (!configAccount) {
throw new Error(`Could not find configuration account for ${feed || configPubkey.toBase58()}`);
}
return [configPubkey, configAccount];
}
/**
* Get the deserialised OracleMappings account for a given feed
* @param feed - either the feed PDA seed or the configuration account address
* @returns OracleMappings
*/
async getOracleMappings(feed: FeedParam): Promise<OracleMappings> {
const [config, configAccount] = await this.getFeedConfiguration(feed);
return this.getOracleMappingsFromConfig(feed, config, configAccount);
}
/**
* Get the deserialized OracleMappings account for a given feed and config
* @param feed - either the feed PDA seed or the configuration account address
* @param config - the configuration account address
* @param configAccount - the deserialized configuration account
* @returns OracleMappings
*/
async getOracleMappingsFromConfig(
feed: FeedParam,
config: PublicKey,
configAccount: Configuration
): Promise<OracleMappings> {
const oracleMappings = await OracleMappings.fetch(
this._connection,
configAccount.oracleMappings,
this._config.programId
);
if (!oracleMappings) {
throw Error(
`Could not get scope oracle mappings account for feed ${JSON.stringify(feed)}, config ${config.toBase58()}`
);
}
return oracleMappings;
}
/**
* Get the price of a token from a chain of token prices
* @param chain
* @param prices
*/
public static getPriceFromScopeChain(chain: Array<number>, prices: OraclePrices): ScopeDatedPrice {
// Protect from bad defaults
if (chain.every((tokenId) => tokenId === 0)) {
throw new Error('Token chain cannot be all 0s');
}
// Protect from bad defaults
const filteredChain = chain.filter((tokenId) => tokenId !== U16_MAX);
if (filteredChain.length === 0) {
throw new Error(`Token chain cannot be all ${U16_MAX}s (u16 max)`);
}
let oldestTimestamp = new Decimal('0');
const priceChain = filteredChain.map((tokenId) => {
const datedPrice = prices.prices[tokenId];
if (!datedPrice) {
throw Error(`Could not get price for token ${tokenId}`);
}
const currentPxTs = new Decimal(datedPrice.unixTimestamp.toString());
if (oldestTimestamp.eq(new Decimal('0'))) {
oldestTimestamp = currentPxTs;
} else if (!currentPxTs.eq(new Decimal('0'))) {
oldestTimestamp = Decimal.min(oldestTimestamp, currentPxTs);
}
const priceInfo = datedPrice.price;
return Scope.priceToDecimal(priceInfo);
});
if (priceChain.length === 1) {
return {
price: priceChain[0],
timestamp: oldestTimestamp,
};
}
// Compute token value by multiplying all values of the chain
const pxFromChain = priceChain.reduce((acc, price) => acc.mul(price), new Decimal(1));
return {
price: pxFromChain,
timestamp: oldestTimestamp,
};
}
/**
* Verify if the scope chain is valid
* @param chain
*/
public static isScopeChainValid(chain: Array<number>) {
return !(
chain.length === 0 ||
chain.every((tokenId) => tokenId === 0) ||
chain.every((tokenId) => tokenId === U16_MAX)
);
}
/**
* Get the price of a token from a chain of token prices
* @param chain
* @param oraclePrices
*/
async getPriceFromChain(chain: Array<number>, oraclePrices?: OraclePrices): Promise<ScopeDatedPrice> {
let prices: OraclePrices;
if (oraclePrices) {
prices = oraclePrices;
} else {
prices = await this.getOraclePrices();
}
return Scope.getPriceFromScopeChain(chain, prices);
}
/**
* Create a new scope price feed
* @param admin
* @param feed
*/
async initialise(
admin: Keypair,
feed: string
): Promise<
[
string,
{
configuration: PublicKey;
oracleMappings: PublicKey;
oraclePrices: PublicKey;
oracleTwaps: PublicKey;
},
]
> {
const config = getConfigurationPda(feed);
const oraclePrices = Keypair.generate();
const createOraclePricesIx = SystemProgram.createAccount({
fromPubkey: admin.publicKey,
newAccountPubkey: oraclePrices.publicKey,
lamports: await this._connection.getMinimumBalanceForRentExemption(ORACLE_PRICES_LEN),
space: ORACLE_PRICES_LEN,
programId: this._config.programId,
});
const oracleMappings = Keypair.generate();
const createOracleMappingsIx = SystemProgram.createAccount({
fromPubkey: admin.publicKey,
newAccountPubkey: oracleMappings.publicKey,
lamports: await this._connection.getMinimumBalanceForRentExemption(ORACLE_MAPPINGS_LEN),
space: ORACLE_MAPPINGS_LEN,
programId: this._config.programId,
});
const tokenMetadatas = Keypair.generate();
const createTokenMetadatasIx = SystemProgram.createAccount({
fromPubkey: admin.publicKey,
newAccountPubkey: tokenMetadatas.publicKey,
lamports: await this._connection.getMinimumBalanceForRentExemption(TOKEN_METADATAS_LEN),
space: TOKEN_METADATAS_LEN,
programId: this._config.programId,
});
const oracleTwaps = Keypair.generate();
const createOracleTwapsIx = SystemProgram.createAccount({
fromPubkey: admin.publicKey,
newAccountPubkey: oracleTwaps.publicKey,
lamports: await this._connection.getMinimumBalanceForRentExemption(ORACLE_TWAPS_LEN),
space: ORACLE_TWAPS_LEN,
programId: this._config.programId,
});
const initScopeIx = ScopeIx.initialize(
{ feedName: feed },
{
admin: admin.publicKey,
configuration: config,
oracleMappings: oracleMappings.publicKey,
oracleTwaps: oracleTwaps.publicKey,
tokenMetadatas: tokenMetadatas.publicKey,
oraclePrices: oraclePrices.publicKey,
systemProgram: SystemProgram.programId,
},
this._config.programId
);
const provider = new AnchorProvider(this._connection, new Wallet(admin), {
commitment: this._connection.commitment,
});
const sig = await provider.sendAndConfirm(
new Transaction().add(
...[createOraclePricesIx, createOracleMappingsIx, createOracleTwapsIx, createTokenMetadatasIx, initScopeIx]
),
[admin, oraclePrices, oracleMappings, oracleTwaps, tokenMetadatas]
);
return [
sig,
{
configuration: config,
oracleMappings: oracleMappings.publicKey,
oraclePrices: oraclePrices.publicKey,
oracleTwaps: oracleTwaps.publicKey,
},
];
}
/**
* Update the price mapping of a token
* @param admin
* @param feed
* @param index
* @param oracleType
* @param mapping
* @param twapEnabled
* @param twapSource
* @param refPriceIndex
* @param genericData
*/
async updateFeedMapping(
admin: Keypair,
feed: string,
index: number,
oracleType: OracleTypeKind,
mapping: PublicKey,
twapEnabled: boolean = false,
twapSource: number = 0,
refPriceIndex: number = 65_535,
genericData: Array<number> = Array(20).fill(0)
): Promise<string> {
const [config, configAccount] = await this.getFeedConfiguration({ feed });
const updateIx = ScopeIx.updateMapping(
{
feedName: feed,
token: index,
priceType: oracleType.discriminator,
twapEnabled,
twapSource,
refPriceIndex,
genericData,
},
{
admin: admin.publicKey,
configuration: config,
oracleMappings: configAccount.oracleMappings,
priceInfo: mapping,
},
this._config.programId
);
const provider = new AnchorProvider(this._connection, new Wallet(admin), {
commitment: this._connection.commitment,
});
return provider.sendAndConfirm(new Transaction().add(updateIx), [admin]);
}
async refreshPriceList(payer: Keypair, feed: FeedParam, tokens: number[]) {
const [, configAccount] = await this.getFeedConfiguration(feed);
const refreshIx = ScopeIx.refreshPriceList(
{
tokens,
},
{
oracleMappings: configAccount.oracleMappings,
oraclePrices: configAccount.oraclePrices,
oracleTwaps: configAccount.oracleTwaps,
instructionSysvarAccountInfo: SYSVAR_INSTRUCTIONS_PUBKEY,
},
this._config.programId
);
const provider = new AnchorProvider(this._connection, new Wallet(payer), {
commitment: this._connection.commitment,
});
const mappings = await this.getOracleMappings(feed);
for (const token of tokens) {
refreshIx.keys.push(
...(await Scope.getRefreshAccounts(
this._connection,
configAccount,
this._config.kliquidityProgramId,
mappings,
token
))
);
}
return provider.sendAndConfirm(new Transaction().add(refreshIx), [payer]);
}
async refreshPriceListIx(feed: FeedParam, tokens: number[]) {
const [config, configAccount] = await this.getFeedConfiguration(feed);
const refreshIx = ScopeIx.refreshPriceList(
{
tokens,
},
{
oracleMappings: configAccount.oracleMappings,
oraclePrices: configAccount.oraclePrices,
oracleTwaps: configAccount.oracleTwaps,
instructionSysvarAccountInfo: SYSVAR_INSTRUCTIONS_PUBKEY,
},
this._config.programId
);
const mappings = await this.getOracleMappingsFromConfig(feed, config, configAccount);
for (const token of tokens) {
refreshIx.keys.push(
...(await Scope.getRefreshAccounts(
this._connection,
configAccount,
this._config.kliquidityProgramId,
mappings,
token
))
);
}
return refreshIx;
}
static async getRefreshAccounts(
connection: Connection,
configAccount: Configuration,
kaminoProgramId: PublicKey,
mappings: OracleMappings,
token: number
): Promise<AccountMeta[]> {
const keys: AccountMeta[] = [];
keys.push({
isSigner: false,
isWritable: false,
pubkey: mappings.priceInfoAccounts[token],
});
switch (mappings.priceTypes[token]) {
case new OracleType.KToken().discriminator: {
keys.push(...(await Scope.getKTokenRefreshAccounts(connection, kaminoProgramId, mappings, token)));
return keys;
}
case new OracleType.JupiterLpFetch().discriminator: {
const lpMint = getJlpMintPda(mappings.priceInfoAccounts[token]);
keys.push({
isSigner: false,
isWritable: false,
pubkey: lpMint,
});
return keys;
}
case new OracleType.JupiterLpCompute().discriminator: {
const lpMint = getJlpMintPda(mappings.priceInfoAccounts[token]);
const jlpRefreshAccounts = await this.getJlpRefreshAccounts(
connection,
configAccount,
mappings,
token,
'compute'
);
jlpRefreshAccounts.unshift({
isSigner: false,
isWritable: false,
pubkey: lpMint,
});
keys.push(...jlpRefreshAccounts);
return keys;
}
case new OracleType.JupiterLpScope().discriminator: {
const lpMint = getJlpMintPda(mappings.priceInfoAccounts[token]);
const jlpRefreshAccounts = await this.getJlpRefreshAccounts(
connection,
configAccount,
mappings,
token,
'scope'
);
jlpRefreshAccounts.unshift({
isSigner: false,
isWritable: false,
pubkey: lpMint,
});
keys.push(...jlpRefreshAccounts);
return keys;
}
default: {
return keys;
}
}
}
static async getJlpRefreshAccounts(
connection: Connection,
configAccount: Configuration,
mappings: OracleMappings,
token: number,
fetchingMechanism: 'compute' | 'scope'
): Promise<AccountMeta[]> {
const pool = await Pool.fetch(connection, mappings.priceInfoAccounts[token], JLP_PROGRAM_ID);
if (!pool) {
throw Error(
`Could not get Jupiter pool ${mappings.priceInfoAccounts[token].toBase58()} to refresh token index ${token}`
);
}
const extraAccounts: AccountMeta[] = [];
if (fetchingMechanism === 'scope') {
const mintsToScopeChain = getMintsToScopeChainPda(
configAccount.oraclePrices,
mappings.priceInfoAccounts[token],
token
);
extraAccounts.push({
isSigner: false,
isWritable: false,
pubkey: mintsToScopeChain,
});
}
extraAccounts.push(
...pool.custodies.map((custody) => {
return {
isSigner: false,
isWritable: false,
pubkey: custody,
};
})
);
if (fetchingMechanism === 'compute') {
for (const custodyPk of pool.custodies) {
const custody = await Custody.fetch(connection, custodyPk, JLP_PROGRAM_ID);
if (!custody) {
throw Error(`Could not get Jupiter custody ${custodyPk.toBase58()} to refresh token index ${token}`);
}
extraAccounts.push({
isSigner: false,
isWritable: false,
pubkey: custody.oracle.oracleAccount,
});
}
}
return extraAccounts;
}
static async getKTokenRefreshAccounts(
connection: Connection,
kaminoProgramId: PublicKey,
mappings: OracleMappings,
token: number
): Promise<AccountMeta[]> {
const strategy = await WhirlpoolStrategy.fetch(connection, mappings.priceInfoAccounts[token], kaminoProgramId);
if (!strategy) {
throw Error(
`Could not get Kamino strategy ${mappings.priceInfoAccounts[token].toBase58()} to refresh token index ${token}`
);
}
const globalConfig = await GlobalConfig.fetch(connection, strategy.globalConfig, kaminoProgramId);
if (!globalConfig) {
throw Error(
`Could not get global config for Kamino strategy ${mappings.priceInfoAccounts[
token
].toBase58()} to refresh token index ${token}`
);
}
return [strategy.globalConfig, globalConfig.tokenInfos, strategy.pool, strategy.position, strategy.scopePrices].map(
(acc) => {
return {
isSigner: false,
isWritable: false,
pubkey: acc,
};
}
);
}
}
export default Scope;