-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathpox-4-delegate-stacking.test.ts
489 lines (442 loc) · 18.3 KB
/
pox-4-delegate-stacking.test.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
import { CoreRpcPoxInfo } from '../../src/core-rpc/client';
import { testnetKeys } from '../../src/api/routes/debug';
import {
Account,
accountFromKey,
fetchGet,
readOnlyFnCall,
standByForNextPoxCycle,
standByForPoxCycle,
standByForTxSuccess,
standByUntilBurnBlock,
testEnv,
} from '../utils/test-helpers';
import { stxToMicroStx } from '../../src/helpers';
import {
AnchorMode,
StacksPrivateKey,
bufferCV,
makeContractCall,
makeRandomPrivKey,
makeSTXTokenTransfer,
noneCV,
someCV,
standardPrincipalCV,
uintCV,
} from '@stacks/transactions';
import { ClarityValueTuple, ClarityValueUInt } from 'stacks-encoding-native-js';
import * as assert from 'assert';
import { StackingClient } from '@stacks/stacking';
import { getPublicKeyFromPrivate } from '@stacks/encryption';
import { hexToBytes } from '@stacks/common';
import { AddressStxBalance } from '../../src/api/schemas/entities/addresses';
describe('PoX-4 - Delegate Stacking operations', () => {
const seedKey = testnetKeys[4].secretKey;
const delegatorKey = '72e8e3725324514c38c2931ed337ab9ab8d8abaae83ed2275456790194b1fd3101';
const delegateeKey = '0d174cf0be276cedcf21727611ef2504aed093d8163f65985c07760fda12a7ea01';
const stxToDelegateIncrease = 2000n;
let seedAccount: Account;
let delegatorAccount: Account;
let delegateeAccount: Account;
let poxInfo: CoreRpcPoxInfo;
let contractAddress: string;
let contractName: string;
let stackingClient: StackingClient;
let signerPrivKey: StacksPrivateKey;
let signerPubKey: string;
beforeAll(() => {
seedAccount = accountFromKey(seedKey);
delegatorAccount = accountFromKey(delegatorKey);
delegateeAccount = accountFromKey(delegateeKey);
stackingClient = new StackingClient(delegatorAccount.stxAddr, testEnv.stacksNetwork);
signerPrivKey = makeRandomPrivKey();
signerPubKey = getPublicKeyFromPrivate(signerPrivKey.data);
});
test('Import testing accounts to bitcoind', async () => {
// register delegatee account to bitcoind wallet
await testEnv.bitcoinRpcClient.importaddress({
address: delegateeAccount.btcAddr,
label: delegateeAccount.btcAddr,
rescan: false,
});
});
test('Seed delegate accounts', async () => {
poxInfo = await testEnv.client.getPox();
// transfer 10 STX (for tx fees) from seed to delegator account
const gasAmount = stxToMicroStx(100);
const stxXfer1 = await makeSTXTokenTransfer({
senderKey: seedAccount.secretKey,
recipient: delegatorAccount.stxAddr,
amount: gasAmount,
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: 200,
});
const { txId: stxXferId1 } = await testEnv.client.sendTransaction(
Buffer.from(stxXfer1.serialize())
);
// transfer pox "min_amount_ustx" from seed to delegatee account
const stackingAmount = BigInt(Math.round(Number(poxInfo.min_amount_ustx) * 1.1).toString());
const stxXfer2 = await makeSTXTokenTransfer({
senderKey: seedAccount.secretKey,
recipient: delegateeAccount.stxAddr,
amount: stackingAmount,
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: 200,
nonce: stxXfer1.auth.spendingCondition.nonce + 1n,
});
const { txId: stxXferId2 } = await testEnv.client.sendTransaction(
Buffer.from(stxXfer2.serialize())
);
const stxXferTx1 = await standByForTxSuccess(stxXferId1);
expect(stxXferTx1.token_transfer_recipient_address).toBe(delegatorAccount.stxAddr);
const stxXferTx2 = await standByForTxSuccess(stxXferId2);
expect(stxXferTx2.token_transfer_recipient_address).toBe(delegateeAccount.stxAddr);
// ensure delegator account balance is correct
const delegatorBalance = await testEnv.client.getAccountBalance(delegatorAccount.stxAddr);
expect(delegatorBalance.toString()).toBe(gasAmount.toString());
// ensure delegatee account balance is correct
const delegateeBalance = await testEnv.client.getAccountBalance(delegateeAccount.stxAddr);
expect(delegateeBalance.toString()).toBe(stackingAmount.toString());
});
test('Get pox-info', async () => {
// wait until the start of the next cycle so we have enough blocks within the cycle to perform the various txs
// poxInfo = await standByForPoxCycle();
poxInfo = await standByForNextPoxCycle();
[contractAddress, contractName] = poxInfo.contract_id.split('.');
expect(contractName).toBe('pox-4');
});
test('Perform delegate-stx operation', async () => {
const txFee = 10000n;
const balanceInfo = await testEnv.client.getAccount(delegateeAccount.stxAddr);
const balanceTotal = BigInt(balanceInfo.balance);
expect(balanceTotal).toBeGreaterThan(txFee);
const balanceLocked = BigInt(balanceInfo.locked);
expect(balanceLocked).toBe(0n);
const delegateAmount = balanceTotal - txFee * 2n;
const delegateStxTx = await makeContractCall({
senderKey: delegateeAccount.secretKey,
contractAddress,
contractName,
functionName: 'delegate-stx',
functionArgs: [
uintCV(delegateAmount),
standardPrincipalCV(delegatorAccount.stxAddr), // delegate-to
noneCV(), // untilBurnBlockHeight
someCV(delegateeAccount.poxAddrClar), // pox-addr
],
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: txFee,
validateWithAbi: false,
});
const { txId: delegateStxTxId } = await testEnv.client.sendTransaction(
Buffer.from(delegateStxTx.serialize())
);
const delegateStxDbTx = await standByForTxSuccess(delegateStxTxId);
// validate delegate-stx pox2 event for this tx
const res: any = await fetchGet(`/extended/v1/pox4_events/tx/${delegateStxDbTx.tx_id}`);
expect(res).toBeDefined();
expect(res.results).toHaveLength(1);
expect(res.results[0]).toEqual(
expect.objectContaining({
name: 'delegate-stx',
pox_addr: delegateeAccount.btcTestnetAddr,
stacker: delegateeAccount.stxAddr,
})
);
expect(res.results[0].data).toEqual(
expect.objectContaining({
amount_ustx: delegateAmount.toString(),
delegate_to: delegatorAccount.stxAddr,
})
);
// validate pool delegations
const stackersRes: any = await fetchGet(
`/extended/v1/pox4/${delegatorAccount.stxAddr}/delegations`
);
expect(stackersRes).toBeDefined();
expect(stackersRes.total).toBe(1);
expect(stackersRes.results).toHaveLength(1);
expect(stackersRes.results[0]).toEqual({
amount_ustx: delegateAmount.toString(),
pox_addr: delegateeAccount.btcTestnetAddr,
stacker: delegateeAccount.stxAddr,
tx_id: delegateStxDbTx.tx_id,
block_height: delegateStxDbTx.block_height,
});
// validate pool delegations respects `after_block` limitter
const stackersRes2: any = await fetchGet(
`/extended/v1/pox4/${delegatorAccount.stxAddr}/delegations?after_block=${delegateStxDbTx.block_height}`
);
expect(stackersRes2).toBeDefined();
expect(stackersRes2.total).toBe(0);
expect(stackersRes2.results).toHaveLength(0);
// check delegatee locked amount is still zero
const balanceInfo2 = await testEnv.client.getAccount(delegateeAccount.stxAddr);
expect(BigInt(balanceInfo2.locked)).toBe(0n);
});
test('Perform delegate-stack-stx operation', async () => {
// get amount delegated
await standByForPoxCycle();
const getDelegationInfo1 = await readOnlyFnCall<
ClarityValueTuple<{ 'amount-ustx': ClarityValueUInt }>
>(
[contractAddress, contractName],
'get-delegation-info',
[standardPrincipalCV(delegateeAccount.stxAddr)],
delegateeAccount.stxAddr
);
const amountDelegated = BigInt(getDelegationInfo1.data['amount-ustx'].value);
expect(amountDelegated).toBeGreaterThan(0n);
const amountToDelegateInitial = amountDelegated - stxToDelegateIncrease;
const poxInfo2 = await testEnv.client.getPox();
const startBurnHt = poxInfo2.current_burnchain_block_height as number;
const txFee = 10000n;
const delegateStackStxTx = await makeContractCall({
senderKey: delegatorAccount.secretKey,
contractAddress,
contractName,
functionName: 'delegate-stack-stx',
functionArgs: [
standardPrincipalCV(delegateeAccount.stxAddr), // stacker
uintCV(amountToDelegateInitial), // amount-ustx
delegateeAccount.poxAddrClar, // pox-addr
uintCV(startBurnHt), // start-burn-ht
uintCV(1), // lock-period,
],
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: txFee,
validateWithAbi: false,
});
const { txId: delegateStackStxTxId } = await testEnv.client.sendTransaction(
Buffer.from(delegateStackStxTx.serialize())
);
const delegateStackStxDbTx = await standByForTxSuccess(delegateStackStxTxId);
// validate stacks-node balance
const coreBalanceInfo = await testEnv.client.getAccount(delegateeAccount.stxAddr);
expect(BigInt(coreBalanceInfo.locked)).toBe(amountToDelegateInitial);
expect(coreBalanceInfo.unlock_height).toBeGreaterThan(0);
// validate delegate-stack-stx pox2 event for this tx
const res: any = await fetchGet(`/extended/v1/pox4_events/tx/${delegateStackStxTxId}`);
expect(res).toBeDefined();
expect(res.results).toHaveLength(1);
expect(res.results[0]).toEqual(
expect.objectContaining({
name: 'delegate-stack-stx',
pox_addr: delegateeAccount.btcTestnetAddr,
stacker: delegateeAccount.stxAddr,
balance: BigInt(coreBalanceInfo.balance).toString(),
locked: amountToDelegateInitial.toString(),
burnchain_unlock_height: coreBalanceInfo.unlock_height.toString(),
})
);
expect(res.results[0].data).toEqual(
expect.objectContaining({
lock_period: '1',
lock_amount: amountToDelegateInitial.toString(),
})
);
// validate API balance state
const apiBalance = await fetchGet<AddressStxBalance>(
`/extended/v1/address/${delegateeAccount.stxAddr}/stx`
);
expect(BigInt(apiBalance.locked)).toBe(BigInt(amountToDelegateInitial));
expect(apiBalance.burnchain_unlock_height).toBe(coreBalanceInfo.unlock_height);
});
test('Perform delegate-stack-increase', async () => {
const coreBalanceInfoPreIncrease = await testEnv.client.getAccount(delegateeAccount.stxAddr);
const txFee = 10000n;
const delegateStackIncreaseTx = await makeContractCall({
senderKey: delegatorAccount.secretKey,
contractAddress,
contractName,
functionName: 'delegate-stack-increase',
functionArgs: [
standardPrincipalCV(delegateeAccount.stxAddr), // stacker
delegateeAccount.poxAddrClar, // pox-addr
uintCV(stxToDelegateIncrease), // increase-by
],
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: txFee,
validateWithAbi: false,
});
const { txId: delegateStackIncreaseTxId } = await testEnv.client.sendTransaction(
Buffer.from(delegateStackIncreaseTx.serialize())
);
const delegateStackIncreaseDbTx = await standByForTxSuccess(delegateStackIncreaseTxId);
// validate stacks-node balance
const coreBalanceInfo = await testEnv.client.getAccount(delegateeAccount.stxAddr);
expect(BigInt(coreBalanceInfo.locked)).toBe(
BigInt(coreBalanceInfoPreIncrease.locked) + stxToDelegateIncrease
);
expect(BigInt(coreBalanceInfo.balance)).toBe(
BigInt(coreBalanceInfoPreIncrease.balance) - stxToDelegateIncrease
);
expect(coreBalanceInfo.unlock_height).toBeGreaterThan(0);
// validate delegate-stack-stx pox2 event for this tx
const res: any = await fetchGet(
`/extended/v1/pox4_events/tx/${delegateStackIncreaseDbTx.tx_id}`
);
expect(res).toBeDefined();
expect(res.results).toHaveLength(1);
expect(res.results[0]).toEqual(
expect.objectContaining({
name: 'delegate-stack-increase',
pox_addr: delegateeAccount.btcTestnetAddr,
stacker: delegateeAccount.stxAddr,
balance: BigInt(coreBalanceInfo.balance).toString(),
locked: BigInt(coreBalanceInfo.locked).toString(),
burnchain_unlock_height: coreBalanceInfo.unlock_height.toString(),
})
);
expect(res.results[0].data).toEqual(
expect.objectContaining({
delegator: delegatorAccount.stxAddr,
increase_by: stxToDelegateIncrease.toString(),
total_locked: BigInt(coreBalanceInfo.locked).toString(),
})
);
// validate API endpoint balance state for account
const apiBalance = await fetchGet<AddressStxBalance>(
`/extended/v1/address/${delegateeAccount.stxAddr}/stx`
);
expect(BigInt(apiBalance.locked)).toBe(BigInt(BigInt(coreBalanceInfo.locked)));
expect(apiBalance.burnchain_unlock_height).toBe(coreBalanceInfo.unlock_height);
});
test('Perform delegate-stack-extend', async () => {
const coreBalanceInfoPreIncrease = await testEnv.client.getAccount(delegateeAccount.stxAddr);
const txFee = 10000n;
const extendCount = 1n;
const delegateStackExtendTx = await makeContractCall({
senderKey: delegatorAccount.secretKey,
contractAddress,
contractName,
functionName: 'delegate-stack-extend',
functionArgs: [
standardPrincipalCV(delegateeAccount.stxAddr), // stacker
delegateeAccount.poxAddrClar, // pox-addr
uintCV(extendCount), // extend-count
],
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: txFee,
validateWithAbi: false,
});
const { txId: delegateStackExtendTxId } = await testEnv.client.sendTransaction(
Buffer.from(delegateStackExtendTx.serialize())
);
const delegateStackExtendDbTx = await standByForTxSuccess(delegateStackExtendTxId);
// validate stacks-node balance
const coreBalanceInfo = await testEnv.client.getAccount(delegateeAccount.stxAddr);
expect(BigInt(coreBalanceInfo.locked)).toBeGreaterThan(0n);
expect(BigInt(coreBalanceInfo.balance)).toBeGreaterThan(0n);
expect(coreBalanceInfo.unlock_height).toBeGreaterThan(coreBalanceInfoPreIncrease.unlock_height);
// validate delegate-stack-extend pox2 event for this tx
const res: any = await fetchGet(`/extended/v1/pox4_events/tx/${delegateStackExtendTxId}`);
expect(res).toBeDefined();
expect(res.results).toHaveLength(1);
expect(res.results[0]).toEqual(
expect.objectContaining({
name: 'delegate-stack-extend',
pox_addr: delegateeAccount.btcTestnetAddr,
stacker: delegateeAccount.stxAddr,
balance: BigInt(coreBalanceInfo.balance).toString(),
locked: BigInt(coreBalanceInfo.locked).toString(),
burnchain_unlock_height: coreBalanceInfo.unlock_height.toString(),
})
);
expect(res.results[0].data).toEqual(
expect.objectContaining({
delegator: delegatorAccount.stxAddr,
extend_count: extendCount.toString(),
unlock_burn_height: coreBalanceInfo.unlock_height.toString(),
})
);
// validate API endpoint balance state for account
const apiBalance = await fetchGet<AddressStxBalance>(
`/extended/v1/address/${delegateeAccount.stxAddr}/stx`
);
expect(BigInt(apiBalance.locked)).toBe(BigInt(BigInt(coreBalanceInfo.locked)));
expect(apiBalance.burnchain_unlock_height).toBe(coreBalanceInfo.unlock_height);
});
test('Perform stack-aggregation-commit - delegator commit to stacking operation', async () => {
await standByForPoxCycle();
const poxInfo2 = await testEnv.client.getPox();
const rewardCycle = BigInt(poxInfo2.next_cycle.id);
const coreBalanceInfo = await testEnv.client.getAccount(delegateeAccount.stxAddr);
const signerSig = hexToBytes(
stackingClient.signPoxSignature({
topic: 'agg-commit',
poxAddress: delegateeAccount.btcAddr,
rewardCycle: Number(rewardCycle),
period: 1,
signerPrivateKey: signerPrivKey,
maxAmount: coreBalanceInfo.locked,
authId: 0,
})
);
const stackAggrCommitTx = await makeContractCall({
senderKey: delegatorAccount.secretKey,
contractAddress,
contractName,
functionName: 'stack-aggregation-commit',
functionArgs: [
delegateeAccount.poxAddrClar, // pox-addr
uintCV(rewardCycle), // reward-cycle
someCV(bufferCV(signerSig)), // signer-sig
bufferCV(hexToBytes(signerPubKey)), // signer-key
uintCV(coreBalanceInfo.locked.toString()), // max-amount
uintCV(0), // auth-id
],
network: testEnv.stacksNetwork,
anchorMode: AnchorMode.OnChainOnly,
fee: 10000,
validateWithAbi: false,
});
const { txId: stackAggrCommitTxId } = await testEnv.client.sendTransaction(
Buffer.from(stackAggrCommitTx.serialize())
);
const stackAggrCommmitDbTx = await standByForTxSuccess(stackAggrCommitTxId);
// validate stack-aggregation-commit pox2 event for this tx
const res: any = await fetchGet(`/extended/v1/pox4_events/tx/${stackAggrCommitTxId}`);
expect(res).toBeDefined();
expect(res.results).toHaveLength(1);
expect(res.results[0]).toEqual(
expect.objectContaining({
name: 'stack-aggregation-commit',
pox_addr: delegateeAccount.btcTestnetAddr,
stacker: delegatorAccount.stxAddr,
})
);
});
test('Wait for current two pox cycles to complete', async () => {
await standByForPoxCycle();
await standByForPoxCycle();
});
test('Validate account balances are unlocked', async () => {
// validate stacks-node balance
const coreBalanceInfo = await testEnv.client.getAccount(delegateeAccount.stxAddr);
expect(BigInt(coreBalanceInfo.locked)).toBe(0n);
expect(coreBalanceInfo.unlock_height).toBe(0);
// validate API endpoint balance state for account
const apiBalance = await fetchGet<AddressStxBalance>(
`/extended/v1/address/${delegateeAccount.stxAddr}/stx`
);
expect(BigInt(apiBalance.locked)).toBe(BigInt(BigInt(coreBalanceInfo.locked)));
expect(apiBalance.burnchain_unlock_height).toBe(coreBalanceInfo.unlock_height);
});
test('BTC stacking reward received', async () => {
const curBlock = await testEnv.db.getCurrentBlock();
assert(curBlock.found);
await standByUntilBurnBlock(curBlock.result.burn_block_height + 1);
const received: number = await testEnv.bitcoinRpcClient.getreceivedbyaddress({
address: delegateeAccount.btcAddr,
minconf: 0,
});
expect(received).toBeGreaterThan(0);
});
});