Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Partial fills #26

Open
wants to merge 9 commits into
base: partial_fills
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 6 additions & 7 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ module.exports = {
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
rules: {
'comma-spacing': ['error', { before: false, after: true }],
'prettier/prettier': 'error',
'mocha-no-only/mocha-no-only': ['error'],
'prettier/prettier': [
'error',
{
endOfFile: 'auto',
},
],
},
'prettier/prettier': [
'errors',
{
endOfFile: 'auto',
},
],
};
22 changes: 22 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"configurations": [
{
"args": [
"-u",
"tdd",
"--timeout",
"999999",
"--colors",
"${pkg/deployments/testprimary}/test"
],
"internalConsoleOptions": "openOnSessionStart",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"request": "launch",
"skipFiles": [
"<node_internals>/**"
],
"type": "node"
}
]
}
4 changes: 4 additions & 0 deletions pkg/deployments/ci/prepare-config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import path from 'path';
import { homedir } from 'os';
import { mkdirSync, writeFileSync } from 'fs';
// import dotenv from 'dotenv';

// dotenv.config();


const HH_CONFIG_FILENAME = `${homedir()}/.hardhat/networks.json`;

Expand Down
18 changes: 14 additions & 4 deletions pkg/deployments/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"lint": "eslint . --ext .ts --ignore-path ../../.eslintignore --max-warnings 0",
"prepack": "yarn build",
"test": "hardhat test ./**/test/*.ts",
"testprimary" : "hardhat test ./tasks/20220415-primary-issue-pool/test/*.ts",
"testprimary": "hardhat test ./tasks/20220415-primary-issue-pool/test/*.ts",
"ci:prepare-config": "ts-node ci/prepare-config.ts"
},
"devDependencies": {
Expand All @@ -37,25 +37,35 @@
"@nomiclabs/hardhat-ethers": "^2.0.1",
"@nomiclabs/hardhat-etherscan": "latest",
"@solidity-parser/parser": "^0.14.0",
"@types/chai": "^4.2.12",
"@types/dotenv": "^8.2.0",
"@types/lodash": "^4.14.181",
"@types/lodash.range": "^3",
"@types/mocha": "^8.0.3",
"@types/node": "^14.6.0",
"@typescript-eslint/eslint-plugin": "^4.1.1",
"@typescript-eslint/parser": "^4.1.1",
"chai": "^4.2.0",
"chalk": "^4.1.1",
"eslint": "^7.9.0",
"eslint-plugin-prettier": "^3.1.4",
"ethers": "^5.4.1",
"hardhat": "^2.8.3",
"hardhat": "v2.12.6",
"hardhat-local-networks-config-plugin": "0.0.5",
"lodash.range": "^3.2.0",
"mocha": "v10.0.0",
"node-fetch": "^2.6.1",
"prettier": "^2.1.2",
"prettier": "^2.7.2",
"ts-node": "^8.10.2",
"typescript": "^4.0.2"
},
"peerDependencies": {
"@nomiclabs/hardhat-ethers": "^2.0.1",
"hardhat": "^2.8.3"
"hardhat": "v2.12.6"
},
"dependencies": {
"@balancer-labs/v2-vault": "workspace:*",
"dotenv": "^16.3.1",
"ethereum-waffle": "^4.0.10"
}
}
213 changes: 179 additions & 34 deletions pkg/deployments/tasks/20220415-primary-issue-pool/test/test.fork.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import hre from 'hardhat';
import { ethers } from 'ethers';
import { expect } from 'chai';
import { Contract, BigNumber } from 'ethers';
import { WeightedPoolEncoder, SwapKind } from '@balancer-labs/balancer-js';
Expand All @@ -12,21 +13,22 @@ import { getSigner, impersonate, impersonateWhale } from '../../../src/signers';
import { MAX_UINT256 } from '@balancer-labs/v2-helpers/src/constants';
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/dist/src/signer-with-address';

describeForkTest('PrimaryPoolFactory', 'goerli', 8586768, function () {
describeForkTest('PrimaryPoolFactory', 'mainnet', 8586768, function () {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vinaykumar0103 we do not have a deployment of the primary pool on mainnet. It is on goerli, can you check with goerli ? The VCUSD and other addresses are also for goerli only.

let owner: SignerWithAddress, whale: SignerWithAddress;
let factory: Contract, vault: Contract, authorizer: Contract, usdc: Contract, vcusd: Contract, usdt: Contract;

let task: Task;

const VCUSD = '0xa6aa25115f23F3ADc4471133bbDC401b613DbF65';
const USDC = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';
const VCUSD = '0xa6aa25115f23F3ADc4471133bbDC401b613DbF65';
const USDT = '0xdac17f958d2ee523a2206206994597c13d831ec7';

const tokens = [USDC, VCUSD];
const swapFeePercentage = fp(0.01);
const initialBalanceVCUSD = fp(1e18); //18 digits
const initialBalanceUSDC = fp(1e6).div(1e12); // 6 digits
const initialBalances = [initialBalanceVCUSD, initialBalanceUSDC];
const initialBalanceVCUSD = fp(1e18); //18 digits

const initialBalances = [, initialBalanceUSDC, initialBalanceVCUSD];

const minimumPrice = fp(8);
const minimumOrderSize = fp(1);
Expand All @@ -48,33 +50,53 @@ describeForkTest('PrimaryPoolFactory', 'goerli', 8586768, function () {
before('setup contracts', async () => {
vault = await new Task('20210418-vault', TaskMode.READ_ONLY, getForkedNetwork(hre)).deployedInstance('Vault');
authorizer = await new Task('20210418-authorizer', TaskMode.READ_ONLY, getForkedNetwork(hre)).deployedInstance(
'Authorizer'
'Authorizer'
);

vcusd = await task.instanceAt('IERC20', VCUSD);
``

usdc = await task.instanceAt('IERC20', USDC);
vcusd = await task.instanceAt('IERC20', VCUSD);
usdt = await task.instanceAt('IERC20', USDT);

await usdc.connect(whale).approve(vault.address, MAX_UINT256);
await vcusd.connect(whale).approve(vault.address, MAX_UINT256);
await usdt.connect(whale).approve(vault.address, MAX_UINT256);


});

describe('create and swap', () => {
let pool: Contract;
let poolId: string;

it('deploy a primary issue pool', async () => {
const tx = await factory.create({name: 'Verified Pool Token', symbol: 'VPT', security: usdc.address, currency: vcusd.address, minimumPrice: minimumPrice, minimumOrderSize: minimumOrderSize, maxAmountsIn: maxSecurityOffered, swapFeePercentage: swapFeePercentage, cutOffTime: issueCutoffTime, offeringDocs: offeringDocs});
const event = expectEvent.inReceipt(await tx.wait(), 'PoolCreated');
it('deploy a primary issue pool', async () => {
try {
const tx = await factory.create({
name: 'Verified Pool Token', symbol: 'VPT', security: usdc.address, currency: vcusd.address, minimumPrice: minimumPrice, minimumOrderSize: minimumOrderSize, maxAmountsIn: maxSecurityOffered, swapFeePercentage: swapFeePercentage, cutOffTime: issueCutoffTime, offeringDocs: offeringDocs, initialBalances: initialBalances,
});
console.log(await tx.wait());
const event = await expectEvent.inReceipt(await tx.wait(), 'PoolCreated');

pool = await task.instanceAt('PrimaryIssuePool', event.args.pool);
expect(await factory.isPoolFromFactory(pool.address)).to.be.true;
const pool = await task.instanceAt('PrimaryIssuePool', event.args.pool);
expect(await factory.isPoolFromFactory(pool.address)).to.be.true;

poolId = await pool.getPoolId();
const [registeredAddress] = await vault.getPool(poolId);
expect(registeredAddress).to.equal(pool.address);
poolId = await pool.getPoolId();
const [registeredAddress] = await vault.getPool(poolId);
expect(registeredAddress).to.equal(pool.address);
} catch (error: any) {
console.error('Error deploying primary issue pool:', error.message);
throw error;
}
});

it('initialize the pool', async () => {
await vcusd.connect(whale).approve(vault.address, MAX_UINT256);


it('Initialize the pool', async () => {
await usdc.connect(whale).approve(vault.address, MAX_UINT256);
await usdc.connect(whale).approve(vault.address, MAX_UINT256);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vinaykumar0103 should this approval be for VCUSD ? We already have given approval for USDC in the above line.




const userData = WeightedPoolEncoder.joinInit(initialBalances);
await vault.connect(whale).joinPool(poolId, whale.address, owner.address, {
Expand All @@ -86,27 +108,150 @@ describeForkTest('PrimaryPoolFactory', 'goerli', 8586768, function () {

const { balances } = await vault.getPoolTokens(poolId);
expect(balances).to.deep.equal(initialBalances);

});


it('swap in the pool', async () => {
const amount = fp(500);
await vcusd.connect(whale).transfer(owner.address, amount);
await vcusd.connect(owner).approve(vault.address, amount);

await vault
.connect(owner)
.swap(
{ kind: SwapKind.GivenIn, poolId, assetIn: VCUSD, assetOut: USDC, amount, userData: '0x' },
{ sender: owner.address, recipient: owner.address, fromInternalBalance: false, toInternalBalance: false },
0,
MAX_UINT256
);

// Assert pool swap
const expectedUSDC = amount.div(1e12);
expectEqualWithError(await vcusd.balanceOf(owner.address), 0, 0.0001);
expectEqualWithError(await usdc.balanceOf(owner.address), expectedUSDC, 0.1);
try {
const amount = fp(500);


// const balance = await vcusd.balanceOf(owner.address);
// console.log("Owner's VCUSD balance: ", balance.toString());

// if (balance.lt(amount)) {
// throw new Error('Insufficient VCUSD balance for the swap');
// }

// if ((await vcusd.balanceOf(owner.address)).lt(amount)) {
// throw new Error('Insufficient VCUSD balance for the swap');
// }


await usdc.connect(whale).transfer(owner.address, amount);
await usdc.connect(owner).approve(vault.address, amount);

await vault
.connect(owner)
.swap(
{ kind: SwapKind.GivenIn, poolId, assetIn: usdc, assetOut: usdc, amount, userData: '0x' },
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vinaykumar0103 swap assetIn and assetOut are the same ? They should be different. And 'amount' of assets swapped in should be there in balance.

{ sender: owner.address, recipient: owner.address, fromInternalBalance: false, toInternalBalance: false },
0,
MAX_UINT256
);

// owner's VCUSD balance
// console.log("Owner's VCUSD balance: ", (await vcusd.balanceOf(owner.address)).toString());

// Assert pool swap
const expectedUSDC = amount.div(1e12);
expectEqualWithError(await usdc.balanceOf(owner.address), 0, 0.0001);
expectEqualWithError(await usdc.balanceOf(owner.address), expectedUSDC, 0.1);
} catch (error) {
console.error('An error occurred:', error);
throw error; //
}
});

it('check owner balance', async () => {
try {
const ownerAddress = owner.address;

const provider = new ethers.providers.JsonRpcProvider();
const ownerBalance = await provider.getBalance(ownerAddress);
console.log("Owner's ETH balance: ", ownerBalance.toString());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vinaykumar0103 why are you checking ETH balance ? You should check if swapped in asset balance is available. assetIn and assetOut (ie, USDC and VCUSD) are ERC20 tokens.

} catch (error) {
console.error('An error occurred while checking owner balance:', error);
throw error;
}
});
});


// it('should allow swapping tokens with fees distributed to the pool', async () => {
// const amount = fp(500);
// const feePercentage = fp(0.01); // 1% fee
// const initialPoolTokenBalance = await pool.balanceOf(owner.address);

// // Transfer tokens to the owner's address
// await vcusd.connect(whale).transfer(owner.address, amount);
// await vcusd.connect(owner).approve(vault.address, amount);

// // Execute a swap with fees
// await vault
// .connect(owner)
// .swap(
// { kind: SwapKind.GivenIn, poolId, assetIn: VCUSD, assetOut: USDC, amount, userData: '0x' },
// { sender: owner.address, recipient: owner.address, fromInternalBalance: false, toInternalBalance: false },
// 0,
// MAX_UINT256
// );

// // Calculate the expected fee amount
// const expectedFee = amount.mul(feePercentage);

// // Check the updated balances
// const finalPoolTokenBalance = await pool.balanceOf(owner.address);
// const finalUSDCBalance = await usdc.balanceOf(owner.address);

// // The pool token balance should have increased by the fee amount
// expect(finalPoolTokenBalance).to.equal(initialPoolTokenBalance.add(expectedFee));

// // The USDC balance should have decreased by the swapped amount
// expectEqualWithError(await vcusd.balanceOf(owner.address), 0, 0.0001);
// expectEqualWithError(await usdc.balanceOf(owner.address), expectedFee, 0.1);
// });



// describe('should swapSecurityIn', function () {
// it('swap security tokens for currency tokens', async function () {
// await TokenSwap(pool, owner, 'Security', 'Currency');
// });
// });

// describe('swapSecurityOut', function () {
// it('should swap security tokens out for currency tokens', async function () {
// await TokenSwap(pool, owner, 'Currency', 'Security');
// });
// });

// describe('swapCurrencyIn', function () {
// it('should swap currency tokens in for security tokens', async function () {
// await TokenSwap(pool, owner, 'Currency', 'Security');
// });
// });

// describe('swapCurrencyOut', function () {
// it('should swap currency tokens out for security tokens', async function () {
// await TokenSwap(pool, owner, 'Security', 'Currency');
// });
// });

// const TokenSwap = async (pool: Contract, owner: SignerWithAddress, fromToken: string, toToken: string) => {
// // amount of tokens to swap
// const amountTokens = 100;

// // Get initial balances of tokens for the owner
// const initialFromBalance = await pool.balanceOf(owner.address, fromToken);
// const initialToBalance = await pool.balanceOf(owner.address, toToken);

// // Approve the contract to spend tokens from the owner's account
// await pool.connect(owner).approveTokens(amountTokens, fromToken);

// // Execute the swap
// const result = await pool.connect(owner).swapTokensIn(amountTokens, fromToken, toToken);

// // Get updated balances after the swap
// const updatedFromBalance = await pool.balanceOf(owner.address, fromToken);
// const updatedToBalance = await pool.balanceOf(owner.address, toToken);

// // Assertions to check the result of the swap
// expect(updatedFromBalance).to.equal(initialFromBalance.sub(amountTokens)); // Tokens were deducted from the 'from' balance
// expect(updatedToBalance).to.be.greaterThan(initialToBalance); // Tokens were received in the 'to' balance

// // Assertions to check the result of the swap
// expect(updatedFromBalance).to.equal(initialFromBalance.sub(amountTokens)); // Tokens were deducted from the 'from' balance
// expect(updatedToBalance).to.be.greaterThan(initialToBalance);
// };
});
19 changes: 15 additions & 4 deletions pkg/deployments/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,18 @@
"outDir": "dist",
"resolveJsonModule": true
},
"include": ["index.ts", "src", "tasks/**/abi/*.json", "tasks/**/bytecode/*.json", "tasks/**/output/*.json"],
"exclude": ["tasks/**/test", "tasks/**/output/test.json"],
"files": ["./hardhat.config.ts"]
}
"include": [
"index.ts",
"src",
"tasks/**/abi/*.json",
"tasks/**/bytecode/*.json",
"tasks/**/output/*.json"
],
"exclude": [
"tasks/**/test",
"tasks/**/output/test.json"
],
"files": [
"./hardhat.config.ts"
]
}