@gooddollar/goodprotocol 1.0.15 → 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/artifacts/contracts/DAOStackInterfaces.sol/Avatar.dbg.json +1 -1
  2. package/artifacts/contracts/DAOStackInterfaces.sol/Controller.dbg.json +1 -1
  3. package/artifacts/contracts/DAOStackInterfaces.sol/GlobalConstraintInterface.dbg.json +1 -1
  4. package/artifacts/contracts/DAOStackInterfaces.sol/IntVoteInterface.dbg.json +1 -1
  5. package/artifacts/contracts/DAOStackInterfaces.sol/ReputationInterface.dbg.json +1 -1
  6. package/artifacts/contracts/DAOStackInterfaces.sol/SchemeRegistrar.dbg.json +1 -1
  7. package/artifacts/contracts/Interfaces.sol/AggregatorV3Interface.dbg.json +1 -1
  8. package/artifacts/contracts/Interfaces.sol/ERC20.dbg.json +1 -1
  9. package/artifacts/contracts/Interfaces.sol/IAaveIncentivesController.dbg.json +1 -1
  10. package/artifacts/contracts/Interfaces.sol/IAdminWallet.dbg.json +1 -1
  11. package/artifacts/contracts/Interfaces.sol/IDonationStaking.dbg.json +1 -1
  12. package/artifacts/contracts/Interfaces.sol/IERC2917.dbg.json +1 -1
  13. package/artifacts/contracts/Interfaces.sol/IFirstClaimPool.dbg.json +1 -1
  14. package/artifacts/contracts/Interfaces.sol/IGoodDollar.dbg.json +1 -1
  15. package/artifacts/contracts/Interfaces.sol/IGoodStaking.dbg.json +1 -1
  16. package/artifacts/contracts/Interfaces.sol/IHasRouter.dbg.json +1 -1
  17. package/artifacts/contracts/Interfaces.sol/IIdentity.dbg.json +1 -1
  18. package/artifacts/contracts/Interfaces.sol/ILendingPool.dbg.json +1 -1
  19. package/artifacts/contracts/Interfaces.sol/INameService.dbg.json +1 -1
  20. package/artifacts/contracts/Interfaces.sol/IUBIScheme.dbg.json +1 -1
  21. package/artifacts/contracts/Interfaces.sol/ProxyAdmin.dbg.json +1 -1
  22. package/artifacts/contracts/Interfaces.sol/Reserve.dbg.json +1 -1
  23. package/artifacts/contracts/Interfaces.sol/Staking.dbg.json +1 -1
  24. package/artifacts/contracts/Interfaces.sol/Uniswap.dbg.json +1 -1
  25. package/artifacts/contracts/Interfaces.sol/UniswapFactory.dbg.json +1 -1
  26. package/artifacts/contracts/Interfaces.sol/UniswapPair.dbg.json +1 -1
  27. package/artifacts/contracts/Interfaces.sol/cERC20.dbg.json +1 -1
  28. package/artifacts/contracts/governance/ClaimersDistribution.sol/ClaimersDistribution.dbg.json +1 -1
  29. package/artifacts/contracts/governance/ClaimersDistribution.sol/ClaimersDistribution.json +2 -2
  30. package/artifacts/contracts/governance/CompoundVotingMachine.sol/CompoundVotingMachine.dbg.json +1 -1
  31. package/artifacts/contracts/governance/GReputation.sol/GReputation.dbg.json +1 -1
  32. package/artifacts/contracts/governance/GReputation.sol/GReputation.json +3 -10
  33. package/artifacts/contracts/governance/GovernanceStaking.sol/GovernanceStaking.dbg.json +1 -1
  34. package/artifacts/contracts/governance/GovernanceStaking.sol/GovernanceStaking.json +41 -3
  35. package/artifacts/contracts/governance/MultiBaseGovernanceShareField.sol/MultiBaseGovernanceShareField.dbg.json +1 -1
  36. package/artifacts/contracts/governance/Reputation.sol/Reputation.dbg.json +1 -1
  37. package/artifacts/contracts/governance/StakersDistribution.sol/StakersDistribution.dbg.json +1 -1
  38. package/artifacts/contracts/governance/StakersDistribution.sol/StakersDistribution.json +2 -2
  39. package/artifacts/contracts/mocks/AaveMock.sol/AaveMock.dbg.json +1 -1
  40. package/artifacts/contracts/mocks/DAIMock.sol/DAIMock.dbg.json +1 -1
  41. package/artifacts/contracts/mocks/DecimalsMock.sol/DecimalsMock.dbg.json +1 -1
  42. package/artifacts/contracts/mocks/GoodCompoundStakingTest.sol/GoodCompoundStakingTest.dbg.json +1 -1
  43. package/artifacts/contracts/mocks/GoodCompoundStakingTest.sol/GoodCompoundStakingTest.json +2 -2
  44. package/artifacts/contracts/mocks/GoodFundManagerTest.sol/GoodFundManagerTest.dbg.json +1 -1
  45. package/artifacts/contracts/mocks/IncentiveControllerMock.sol/IncentiveControllerMock.dbg.json +1 -1
  46. package/artifacts/contracts/mocks/LendingPoolMock.sol/LendingPoolMock.dbg.json +1 -1
  47. package/artifacts/contracts/mocks/OverMintTester.sol/OverMintTester.dbg.json +1 -1
  48. package/artifacts/contracts/mocks/OverMintTester.sol/OverMintTester.json +2 -2
  49. package/artifacts/contracts/mocks/OverMintTesterRegularStake.sol/OverMintTesterRegularStake.dbg.json +1 -1
  50. package/artifacts/contracts/mocks/OverMintTesterRegularStake.sol/OverMintTesterRegularStake.json +2 -2
  51. package/artifacts/contracts/mocks/SixteenDecimalsTokenMock.sol/SixteenDecimalsTokenMock.dbg.json +1 -1
  52. package/artifacts/contracts/mocks/SwapHelperTest.sol/SwapHelperTest.dbg.json +1 -1
  53. package/artifacts/contracts/mocks/TwentyDecimalsTokenMock.sol/TwentyDecimalsTokenMock.dbg.json +1 -1
  54. package/artifacts/contracts/mocks/UpgradableMocks.sol/UpgradableMock.dbg.json +1 -1
  55. package/artifacts/contracts/mocks/UpgradableMocks.sol/UpgradableMock2.dbg.json +1 -1
  56. package/artifacts/contracts/mocks/UsdcMock.sol/USDCMock.dbg.json +1 -1
  57. package/artifacts/contracts/mocks/cBATMock.sol/cBATMock.dbg.json +1 -1
  58. package/artifacts/contracts/mocks/cDAILowWorthMock.sol/cDAILowWorthMock.dbg.json +1 -1
  59. package/artifacts/contracts/mocks/cDAIMock.sol/cDAIMock.dbg.json +1 -1
  60. package/artifacts/contracts/mocks/cDAINonMintableMock.sol/cDAINonMintableMock.dbg.json +1 -1
  61. package/artifacts/contracts/mocks/cDecimalsMock.sol/cDecimalsMock.dbg.json +1 -1
  62. package/artifacts/contracts/mocks/cSDTMock.sol/cSDTMock.dbg.json +1 -1
  63. package/artifacts/contracts/mocks/cUSDCMock.sol/cUSDCMock.dbg.json +1 -1
  64. package/artifacts/contracts/reserve/ExchangeHelper.sol/ExchangeHelper.dbg.json +1 -1
  65. package/artifacts/contracts/reserve/GoodMarketMaker.sol/GoodMarketMaker.dbg.json +1 -1
  66. package/artifacts/contracts/reserve/GoodReserveCDai.sol/ContributionCalc.dbg.json +1 -1
  67. package/artifacts/contracts/reserve/GoodReserveCDai.sol/GoodReserveCDai.dbg.json +1 -1
  68. package/artifacts/contracts/staking/BaseShareField.sol/BaseShareField.dbg.json +1 -1
  69. package/artifacts/contracts/staking/BaseShareFieldV2.sol/BaseShareFieldV2.dbg.json +1 -1
  70. package/artifacts/contracts/staking/DonationsStaking.sol/DonationsStaking.dbg.json +1 -1
  71. package/artifacts/contracts/staking/DonationsStaking.sol/DonationsStaking.json +2 -2
  72. package/artifacts/contracts/staking/GoodFundManager.sol/GoodFundManager.dbg.json +1 -1
  73. package/artifacts/contracts/staking/SimpleStaking.sol/SimpleStaking.dbg.json +1 -1
  74. package/artifacts/contracts/staking/SimpleStakingV2.sol/SimpleStakingV2.dbg.json +1 -1
  75. package/artifacts/contracts/staking/UniswapV2SwapHelper.sol/UniswapV2SwapHelper.dbg.json +1 -1
  76. package/artifacts/contracts/staking/aave/AaveStakingFactory.sol/AaveStakingFactory.dbg.json +1 -1
  77. package/artifacts/contracts/staking/aave/AaveStakingFactory.sol/AaveStakingFactory.json +2 -2
  78. package/artifacts/contracts/staking/aave/GoodAaveStaking.sol/GoodAaveStaking.dbg.json +1 -1
  79. package/artifacts/contracts/staking/aave/GoodAaveStaking.sol/GoodAaveStaking.json +2 -2
  80. package/artifacts/contracts/staking/aave/GoodAaveStakingV2.sol/GoodAaveStakingV2.dbg.json +1 -1
  81. package/artifacts/contracts/staking/aave/GoodAaveStakingV2.sol/GoodAaveStakingV2.json +2 -2
  82. package/artifacts/contracts/staking/compound/CompoundStakingFactory.sol/CompoundStakingFactory.dbg.json +1 -1
  83. package/artifacts/contracts/staking/compound/CompoundStakingFactory.sol/CompoundStakingFactory.json +2 -2
  84. package/artifacts/contracts/staking/compound/GoodCompoundStaking.sol/GoodCompoundStaking.dbg.json +1 -1
  85. package/artifacts/contracts/staking/compound/GoodCompoundStaking.sol/GoodCompoundStaking.json +2 -2
  86. package/artifacts/contracts/staking/compound/GoodCompoundStakingV2.sol/GoodCompoundStakingV2.dbg.json +1 -1
  87. package/artifacts/contracts/staking/compound/GoodCompoundStakingV2.sol/GoodCompoundStakingV2.json +2 -2
  88. package/artifacts/contracts/ubi/UBIScheme.sol/UBIScheme.dbg.json +1 -1
  89. package/artifacts/contracts/ubi/UBIScheme.sol/UBIScheme.json +2 -2
  90. package/artifacts/contracts/unaudited-foundation/FuseFaucet.sol/FuseFaucet.dbg.json +1 -1
  91. package/artifacts/contracts/unaudited-foundation/InvitesV1.sol/InvitesV1.dbg.json +1 -1
  92. package/artifacts/contracts/utils/BancorFormula.sol/BancorFormula.dbg.json +1 -1
  93. package/artifacts/contracts/utils/BulkProof.sol/BulkProof.dbg.json +4 -0
  94. package/artifacts/contracts/utils/BulkProof.sol/BulkProof.json +41 -0
  95. package/artifacts/contracts/utils/DAOContract.sol/DAOContract.dbg.json +1 -1
  96. package/artifacts/contracts/utils/DAOUpgradeableContract.sol/DAOUpgradeableContract.dbg.json +1 -1
  97. package/artifacts/contracts/utils/DSMath.sol/DSMath.dbg.json +1 -1
  98. package/artifacts/contracts/utils/DataTypes.sol/DataTypes.dbg.json +1 -1
  99. package/artifacts/contracts/utils/NameService.sol/NameService.dbg.json +1 -1
  100. package/artifacts/contracts/utils/ProtocolUpgrade.sol/OldMarketMaker.dbg.json +1 -1
  101. package/artifacts/contracts/utils/ProtocolUpgrade.sol/ProtocolUpgrade.dbg.json +1 -1
  102. package/artifacts/contracts/utils/ProtocolUpgradeFuse.sol/ProtocolUpgradeFuse.dbg.json +1 -1
  103. package/artifacts/contracts/utils/ProtocolUpgradeFuseRecover.sol/ProtocolUpgradeFuseRecover.dbg.json +1 -1
  104. package/artifacts/contracts/utils/ProtocolUpgradeRecover.sol/ProtocolUpgradeRecover.dbg.json +1 -1
  105. package/artifacts/contracts/utils/ReputationTestHelper.sol/ReputationTestHelper.dbg.json +1 -1
  106. package/contracts/governance/GReputation.sol +10 -31
  107. package/contracts/governance/GovernanceStaking.sol +15 -2
  108. package/contracts/utils/BulkProof.sol +45 -0
  109. package/hardhat.config.ts +41 -1
  110. package/package.json +1 -1
  111. package/releases/deployment.json +1 -1
  112. package/scripts/bulkProof.ts +207 -0
  113. package/scripts/gdx/gdxAirdropCalculation.ts +223 -0
  114. package/scripts/governance/airdropCalculationRecover.ts +406 -0
  115. package/test/governance/GReputation.test.ts +16 -3
@@ -0,0 +1,207 @@
1
+ import fs from "fs";
2
+ import { chunk } from "lodash";
3
+ import { ethers, upgrades, network } from "hardhat";
4
+ import { networkNames } from "@openzeppelin/upgrades-core";
5
+ import GReputationABI from "../artifacts/contracts/governance/GReputation.sol/GReputation.json";
6
+ import BulkProofABI from "../artifacts/contracts/utils/BulkProof.sol/BulkProof.json";
7
+
8
+ import MerkleTree, {
9
+ checkProof,
10
+ checkProofOrdered
11
+ } from "merkle-tree-solidity";
12
+ import { BigNumber } from "ethers";
13
+
14
+ console.log({
15
+ networkNames,
16
+ network: network.name,
17
+ upgrade: process.env.UPGRADE
18
+ });
19
+ const { name: networkName } = network;
20
+ networkNames[1] = networkName;
21
+ networkNames[122] = networkName;
22
+ networkNames[3] = networkName;
23
+
24
+ export const bulkProof = async () => {
25
+ console.log("signer", await ethers.getSigners());
26
+ const fuseProvider = new ethers.providers.JsonRpcProvider(
27
+ "https://rpc.fuse.io"
28
+ );
29
+
30
+ const fuseGDProvider = new ethers.providers.JsonRpcProvider(
31
+ "https://gooddollar-rpc.fuse.io"
32
+ );
33
+
34
+ const goodFuse = new ethers.Contract(
35
+ "0x3A9299BE789ac3730e4E4c49d6d2Ad1b8BC34DFf",
36
+ GReputationABI.abi,
37
+ fuseGDProvider
38
+ );
39
+
40
+ const START_BLOCK_FUSE = 14149729;
41
+
42
+ const LAST_BLOCK = await goodFuse.provider.getBlockNumber();
43
+
44
+ const claimedLogs = await goodFuse.queryFilter(
45
+ goodFuse.filters.StateHashProof(),
46
+ START_BLOCK_FUSE,
47
+ LAST_BLOCK
48
+ );
49
+ console.log("found logs:", claimedLogs.length);
50
+ console.log(claimedLogs.filter(_ => !_.args?.user));
51
+
52
+ const addrs = claimedLogs.map(_ => _.args?.user);
53
+
54
+ const { treeData, merkleRoot } = JSON.parse(
55
+ fs.readFileSync("airdrop/airdrop.json").toString()
56
+ );
57
+
58
+ let entries = Object.entries(treeData);
59
+
60
+ let elements = entries.map((e: any) =>
61
+ Buffer.from(e[1].hash.slice(2), "hex")
62
+ );
63
+
64
+ console.log("creating merkletree...", elements.length);
65
+ const merkleTree = new MerkleTree(elements, true);
66
+
67
+ const calcMerkleRoot = merkleTree.getRoot().toString("hex");
68
+ console.log("merkleroots:", {
69
+ fromFile: merkleRoot,
70
+ calculated: calcMerkleRoot
71
+ });
72
+
73
+ const proofs = addrs => {
74
+ return addrs.map(addr => {
75
+ if (!addr) {
76
+ console.log("missing", addr);
77
+ return;
78
+ }
79
+ const addrData = treeData[addr] || treeData[addr.toLowerCase()];
80
+ const proofFor = Buffer.from(addrData.hash.slice(2), "hex");
81
+
82
+ const proof = merkleTree.getProof(proofFor);
83
+ const proofIndex =
84
+ entries.findIndex((_: any) => _[1].hash === addrData.hash) + 1;
85
+
86
+ // console.log(
87
+ // "checkProof:",
88
+ // checkProofOrdered(proof, merkleTree.getRoot(), proofFor, proofIndex)
89
+ // );
90
+
91
+ const hexProof = proof.map(_ => "0x" + _.toString("hex"));
92
+ // console.log({
93
+ // proofIndex,
94
+ // rep: BigNumber.from(addrData.rep).toString(),
95
+ // // hexProof,
96
+ // addr
97
+ // });
98
+
99
+ return {
100
+ index: proofIndex,
101
+ balance: BigNumber.from(addrData.rep).toString(),
102
+ proof: hexProof,
103
+ account: addr
104
+ };
105
+ });
106
+ };
107
+
108
+ const bulkProofContract = await ethers.getContractAt(
109
+ "BulkProof",
110
+ "0x8449bb7BDa431F76c21bcCDEce2794D8aD24D8a8"
111
+ );
112
+ for (let addrChunk of chunk(addrs, 50)) {
113
+ console.log("calling bulk proof");
114
+ const proofsChunk = proofs(addrChunk);
115
+ await (
116
+ await bulkProofContract.bulkProof(proofsChunk, { gasLimit: 10000000 })
117
+ ).wait();
118
+ }
119
+ };
120
+
121
+ export const bulkProofGDX = async () => {
122
+ const signers = await ethers.getSigners();
123
+ console.log("signer", await ethers.getSigners());
124
+ // const signer = signers[0].connect(new ethers.providers.InfuraProvider());
125
+ const reserve = await ethers.getContractAt(
126
+ "GoodReserveCDai",
127
+ "0xa150a825d425B36329D8294eeF8bD0fE68f8F6E0"
128
+ );
129
+
130
+ const { treeData, merkleRoot } = JSON.parse(
131
+ fs.readFileSync("airdrop/gdxAirdropRecovery.json").toString()
132
+ );
133
+
134
+ let entries = Object.entries(treeData);
135
+
136
+ let elements = entries.map((e: any) =>
137
+ Buffer.from(e[1].hash.slice(2), "hex")
138
+ );
139
+
140
+ let addrs = Object.keys(treeData);
141
+
142
+ console.log("creating merkletree...", elements.length, addrs);
143
+ const merkleTree = new MerkleTree(elements, false);
144
+
145
+ const calcMerkleRoot = merkleTree.getRoot().toString("hex");
146
+ console.log("merkleroots:", {
147
+ fromFile: merkleRoot,
148
+ calculated: calcMerkleRoot
149
+ });
150
+
151
+ const proofs = addrs => {
152
+ return addrs.map(addr => {
153
+ if (!addr) {
154
+ console.log("missing", addr);
155
+ return;
156
+ }
157
+ const addrData = treeData[addr] || treeData[addr.toLowerCase()];
158
+ const proofFor = Buffer.from(addrData.hash.slice(2), "hex");
159
+
160
+ const proof = merkleTree.getProof(proofFor);
161
+
162
+ // console.log(
163
+ // "checkProof:",
164
+ // checkProofOrdered(proof, merkleTree.getRoot(), proofFor, proofIndex)
165
+ // );
166
+
167
+ const hexProof = proof.map(_ => "0x" + _.toString("hex"));
168
+ // console.log({
169
+ // proofIndex,
170
+ // rep: BigNumber.from(addrData.rep).toString(),
171
+ // // hexProof,
172
+ // addr
173
+ // });
174
+
175
+ return {
176
+ balance: BigNumber.from(addrData.gdx).toString(),
177
+ proof: hexProof,
178
+ account: addr
179
+ };
180
+ });
181
+ };
182
+
183
+ const bulkProofContract = await ethers.getContractAt(
184
+ "BulkProof",
185
+ "0xDB8563287ecF1484228951804eC6bf241f884099"
186
+ );
187
+ for (let addrChunk of chunk(addrs, 60)) {
188
+ const proofsChunk = proofs(addrChunk);
189
+ console.log("calling bulk proof");
190
+ const tx = await bulkProofContract.callStatic.bulkProof(proofsChunk, {
191
+ gasLimit: 5000000,
192
+ maxPriorityFeePerGas: 1000000000,
193
+ maxFeePerGas: 40000000000
194
+ });
195
+ console.log(tx);
196
+ await (
197
+ await bulkProofContract.bulkProof(proofsChunk, {
198
+ gasLimit: 5000000,
199
+ maxPriorityFeePerGas: 1000000000,
200
+ maxFeePerGas: 40000000000
201
+ })
202
+ ).wait();
203
+ }
204
+ };
205
+
206
+ // bulkProof().catch(console.log);
207
+ bulkProofGDX().catch(console.log);
@@ -3,6 +3,7 @@ import fs from "fs";
3
3
  import MerkleTree from "merkle-tree-solidity";
4
4
  import stakingContracts from "@gooddollar/goodcontracts/stakingModel/releases/deployment.json";
5
5
  import { ethers as Ethers } from "hardhat";
6
+ import { BigNumber } from "ethereum-waffle/node_modules/ethers";
6
7
 
7
8
  type Tree = {
8
9
  [key: string]: {
@@ -21,6 +22,17 @@ const quantile = (sorted, q) => {
21
22
  return sum;
22
23
  };
23
24
 
25
+ const quantileBN = (sorted, q) => {
26
+ const pos = (sorted.length - 1) * q;
27
+ const base = Math.floor(pos);
28
+
29
+ let sum = BigNumber.from("0");
30
+ for (let i = 0; i < base; i++)
31
+ sum = BigNumber.from(sum).add(BigNumber.from(sorted[i]));
32
+
33
+ return sum.toString();
34
+ };
35
+
24
36
  let ETH_SNAPSHOT_BLOCK = 13320531; //first blocka after 12pm Sep-29-2021 12:00:20 PM +UTC
25
37
 
26
38
  export const airdrop = (ethers: typeof Ethers, ethSnapshotBlock) => {
@@ -198,3 +210,214 @@ export const airdrop = (ethers: typeof Ethers, ethSnapshotBlock) => {
198
210
 
199
211
  return { buildMerkleTree, collectAirdropData, getProof };
200
212
  };
213
+
214
+ export const airdropRecover = (ethers: typeof Ethers) => {
215
+
216
+ const ZERO = ethers.BigNumber.from("0");
217
+
218
+ const getHoldersInformation = async (newAddresses = {}, newIsContracts = {}) => {
219
+ const provider = new ethers.providers.InfuraProvider();
220
+
221
+ const eventsABI = [
222
+ "event TokenPurchased(address indexed caller,address indexed inputToken,uint256 inputAmount,uint256 actualReturn,address indexed receiverAddress)",
223
+ "event TokenSold(address indexed caller,address indexed outputToken,uint256 gdAmount,uint256 contributionAmount,uint256 actualReturn,address indexed receiverAddress)"
224
+ ];
225
+
226
+ let newReserve = await ethers.getContractAt(eventsABI, "0x6C35677206ae7FF1bf753877649cF57cC30D1c42");
227
+ let exchangeHelper = await ethers.getContractAt(eventsABI, "0x0a8c6bB832801454F6CC21761D0A293Caa003296");
228
+
229
+ exchangeHelper = exchangeHelper.connect(provider);
230
+ newReserve = newReserve.connect(provider);
231
+
232
+ const step = 100000;
233
+ const START_BLOCK = 13683748; // Reserve was created
234
+ const END_BLOCK = 14296271; // Following reserve created
235
+ const blocks = range(START_BLOCK, END_BLOCK, step);
236
+
237
+ const reserveTokenPurchasedFilter = newReserve.filters.TokenPurchased();
238
+ const reserveTokenSoldFilter = newReserve.filters.TokenSold();
239
+
240
+ const exchangeHelperTokenPurchasedFilter = exchangeHelper.filters.TokenPurchased();
241
+ const exchangeHelperTokenSoldFilter = exchangeHelper.filters.TokenSold();
242
+
243
+ const populateListOfAddressesAndBalances = async (contractInstance, purchaseFilter, soldFilter) => {
244
+ for (let blockChunk of chunk(blocks, 10)) {
245
+ // Get the filter (the second null could be omitted)
246
+ const processedChunks = blockChunk.map(async bc => {
247
+ // Query the filter (the latest could be omitted)
248
+ const purchaseEvents = await contractInstance
249
+ .queryFilter(purchaseFilter, bc, Math.min(bc + step - 1, END_BLOCK))
250
+ .catch(e => {
251
+ console.log("block transfer logs failed retrying...", bc);
252
+ return contractInstance.queryFilter(
253
+ purchaseFilter,
254
+ bc,
255
+ Math.min(bc + step - 1, END_BLOCK)
256
+ );
257
+ });
258
+
259
+ // console.log({purchaseEvents});
260
+
261
+ const soldEvents = await contractInstance
262
+ .queryFilter(soldFilter, bc, Math.min(bc + step - 1, END_BLOCK))
263
+ .catch(e => {
264
+ console.log("block swaphelper logs failed retrying...", bc);
265
+ return contractInstance.queryFilter(
266
+ soldFilter,
267
+ bc,
268
+ Math.min(bc + step - 1, END_BLOCK)
269
+ );
270
+ });
271
+
272
+ // console.log(
273
+ // "found transfer logs in block:",
274
+ // { bc },
275
+ // { purchaseEvents: purchaseEvents.length, soldEvents: soldEvents.length }
276
+ // );
277
+
278
+ const isContract = async (log, role) => {
279
+ const possibleCodeStateOfAddress = await contractInstance.provider.getCode(log.args[role])
280
+ .catch(e => "0x");
281
+ return possibleCodeStateOfAddress !== "0x";
282
+ };
283
+
284
+ // Print out all the values:
285
+ const purchasedEventsMapped = purchaseEvents.map(async log => {
286
+ let balance = newAddresses[log.args.receiverAddress] || ZERO;
287
+ // console.log({balance});
288
+ // console.log(`actualReturn: ${log.args.actualReturn.toString()}`);
289
+ newAddresses[log.args.receiverAddress] =
290
+ balance.add(log.args.actualReturn);
291
+ newIsContracts[log.args.receiverAddress] = await isContract(
292
+ log, "receiverAddress"
293
+ );
294
+ });
295
+ const soldEventsMapped = soldEvents.map(async log => {
296
+ let balance = newAddresses[log.args.caller] || ZERO;
297
+ newAddresses[log.args.caller] = balance.sub(log.args.gdAmount);
298
+ newIsContracts[log.args.caller] = await isContract(
299
+ log, "caller"
300
+ );
301
+ });
302
+
303
+ await Promise.all([...purchasedEventsMapped, ...soldEventsMapped]);
304
+ });
305
+ await Promise.all(processedChunks);
306
+ }
307
+ };
308
+
309
+ await populateListOfAddressesAndBalances(newReserve, reserveTokenPurchasedFilter, reserveTokenSoldFilter);
310
+ await populateListOfAddressesAndBalances(exchangeHelper, exchangeHelperTokenPurchasedFilter, exchangeHelperTokenSoldFilter);
311
+
312
+ // console.log({ newAddresses, newIsContracts });
313
+ return { newAddresses, newIsContracts };
314
+ };
315
+
316
+ const buildMerkleTree = () => {
317
+ const { addressesCombined } = JSON.parse(
318
+ fs.readFileSync("airdrop/buyBalancesCombined.json").toString()
319
+ );
320
+
321
+ let toTree: Array<[string, BigNumber]> = Object.entries(addressesCombined).map(
322
+ ([addr, gdx]) => {
323
+ return [addr, gdx as BigNumber];
324
+ }
325
+ );
326
+
327
+ // console.log(`Before sorting`);
328
+ // toTree.forEach((a,_) => { console.log(`${a[0].toString()}:${ethers.BigNumber.from(a[1]).toString()}\n`)});
329
+
330
+ toTree.sort((a, b) => BigNumber.from(b[1]).gt(a[1]) ? 0 : -1 );
331
+
332
+ // console.log(`After sorting`);
333
+ // toTree.forEach((a,_) => { console.log(`${a[0].toString()}:${ethers.BigNumber.from(a[1]).toString()}\n`)});
334
+
335
+ let totalGDX = ZERO;
336
+ toTree.forEach((a,_) => totalGDX = totalGDX.add(a[1]))
337
+ console.log({
338
+ toTree: toTree.forEach((a,_) => console.log({address: a[0].toString(), balance: BigNumber.from(a[1]).toString()})),
339
+ numberOfAccounts: toTree.length,
340
+ TotalGDX: totalGDX.toString()
341
+ });
342
+
343
+ // Print statistics
344
+ const sorted = toTree.map(_ => _[1]);
345
+ console.log("GDX Distribution\n");
346
+ [0.001, 0.01, 0.1, 0.5].forEach(q =>
347
+ console.log({
348
+ precentile: q * 100 + "%",
349
+ gdx: quantileBN(sorted, q)
350
+ })
351
+ );
352
+
353
+ const treeData = {};
354
+ const elements = toTree.map(e => {
355
+ const hash = ethers.utils.keccak256(
356
+ ethers.utils.defaultAbiCoder.encode(
357
+ ["address", "uint256"],
358
+ [e[0], e[1]]
359
+ )
360
+ );
361
+ treeData[e[0]] = {
362
+ gdx: e[1],
363
+ hash
364
+ };
365
+ return Buffer.from(hash.slice(2), "hex");
366
+ });
367
+
368
+ console.log(elements);
369
+ const merkleTree = new MerkleTree(elements, false);
370
+ // get the merkle root
371
+ // returns 32 byte buffer
372
+ const merkleRoot = merkleTree.getRoot().toString("hex");
373
+ // generate merkle proof
374
+ // returns array of 32 byte buffers
375
+ const proof = merkleTree.getProof(elements[0]).map(_ => _.toString("hex"));
376
+ console.log({ merkleRoot, proof, sampleProofFor: toTree[0] });
377
+ fs.writeFileSync(
378
+ "airdrop/gdxAirdropRecovery.json",
379
+ JSON.stringify({ treeData, merkleRoot })
380
+ );
381
+ };
382
+
383
+ const addCalculationsToPreviousData = async () => {
384
+ // get previous airdrop and turn it into BigNumbers
385
+ const gdxAirdropData = JSON.parse(
386
+ fs.readFileSync("airdrop/gdxairdrop.json").toString()
387
+ );
388
+ const addressesCombined = {}
389
+ for (const [address, balance] of Object.entries(gdxAirdropData.treeData)) {
390
+ addressesCombined[address] = BigNumber.from(balance['gdx']);
391
+ }
392
+
393
+ // get new holders info and turn into array
394
+ const { newAddresses, } = await getHoldersInformation();
395
+
396
+ let newAddressesArray: Array<[string, BigNumber]> = Object.entries(newAddresses).map(
397
+ ([addr, gdx]) => {
398
+ return [addr, gdx as BigNumber];
399
+ }
400
+ );
401
+
402
+
403
+ // Unite previous airdrop with current information
404
+ for (const newAddressEntry of newAddressesArray) {
405
+ const address = newAddressEntry[0];
406
+ const addition = newAddressEntry[1];
407
+
408
+ if (addition<=ZERO)
409
+ continue;
410
+
411
+ // console.log({address})
412
+ // console.log({before: BigNumber.from(addressesCombined[address] || "0").toString() })
413
+ // console.log({addition: addition.toString()})
414
+ addressesCombined[address] = ethers.BigNumber.from(addressesCombined[address] || 0).add(addition.toString()).toString();
415
+ // console.log({total: addressesCombined[address].toString()})
416
+ // console.log(`\n`);
417
+ }
418
+
419
+ fs.writeFileSync("airdrop/buyBalancesCombined.json", JSON.stringify({ addressesCombined }));
420
+ };
421
+
422
+ return { buildMerkleTree, addCalculationsToPreviousData };
423
+ };