-
Notifications
You must be signed in to change notification settings - Fork 7
/
staking.pool.e2e.ts
247 lines (219 loc) · 9.46 KB
/
staking.pool.e2e.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
import { IRoleDefinition } from "@energyweb/iam-contracts";
import { Methods, Chain } from "@ew-did-registry/did";
import { KeyTags } from "@ew-did-registry/did-resolver-interface";
import { BigNumber, providers, utils, Wallet } from "ethers";
import {
DomainsService,
initWithPrivateKeySigner,
MessagingService,
ProviderType,
RegistrationTypes,
SignerService,
StakeStatus,
StakingPool,
StakingService,
} from "../src";
import { calculateReward, defaultPrincipalThreshold, setupStakingPoolFactory } from "./utils/staking";
import { replenish, root, rpcUrl, setupENS } from "./utils/setup_contracts";
const { parseEther } = utils;
const defaultMinStakingPeriod = 1;
const patronRewardPortion = 1000;
const orgName = "orgname";
const orgDomain = `${orgName}.${root}`;
const patronRole = "patronrole";
const provider = new providers.JsonRpcProvider(rpcUrl);
const rootOwner = Wallet.createRandom().connect(provider);
const orgOwner = Wallet.createRandom().connect(provider);
const orgOwnerDid = `did:${Methods.Erc1056}:${Chain.VOLTA}:${orgOwner.address}`;
const patron = Wallet.createRandom().connect(provider);
const patronDID = `did:${Methods.Erc1056}:${Chain.VOLTA}:${patron.address}`;
MessagingService.create = (signerService: SignerService) => Promise.resolve(new MessagingService(signerService));
const mockPublish = jest.fn();
jest.mock("../src/modules/messaging/messaging.service", () => {
return {
MessagingService: jest.fn().mockImplementation(() => {
return { publish: mockPublish };
}),
};
});
const mockGetRoleDefinition = jest.fn();
const mockGetDidDocument = jest.fn().mockImplementation(({ did }: { did: string }) => {
return { publicKey: [{ id: `did:${Methods.Erc1056}:${Chain.VOLTA}:${did}-${KeyTags.OWNER}` }] };
});
const mockGetApplicationsByOrgNamespace = jest.fn();
const mockRequestClaim = jest.fn();
jest.mock("../src/modules/cacheClient/cacheClient.service", () => {
return {
CacheClient: jest.fn().mockImplementation(() => {
return {
getRoleDefinition: mockGetRoleDefinition,
getDidDocument: mockGetDidDocument,
getApplicationsByOrganization: mockGetApplicationsByOrgNamespace,
init: jest.fn(),
login: jest.fn(),
requestClaim: mockRequestClaim,
issueClaim: jest.fn(),
};
}),
};
});
describe("StakingPool tests", () => {
let stakingService: StakingService;
let domainsService: DomainsService;
let signerService: SignerService;
let pool: StakingPool;
beforeAll(async () => {
await replenish(orgOwner.address);
await replenish(patron.address);
await replenish(rootOwner.address);
await setupENS(rootOwner.address);
await setupStakingPoolFactory();
let connectToCacheServer;
({ connectToCacheServer, signerService } = await initWithPrivateKeySigner(rootOwner.privateKey, rpcUrl));
let connectToDidRegistry;
({ domainsService, stakingService, connectToDidRegistry } = await connectToCacheServer());
const { claimsService } = await connectToDidRegistry();
const data: IRoleDefinition = {
fields: [],
issuerFields: [],
issuer: {
issuerType: "DID",
did: [orgOwnerDid],
},
metadata: [],
roleName: patronRole,
roleType: "test",
version: 1,
enrolmentPreconditions: [],
};
await domainsService.createRole({
roleName: patronRole,
namespace: root,
data,
});
await domainsService.createOrganization({
orgName,
namespace: root,
data: { orgName },
returnSteps: false,
});
mockGetApplicationsByOrgNamespace.mockReturnValueOnce([]);
await domainsService.changeOrgOwnership({
namespace: `${orgName}.${root}`,
newOwner: orgOwner.address,
});
const registrationTypes = [RegistrationTypes.OnChain];
await signerService.connect(patron, ProviderType.PrivateKey);
mockGetRoleDefinition.mockReturnValueOnce(data);
await claimsService.createClaimRequest({
claim: { claimType: `${patronRole}.${root}`, claimTypeVersion: 1, fields: [] },
registrationTypes,
});
const [, message] = mockRequestClaim.mock.calls.pop();
const { id, subjectAgreement, token } = message;
await signerService.connect(orgOwner, ProviderType.PrivateKey);
mockGetRoleDefinition.mockReturnValueOnce(data);
await claimsService.issueClaimRequest({
id,
registrationTypes,
requester: patronDID,
subjectAgreement,
token,
});
});
beforeEach(async () => {
jest.clearAllMocks();
await setupStakingPoolFactory();
await stakingService.init();
await launchPool();
await signerService.connect(patron, ProviderType.PrivateKey);
await replenish(patron.address);
});
async function launchPool(
minStakingPeriod = defaultMinStakingPeriod,
principalThreshold = defaultPrincipalThreshold,
) {
await replenish(orgOwner.address, principalThreshold);
await signerService.connect(orgOwner, ProviderType.PrivateKey);
await stakingService.launchPool({
org: orgDomain,
minStakingPeriod,
patronRewardPortion,
patronRoles: [`${patronRole}.${root}`],
principal: principalThreshold,
});
pool = (await stakingService.getPool(orgDomain)) as StakingPool;
}
it("patron should be able to stake", async () => {
const amount = parseEther("0.1");
await pool.putStake(amount);
return expect(pool.getStake()).resolves.toMatchObject({ status: StakeStatus.STAKING });
});
it("should not be able to stake without having patron role", async () => {
const nonPatron = Wallet.createRandom().connect(provider);
await replenish(await nonPatron.getAddress());
await signerService.connect(nonPatron, ProviderType.PrivateKey);
return expect(pool.putStake(parseEther("0.1"))).rejects.toThrow(
"StakingPool: patron is not registered with patron role",
);
});
it("should reject when stake amount isn't provided", async () => {
return expect(pool.putStake(parseEther("0"))).rejects.toThrow("StakingPool: stake amount is not provided");
});
it("should be able to stake whole balance", async () => {
const stake = await signerService.balance();
await pool.putStake(stake);
return expect(pool.getStake()).resolves.toMatchObject({ status: StakeStatus.STAKING });
});
it("stake should not be replenished", async () => {
await pool.putStake(parseEther("0.1"));
return expect(pool.putStake(parseEther("0.1"))).rejects.toThrow(
"StakingPool: Replenishment of the stake is not allowed",
);
});
it("staker should be able to request withdraw", async () => {
await pool.putStake(parseEther("0.1"));
const requestDelay = await pool.requestWithdrawDelay();
await new Promise((resolve) => setTimeout(resolve, 1000 * requestDelay));
await pool.requestWithdraw();
return expect(pool.getStake()).resolves.toMatchObject({ status: StakeStatus.WITHDRAWING });
});
it("can't request withdraw when no stake", async () => {
return expect(pool.requestWithdraw()).rejects.toThrow("StakingPool: No stake to withdraw");
});
it("can't request withdraw until minimum staking period is last", async () => {
await setupStakingPoolFactory();
await launchPool(10);
await signerService.connect(patron, ProviderType.PrivateKey);
await pool.putStake(parseEther("0.1"));
return expect(pool.requestWithdraw()).rejects.toThrow("StakingPool: Minimum staking period is not expired yet");
});
it("withdraw can't be requested twice", async () => {
await pool.putStake(parseEther("0.1"));
const requestDelay = await pool.requestWithdrawDelay();
await new Promise((resolve) => setTimeout(resolve, 1000 * requestDelay));
await pool.requestWithdraw();
return expect(pool.requestWithdraw()).rejects.toThrow("StakingPool: No stake to withdraw");
});
it("stake can be withdrawn", async () => {
const stake = parseEther("0.1");
await pool.putStake(stake);
const depositStart = (await pool.getStake()).depositStart;
const requestDelay = await pool.requestWithdrawDelay();
await new Promise((resolve) => setTimeout(resolve, 1000 * requestDelay));
await pool.requestWithdraw();
const depositEnd = (await pool.getStake()).depositEnd;
const expectedReward = calculateReward(
stake,
depositEnd.sub(depositStart),
BigNumber.from(patronRewardPortion),
);
expect(await pool.checkReward()).toEqual(expectedReward);
const withdrawalDelay = await pool.withdrawalDelay();
await new Promise((resolve) => setTimeout(resolve, 1000 * withdrawalDelay));
const balanceBeforeWithdraw = await patron.getBalance();
await pool.withdraw();
const balanceAfterWithdraw = await patron.getBalance();
expect(balanceAfterWithdraw.eq(balanceBeforeWithdraw.add(stake).add(expectedReward)));
});
});