-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
262 lines (222 loc) · 7.71 KB
/
index.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
import { setupContext } from "@acala-network/chopsticks-utils";
import { overrideStorage } from "@acala-network/chopsticks/utils/override";
import { ApiPromise, WsProvider } from "@polkadot/api";
import { hexToBigInt, u8aToHex } from "@polkadot/util";
const START_BLOCK = 6216237; // runtime upgrade with the issue
const END_BLOCK = 6285334; // runtime upgrade with the fix
// use a healthy one
const ENDPOINT = "wss://rpc.astar.network";
const replacer = (_k: string, v: any) =>
typeof v === "bigint" ? v.toString() : v;
type Reward = { reward: bigint; tierId: number; beneficiary: string };
async function main() {
const api = await ApiPromise.create({
provider: new WsProvider(ENDPOINT),
});
const blockHash = async (number: number) =>
api.rpc.chain.getBlockHash(number);
const ensureHasEvent = (events: any) => {
for (const event of events) {
if (
event.event.section === "dappStaking" &&
event.event.method === "NewEra"
) {
return;
}
}
throw new Error("Missing dappStaking::NewEra event");
};
let apiAt = await api.at(await blockHash(START_BLOCK));
let protocolState = await apiAt.query.dappStaking.activeProtocolState<any>();
// map of era and block number
let blocks: Map<number, number> = new Map();
let actualTiers: Map<number, Map<number, Reward>> = new Map();
// iterate eras affected by the bug and query data
do {
const blockNo = protocolState.nextEraStart.toNumber();
const era = protocolState.era.toNumber();
blocks.set(era, blockNo);
console.log(`Query ${blockNo} for era: ${era}`);
// move to next era bump when tier is calculated
apiAt = await api.at(await blockHash(blockNo));
// ensure era bump event is emitted
ensureHasEvent((await apiAt.query.system.events()).toHuman());
// extract new calculated reward
{
const { dapps, rewards } = (
await apiAt.query.dappStaking.dAppTiers<any>(era)
).toJSON();
const integratedDApps = (
await apiAt.query.dappStaking.integratedDApps.entries()
).map(([_, value]) => value.toJSON() as any);
const dappsReward = new Map();
for (const [dappId, tierId] of Object.entries(dapps)) {
const reward = hexToBigInt(rewards[tierId as number]);
const dapp = integratedDApps.find((x) => x.id === Number(dappId));
if (!dapp) throw new Error("dapp should exists");
dappsReward.set(Number(dappId), {
reward,
tierId,
beneficiary: dapp.rewardBeneficiary || dapp.owner,
});
}
actualTiers.set(era, dappsReward);
}
protocolState = await apiAt.query.dappStaking.activeProtocolState<any>();
} while (protocolState.nextEraStart.toNumber() < END_BLOCK);
// block which contains runtime with the fix
const runtime = (
await (await api.at(await blockHash(END_BLOCK))).query.substrate.code()
).toHex();
await api.disconnect();
/************************/
/** recalculate section using chopsticks */
/************************/
let tierConfig: string | undefined;
// replay blocks with new runtime
const expectedTiers: Map<number, Map<number, Reward>> = new Map();
for (const [era, block] of blocks) {
console.log(`Replay ${block} for era: ${era}`);
// setup chopsticks one block prior to era bump/reward calculation
const ctx = await setupContext({
endpoint: ENDPOINT,
blockNumber: block - 1,
db: "cache.sqlite",
timeout: 1_000_000,
});
// override runtime with the fix
ctx.chain.head.setWasm(runtime);
if (tierConfig) {
// override tier config from previous adjusment
await overrideStorage(ctx.chain, { dappStaking: { tierConfig } });
}
// build the new block to calculate reward
await ctx.dev.newBlock();
// ensure era bump event is emitted
ensureHasEvent((await ctx.api.query.system.events()).toHuman());
// read TierConfig for next era calculation
tierConfig = (await ctx.api.query.dappStaking.tierConfig()).toHex();
// extract new calculated reward
{
const { dapps, rewards } = (
await ctx.api.query.dappStaking.dAppTiers<any>(era)
).toJSON();
const integratedDApps = (
await ctx.api.query.dappStaking.integratedDApps.entries()
).map(([_, value]) => value.toJSON() as any);
const dappsReward = new Map();
for (const [dappId, tierId] of Object.entries(dapps)) {
const reward = hexToBigInt(rewards[tierId as number]);
const dapp = integratedDApps.find((x) => x.id === Number(dappId));
if (!dapp) throw new Error("dapp should exists");
dappsReward.set(Number(dappId), {
reward,
tierId,
beneficiary: dapp.rewardBeneficiary || dapp.owner,
});
}
expectedTiers.set(era, dappsReward);
}
await new Promise((r) => setTimeout(r, 1_000));
// teardown chopsticks
await ctx.teardown();
}
// merge results
let finalResults = [];
for (const [era, dapps] of expectedTiers) {
for (const [dapp_id, expected] of dapps) {
const actual = actualTiers.get(era)!.get(dapp_id)!;
const delta = expected.reward - actual.reward;
if (delta < 0) {
throw new Error("amount delta should not be negative");
}
finalResults.push({
era,
dapp_id,
beneficiary: expected.beneficiary,
expected_tier: expected.tierId,
actual_tier: actual.tierId,
expected_reward: expected.reward,
actual_reward: actual.reward,
delta,
});
}
}
await Bun.write(
"./raw-result.json",
JSON.stringify(finalResults, replacer, 2),
);
// extract result csv
{
let table = [
"era,dapp_id,beneficiary,expected_tier,actual_tier,expected_reward,actual_reward,delta",
];
for (
const {
era,
dapp_id,
beneficiary,
expected_tier,
actual_tier,
expected_reward,
actual_reward,
delta,
} of finalResults
) {
table.push(
[
era,
dapp_id,
beneficiary,
expected_tier,
actual_tier,
expected_reward,
actual_reward,
delta,
].join(","),
);
}
await Bun.write("./raw-result.csv", table.join("\n"));
}
const reimburse = finalResults
.filter(({ delta }) => delta !== 0n)
.reduce<Record<string, bigint>>((acc, x) => {
const amount = acc[x.beneficiary] || 0n;
acc[x.beneficiary] = amount + x.delta;
return acc;
}, {});
await Bun.write("./reimburse.json", JSON.stringify(reimburse, replacer, 2));
// write csv
{
let table = ["beneficiary,amount"];
for (const [beneficiary, amount] of Object.entries(reimburse)) {
table.push([beneficiary, amount].join(","));
}
await Bun.write("./reimburse.csv", table.join("\n"));
}
// prepare reimbursement sudo call
{
const api = await ApiPromise.create({
provider: new WsProvider(ENDPOINT),
});
// Can be verified here: https://astar.subscan.io/account/YQnbw3oWxBk2zTouRxQyxnD2dDCFsGrRGQRaCeDLy7KKMdJ
const dappStakingAccount = "YQnbw3oWxBk2zTouRxQyxnD2dDCFsGrRGQRaCeDLy7KKMdJ";
const transferCalls = Object.entries(reimburse).map(([beneficiary, amount]) =>
api.tx.balances.transferAllowDeath(beneficiary, amount)
);
const sudoCall = api.tx.sudo.sudoAs(dappStakingAccount, api.tx.utility.batch(transferCalls));
console.log("Hex encoded Sudo call for reimbursement:", sudoCall.method.toHex());
}
console.log(
"Total reimbursement amount",
Object.values(reimburse).reduce((acc, amount) => acc + amount, 0n) /
10n ** 18n,
"ASTR",
);
}
main()
.then(() => process.exit())
.catch((err) => {
console.error(err);
process.exit(1);
});