How to use totalWeightBefore method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

1_TokenBonding.test.ts

Source:1_TokenBonding.test.ts Github

copy

Full Screen

1import chai, { assert, expect } from "chai";2import chaiAsPromised from "chai-as-promised";3import { ethers, upgrades } from "hardhat";4import { BigNumber } from "ethers";5import { solidity } from "ethereum-waffle";6import {7 advanceTime,8 daysToSeconds,9 getNextTimestampDivisibleBy,10 getTimestamp,11 setTimestamp,12} from "../helpers/utils";13import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";14import { FakeERC20, TokenBonding } from "../typechain-types";15import NetworkSnapshotter from "../helpers/NetworkSnapshotter";16const { AddressZero, MaxUint256 } = ethers.constants;17chai.use(solidity);18chai.use(chaiAsPromised);19const week = daysToSeconds(BigNumber.from(7));20const ten = BigNumber.from(10);21const tenPow18 = ten.pow(18);22describe("TokenBonding", () => {23 let deployer: SignerWithAddress;24 let signer1: SignerWithAddress;25 let signer2: SignerWithAddress;26 let signer3: SignerWithAddress;27 let helio: FakeERC20;28 let helioLp: FakeERC20;29 let tokenBonding: TokenBonding;30 let startTime: BigNumber;31 let helioCoefficient: BigNumber;32 let helioLpCoefficient: BigNumber;33 const networkSnapshotter = new NetworkSnapshotter();34 const setStartContractTimestamp = async () => {35 // set right time36 await setTimestamp(startTime.toNumber() + 1);37 };38 const getVeTokenByCoefficient = (amount: BigNumber, coefficient: BigNumber): BigNumber => {39 return amount.mul(coefficient).div(tenPow18);40 };41 before("setup", async () => {42 // setup43 [deployer, signer1, signer2, signer3] = await ethers.getSigners();44 const FakeToken = await ethers.getContractFactory("FakeERC20");45 const TokenBonding = await ethers.getContractFactory("TokenBonding");46 helio = await FakeToken.connect(deployer).deploy("Helio Token", "Helio");47 await helio.deployed();48 helioLp = await FakeToken.connect(deployer).deploy("Helio LP Token", "HelioLP");49 await helioLp.deployed();50 helioCoefficient = tenPow18.mul(1);51 helioLpCoefficient = tenPow18.mul(2);52 startTime = await getNextTimestampDivisibleBy(week.toNumber());53 const tokens = [helio.address, helioLp.address];54 const coefficients = [helioCoefficient, helioLpCoefficient];55 tokenBonding = (await upgrades.deployProxy(TokenBonding, [56 startTime,57 tokens,58 coefficients,59 ])) as TokenBonding;60 await tokenBonding.deployed();61 // mint tokens62 const amount = BigNumber.from("100000").mul(tenPow18);63 await helio.mint(signer1.address, amount);64 await helioLp.mint(signer1.address, amount);65 await helio.mint(signer2.address, amount);66 await helioLp.mint(signer2.address, amount);67 await networkSnapshotter.firstSnapshot();68 });69 afterEach("revert", async () => await networkSnapshotter.revert());70 describe("# constructor", () => {71 it("startTime should be divisible to week", async () => {72 const wrongStartTime = BigNumber.from(Math.floor(Date.now() / 1000) + 1000);73 expect(wrongStartTime.div(week).mul(week)).to.not.be.equal(wrongStartTime);74 const TokenBonding = await ethers.getContractFactory("TokenBonding");75 await expect(76 upgrades.deployProxy(TokenBonding, [wrongStartTime, [], []])77 ).to.eventually.be.rejectedWith(Error, "!epoch week");78 });79 it("startTime should be more thant block timestamp", async () => {80 const now = BigNumber.from(Math.floor(Date.now() / 1000));81 const wrongStartTime = now.sub(1000);82 assert.isTrue(wrongStartTime.lt(now));83 const TokenBonding = await ethers.getContractFactory("TokenBonding");84 await expect(85 upgrades.deployProxy(TokenBonding, [wrongStartTime, [], []])86 ).to.eventually.be.rejectedWith(Error, "!epoch week");87 });88 it("should revert if tokens length is not equal to coefficients length", async () => {89 const tokens = [helio.address];90 const coefficients = [helioCoefficient, helioLpCoefficient];91 expect(tokens.length).to.be.not.equal(coefficients.length);92 const TokenBonding = await ethers.getContractFactory("TokenBonding");93 await expect(94 upgrades.deployProxy(TokenBonding, [startTime, tokens, coefficients])95 ).to.eventually.be.rejectedWith(Error, "Not equal lengths");96 });97 it("should emit events in construction", async () => {98 const tokens = [helio.address, helioLp.address];99 const coefficients = [helioCoefficient, helioLpCoefficient];100 const TokenBonding = await ethers.getContractFactory("TokenBonding");101 const tokenBonding = await upgrades.deployProxy(TokenBonding, [102 startTime,103 tokens,104 coefficients,105 ]);106 await expect(tokenBonding.deployTransaction)107 .to.emit(tokenBonding, "TokenAdded")108 .withArgs(tokens[0], coefficients[0])109 .and.to.emit(tokenBonding, "TokenAdded")110 .withArgs(tokens[1], coefficients[1]);111 });112 });113 describe("# initial values", () => {114 it("startTime is ok", async () => {115 expect(await tokenBonding.startTime()).to.be.equal(startTime);116 });117 it("name, symbol, decimals are ok", async () => {118 expect(await tokenBonding.name()).to.be.equal("veHELIO");119 expect(await tokenBonding.symbol()).to.be.equal("veHELIO");120 expect(await tokenBonding.decimals()).to.be.equal(18);121 });122 it("allowance should be 0", async () => {123 expect(await tokenBonding.allowance(AddressZero, AddressZero)).to.be.equal(0);124 });125 it("initial coefficients are ok", async () => {126 const helioInfo = await tokenBonding.tokenInfo(helio.address);127 const helioLpInfo = await tokenBonding.tokenInfo(helioLp.address);128 expect(helioInfo.coefficient).to.be.equal(helioCoefficient);129 expect(helioLpInfo.coefficient).to.be.equal(helioLpCoefficient);130 });131 });132 describe("# transfers and approve should revert", () => {133 it("'transfer', 'transferFrom', 'approve' functions revert", async () => {134 await expect(tokenBonding.transfer(AddressZero, 0)).to.eventually.be.rejectedWith(135 Error,136 "NON-TRANSFERABLE TOKEN"137 );138 await expect(139 tokenBonding.transferFrom(AddressZero, AddressZero, 0)140 ).to.eventually.be.rejectedWith(Error, "NON-TRANSFERABLE TOKEN");141 await expect(tokenBonding.approve(AddressZero, 0)).to.eventually.be.rejectedWith(142 Error,143 "NON-TRANSFERABLE TOKEN"144 );145 });146 });147 describe("# tokenInfo", () => {148 it("should revert if tokens is not supported", async () => {149 await expect(tokenBonding.tokenInfo(AddressZero)).to.eventually.be.rejected;150 });151 });152 describe("# add bonding token", () => {153 it("only owner can call addToken function", async () => {154 await expect(155 tokenBonding.connect(signer3).addToken(AddressZero, 0)156 ).to.eventually.be.rejectedWith(Error, "Ownable: caller is not the owner");157 });158 it("adding token works correctly", async () => {159 // deploy net token160 const FakeToken = await ethers.getContractFactory("FakeERC20");161 const newToken = await FakeToken.connect(deployer).deploy("New Token", "New");162 await newToken.deployed();163 const newCoefficient = tenPow18.mul(15).div(10);164 const tokenLengthBefore = await tokenBonding.getTokensLength();165 await expect(tokenBonding.connect(deployer).addToken(newToken.address, newCoefficient))166 .to.emit(tokenBonding, "TokenAdded")167 .withArgs(newToken.address, newCoefficient);168 const tokenLengthAfter = await tokenBonding.getTokensLength();169 const tokenInfo = await tokenBonding.tokenInfo(newToken.address);170 const tokenInfoByIndex = await tokenBonding.getTokenInfoByIndex(tokenInfo.index);171 expect(tokenLengthAfter).to.be.equal(tokenLengthBefore.add(1));172 expect(tokenInfo.coefficient).to.be.equal(newCoefficient);173 expect(await tokenBonding.getTokenByIndex(tokenLengthAfter)).to.be.equal(newToken.address);174 // check equality of token info175 expect(tokenInfo.coefficient).to.be.equal(tokenInfoByIndex.coefficient);176 expect(tokenInfo.index).to.be.equal(tokenInfoByIndex.index);177 expect(tokenInfo.totalStaked).to.be.equal(tokenInfoByIndex.totalStaked);178 });179 it("cannot add already added token", async () => {180 const FakeToken = await ethers.getContractFactory("FakeERC20");181 const newToken = await FakeToken.connect(deployer).deploy("New Token", "New");182 await newToken.deployed();183 const newCoefficient = tenPow18.mul(15).div(10);184 await tokenBonding.connect(deployer).addToken(newToken.address, newCoefficient);185 await expect(186 tokenBonding.connect(deployer).addToken(newToken.address, newCoefficient)187 ).to.eventually.be.rejectedWith(Error, "Token already added");188 });189 });190 describe("# bonding", () => {191 const bondingAmount = BigNumber.from("10000");192 it("cannot bond if contract is not started yet", async () => {193 await expect(194 tokenBonding.connect(signer1).bond(helio.address, bondingAmount)195 ).to.eventually.be.rejectedWith(Error, "Contract is not started yet");196 });197 it("cannot bond zero tokens", async () => {198 await setStartContractTimestamp();199 await expect(200 tokenBonding.connect(signer1).bond(helio.address, 0)201 ).to.eventually.be.rejectedWith(Error, "cannot bond zero amount");202 });203 it("cannot bond if token is not approved", async () => {204 await setStartContractTimestamp();205 await expect(206 tokenBonding.connect(signer1).bond(helio.address, bondingAmount)207 ).to.eventually.be.rejectedWith(Error, "ERC20: insufficient allowance");208 });209 it("cannot bond unsupported token", async () => {210 await setStartContractTimestamp();211 const FakeToken = await ethers.getContractFactory("FakeERC20");212 const wrongToken = await FakeToken.connect(deployer).deploy("Wrong Token", "Wrong");213 await wrongToken.deployed();214 await wrongToken.mint(signer1.address, bondingAmount);215 await wrongToken.connect(signer1).approve(tokenBonding.address, bondingAmount);216 await expect(217 tokenBonding.connect(signer1).bond(wrongToken.address, bondingAmount)218 ).to.eventually.be.rejectedWith(Error, "Unsupported Token");219 });220 it("cannot batch bond if tokens length is not equal to amounts length", async () => {221 await setStartContractTimestamp();222 const bondingAmountHelio = BigNumber.from("10000");223 const bondingAmountLP = BigNumber.from("20000");224 // approve225 await helio.connect(signer1).approve(tokenBonding.address, bondingAmountHelio);226 await helioLp.connect(signer1).approve(tokenBonding.address, bondingAmountLP);227 await expect(228 tokenBonding229 .connect(signer1)230 .bondBatch(231 [helio.address, helioLp.address, AddressZero],232 [bondingAmountHelio, bondingAmountLP]233 )234 ).to.eventually.be.rejectedWith(Error, "tokens length must be equal to amounts length");235 });236 it("bonding works", async () => {237 await setStartContractTimestamp();238 // approve239 await helio.connect(signer1).approve(tokenBonding.address, bondingAmount);240 await helioLp.connect(signer2).approve(tokenBonding.address, bondingAmount);241 const helioCoeff = (await tokenBonding.tokenInfo(helio.address)).coefficient;242 const helioLpCoeff = (await tokenBonding.tokenInfo(helioLp.address)).coefficient;243 const user1VeTokenBalBefore = await tokenBonding.balanceOf(signer1.address);244 const user2VeTokenBalBefore = await tokenBonding.balanceOf(signer2.address);245 const user1VeTokenAmt = getVeTokenByCoefficient(bondingAmount, helioCoeff);246 const user2VeTokenAmt = getVeTokenByCoefficient(bondingAmount, helioLpCoeff);247 const user1WeightBefore = await tokenBonding.userWeight(signer1.address);248 const user2WeightBefore = await tokenBonding.userWeight(signer2.address);249 const totalSupplyBefore = await tokenBonding.totalSupply();250 const totalWeightBefore = await tokenBonding.totalWeight();251 await expect(tokenBonding.connect(signer1).bond(helio.address, bondingAmount))252 .to.emit(tokenBonding, "Transfer")253 .withArgs(AddressZero, signer1.address, user1VeTokenAmt)254 .and.to.emit(helio, "Transfer")255 .withArgs(signer1.address, tokenBonding.address, bondingAmount);256 await expect(tokenBonding.connect(signer2).bond(helioLp.address, bondingAmount))257 .to.emit(tokenBonding, "Transfer")258 .withArgs(AddressZero, signer2.address, user2VeTokenAmt)259 .and.to.emit(helioLp, "Transfer")260 .withArgs(signer2.address, tokenBonding.address, bondingAmount);261 const expectedUser1VeTokenBal = user1VeTokenAmt.add(user1VeTokenBalBefore);262 const expectedUser2VeTokenBal = user2VeTokenAmt.add(user2VeTokenBalBefore);263 const expectedUser1Weight = user1VeTokenAmt.add(user1WeightBefore);264 const expectedUser2Weight = user2VeTokenAmt.add(user2WeightBefore);265 const expectedTotalSupply = totalSupplyBefore.add(user1VeTokenAmt).add(user2VeTokenAmt);266 const expectedTotalWeight = totalWeightBefore.add(user1VeTokenAmt).add(user2VeTokenAmt);267 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(expectedUser1VeTokenBal);268 expect(await tokenBonding.balanceOf(signer2.address)).to.be.equal(expectedUser2VeTokenBal);269 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUser1Weight);270 expect(await tokenBonding.userWeight(signer2.address)).to.be.equal(expectedUser2Weight);271 expect(await tokenBonding.totalSupply()).to.be.equal(expectedTotalSupply);272 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);273 });274 it("batch bonding works", async () => {275 await setStartContractTimestamp();276 const bondingAmountHelio = BigNumber.from("10000");277 const bondingAmountLP = BigNumber.from("20000");278 // approve279 await helio.connect(signer1).approve(tokenBonding.address, bondingAmountHelio);280 await helioLp.connect(signer1).approve(tokenBonding.address, bondingAmountLP);281 const helioCoeff = (await tokenBonding.tokenInfo(helio.address)).coefficient;282 const helioLpCoeff = (await tokenBonding.tokenInfo(helioLp.address)).coefficient;283 const veTokenBalBefore = await tokenBonding.balanceOf(signer1.address);284 const userWeightBefore = await tokenBonding.userWeight(signer1.address);285 const totalSupplyBefore = await tokenBonding.totalSupply();286 const totalWeightBefore = await tokenBonding.totalWeight();287 const veTokenAmtByHelio = getVeTokenByCoefficient(bondingAmountHelio, helioCoeff);288 const veTokenAmtByLP = getVeTokenByCoefficient(bondingAmountLP, helioLpCoeff);289 await expect(290 tokenBonding291 .connect(signer1)292 .bondBatch([helio.address, helioLp.address], [bondingAmountHelio, bondingAmountLP])293 )294 .to.emit(tokenBonding, "Transfer")295 .withArgs(AddressZero, signer1.address, veTokenAmtByHelio)296 .and.to.emit(tokenBonding, "Transfer")297 .withArgs(AddressZero, signer1.address, veTokenAmtByLP)298 .and.to.emit(helio, "Transfer")299 .withArgs(signer1.address, tokenBonding.address, bondingAmountHelio)300 .and.to.emit(helioLp, "Transfer")301 .withArgs(signer1.address, tokenBonding.address, bondingAmountLP);302 const expectedVeTokenBal = veTokenBalBefore.add(veTokenAmtByLP).add(veTokenAmtByHelio);303 const expectedUserWeight = userWeightBefore.add(veTokenAmtByLP).add(veTokenAmtByHelio);304 const expectedTotalSupply = totalSupplyBefore.add(veTokenAmtByLP).add(veTokenAmtByHelio);305 const expectedTotalWeight = totalWeightBefore.add(veTokenAmtByLP).add(veTokenAmtByHelio);306 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(expectedVeTokenBal);307 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUserWeight);308 expect(await tokenBonding.totalSupply()).to.be.equal(expectedTotalSupply);309 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);310 });311 });312 describe("# request unbond", () => {313 const bondingAmount = BigNumber.from("10000");314 beforeEach("bond tokens", async () => {315 // start contract316 await setStartContractTimestamp();317 // approve318 await helio.connect(signer1).approve(tokenBonding.address, bondingAmount);319 await helio.connect(signer2).approve(tokenBonding.address, bondingAmount);320 await helioLp.connect(signer1).approve(tokenBonding.address, bondingAmount);321 await helioLp.connect(signer2).approve(tokenBonding.address, bondingAmount);322 // bond323 await tokenBonding.connect(signer1).bond(helio.address, bondingAmount);324 await tokenBonding.connect(signer2).bond(helio.address, bondingAmount);325 await tokenBonding.connect(signer1).bond(helioLp.address, bondingAmount);326 await tokenBonding.connect(signer2).bond(helioLp.address, bondingAmount);327 });328 it("should not request if not bonded yet", async () => {329 const arithmeticErrorCode = "0x11";330 await expect(331 tokenBonding.connect(signer3).requestUnbond(helio.address, bondingAmount)332 ).to.eventually.be.rejectedWith(Error, arithmeticErrorCode);333 });334 it("cannot request 0 amount", async () => {335 await expect(336 tokenBonding.connect(signer1).requestUnbond(helio.address, 0)337 ).to.eventually.be.rejectedWith(Error, "Cannot request for zero amount");338 });339 it("cannot request if requested amount is more than bonded amount", async () => {340 const arithmeticErrorCode = "0x11";341 const requestedAmount = bondingAmount.add(1);342 await expect(343 tokenBonding.connect(signer1).requestUnbond(helio.address, requestedAmount)344 ).to.eventually.be.rejectedWith(Error, arithmeticErrorCode);345 });346 it("cannot request unbond batch if tokens length is not equal to amounts length", async () => {347 await expect(348 tokenBonding.connect(signer1).requestUnbondBatch([helio.address], [])349 ).to.eventually.be.rejectedWith(Error, "tokens length must be equal to amounts length");350 });351 it("request works as expected", async () => {352 const requestedAmount = bondingAmount.div(2);353 const user1BalBefore = await tokenBonding.balanceOf(signer1.address);354 const user2BalBefore = await tokenBonding.balanceOf(signer2.address);355 const user1WeightBefore = await tokenBonding.userWeight(signer1.address);356 const user2WeightBefore = await tokenBonding.userWeight(signer2.address);357 const totalSupplyBefore = await tokenBonding.totalSupply();358 const totalWeightBefore = await tokenBonding.totalWeight();359 const user1RequestedVeAmount = getVeTokenByCoefficient(requestedAmount, helioCoefficient);360 const user2RequestedVeAmount = getVeTokenByCoefficient(requestedAmount, helioLpCoefficient);361 await expect(362 tokenBonding.connect(signer1).requestUnbond(helio.address, requestedAmount)363 ).to.emit(tokenBonding, "UnbondingRequest");364 await expect(365 tokenBonding.connect(signer2).requestUnbond(helioLp.address, requestedAmount)366 ).to.emit(tokenBonding, "UnbondingRequest");367 const expectedUser1Weight = user1WeightBefore.sub(user1RequestedVeAmount);368 const expectedUser2Weight = user2WeightBefore.sub(user2RequestedVeAmount);369 const expectedTotalWeight = totalWeightBefore370 .sub(user1RequestedVeAmount)371 .sub(user2RequestedVeAmount);372 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(user1BalBefore);373 expect(await tokenBonding.balanceOf(signer2.address)).to.be.equal(user2BalBefore);374 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUser1Weight);375 expect(await tokenBonding.userWeight(signer2.address)).to.be.equal(expectedUser2Weight);376 expect(await tokenBonding.totalSupply()).to.be.equal(totalSupplyBefore);377 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);378 });379 it("should request all amount if requested amount is uint256 max value", async () => {380 const requestedAmount = MaxUint256;381 await expect(382 tokenBonding.connect(signer1).requestUnbond(helio.address, requestedAmount)383 ).to.emit(tokenBonding, "UnbondingRequest");384 const userStakeInfo = await tokenBonding.userStakeInfo(signer1.address, helio.address);385 expect(userStakeInfo.staked).to.be.equal(0);386 });387 it("request batch works as expected", async () => {388 const requestedAmount = bondingAmount.div(2);389 const userBalBefore = await tokenBonding.balanceOf(signer1.address);390 const userWeightBefore = await tokenBonding.userWeight(signer1.address);391 const totalSupplyBefore = await tokenBonding.totalSupply();392 const totalWeightBefore = await tokenBonding.totalWeight();393 const userRequestedVeHelio = getVeTokenByCoefficient(requestedAmount, helioCoefficient);394 const userRequestedVeHelioLp = getVeTokenByCoefficient(requestedAmount, helioLpCoefficient);395 await expect(396 tokenBonding397 .connect(signer1)398 .requestUnbondBatch([helio.address, helioLp.address], [requestedAmount, requestedAmount])399 )400 .to.emit(tokenBonding, "UnbondingRequest")401 .and.to.emit(tokenBonding, "UnbondingRequest");402 const expectedUserWeight = userWeightBefore403 .sub(userRequestedVeHelio)404 .sub(userRequestedVeHelioLp);405 const expectedTotalWeight = totalWeightBefore406 .sub(userRequestedVeHelio)407 .sub(userRequestedVeHelioLp);408 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(userBalBefore);409 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUserWeight);410 expect(await tokenBonding.totalSupply()).to.be.equal(totalSupplyBefore);411 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);412 });413 });414 describe("# unbond", () => {415 const bondingAmount = BigNumber.from("10000");416 const requestedAmount = bondingAmount.div(2);417 beforeEach("bond tokens", async () => {418 // start contract419 await setStartContractTimestamp();420 // approve421 await helio.connect(signer1).approve(tokenBonding.address, bondingAmount);422 await helio.connect(signer2).approve(tokenBonding.address, bondingAmount);423 await helioLp.connect(signer1).approve(tokenBonding.address, bondingAmount);424 await helioLp.connect(signer2).approve(tokenBonding.address, bondingAmount);425 // bond426 await tokenBonding.connect(signer1).bond(helio.address, bondingAmount);427 await tokenBonding.connect(signer2).bond(helio.address, bondingAmount);428 await tokenBonding.connect(signer1).bond(helioLp.address, bondingAmount);429 await tokenBonding.connect(signer2).bond(helioLp.address, bondingAmount);430 });431 beforeEach("request unbond", async () => {432 await tokenBonding.connect(signer1).requestUnbond(helio.address, requestedAmount);433 await tokenBonding.connect(signer2).requestUnbond(helio.address, requestedAmount);434 await tokenBonding.connect(signer1).requestUnbond(helioLp.address, requestedAmount);435 await tokenBonding.connect(signer2).requestUnbond(helioLp.address, requestedAmount);436 });437 it("cannot unbond if amount is 0", async () => {438 await expect(439 tokenBonding.connect(signer3).unbond(helio.address)440 ).to.eventually.be.rejectedWith(Error, "Claimed amount should not be zero");441 });442 it("cannot unbond if a week is not passed", async () => {443 const currentTimestamp = await getTimestamp();444 const userStakeInfo = await tokenBonding.userStakeInfo(signer1.address, helio.address);445 assert.isTrue(userStakeInfo.requestTime.add(week).gt(currentTimestamp));446 await expect(447 tokenBonding.connect(signer1).unbond(helio.address)448 ).to.eventually.be.rejectedWith(Error, "You should wait seven days");449 });450 it("unbonding works", async () => {451 await advanceTime(week.toNumber());452 const user1WeightBefore = await tokenBonding.userWeight(signer1.address);453 const user2WeightBefore = await tokenBonding.userWeight(signer2.address);454 const user1BalBefore = await tokenBonding.balanceOf(signer1.address);455 const user2BalBefore = await tokenBonding.balanceOf(signer2.address);456 const totalWeightBefore = await tokenBonding.totalWeight();457 const totalSupplyBefore = await tokenBonding.totalSupply();458 const user1StakeInfoBefore = await tokenBonding.userStakeInfo(signer1.address, helio.address);459 const user2StakeInfoBefore = await tokenBonding.userStakeInfo(460 signer2.address,461 helioLp.address462 );463 const user1VeTokenAmt = getVeTokenByCoefficient(requestedAmount, helioCoefficient);464 const user2VeTokenAmt = getVeTokenByCoefficient(requestedAmount, helioLpCoefficient);465 await expect(tokenBonding.connect(signer1).unbond(helio.address))466 .to.emit(helio, "Transfer")467 .withArgs(tokenBonding.address, signer1.address, user1StakeInfoBefore.wantClaim)468 .and.to.emit(tokenBonding, "Transfer")469 .withArgs(signer1.address, AddressZero, user1VeTokenAmt);470 await expect(tokenBonding.connect(signer2).unbond(helioLp.address))471 .to.emit(helioLp, "Transfer")472 .withArgs(tokenBonding.address, signer2.address, user2StakeInfoBefore.wantClaim)473 .and.to.emit(tokenBonding, "Transfer")474 .withArgs(signer2.address, AddressZero, user2VeTokenAmt);475 const user1StakeInfoAfter = await tokenBonding.userStakeInfo(signer1.address, helio.address);476 const user2StakeInfoAfter = await tokenBonding.userStakeInfo(477 signer2.address,478 helioLp.address479 );480 const expectedUser1BalAfter = user1BalBefore.sub(user1VeTokenAmt);481 const expectedUser2BalAfter = user2BalBefore.sub(user2VeTokenAmt);482 const expectedTotalSupply = totalSupplyBefore.sub(user1VeTokenAmt).sub(user2VeTokenAmt);483 expect(user1StakeInfoAfter.wantClaim).to.be.equal(0);484 expect(user2StakeInfoAfter.wantClaim).to.be.equal(0);485 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(user1WeightBefore);486 expect(await tokenBonding.userWeight(signer2.address)).to.be.equal(user2WeightBefore);487 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(expectedUser1BalAfter);488 expect(await tokenBonding.balanceOf(signer2.address)).to.be.equal(expectedUser2BalAfter);489 expect(await tokenBonding.totalWeight()).to.be.equal(totalWeightBefore);490 expect(await tokenBonding.totalSupply()).to.be.equal(expectedTotalSupply);491 });492 it("batch unbonding works", async () => {493 await advanceTime(week.toNumber());494 const userWeightBefore = await tokenBonding.userWeight(signer1.address);495 const userBalBefore = await tokenBonding.balanceOf(signer1.address);496 const totalWeightBefore = await tokenBonding.totalWeight();497 const totalSupplyBefore = await tokenBonding.totalSupply();498 const userHelioStakeInfoBefore = await tokenBonding.userStakeInfo(499 signer1.address,500 helio.address501 );502 const userHelioLPStakeInfoBefore = await tokenBonding.userStakeInfo(503 signer1.address,504 helioLp.address505 );506 const userVeHelioAmt = getVeTokenByCoefficient(requestedAmount, helioCoefficient);507 const userVeHelioLpAmt = getVeTokenByCoefficient(requestedAmount, helioLpCoefficient);508 await expect(tokenBonding.connect(signer1).unbondBatch([helio.address, helioLp.address]))509 .to.emit(helio, "Transfer")510 .withArgs(tokenBonding.address, signer1.address, userHelioStakeInfoBefore.wantClaim)511 .and.to.emit(helio, "Transfer")512 .withArgs(tokenBonding.address, signer1.address, userHelioLPStakeInfoBefore.wantClaim)513 .and.to.emit(tokenBonding, "Transfer")514 .withArgs(signer1.address, AddressZero, userVeHelioAmt)515 .and.to.emit(tokenBonding, "Transfer")516 .withArgs(signer1.address, AddressZero, userVeHelioLpAmt);517 const userHelioStakeInfo = await tokenBonding.userStakeInfo(signer1.address, helio.address);518 const userHelioLpStakeInfo = await tokenBonding.userStakeInfo(519 signer1.address,520 helioLp.address521 );522 const expectedUserBal = userBalBefore.sub(userVeHelioAmt).sub(userVeHelioLpAmt);523 const expectedTotalSupply = totalSupplyBefore.sub(userVeHelioAmt).sub(userVeHelioLpAmt);524 expect(userHelioStakeInfo.wantClaim).to.be.equal(0);525 expect(userHelioLpStakeInfo.wantClaim).to.be.equal(0);526 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(userWeightBefore);527 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(expectedUserBal);528 expect(await tokenBonding.totalWeight()).to.be.equal(totalWeightBefore);529 expect(await tokenBonding.totalSupply()).to.be.equal(expectedTotalSupply);530 });531 });532 describe("# decrease unbond amount", () => {533 const bondingAmount = BigNumber.from("10000");534 const requestedAmount = bondingAmount.div(2);535 const decreaseAmount = requestedAmount.div(2);536 beforeEach("bond tokens", async () => {537 // start contract538 await setStartContractTimestamp();539 // approve540 await helio.connect(signer1).approve(tokenBonding.address, bondingAmount);541 await helioLp.connect(signer1).approve(tokenBonding.address, bondingAmount);542 // bond543 await tokenBonding.connect(signer1).bond(helio.address, bondingAmount);544 await tokenBonding.connect(signer1).bond(helioLp.address, bondingAmount);545 });546 beforeEach("request unbond", async () => {547 await tokenBonding.connect(signer1).requestUnbond(helio.address, requestedAmount);548 await tokenBonding.connect(signer1).requestUnbond(helioLp.address, requestedAmount);549 });550 it("cannot decrease more than requested unbond amount", async () => {551 await expect(552 tokenBonding.connect(signer1).decreaseUnbondAmount(helio.address, requestedAmount.add(1))553 ).to.eventually.be.rejectedWith(Error, "amount is more than wantClaim amount");554 });555 it("cannot batch decrease amount if tokens length is not equal to amounts length", async () => {556 await expect(557 tokenBonding.connect(signer1).decreaseUnbondAmountBatch([helio.address], [])558 ).to.eventually.be.rejectedWith(Error, "tokens length must be equal to amounts length");559 });560 it("decrease unbond amount works", async () => {561 const userBalBefore = await tokenBonding.balanceOf(signer1.address);562 const userWeightBefore = await tokenBonding.userWeight(signer1.address);563 const totalSupplyBefore = await tokenBonding.totalSupply();564 const totalWeightBefore = await tokenBonding.totalWeight();565 const userVeHelioAmt = getVeTokenByCoefficient(decreaseAmount, helioCoefficient);566 const userStakeInfoBefore = await tokenBonding.userStakeInfo(signer1.address, helio.address);567 await expect(568 tokenBonding.connect(signer1).decreaseUnbondAmount(helio.address, decreaseAmount)569 )570 .to.emit(tokenBonding, "UnbondingRequest")571 .withArgs(572 helio.address,573 userStakeInfoBefore.wantClaim.sub(decreaseAmount),574 userStakeInfoBefore.requestTime575 );576 const expectedUserWeight = userWeightBefore.add(userVeHelioAmt);577 const expectedTotalWeight = totalWeightBefore.add(userVeHelioAmt);578 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(userBalBefore);579 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUserWeight);580 expect(await tokenBonding.totalSupply()).to.be.equal(totalSupplyBefore);581 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);582 });583 it("will decrease all amounts if the given amount is equal to MaxUint256", async () => {584 const userBalBefore = await tokenBonding.balanceOf(signer1.address);585 const userWeightBefore = await tokenBonding.userWeight(signer1.address);586 const totalSupplyBefore = await tokenBonding.totalSupply();587 const totalWeightBefore = await tokenBonding.totalWeight();588 const userVeHelioAmt = getVeTokenByCoefficient(requestedAmount, helioCoefficient);589 const userStakeInfoBefore = await tokenBonding.userStakeInfo(signer1.address, helio.address);590 await expect(591 tokenBonding592 .connect(signer1)593 .decreaseUnbondAmount(helio.address, ethers.constants.MaxUint256)594 )595 .to.emit(tokenBonding, "UnbondingRequest")596 .withArgs(helio.address, 0, userStakeInfoBefore.requestTime);597 const expectedUserWeight = userWeightBefore.add(userVeHelioAmt);598 const expectedTotalWeight = totalWeightBefore.add(userVeHelioAmt);599 const userStakeInfoAfter = await tokenBonding.userStakeInfo(signer1.address, helio.address);600 expect(userStakeInfoAfter.wantClaim).to.be.equal(0);601 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(userBalBefore);602 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUserWeight);603 expect(await tokenBonding.totalSupply()).to.be.equal(totalSupplyBefore);604 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);605 });606 it("decrease unbond batch works", async () => {607 const decreaseAmount1 = decreaseAmount;608 const decreaseAmount2 = decreaseAmount.mul(2);609 const userBalBefore = await tokenBonding.balanceOf(signer1.address);610 const userWeightBefore = await tokenBonding.userWeight(signer1.address);611 const totalSupplyBefore = await tokenBonding.totalSupply();612 const totalWeightBefore = await tokenBonding.totalWeight();613 const userVeHelioAmt = getVeTokenByCoefficient(decreaseAmount1, helioCoefficient);614 const userVeHelioLpAmt = getVeTokenByCoefficient(decreaseAmount2, helioLpCoefficient);615 const userHelioStakeInfoBefore = await tokenBonding.userStakeInfo(616 signer1.address,617 helio.address618 );619 const userHelioLpStakeInfoBefore = await tokenBonding.userStakeInfo(620 signer1.address,621 helioLp.address622 );623 await expect(624 tokenBonding625 .connect(signer1)626 .decreaseUnbondAmountBatch(627 [helio.address, helioLp.address],628 [decreaseAmount1, decreaseAmount2]629 )630 )631 .to.emit(tokenBonding, "UnbondingRequest")632 .withArgs(633 helio.address,634 userHelioStakeInfoBefore.wantClaim.sub(decreaseAmount1),635 userHelioStakeInfoBefore.requestTime636 )637 .and.to.emit(tokenBonding, "UnbondingRequest")638 .withArgs(639 helioLp.address,640 userHelioLpStakeInfoBefore.wantClaim.sub(decreaseAmount2),641 userHelioLpStakeInfoBefore.requestTime642 );643 const expectedUserWeight = userWeightBefore.add(userVeHelioAmt).add(userVeHelioLpAmt);644 const expectedTotalWeight = totalWeightBefore.add(userVeHelioAmt).add(userVeHelioLpAmt);645 expect(await tokenBonding.balanceOf(signer1.address)).to.be.equal(userBalBefore);646 expect(await tokenBonding.userWeight(signer1.address)).to.be.equal(expectedUserWeight);647 expect(await tokenBonding.totalSupply()).to.be.equal(totalSupplyBefore);648 expect(await tokenBonding.totalWeight()).to.be.equal(expectedTotalWeight);649 });650 });...

Full Screen

Full Screen

advancedPoolFunctionality.ts

Source:advancedPoolFunctionality.ts Github

copy

Full Screen

1// This way of importing is a bit funky. We should fix this in the Mock Contracts package2import {MockTokenFactory} from "@pie-dao/mock-contracts/dist/typechain/MockTokenFactory";3import {MockToken} from "@pie-dao/mock-contracts/typechain/MockToken";4import {ethers, run, ethereum} from "@nomiclabs/buidler";5import {Signer, Wallet, utils, constants} from "ethers";6import {BigNumber, BigNumberish, parseEther} from "ethers/utils";7import chai from "chai";8import {deployContract, solidity} from "ethereum-waffle";9import {deployBalancerPool, linkArtifact, TimeTraveler} from "../utils";10import {IbPool} from "../typechain/IbPool";11import {IbPoolFactory} from "../typechain/IbPoolFactory";12import {Pv2SmartPool} from "../typechain/Pv2SmartPool";13import PV2SmartPoolArtifact from "../artifacts/PV2SmartPool.json";14import {MaxUint256} from "ethers/constants";15chai.use(solidity);16const {expect} = chai;17const NAME = "TEST POOL";18const SYMBOL = "TPL";19const INITIAL_SUPPLY = constants.WeiPerEther;20const timeTraveler = new TimeTraveler(ethereum);21describe("Advanced Pool Functionality", function () {22 this.timeout(3000000);23 let signers: Signer[];24 let account: string;25 let account2: string;26 let tokens: MockToken[];27 let pool: IbPool;28 let smartpool: Pv2SmartPool;29 let startBlock: number;30 let endBlock: number;31 let tokenFactory : MockTokenFactory32 beforeEach(async () => {33 signers = await ethers.signers();34 account = await signers[0].getAddress();35 account2 = await signers[1].getAddress();36 pool = IbPoolFactory.connect(await deployBalancerPool(signers[0]), signers[0]);37 tokenFactory = new MockTokenFactory(signers[0]);38 tokens = [];39 for (let i = 0; i < 8; i++) {40 const token: MockToken = await tokenFactory.deploy(`Mock ${i}`, `M${i}`, 18);41 await token.mint(account, constants.WeiPerEther.mul(1000000));42 await token.mint(await signers[1].getAddress(), constants.WeiPerEther.mul(1000000));43 await token.approve(pool.address, constants.MaxUint256);44 pool.bind(token.address, constants.WeiPerEther, constants.WeiPerEther.mul(2));45 tokens.push(token);46 }47 smartpool = (await run("deploy-libraries-and-smartpool")) as Pv2SmartPool;48 await smartpool.init(pool.address, NAME, SYMBOL, INITIAL_SUPPLY);49 await smartpool.approveTokens();50 await pool.setController(smartpool.address);51 for (const token of tokens) {52 await token.approve(smartpool.address, constants.MaxUint256);53 // Attach alt signer to token and approve pool54 await MockTokenFactory.connect(token.address, signers[1]).approve(55 smartpool.address,56 constants.MaxUint25657 );58 }59 startBlock = (await ethers.provider.getBlockNumber()) + 1;60 endBlock = startBlock + 100;61 });62 describe("updateWeight()", async () => {63 it("Updating the weigth from a non controller should fail", async () => {64 smartpool = smartpool.connect(signers[1]);65 await expect(66 smartpool.updateWeight(tokens[0].address, constants.WeiPerEther)67 ).to.be.revertedWith("PV2SmartPool.onlyController: not controller");68 });69 it("Updating down should work", async () => {70 const weightBefore = await smartpool.getDenormalizedWeight(tokens[0].address);71 const totalWeightBefore = await pool.getTotalDenormalizedWeight();72 const poolTokenBalanceBefore = await tokens[0].balanceOf(pool.address);73 const userTokenBalanceBefore = await tokens[0].balanceOf(account);74 const userSmartPoolTokenBalanceBefore = await smartpool.balanceOf(account);75 const poolSmartPoolTokenTotalSupplyBefore = await smartpool.totalSupply();76 await smartpool.updateWeight(tokens[0].address, constants.WeiPerEther);77 const newWeight = await smartpool.getDenormalizedWeight(tokens[0].address);78 const totalWeightAfter = await pool.getTotalDenormalizedWeight();79 const poolTokenBalanceAfter = await tokens[0].balanceOf(pool.address);80 const userTokenBalanceAfter = await tokens[0].balanceOf(account);81 const userSmartPoolTokenBalanceAfter = await smartpool.balanceOf(account);82 const poolSmartPoolTokenTotalSupplyAfter = await smartpool.totalSupply();83 const expectedBurn = poolSmartPoolTokenTotalSupplyBefore84 .mul(totalWeightBefore.sub(totalWeightAfter))85 .div(totalWeightBefore);86 const expectedTokenWithdraw = poolTokenBalanceBefore.mul(newWeight).div(weightBefore);87 expect(newWeight).to.eq(constants.WeiPerEther);88 expect(userSmartPoolTokenBalanceAfter).to.eq(89 userSmartPoolTokenBalanceBefore.sub(expectedBurn)90 );91 expect(poolSmartPoolTokenTotalSupplyAfter).to.eq(92 poolSmartPoolTokenTotalSupplyBefore.sub(expectedBurn)93 );94 expect(userTokenBalanceAfter).to.eq(userTokenBalanceBefore.add(expectedTokenWithdraw));95 expect(poolTokenBalanceAfter).to.eq(poolTokenBalanceBefore.sub(expectedTokenWithdraw));96 expect(totalWeightAfter).to.eq(totalWeightBefore.sub(constants.WeiPerEther));97 });98 it("Updating down while the token transfer returns false should fail", async () => {99 await tokens[0].setTransferReturnFalse(true);100 await expect(101 smartpool.updateWeight(tokens[0].address, constants.WeiPerEther)102 ).to.be.revertedWith("ERR_ERC20_FALSE");103 });104 it("Updating down while not having enough pool tokens should fail", async () => {105 const balance = await smartpool.balanceOf(account);106 await smartpool.transfer(account2, balance);107 await expect(108 smartpool.updateWeight(tokens[0].address, constants.WeiPerEther)109 ).to.be.revertedWith("ERR_INSUFFICIENT_BAL");110 });111 it("Updating up should work", async () => {112 const weightBefore = await smartpool.getDenormalizedWeight(tokens[0].address);113 const totalWeightBefore = await pool.getTotalDenormalizedWeight();114 const poolTokenBalanceBefore = await tokens[0].balanceOf(pool.address);115 const userTokenBalanceBefore = await tokens[0].balanceOf(account);116 const userSmartPoolTokenBalanceBefore = await smartpool.balanceOf(account);117 const poolSmartPoolTokenTotalSupplyBefore = await smartpool.totalSupply();118 await smartpool.updateWeight(tokens[0].address, constants.WeiPerEther.mul(4));119 const newWeight = await smartpool.getDenormalizedWeight(tokens[0].address);120 const totalWeightAfter = await pool.getTotalDenormalizedWeight();121 const poolTokenBalanceAfter = await tokens[0].balanceOf(pool.address);122 const userTokenBalanceAfter = await tokens[0].balanceOf(account);123 const userSmartPoolTokenBalanceAfter = await smartpool.balanceOf(account);124 const poolSmartPoolTokenTotalSupplyAfter = await smartpool.totalSupply();125 const expectedMint = poolSmartPoolTokenTotalSupplyBefore126 .mul(totalWeightAfter.sub(totalWeightBefore))127 .div(totalWeightBefore);128 const expectedTokenDeposit = poolTokenBalanceBefore129 .mul(newWeight)130 .div(weightBefore)131 .sub(poolTokenBalanceBefore);132 expect(newWeight).to.eq(constants.WeiPerEther.mul(4));133 expect(userSmartPoolTokenBalanceAfter).to.eq(134 userSmartPoolTokenBalanceBefore.add(expectedMint)135 );136 expect(poolSmartPoolTokenTotalSupplyAfter).to.eq(137 poolSmartPoolTokenTotalSupplyBefore.add(expectedMint)138 );139 expect(userTokenBalanceAfter).to.eq(userTokenBalanceBefore.sub(expectedTokenDeposit));140 expect(poolTokenBalanceAfter).to.eq(poolTokenBalanceBefore.add(expectedTokenDeposit));141 expect(totalWeightAfter).to.eq(totalWeightBefore.add(constants.WeiPerEther.mul(2)));142 });143 it("Updating up while not having enough of the underlying should fail", async () => {144 const balance = await tokens[0].balanceOf(account);145 await tokens[0].transfer(account2, balance);146 await expect(147 smartpool.updateWeight(tokens[0].address, constants.WeiPerEther.mul(4))148 ).to.be.revertedWith("ERC20: transfer amount exceeds balance");149 });150 it("Updating up while the token transferFrom returns false should fail", async () => {151 await tokens[0].setTransferFromReturnFalse(true);152 await expect(153 smartpool.updateWeight(tokens[0].address, constants.WeiPerEther.mul(4))154 ).to.be.revertedWith("TRANSFER_FAILED");155 });156 it("Updating up while the underlying token is not approved should fail", async () => {157 await tokens[0].approve(smartpool.address, 0);158 await expect(159 smartpool.updateWeight(tokens[0].address, constants.WeiPerEther.mul(4))160 ).to.be.revertedWith("ERC20: transfer amount exceeds allowance");161 });162 });163 describe("updateWeightsGradually()", async () => {164 const weightsFixtureUp = [165 constants.WeiPerEther.mul(4),166 constants.WeiPerEther.mul(2),167 constants.WeiPerEther.mul(2),168 constants.WeiPerEther.mul(2),169 constants.WeiPerEther.mul(2),170 constants.WeiPerEther.mul(2),171 constants.WeiPerEther.mul(2),172 constants.WeiPerEther.mul(2),173 ];174 const weightsFixtureTokenAboveMax = [175 constants.WeiPerEther.mul(51),176 constants.WeiPerEther.mul(2),177 constants.WeiPerEther.mul(2),178 constants.WeiPerEther.mul(2),179 constants.WeiPerEther.mul(2),180 constants.WeiPerEther.mul(2),181 constants.WeiPerEther.mul(2),182 constants.WeiPerEther.mul(2),183 ];184 const weightsFixtureTokenBelowMin = [185 constants.WeiPerEther.div(2),186 constants.WeiPerEther.mul(2),187 constants.WeiPerEther.mul(2),188 constants.WeiPerEther.mul(2),189 constants.WeiPerEther.mul(2),190 constants.WeiPerEther.mul(2),191 constants.WeiPerEther.mul(2),192 constants.WeiPerEther.mul(2),193 ];194 const weightsFixtureTotalAboveMax = [195 constants.WeiPerEther.mul(10),196 constants.WeiPerEther.mul(10),197 constants.WeiPerEther.mul(10),198 constants.WeiPerEther.mul(10),199 constants.WeiPerEther.mul(10),200 constants.WeiPerEther.mul(10),201 constants.WeiPerEther.mul(10),202 constants.WeiPerEther.mul(10),203 ];204 it("Updating from a non controller should fail", async () => {205 smartpool = smartpool.connect(signers[1]);206 await expect(207 smartpool.updateWeightsGradually(weightsFixtureUp, startBlock, endBlock)208 ).to.be.revertedWith("PV2SmartPool.onlyController: not controller");209 });210 it("Updating should work", async () => {211 const currentWeights = await smartpool.getDenormalizedWeights();212 await smartpool.updateWeightsGradually(weightsFixtureUp, startBlock, endBlock);213 const newWeights = await smartpool.getNewWeights();214 const newCurrentWeights = await smartpool.getDenormalizedWeights();215 expect(newWeights).to.eql(weightsFixtureUp);216 expect(newCurrentWeights).to.eql(currentWeights);217 });218 it("Setting a start block in the past should set it to the current block", async () => {219 const currentWeights = await smartpool.getDenormalizedWeights();220 await smartpool.updateWeightsGradually(weightsFixtureUp, 0, endBlock);221 const currentBlock = await ethers.provider.getBlockNumber();222 const newWeights = await smartpool.getNewWeights();223 const newCurrentWeights = await smartpool.getDenormalizedWeights();224 const startBlockVal = await smartpool.getStartBlock();225 expect(startBlockVal).to.eq(currentBlock);226 expect(newWeights).to.eql(weightsFixtureUp);227 expect(newCurrentWeights).to.eql(currentWeights);228 });229 it("Updating the weight of a token above the max should fail", async () => {230 await expect(231 smartpool.updateWeightsGradually(weightsFixtureTokenAboveMax, startBlock, endBlock)232 ).to.be.revertedWith("ERR_WEIGHT_ABOVE_MAX");233 });234 it("Updating the weight of a token below the minimum should fail", async () => {235 await expect(236 smartpool.updateWeightsGradually(weightsFixtureTokenBelowMin, startBlock, endBlock)237 ).to.be.revertedWith("ERR_WEIGHT_BELOW_MIN");238 });239 it("Updating the weights above the total max weight should fail", async () => {240 await expect(241 smartpool.updateWeightsGradually(weightsFixtureTotalAboveMax, startBlock, endBlock)242 ).to.be.revertedWith("ERR_MAX_TOTAL_WEIGHT");243 });244 it("Updating to a start block which is bigger before the end block should fail", async () => {245 await expect(246 smartpool.updateWeightsGradually(weightsFixtureUp, endBlock + 1, endBlock)247 ).to.be.revertedWith(248 "PWeightControlledSmartPool.updateWeightsGradually: End block must be after start block"249 );250 });251 });252 describe("pokeWeight()", async () => {253 const weigthsFixturePokeWeightsUp = [254 constants.WeiPerEther.mul(4),255 constants.WeiPerEther.mul(4),256 constants.WeiPerEther.mul(4),257 constants.WeiPerEther.mul(4),258 constants.WeiPerEther.mul(4),259 constants.WeiPerEther.mul(4),260 constants.WeiPerEther.mul(4),261 constants.WeiPerEther.mul(4),262 ];263 const weigthsFixturePokeWeightsDown = [264 constants.WeiPerEther.mul(1),265 constants.WeiPerEther.mul(1),266 constants.WeiPerEther.mul(1),267 constants.WeiPerEther.mul(1),268 constants.WeiPerEther.mul(1),269 constants.WeiPerEther.mul(1),270 constants.WeiPerEther.mul(1),271 constants.WeiPerEther.mul(1),272 ];273 it("Poking the weights up should work", async () => {274 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);275 const weightsBefore = await smartpool.getDenormalizedWeights();276 await smartpool.pokeWeights();277 const currentBlock = await ethers.provider.getBlockNumber();278 const weightsAfter = await smartpool.getDenormalizedWeights();279 for (let i = 0; i < weightsAfter.length; i++) {280 const expectedIncrease = weigthsFixturePokeWeightsUp[i]281 .sub(weightsBefore[i])282 .mul(currentBlock - startBlock)283 .div(endBlock - startBlock);284 expect(weightsAfter[i]).to.eq(285 weightsBefore[i].add(expectedIncrease),286 "Weight increase incorrect"287 );288 }289 });290 it("Poking the weights down should work", async () => {291 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsDown, startBlock, endBlock);292 const weightsBefore = await smartpool.getDenormalizedWeights();293 await smartpool.pokeWeights();294 const currentBlock = await ethers.provider.getBlockNumber();295 const weightsAfter = await smartpool.getDenormalizedWeights();296 for (let i = 0; i < weightsAfter.length; i++) {297 const expectedDecrease = weightsBefore[i]298 .sub(weigthsFixturePokeWeightsDown[i])299 .mul(currentBlock - startBlock)300 .div(endBlock - startBlock);301 expect(weightsAfter[i]).to.eq(302 weightsBefore[i].sub(expectedDecrease),303 "Weight decrease incorrect"304 );305 }306 });307 it("Poking the weight after the end block should work", async () => {308 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);309 await mine_blocks(200);310 await smartpool.pokeWeights();311 const weightsAfter = await smartpool.getDenormalizedWeights();312 expect(weightsAfter).to.eql(weigthsFixturePokeWeightsUp, "Weight increase incorrect");313 });314 it("Poking the weight twice after the end block should fail", async () => {315 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);316 await smartpool.pokeWeights();317 await mine_blocks(5);318 await smartpool.pokeWeights();319 await mine_blocks(200);320 await smartpool.pokeWeights();321 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");322 });323 describe("Adding tokens", async () => {324 let newToken: MockToken;325 beforeEach(async () => {326 // Pop off the last token for testing327 await smartpool.removeToken(tokens[tokens.length - 1].address);328 newToken = tokens[tokens.length - 1];329 });330 it("Weight update should cancel when removing token", async () => {331 // verify there is no current adjustment going on332 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");333 // start adjustment334 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);335 await smartpool.pokeWeights();336 // remove a token337 await smartpool.removeToken(tokens[tokens.length - 2].address);338 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");339 // weight adjustment should still work340 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);341 await smartpool.pokeWeights();342 });343 it("Weight update should cancel when adding token", async () => {344 // start adjustment345 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);346 await smartpool.pokeWeights();347 // add new token348 const balance = constants.WeiPerEther.mul(100);349 const weight = constants.WeiPerEther.mul(2);350 await smartpool.commitAddToken(newToken.address, balance, weight);351 await smartpool.pokeWeights();352 await smartpool.applyAddToken();353 // throws 'VM Exception while processing transaction: invalid opcode' @ f4aab193354 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");355 // weight adjustment should still work356 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);357 await smartpool.pokeWeights();358 });359 it("Weight update should cancel when calling bind", async () => {360 // start adjustment361 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);362 await smartpool.pokeWeights();363 // binding a token364 const mintAmount = constants.WeiPerEther.mul(1000000);365 const token: MockToken = await tokenFactory.deploy("Mock", "M", 18);366 await token.mint(account, mintAmount);367 await token.approve(smartpool.address, constants.MaxUint256);368 await smartpool.bind(token.address, constants.WeiPerEther, constants.WeiPerEther);369 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");370 // weight adjustment should still work371 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);372 await smartpool.pokeWeights();373 });374 it("Weight update should cancel when calling unbind", async () => {375 // start adjustment376 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);377 await smartpool.pokeWeights();378 // unbinding a token379 smartpool.unbind(tokens[0].address);380 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");381 // weight adjustment should still work382 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);383 await smartpool.pokeWeights();384 });385 it("Weight update should cancel when calling rebind", async () => {386 // start adjustment387 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);388 await smartpool.pokeWeights();389 // rebinding a token390 await smartpool.rebind(391 tokens[0].address,392 constants.WeiPerEther.mul(2),393 constants.WeiPerEther.mul(2)394 );395 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");396 // weight adjustment should still work397 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);398 await smartpool.pokeWeights();399 });400 it("Weight update should cancel when calling updateWeight (down)", async () => {401 // start adjustment402 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);403 await smartpool.pokeWeights();404 // updating weight down405 const weightsBefore = await smartpool.getDenormalizedWeights();406 await smartpool.updateWeight(tokens[0].address, weightsBefore[0].div(2))407 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");408 // weight adjustment should still work409 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);410 await smartpool.pokeWeights();411 });412 it("Weight update should cancel when calling updateWeight (up)", async () => {413 // start adjustment414 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);415 await smartpool.pokeWeights();416 // updating weight up417 const weightsBefore = await smartpool.getDenormalizedWeights();418 await smartpool.updateWeight(tokens[0].address, weightsBefore[0].mul(2))419 await expect(smartpool.pokeWeights()).to.be.revertedWith("ERR_WEIGHT_ADJUSTMENT_FINISHED");420 // weight adjustment should still work421 await smartpool.updateWeightsGradually(weigthsFixturePokeWeightsUp, startBlock, endBlock);422 await smartpool.pokeWeights();423 });424 it("commitAddToken should work", async () => {425 const balance = constants.WeiPerEther.mul(100);426 const weight = constants.WeiPerEther.mul(2);427 await smartpool.commitAddToken(newToken.address, balance, weight);428 const blockNumber = await ethers.provider.getBlockNumber();429 const newTokenStruct = await smartpool.getNewToken();430 expect(newTokenStruct.addr).to.eq(newToken.address);431 expect(newTokenStruct.isCommitted).to.eq(true);432 expect(newTokenStruct.balance).to.eq(balance);433 expect(newTokenStruct.denorm).to.eq(weight);434 expect(newTokenStruct.commitBlock).to.eq(blockNumber);435 });436 it("commitAddToken from a non controller should fail", async () => {437 await smartpool.setController(account2);438 await expect(439 smartpool.commitAddToken(newToken.address, new BigNumber(1), constants.WeiPerEther.mul(2))440 ).to.be.revertedWith("PV2SmartPool.onlyController: not controller");441 });442 it("Apply add token should work", async () => {443 const balance = constants.WeiPerEther.mul(100);444 const weight = constants.WeiPerEther.mul(2);445 await smartpool.commitAddToken(newToken.address, balance, weight);446 const blockNumber = await ethers.provider.getBlockNumber();447 const tokensBefore = await smartpool.getTokens();448 const totalWeightBefore = await pool.getTotalDenormalizedWeight();449 const totalSupplyBefore = await smartpool.totalSupply();450 const expectedMint = await totalSupplyBefore.mul(weight).div(totalWeightBefore);451 const userPoolBalanceBefore = await smartpool.balanceOf(account);452 await smartpool.applyAddToken();453 const newTokenStruct = await smartpool.getNewToken();454 const tokensAfter = await smartpool.getTokens();455 const poolNewTokenBalance = await newToken.balanceOf(pool.address);456 const totalWeightAfter = await pool.getTotalDenormalizedWeight();457 const totalSupplyAfter = await smartpool.totalSupply();458 const userPoolBalanceAfter = await smartpool.balanceOf(account);459 expect(newTokenStruct.addr).to.eq(newToken.address);460 expect(newTokenStruct.isCommitted).to.eq(false);461 expect(newTokenStruct.balance).to.eq(balance);462 expect(newTokenStruct.denorm).to.eq(weight);463 expect(newTokenStruct.commitBlock).to.eq(blockNumber);464 expect(tokensAfter.length).to.eq(tokensBefore.length + 1);465 expect(poolNewTokenBalance).to.eq(balance);466 expect(totalWeightAfter).to.eq(totalWeightBefore.add(weight));467 expect(totalSupplyAfter).to.eq(totalSupplyBefore.add(expectedMint));468 expect(userPoolBalanceAfter).to.eq(userPoolBalanceBefore.add(expectedMint));469 });470 });471 describe("removeToken", async () => {472 it("removeToken should work", async () => {473 const removedToken = tokens[0];474 const tokenWeight = await smartpool.getDenormalizedWeight(removedToken.address);475 const totalWeightBefore = await pool.getTotalDenormalizedWeight();476 const totalSupplyBefore = await smartpool.totalSupply();477 const userPoolBalanceBefore = await smartpool.balanceOf(account);478 const userTokenBalanceBefore = await removedToken.balanceOf(account);479 const poolTokenBalanceBefore = await removedToken.balanceOf(pool.address);480 const tokensBefore = await smartpool.getTokens();481 const expectedPoolBurn = totalSupplyBefore.mul(tokenWeight).div(totalWeightBefore);482 await smartpool.removeToken(removedToken.address);483 const totalWeightAfter = await pool.getTotalDenormalizedWeight();484 const totalSupplyAfter = await smartpool.totalSupply();485 const userPoolBalanceAfter = await smartpool.balanceOf(account);486 const userTokenBalanceAfter = await removedToken.balanceOf(account);487 const poolTokenBalanceAfter = await removedToken.balanceOf(pool.address);488 const tokensAfter = await smartpool.getTokens();489 expect(totalWeightAfter).to.eq(totalWeightBefore.sub(tokenWeight));490 expect(totalSupplyAfter).to.eq(totalSupplyBefore.sub(expectedPoolBurn));491 expect(userPoolBalanceAfter).to.eq(userPoolBalanceBefore.sub(expectedPoolBurn));492 expect(userTokenBalanceAfter).to.eq(userTokenBalanceBefore.add(poolTokenBalanceBefore));493 expect(poolTokenBalanceAfter).to.eq(0);494 expect(tokensAfter.length).to.eq(tokensBefore.length - 1);495 });496 it("removeToken should fail when controller does not have enough pool tokens", async () => {497 const removedToken = tokens[0];498 const balance = await smartpool.balanceOf(account);499 await smartpool.transfer(account2, balance);500 await expect(smartpool.removeToken(removedToken.address)).to.be.revertedWith(501 "ERR_INSUFFICIENT_BAL"502 );503 });504 it("removeToken should fail if underlying token transfer returns false", async () => {505 const removedToken = tokens[0];506 await removedToken.setTransferReturnFalse(true);507 await expect(smartpool.removeToken(removedToken.address)).to.be.revertedWith(508 "ERR_ERC20_FALSE"509 );510 });511 });512 describe("Setting joining and exiting enabled", async () => {513 it("setJoinExitEnabled should work", async () => {514 await smartpool.setJoinExitEnabled(true);515 const joinExitEnabled = await smartpool.getJoinExitEnabled();516 expect(joinExitEnabled).to.eq(true);517 });518 it("setJoinExitEnabled from a non controller address should fail", async () => {519 await smartpool.setController(account2);520 await expect(smartpool.setJoinExitEnabled(true)).to.be.revertedWith(521 "PV2SmartPool.onlyController: not controller"522 );523 });524 });525 describe("Circuit Breaker", async () => {526 it("setCircuitBreaker should work", async () => {527 await smartpool.setCircuitBreaker(account2);528 const circuitBreaker = await smartpool.getCircuitBreaker();529 expect(circuitBreaker).to.eq(account2);530 });531 it("setCircuitBreaker from a non controller should fail", async () => {532 await smartpool.setController(account2);533 await expect(smartpool.setCircuitBreaker(account2)).to.be.revertedWith(534 "PV2SmartPool.onlyController: not controller"535 );536 });537 it("tripCircuitBreaker should work", async () => {538 await smartpool.setCircuitBreaker(account);539 await smartpool.setPublicSwap(true);540 await smartpool.setJoinExitEnabled(true);541 await smartpool.tripCircuitBreaker();542 const publicSwapEnabled = await smartpool.isPublicSwap();543 const joinExitEnabled = await smartpool.getJoinExitEnabled();544 expect(publicSwapEnabled).to.eq(false);545 expect(joinExitEnabled).to.eq(false);546 });547 it("tripCircuitBreaker from a non circuitbreaker address should fail", async () => {548 await expect(smartpool.tripCircuitBreaker()).to.be.revertedWith(549 "PV2SmartPool.onlyCircuitBreaker: not circuit breaker"550 );551 });552 });553 describe("Join exit disabled enforcement", async () => {554 beforeEach(async () => {555 await smartpool.setPublicSwap(true);556 });557 it("joinPool", async () => {558 await expect(smartpool.joinPool(constants.WeiPerEther)).to.be.revertedWith(559 "PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled"560 );561 });562 it("joinPool with front running protection", async () => {563 await expect(564 smartpool["joinPool(uint256,uint256[])"](565 constants.WeiPerEther,566 createBigNumberArray(8, constants.Zero)567 )568 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");569 });570 it("exitPool", async () => {571 await expect(572 smartpool["exitPool(uint256)"](constants.WeiPerEther.div(2))573 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");574 });575 it("exitPool with frontrunning protection", async () => {576 await expect(577 smartpool["exitPool(uint256,uint256[])"](578 constants.WeiPerEther.div(2),579 createBigNumberArray(8, constants.MaxUint256)580 )581 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");582 });583 it("exitPoolTakingLoss", async () => {584 await expect(smartpool.exitPoolTakingloss(constants.WeiPerEther, [])).to.be.revertedWith(585 "PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled"586 );587 });588 it("joinswapExternAmountIn", async () => {589 await expect(590 smartpool.joinswapExternAmountIn(tokens[0].address, constants.WeiPerEther, constants.Zero)591 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");592 });593 it("joinswapPoolAmountOut", async () => {594 await expect(595 smartpool.joinswapPoolAmountOut(596 tokens[0].address,597 constants.WeiPerEther,598 constants.MaxUint256599 )600 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");601 });602 it("exitswapPoolAmountIn", async () => {603 await expect(604 smartpool.exitswapPoolAmountIn(tokens[0].address, constants.WeiPerEther, constants.Zero)605 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");606 });607 it("exitswapExternAmountOut", async () => {608 await expect(609 smartpool.exitswapExternAmountOut(tokens[0].address, constants.WeiPerEther, MaxUint256)610 ).to.be.revertedWith("PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled");611 });612 });613 describe("Annual Fee", async () => {614 it("Charging the fee should work [ @skip-on-coverage ]", async () => {615 const totalSupplyBefore = await smartpool.totalSupply();616 const feePercentage = parseEther("0.1");617 const beginTimeStamp = Math.floor(Date.now() / 1000) + 3600;618 const endTimeStamp = beginTimeStamp + 60 * 60 * 24 * 365;619 const expectedMint = totalSupplyBefore.mul(feePercentage).div(constants.WeiPerEther);620 await timeTraveler.setNextBlockTimestamp(beginTimeStamp);621 await smartpool.setAnnualFee(feePercentage);622 await timeTraveler.setNextBlockTimestamp(endTimeStamp);623 await smartpool.chargeOutstandingAnnualFee();624 const feeRecipientPoolBalanceAfter = await smartpool.balanceOf(constants.AddressZero);625 const totalSupplyAfter = await smartpool.totalSupply();626 expect(totalSupplyAfter).to.eq(totalSupplyBefore.add(expectedMint));627 expect(feeRecipientPoolBalanceAfter).to.eq(expectedMint);628 });629 it("Setting the fee should work", async () => {630 const newFee = parseEther("0.01");631 await smartpool.setAnnualFee(newFee);632 const actualFee = await smartpool.getAnnualFee();633 expect(actualFee).to.eq(newFee);634 });635 it("Setting the fee from a non controller should fail", async () => {636 const newFee = parseEther("0.01");637 await smartpool.setController(account2);638 await expect(smartpool.setAnnualFee(newFee)).to.be.revertedWith(639 "PV2SmartPool.onlyController: not controller"640 );641 });642 it("Setting the fee too high (10%) should fail", async () => {643 const newFee = parseEther("0.1000001");644 await expect(smartpool.setAnnualFee(newFee)).to.be.revertedWith(645 "LibFees.setAnnualFee: Annual fee too high"646 );647 });648 it("Setting the fee recipient should work", async () => {649 await smartpool.setFeeRecipient(account2);650 const newFeeRecipient = await smartpool.getFeeRecipient();651 expect(newFeeRecipient).to.eq(account2);652 });653 it("Setting the fee recipient from a non controller should fail", async () => {654 await smartpool.setController(account2);655 await expect(smartpool.setFeeRecipient(account2)).to.be.revertedWith(656 "PV2SmartPool.onlyController: not controller"657 );658 });659 it("Changing the fee should charge it [ @skip-on-coverage ]", async () => {660 const totalSupplyBefore = await smartpool.totalSupply();661 const feePercentage = parseEther("0.1");662 const beginTimeStamp = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 365 * 2;663 const endTimeStamp = beginTimeStamp + 60 * 60 * 24 * 365;664 const expectedMint = totalSupplyBefore.mul(feePercentage).div(constants.WeiPerEther);665 await timeTraveler.setNextBlockTimestamp(beginTimeStamp);666 await smartpool.setAnnualFee(feePercentage);667 await timeTraveler.setNextBlockTimestamp(endTimeStamp);668 await smartpool.setAnnualFee(parseEther("0.05"));669 const feeRecipientPoolBalanceAfter = await smartpool.balanceOf(constants.AddressZero);670 const totalSupplyAfter = await smartpool.totalSupply();671 expect(totalSupplyAfter).to.eq(totalSupplyBefore.add(expectedMint));672 expect(feeRecipientPoolBalanceAfter).to.eq(expectedMint);673 });674 });675 });676});677function createBigNumberArray(length: number, value: BigNumber): BigNumber[] {678 const result: BigNumber[] = [];679 for (let i = 0; i < length; i++) {680 result.push(value);681 }682 return result;683}684async function mine_blocks(amount: number) {685 for (let i = 0; i < amount; i++) {686 await ethers.provider.send("evm_mine", []);687 }...

Full Screen

Full Screen

votingTests_w8_6.js

Source:votingTests_w8_6.js Github

copy

Full Screen

1const {2 BN,3 constants,4 expectEvent,5 expectRevert,6 time,7} = require("@openzeppelin/test-helpers");8var jsonfile = require("jsonfile");9var baseContractList = jsonfile.readFileSync("contracts.json");10const {11 loadContracts,12 contractAddresseList,13} = require("./helper/dumpAddresses");14const pickleProxyABI = require("./helper/gaugeProxyABI_pickle.json");15const gaugeProxyABI = require("./helper/gaugeProxyABI.json");16const { hashMessage } = require("@ethersproject/hash");17const Reverter = require("./helper/reverter");18const BigNumber = require("bignumber.js");19const Booster = artifacts.require("Booster");20const VoterProxy = artifacts.require("VoterProxy");21const BaseRewardPool = artifacts.require("BaseRewardPool");22const VE3DRewardPool = artifacts.require("VE3DRewardPool");23const VE3Token = artifacts.require("VE3Token");24const VeToken = artifacts.require("VeToken");25const VeAssetDepositor = artifacts.require("VeAssetDepositor");26const IERC20 = artifacts.require("IERC20");27const IVoting = artifacts.require("IVoting");28function toBN(number) {29 return new BigNumber(number);30}31contract("Voting Test", async (accounts) => {32 let vetoken;33 let vetokenRewards;34 let veassetToken;35 let lpToken;36 let voterProxy;37 let booster;38 let veassetDepositor;39 let ve3Token;40 let ve3TokenRewardPool;41 let vote;42 let votestart;43 let controller;44 const reverter = new Reverter(web3);45 const eip1271MagicValue = "0x1626ba7e";46 const data = {47 data: {48 vote: {49 id: "QmeU7ct9Y4KLrh6F6mbT1eJNMkeQKMSnSujEfMCfbRLCMp",50 voter: "0x96176C25803Ce4cF046aa74895646D8514Ea1611",51 created: 1621183227,52 proposal: {53 id: "QmPvbwguLfcVryzBRrbY4Pb9bCtxURagdv1XjhtFLf3wHj",54 },55 choice: 1,56 space: {57 id: "spookyswap.eth",58 },59 },60 },61 };62 const msg = JSON.stringify(data);63 const hash = hashMessage(msg);64 const invalidHash = hashMessage(JSON.stringify({ ...data, version: "faux" }));65 before("setup", async () => {66 await loadContracts();67 vetoken = await VeToken.at(baseContractList.system.vetoken);68 vetokenRewards = await VE3DRewardPool.at(69 baseContractList.system.vetokenRewards70 );71 veassetToken = await IERC20.at(contractAddresseList[0]);72 lpToken = await IERC20.at(contractAddresseList[2]);73 voterProxy = await VoterProxy.at(contractAddresseList[3]);74 booster = await Booster.at(contractAddresseList[4]);75 ve3Token = await VE3Token.at(contractAddresseList[5]);76 veassetDepositor = await VeAssetDepositor.at(contractAddresseList[6]);77 ve3TokenRewardPool = await BaseRewardPool.at(contractAddresseList[7]);78 await reverter.snapshot();79 });80 afterEach("revert", reverter.revert);81 it("Test gauge weight voting functions", async () => {82 const userA = accounts[0];83 const userB = accounts[8];84 const controllerAddress = await voterProxy.gaugeProxy();85 console.log("controller, gauge controller address", controllerAddress);86 const poolId = 0;87 const poolInfo = JSON.stringify(await booster.poolInfo(poolId));88 const parsedPoolInfo = JSON.parse(poolInfo);89 //deposit veAsset90 const veAssetBalanceBefore = await veassetToken.balanceOf(userA);91 console.log("userA veasset balance:", veAssetBalanceBefore.toString());92 await veassetToken.approve(veassetDepositor.address, veAssetBalanceBefore, {93 from: userA,94 });95 await veassetDepositor.deposit(96 toBN(veAssetBalanceBefore).div(2),97 true,98 ve3TokenRewardPool.address,99 {100 from: userA,101 }102 );103 const veAssetBalanceAfter = await veassetToken.balanceOf(userA);104 console.log("userA veasset balance after:", veAssetBalanceAfter.toString());105 await veassetToken106 .balanceOf(veassetDepositor.address)107 .then((a) => console.log("depositor veassetToken: " + a));108 await veassetToken109 .balanceOf(voterProxy.address)110 .then((a) => console.log("voterProxy veassetToken: " + a));111 await time.increase(86400);112 await time.advanceBlock();113 console.log("advance time....");114 // test gauge weight voting115 console.log("gauge weight testing...");116 // case 1: vote as non-delegate(revert)117 await expectRevert(118 booster.voteGaugeWeight([parsedPoolInfo.gauge], [10000], { from: userB }),119 "revert"120 );121 // case 2: vote as delegate122 // PICKLE: https://etherscan.io/address/0x2e57627ACf6c1812F99e274d0ac61B786c19E74f#readContract123 if (controllerAddress == "0x2e57627ACf6c1812F99e274d0ac61B786c19E74f") {124 // check to make sure our voterProxy has dill(vePickle) so it can vote.125 const vePickleAddress = "0xbBCf169eE191A1Ba7371F30A1C344bFC498b29Cf";126 const vePickle = await IERC20.at(vePickleAddress);127 await vePickle128 .balanceOf(veassetDepositor.address)129 .then((a) => console.log("depositor vePickle: " + a));130 await vePickle131 .balanceOf(voterProxy.address)132 .then((a) => console.log("voterProxy vePickle >0: " + a));133 // show that weight power has changed134 const pickleProxyControllerContract = new web3.eth.Contract(135 pickleProxyABI,136 controllerAddress137 );138 const totalWeightBefore = await pickleProxyControllerContract.methods139 .totalWeight()140 .call();141 console.log("totalWeightBefore: " + totalWeightBefore.toString());142 await booster.voteGaugeWeight([lpToken.address], [10000]);143 const totalWeightAfter = await pickleProxyControllerContract.methods144 .totalWeight()145 .call();146 const votes = await pickleProxyControllerContract.methods147 .votes(voterProxy.address, lpToken.address)148 .call();149 console.log("votes: " + votes);150 console.log("totalWeightAfter: " + totalWeightAfter);151 assert.isAbove(Number(totalWeightAfter - totalWeightBefore), 0);152 }153 // IDLE: https://etherscan.io/address/0xaC69078141f76A1e257Ee889920d02Cc547d632f#readContract154 // Angle: https://etherscan.io/address/0x9aD7e7b0877582E14c17702EecF49018DD6f2367155 else {156 let controller = new web3.eth.Contract(gaugeProxyABI, controllerAddress);157 console.log("lptokenGauge info:", parsedPoolInfo.gauge);158 var voteInfoBefore = await controller.methods159 .vote_user_slopes(voterProxy.address, parsedPoolInfo.gauge)160 .call();161 console.log("gauge weight power before: " + voteInfoBefore[1]);162 await booster.voteGaugeWeight([parsedPoolInfo.gauge], [10]);163 const voteInfoAfter = await controller.methods164 .vote_user_slopes(voterProxy.address, parsedPoolInfo.gauge)165 .call();166 console.log("gauge weight power after: " + voteInfoAfter[1]);167 assert.isAbove(Number(voteInfoAfter[1] - voteInfoBefore[1]), 0);168 }169 });170 it("test snapshot voting with a valid hash", async () => {171 const voteSinger = accounts[5];172 const voteDelegateSigner = accounts[0];173 const sig = await web3.eth.sign(msg, voteSinger);174 await booster.setVote(hash, true, { from: voteDelegateSigner });175 let isValid = await voterProxy.isValidSignature(hash, sig);176 expect(isValid).to.equal(eip1271MagicValue);177 await booster.setVote(hash, false, { from: voteDelegateSigner });178 isValid = await voterProxy.isValidSignature(invalidHash, sig);179 expect(isValid).to.equal("0xffffffff");180 });181 it("test snapshot voting with an invalid hash", async () => {182 const voteSinger = accounts[4];183 const voteDelegateSigner = accounts[0];184 const sig = await web3.eth.sign(msg, voteSinger);185 await booster.setVote(hash, true, { from: voteDelegateSigner });186 const isValid = await voterProxy.isValidSignature(invalidHash, sig);187 expect(isValid).to.equal("0xffffffff");188 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { totalWeightBefore } = require('fast-check-monorepo');2const { totalWeightBefore } = require('fast-check');3const { totalWeightBefore } = require('fast-check-monorepo');4const { totalWeightBefore } = require('fast-check');5const { totalWeightBefore } = require('fast-check-monorepo');6const { totalWeightBefore } = require('fast-check');7const { totalWeightBefore } = require('fast-check-monorepo');8const { totalWeightBefore } = require('fast-check');9const { totalWeightBefore } = require('fast-check-monorepo');10const { totalWeightBefore } = require('fast-check');11const { totalWeightBefore } = require('fast-check-monorepo');12const { totalWeightBefore } = require('fast-check');13const { totalWeightBefore } = require('fast-check-monorepo');14const { totalWeightBefore } = require('fast-check');15const { totalWeightBefore } = require('fast-check-monorepo');16const { totalWeightBefore } = require('fast-check');17const { totalWeightBefore } = require('fast-check-monorepo');18const { totalWeightBefore } = require('fast-check');19const { totalWeightBefore } = require('fast-check-mon

Full Screen

Using AI Code Generation

copy

Full Screen

1const { totalWeightBefore } = require('fast-check-monorepo');2const { totalWeightBefore } = require('fast-check');3const { totalWeightBefore } = require('fast-check/lib/check/arbitrary/WeightedArbitrary');4const { totalWeightBefore } = require('./WeightedArbitrary');5const { totalWeightBefore } = require('./totalWeightBefore');6const totalWeightBefore = (index, weights) => {7 if (index === 0) return 0;8 if (index < 0 || index > weights.length) throw new Error('index out of range');9 let total = 0;10 for (let idx = 0; idx !== index; ++idx) total += weights[idx];11 return total;12};13const totalWeightBefore = (index, weights) => {14 if (index === 0) return 0;15 if (index < 0 || index > weights.length) throw new Error('index out of range');16 return weights.slice(0, index).reduce((total, weight) => total + weight, 0);17};18console.log(totalWeightBefore(0, [10, 20, 30]));19console.log(totalWeightBefore(1, [10, 20, 30]));20console.log(totalWeightBefore(2, [10, 20, 30]));21console.log(totalWeightBefore(3, [10, 20, 30]));22console.log(totalWeightBefore(0, [10, 20]));23console.log(totalWeightBefore(1, [10, 20]));24console.log(totalWeightBefore(2

Full Screen

Using AI Code Generation

copy

Full Screen

1import * as fc from 'fast-check';2import { WeightedArbitrary } from 'fast-check-monorepo/packages/arbitrary-weighted-choice/src/WeightedArbitrary';3const weightArb = new WeightedArbitrary(4 fc.string(),5 fc.integer(0, 100),6 (a, b) => a + b7);8const weightArb2 = new WeightedArbitrary(9 fc.string(),10 fc.integer(0, 100),11 (a, b) => a + b12);13const weightArb3 = new WeightedArbitrary(14 fc.string(),15 fc.integer(0, 100),16 (a, b) => a + b17);18const weightArb4 = new WeightedArbitrary(19 fc.string(),20 fc.integer(0, 100),21 (a, b) => a + b22);23const weightArb5 = new WeightedArbitrary(24 fc.string(),25 fc.integer(0, 100),26 (a, b) => a + b27);28const weightArb6 = new WeightedArbitrary(29 fc.string(),30 fc.integer(0, 100),31 (a, b) => a + b32);33const weightArb7 = new WeightedArbitrary(34 fc.string(),35 fc.integer(0, 100),36 (a, b) => a + b37);38const weightArb8 = new WeightedArbitrary(39 fc.string(),40 fc.integer(0, 100),41 (a, b) => a + b42);43const weightArb9 = new WeightedArbitrary(44 fc.string(),45 fc.integer(0, 100),46 (a, b) => a + b47);48const weightArb10 = new WeightedArbitrary(49 fc.string(),50 fc.integer(0, 100),51 (a, b) => a + b52);53const weightArb11 = new WeightedArbitrary(54 fc.string(),55 fc.integer(0, 100),56 (a, b) => a + b57);58const weightArb12 = new WeightedArbitrary(59 fc.string(),60 fc.integer(0, 100),61 (a, b) => a + b62);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { totalWeightBefore } = require('fast-check-monorepo');2const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);3console.log(sum);4const { totalWeightBefore } = require('fast-check-monorepo');5const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);6console.log(sum);7const { totalWeightBefore } = require('fast-check-monorepo');8const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);9console.log(sum);10const { totalWeightBefore } = require('fast-check-monorepo');11const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);12console.log(sum);13const { totalWeightBefore } = require('fast-check-monorepo');14const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);15console.log(sum);16const { totalWeightBefore } = require('fast-check-monorepo');17const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);18console.log(sum);19const { totalWeightBefore } = require('fast-check-monorepo');20const sum = totalWeightBefore([1, 2, 3, 4, 5, 6]);21console.log(sum);22const { totalWeightBefore } = require

Full Screen

Using AI Code Generation

copy

Full Screen

1const {totalWeightBefore} = require('fast-check-monorepo');2const {property} = require('fast-check');3property(4 [totalWeightBefore(100)],5 (values) => {6 }7);8const {totalWeightBefore} = require('fast-check-monorepo');9const {property} = require('fast-check');10property(11 [totalWeightBefore(100)],12 (values) => {13 }14);15const {totalWeightBefore} = require('fast-check-monorepo');16const {property} = require('fast-check');17property(18 [totalWeightBefore(100)],19 (values) => {20 }21);22const {totalWeightBefore} = require('fast-check-monorepo');23const {property} = require('fast-check');24property(25 [totalWeightBefore(100)],26 (values) => {27 }28);29const {totalWeightBefore} = require('fast-check-monorepo');30const {property} = require('fast-check');31property(32 [totalWeightBefore(100)],33 (values) => {34 }35);36const {totalWeightBefore} = require('fast-check-monorepo');37const {property} = require('fast-check');38property(39 [totalWeightBefore(100)],40 (values) => {41 }42);43const {totalWeightBefore} = require('fast-check-monorepo');44const {property} = require('fast-check');45property(46 [totalWeightBefore(100)],47 (values) => {48 }49);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fast-check-monorepo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful