forked from step-finance/reward-pool
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.js
580 lines (517 loc) · 21.6 KB
/
user.js
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
const anchor = require("@project-serum/anchor");
const { TOKEN_PROGRAM_ID, Token, AccountLayout } = require("@solana/spl-token");
const utils = require("./utils");
async function claimForUsers(users) {
//some eye piercing way to claim for all users async, then print out all users balances
//if you're reading this, all we're effectively doing here is calling "claim()" on a user.
let r = await Promise.all(
users.map(a => a.claim().then(b=>[a,b]))
);
console.log("--- users claimed ---")
r.sort((a,b)=>a[0].id < b[0].id)
.forEach(a=>{
a[0].currentA = a[1][0];
a[0].currentB = a[1][1];
console.log(a[0].id, "amtA", a[0].currentA, "amtB", a[0].currentB);
});
}
///user can be an admin or a staker. either way, call init - then can call other methods
class User {
constructor(a) { this.id = a; }
async init(initialLamports, xTokenMint, initialXToken, stakingMint, initialStaking, mintA, initialA, mintB, initialB) {
this.keypair = new anchor.web3.Keypair();
this.pubkey = this.keypair.publicKey;
let envProvider = anchor.Provider.env();
envProvider.commitment = 'pending';
await utils.sendLamports(envProvider, this.pubkey, initialLamports);
this.provider = new anchor.Provider(envProvider.connection, new anchor.Wallet(this.keypair), envProvider.opts);
let program = anchor.workspace.RewardPool;
this.program = new anchor.Program(program.idl, program.programId, this.provider);
this.initialLamports = initialLamports;
this.xTokenMintObject = new Token(this.provider.connection, xTokenMint, TOKEN_PROGRAM_ID, this.provider.wallet.payer);
this.initialXToken = initialXToken;
this.stakingMintObject = new Token(this.provider.connection, stakingMint, TOKEN_PROGRAM_ID, this.provider.wallet.payer);
this.initialStaking = initialStaking;
this.mintAObject = new Token(this.provider.connection, mintA, TOKEN_PROGRAM_ID, this.provider.wallet.payer);
this.initialA = initialA;
this.mintBObject = new Token(this.provider.connection, mintB, TOKEN_PROGRAM_ID, this.provider.wallet.payer);
this.initialB = initialB;
this.poolPubkey = null;
this.userPubkey = null;
this.userNonce = null;
this.lpPubkey = null;
this.xTokenPubkey = await this.xTokenMintObject.createAssociatedTokenAccount(this.pubkey);
if (initialXToken > 0) {
await this.xTokenMintObject.mintTo(this.xTokenPubkey, envProvider.wallet.payer, [], initialXToken);
}
this.stakingPubkey = await this.stakingMintObject.createAssociatedTokenAccount(this.pubkey);
if (initialStaking > 0) {
await this.stakingMintObject.mintTo(this.stakingPubkey, envProvider.wallet.payer, [], initialStaking);
}
this.mintAPubkey = await this.mintAObject.createAssociatedTokenAccount(this.pubkey);
if (initialA > 0) {
await this.mintAObject.mintTo(this.mintAPubkey, envProvider.wallet.payer, [], initialA);
}
//single staking, will use same for each
if (mintA != mintB) {
this.mintBPubkey = await this.mintBObject.createAssociatedTokenAccount(this.pubkey);
if (initialB > 0) {
await this.mintBObject.mintTo(this.mintBPubkey, envProvider.wallet.payer, [], initialB);
}
} else {
this.mintBPubkey = this.mintAPubkey;
}
}
async initializePool(poolKeypair, rewardDuration, singleStake) {
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[poolKeypair.publicKey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
let poolNonce = _nonce;
let xTokenPoolVault = await this.xTokenMintObject.createAccount(poolSigner);
let stakingMintVault = await this.stakingMintObject.createAccount(poolSigner);
let mintAVault = await this.mintAObject.createAccount(poolSigner);
let mintBVault = null;
if (!singleStake) {
mintBVault = await this.mintBObject.createAccount(poolSigner);
}
this.poolPubkey = poolKeypair.publicKey;
this.admin = {
poolKeypair,
poolSigner,
poolNonce,
xTokenPoolVault,
stakingMintVault,
mintAVault,
mintBVault
};
await this.program.rpc.initializePool(
poolNonce,
rewardDuration,
{
accounts: {
authority: this.provider.wallet.publicKey,
xTokenPoolVault: xTokenPoolVault,
xTokenDepositor: this.xTokenPubkey,
xTokenDepositAuthority: this.provider.wallet.publicKey,
stakingMint: this.stakingMintObject.publicKey,
stakingVault: stakingMintVault,
rewardAMint: this.mintAObject.publicKey,
rewardAVault: mintAVault,
rewardBMint: singleStake ? this.mintAObject.publicKey : this.mintBObject.publicKey,
rewardBVault: singleStake ? mintAVault : mintBVault,
poolSigner: poolSigner,
pool: this.poolPubkey,
tokenProgram: TOKEN_PROGRAM_ID,
},
signers: [poolKeypair],
instructions: [
await this.program.account.pool.createInstruction(poolKeypair, ),
],
}
);
//console.log("tx", tx.instructions.map(a=>a.keys));
//await this.provider.send(tx);
}
async createUserStakingAccount(poolPubkey) {
this.poolPubkey = poolPubkey;
const [
_userPubkey, _userNonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.provider.wallet.publicKey.toBuffer(), poolPubkey.toBuffer()],
this.program.programId
);
this.userPubkey = _userPubkey;
this.userNonce = _userNonce;
const balanceNeeded = await Token.getMinBalanceRentForExemptAccount(this.provider.connection);
await this.program.rpc.createUser(this.userNonce, {
accounts: {
pool: poolPubkey,
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
});
}
async stakeTokens(amount) {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
await this.program.rpc.stake(
new anchor.BN(amount),
{
accounts: {
// Stake instance.
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
// User.
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
stakeFromAccount: this.stakingPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
}
);
}
async pausePool(authority) {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
await this.program.rpc.pause(
{
accounts: {
xTokenPoolVault: poolObject.xTokenPoolVault,
xTokenReceiver: this.xTokenPubkey,
pool: this.poolPubkey,
authority: authority ?? this.provider.wallet.publicKey,
poolSigner: poolSigner,
tokenProgram: TOKEN_PROGRAM_ID,
},
}
);
}
async unpausePool(authority) {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
let xTokenPoolVault = await this.xTokenMintObject.createAccount(poolSigner);
this.admin.xTokenPoolVault = xTokenPoolVault;
await this.program.rpc.unpause(
{
accounts: {
xTokenPoolVault: xTokenPoolVault,
xTokenDepositor: this.xTokenPubkey,
xTokenDepositAuthority: this.provider.wallet.publicKey,
pool: this.poolPubkey,
authority: authority ?? this.provider.wallet.publicKey,
poolSigner: poolSigner,
tokenProgram: TOKEN_PROGRAM_ID,
},
}
);
}
async unstakeTokens(amount) {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
await this.program.rpc.unstake(
new anchor.BN(amount),
{
accounts: {
// Stake instance.
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
// User.
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
stakeFromAccount: this.stakingPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
}
async authorizeFunder(newFunder) {
await this.program.rpc.authorizeFunder(
newFunder,
{
accounts: {
pool: this.poolPubkey,
authority: this.provider.wallet.publicKey,
},
});
}
async deauthorizeFunder(oldFunder) {
await this.program.rpc.deauthorizeFunder(
oldFunder,
{
accounts: {
pool: this.poolPubkey,
authority: this.provider.wallet.publicKey,
},
});
}
async fund(amountA, amountB, poolPubkey) {
let pubkeyToUse = poolPubkey ?? this.poolPubkey;
let poolObject = await this.program.account.pool.fetch(pubkeyToUse);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[pubkeyToUse.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
await this.program.rpc.fund(
new anchor.BN(amountA),
new anchor.BN(amountB),
{
accounts: {
// Stake instance.
pool: pubkeyToUse,
stakingVault: poolObject.stakingVault,
rewardAVault: poolObject.rewardAVault,
rewardBVault: poolObject.rewardBVault,
funder: this.provider.wallet.publicKey,
fromA: this.mintAPubkey,
fromB: this.mintBPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
}
async getUserPendingRewardsFunction() {
return await User.getPendingRewardsFunction(this.program, this.poolPubkey);
}
// *returns a function* that when called returns an array of 2 values, the pending rewardA and rewardB
// this function is accurate forever (even after pool ends), unless the pool is changed through
// funding, or anyone staking/unstaking.
// Querying the chain is only done on initial call (this method) to build the function.
// Computations are done against current date/time every time the returned function is called; thus you
// could hook this up to a timer for a fancy UX.
static async getPendingRewardsFunction(rewardsPoolAnchorProgram, rewardsPoolPubkey) {
const U64_MAX = new anchor.BN("18446744073709551615", 10);
let poolObject = await rewardsPoolAnchorProgram.account.pool.fetch(rewardsPoolPubkey);
let rewardAPerToken = new anchor.BN(poolObject.rewardAPerTokenStored);
let rewardBPerToken = new anchor.BN(poolObject.rewardBPerTokenStored);
let rewardARate = new anchor.BN(poolObject.rewardARate);
let rewardBRate = new anchor.BN(poolObject.rewardBRate);
let lastUpdate = poolObject.lastUpdateTime;
var singleStaking = poolObject.rewardAMint.toString() == poolObject.rewardBMint.toString();
let vaultBalance = await rewardsPoolAnchorProgram.provider.connection.getTokenAccountBalance(poolObject.stakingVault);
vaultBalance = new anchor.BN(parseInt(vaultBalance.value.amount));
//a function that gives the total rewards emitted over the whole pool since last update
let fnAllRewardsPerToken = () => {
var lastApplicable = Math.min(Math.floor(Date.now() / 1000), poolObject.rewardDurationEnd);
var elapsed = new anchor.BN(lastApplicable - lastUpdate);
var currentARewardPerToken = rewardAPerToken.add(elapsed.mul(rewardARate).mul(U64_MAX).div(vaultBalance));
var currentBRewardPerToken;
if (singleStaking) {
currentBRewardPerToken = new anchor.BN(0);
} else {
currentBRewardPerToken = rewardBPerToken.add(elapsed.mul(rewardBRate).mul(U64_MAX).div(vaultBalance));
}
return [currentARewardPerToken, currentBRewardPerToken];
};
const [
userPubkey, _userNonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[rewardsPoolAnchorProgram.provider.wallet.publicKey.toBuffer(), rewardsPoolPubkey.toBuffer()],
rewardsPoolAnchorProgram.programId
);
let userObject = await rewardsPoolAnchorProgram.account.user.fetch(userPubkey);
let completeA = new anchor.BN(userObject.rewardAPerTokenComplete);
let completeB = new anchor.BN(userObject.rewardBPerTokenComplete);
let pendingA = new anchor.BN(userObject.rewardAPerTokenPending);
let pendingB = new anchor.BN(userObject.rewardBPerTokenPending);
let balanceStaked = new anchor.BN(userObject.balanceStaked);
//a function that gives a user's total unclaimed rewards since last update
let currentPending = () => {
var rwds = fnAllRewardsPerToken();
var a = balanceStaked.mul(rwds[0]).sub(completeA).div(U64_MAX).add(pendingA).toNumber();
var b;
if (singleStaking) {
b = 0;
} else {
b = balanceStaked.mul(rwds[1]).sub(completeB).div(U64_MAX).add(pendingB).toNumber();
}
return [a, b];
}
return currentPending;
}
async claim() {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
await this.program.rpc.claim({
accounts: {
// Stake instance.
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
rewardAVault: poolObject.rewardAVault,
rewardBVault: poolObject.rewardBVault,
// User.
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
rewardAAccount: this.mintAPubkey,
rewardBAccount: this.mintBPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
let amtA = await this.provider.connection.getTokenAccountBalance(this.mintAPubkey);
let amtB = await this.provider.connection.getTokenAccountBalance(this.mintBPubkey);
return [amtA.value.uiAmount, amtB.value.uiAmount];
}
//a transaction to stake, claim, unstake all at once - should net nothing
async snipe(amount) {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
let ixStake = this.program.instruction.stake(
new anchor.BN(amount),
{
accounts: {
// Stake instance.
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
// User.
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
stakeFromAccount: this.stakingPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
}
);
let ixClaim = this.program.instruction.claim({
accounts: {
// Stake instance.
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
rewardAVault: poolObject.rewardAVault,
rewardBVault: poolObject.rewardBVault,
// User.
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
rewardAAccount: this.mintAPubkey,
rewardBAccount: this.mintBPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
await this.program.rpc.unstake(
new anchor.BN(amount),
{
accounts: {
// Stake instance.
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
// User.
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
stakeFromAccount: this.stakingPubkey,
// Program signers.
poolSigner,
// Misc.
clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
tokenProgram: TOKEN_PROGRAM_ID,
},
instructions: [
ixStake,
ixClaim,
]
}
);
let amtA = await this.provider.connection.getTokenAccountBalance(this.mintAPubkey);
let amtB = await this.provider.connection.getTokenAccountBalance(this.mintBPubkey);
return [amtA.value.uiAmount, amtB.value.uiAmount];
}
async closeUser() {
await this.program.rpc.closeUser(
{
accounts: {
// Stake instance.
pool: this.poolPubkey,
user: this.userPubkey,
owner: this.provider.wallet.publicKey,
},
});
}
async closePool() {
let poolObject = await this.program.account.pool.fetch(this.poolPubkey);
const [ configPubkey, ___nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("config")],
this.program.programId
);
const [
_poolSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[this.poolPubkey.toBuffer()],
this.program.programId
);
let poolSigner = _poolSigner;
let nonce = _nonce;
await this.program.rpc.closePool(
{
accounts: {
// Stake instance.
authority: this.provider.wallet.publicKey,
refundee: this.provider.wallet.publicKey,
stakingRefundee: this.stakingPubkey,
rewardARefundee: this.mintAPubkey,
rewardBRefundee: this.mintBPubkey,
pool: this.poolPubkey,
stakingVault: poolObject.stakingVault,
rewardAVault: poolObject.rewardAVault,
rewardBVault: poolObject.rewardBVault,
poolSigner,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
}
}
module.exports = {
claimForUsers,
User
};