Skip to content

Commit

Permalink
dynamic addresses generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Krishnakumarskr committed Mar 27, 2024
1 parent c9666e7 commit 78cc934
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 99 deletions.
191 changes: 101 additions & 90 deletions packages/sdk/tests/claim-yield-and-principal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import {
distributeFixedYieldVault,
getVaultEntities,
login,
toggleWindowCheck,
generateAddress,
whitelist,
TRASH_ADDRESS,
sleep
} from './utils/admin-ops';

config();
Expand All @@ -23,6 +25,8 @@ let walletSignerB: Signer | undefined = undefined;
let operatorSigner: Signer | undefined = undefined;
let custodianSigner: Signer | undefined = undefined;



let sdkA: CredbullSDK;
let sdkB: CredbullSDK;

Expand Down Expand Up @@ -64,36 +68,57 @@ test.beforeAll(async () => {
});

test.describe('Claim yield and principal - Fixed', async () => {
test('create vault', async () => {
await createFixedYieldVault();
await createFixedYieldVault();
});

test('Whitelist users', async () => {
await whitelist(userAddressA, userAId);
await whitelist(userAddressB, userBId);
});

test('Deposit to the vault', async () => {
test('Claim yield and principal - Fixed ', async () => {
const depositAmount = BigNumber.from('1000000000');

vaultAddress = await test.step('Get all vaults', async () => {
const vaults = await sdkA.getAllVaults();
const totalVaults = vaults.data.length;

expect(totalVaults).toBeGreaterThan(0);
expect(vaults).toBeTruthy();

const fixedYieldVaults = vaults.data.filter((vault: any) => vault.type === 'fixed_yield');
let treasuryAddresses: string[];
let activityRewardAddresses: string[];
let treasuryPrivateKey: string[];
let activityRewardPrivateKey: string[];

await test.step('Create fixed yield vault', async () => {
const { pkey: treasuryPkey, address: treasury } = generateAddress('treasury');
const { pkey: activityRewardPkey, address: activityReward } = generateAddress('activity_reward');
await createFixedYieldVault({
ADDRESSES_TREASURY: treasury,
ADDRESSES_ACTIVITY_REWARD: activityReward
});

const { pkey: treasuryPkey2, address: treasury2 } = generateAddress('treasury2');
const { pkey: activityRewardPkey2, address: activityReward2 } = generateAddress('activity_reward2');
await createFixedYieldVault({
ADDRESSES_TREASURY: treasury2,
ADDRESSES_ACTIVITY_REWARD: activityReward2
});

treasuryAddresses = [treasury, treasury2];
activityRewardAddresses = [activityReward, activityReward2];
treasuryPrivateKey = [treasuryPkey, treasuryPkey2];
activityRewardPrivateKey = [activityRewardPkey, activityRewardPkey2];
});

//sort by created_at
fixedYieldVaults.sort((a: any, b: any) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
expect(fixedYieldVaults).toBeTruthy();
await test.step('Whitelist users', async () => {
await whitelist(userAddressA, userAId);
await whitelist(userAddressB, userBId);
});

return [
fixedYieldVaults[fixedYieldVaults.length - 1].address,
fixedYieldVaults[fixedYieldVaults.length - 2].address,
];
vaultAddress = await test.step("Get vault and filter", async () => {
const vaults = await sdkA.getAllVaults();
const totalVaults = vaults.data.length;

expect(totalVaults).toBeGreaterThan(0);
expect(vaults).toBeTruthy();

const fixedYieldVaults = vaults.data.filter((vault: any) => vault.type === 'fixed_yield');

//sort by created_at
fixedYieldVaults.sort((a: any, b: any) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
expect(fixedYieldVaults).toBeTruthy();

return [
fixedYieldVaults[fixedYieldVaults.length - 1].address,
fixedYieldVaults[fixedYieldVaults.length - 2].address,
];
});

await test.step('Empty custodian', async () => {
Expand All @@ -102,23 +127,22 @@ test.describe('Claim yield and principal - Fixed', async () => {
const usdc = await sdkA.getAssetInstance(vaultAddress[i]);
const custodian = await vault.CUSTODIAN();
const custodianBalance = await usdc.balanceOf(custodian);
console.log('custodian balance', custodianBalance.toString());
console.log('signer address', await custodianSigner?.getAddress());
if (custodianBalance.gt(0))
usdc
.connect(custodianSigner as Signer)
.transfer('0xcabE80b332Aa9d900f5e32DF51cb0Bc5b276c556', custodianBalance);
console.log('custodian address', custodian);
console.log('custodian balance', (await usdc.balanceOf(custodian)).toString());
.transfer(TRASH_ADDRESS, custodianBalance);
}
});

await test.step('MINT USDC for user', async () => {
for (let i = 0; i < vaultAddress.length; i++) {
const vault = await sdkA.getVaultInstance(vaultAddress[i]);

console.log('got vault instance at mint usdc')

await __mockMint(userAddressA, depositAmount, vault, walletSignerA as Signer);
await sleep(1000);
await __mockMint(userAddressB, depositAmount, vault, walletSignerB as Signer);
await sleep(1000);
}
});

Expand All @@ -136,67 +160,54 @@ test.describe('Claim yield and principal - Fixed', async () => {
await sdkB.deposit(vaultAddress[i], depositAmount, userAddressB);
}
});
});

test('Distributioin of yield', async () => {
vaultAddress = await test.step('Get all vaults', async () => {
await test.step('Distribute yield', async () => {
const vaults = await sdkA.getAllVaults();
const totalVaults = vaults.data.length;

expect(totalVaults).toBeGreaterThan(0);
expect(vaults).toBeTruthy();

const fixedYieldVaults = vaults.data.filter((vault: any) => vault.type === 'fixed_yield');
expect(fixedYieldVaults).toBeTruthy();
for (let i = 0; i < vaultAddress.length; i++) {
const vault = await sdkA.getVaultInstance(vaultAddress[i]);
const custodian = await vault.CUSTODIAN();
await __mockMint(custodian, BigNumber.from('1000000000'), vault, walletSignerA as Signer);

const usdc = await sdkA.getAssetInstance(vaultAddress[i]);

return [
fixedYieldVaults[fixedYieldVaults.length - 1].address,
fixedYieldVaults[fixedYieldVaults.length - 2].address,
];
//Get vault id
const vaultId = vaults.data.find((v: any) => v.address === vaultAddress[i])?.id;

console.log('vault entities', await getVaultEntities(vaultId));

console.log(treasuryAddresses, activityRewardAddresses);

//Clean up treasury and activity reward balances
const treasuryBalance = await usdc.balanceOf(treasuryAddresses[i]);
const activityRewardBalance = await usdc.balanceOf(activityRewardAddresses[i]);

const treasurySigner = signer(treasuryPrivateKey[i]);
const activityRewardSigner = signer(activityRewardPrivateKey[i]);
if(treasuryBalance.gt(0))
await usdc.connect(treasurySigner).transfer(TRASH_ADDRESS, treasuryBalance);
await sleep(1000);
if(activityRewardBalance.gt(0))
await usdc.connect(activityRewardSigner).transfer(TRASH_ADDRESS, activityRewardBalance);
await sleep(1000);
}

await distributeFixedYieldVault();

for (let i = 0; i < vaultAddress.length; i++) {
const usdc = await sdkA.getAssetInstance(vaultAddress[i]);
const treasuryBalanceAfterDistribution = await usdc.balanceOf(treasuryAddresses[i]);
const activityRewardBalanceAfterDistribution = await usdc.balanceOf(activityRewardAddresses[i]);

console.log(treasuryBalanceAfterDistribution.toString(), activityRewardBalanceAfterDistribution.toString());

expect(treasuryBalanceAfterDistribution.toString()).toEqual(
(BigNumber.from('640000000')).toString(),
);
expect(activityRewardBalanceAfterDistribution.toString()).toEqual(
(BigNumber.from('160000000')).toString(),
);
}
});

const vaults = await sdkA.getAllVaults();

let treasuryAddresses = [];
let activityRewardAddresses = [];
let treasuryBalances = [];
let activityRewardBalances = [];
for (let i = 0; i < vaultAddress.length; i++) {
const vault = await sdkA.getVaultInstance(vaultAddress[i]);
const custodian = await vault.CUSTODIAN();
await __mockMint(custodian, BigNumber.from('1000000000'), vault, walletSignerA as Signer);

const usdc = await sdkA.getAssetInstance(vaultAddress[i]);
const id = vaults.data.find((vault: any) => vault.address === vaultAddress[i]).id;
const entities = await getVaultEntities(String(id));

const treasuryAddress = entities.data.find((entity: any) => entity.type === 'treasury').address;
const activityRewardAddress = entities.data.find((entity: any) => entity.type === 'activity_reward').address;

treasuryAddresses.push(treasuryAddress);
activityRewardAddresses.push(activityRewardAddress);

treasuryBalances.push(await usdc.balanceOf(treasuryAddress));
activityRewardBalances.push(await usdc.balanceOf(activityRewardAddress));

console.log(treasuryBalances[i].toString(), activityRewardBalances[i].toString());
}

await distributeFixedYieldVault();

for (let i = 0; i < vaultAddress.length; i++) {
const usdc = await sdkA.getAssetInstance(vaultAddress[i]);
const treasuryBalanceAfterDistribution = await usdc.balanceOf(treasuryAddresses[i]);
const activityRewardBalanceAfterDistribution = await usdc.balanceOf(activityRewardAddresses[i]);

console.log(treasuryBalanceAfterDistribution.toString(), activityRewardBalanceAfterDistribution.toString());

expect(treasuryBalanceAfterDistribution.toString()).toEqual(
treasuryBalances[i].add(BigNumber.from('640000000').mul(2)).toString(),
);
expect(activityRewardBalanceAfterDistribution.toString()).toEqual(
activityRewardBalances[i].add(BigNumber.from('160000000').mul(2)).toString(),
);
}
});
});
9 changes: 5 additions & 4 deletions packages/sdk/tests/multi-user-deposit.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Multi user deposit test similar to deposit.spec.ts
import { expect, test } from '@playwright/test';
import { config } from 'dotenv';
import { BigNumber, Signer, constants } from 'ethers';
import { BigNumber, Signer } from 'ethers';

import { CredbullSDK } from '../index';
import { signer } from '../mock/utils/helpers';

import { __mockMint, createFixedYieldVault, login, toggleWindowCheck, whitelist } from './utils/admin-ops';
import { TRASH_ADDRESS, __mockMint, createFixedYieldVault, generateAddress, login, toggleWindowCheck, whitelist } from './utils/admin-ops';

config();

Expand Down Expand Up @@ -59,7 +59,8 @@ test.describe('Multi user Interaction - Fixed', async () => {
test('Deposit and redeem flow', async () => {
const depositAmount = BigNumber.from('100000000');

await test.step('Create upside vault', async () => {

await test.step('Create Fixed yeild vault', async () => {
await createFixedYieldVault();
});

Expand Down Expand Up @@ -89,7 +90,7 @@ test.describe('Multi user Interaction - Fixed', async () => {
const custodianBalance = await usdc.balanceOf(custodian);
console.log('custodian balance', custodianBalance.toString());
console.log('signer address', await custodianSigner?.getAddress());
usdc.connect(custodianSigner as Signer).transfer('0xcabE80b332Aa9d900f5e32DF51cb0Bc5b276c556', custodianBalance);
usdc.connect(custodianSigner as Signer).transfer(TRASH_ADDRESS, custodianBalance);
console.log('custodian address', custodian);
console.log('custodian balance', (await usdc.balanceOf(custodian)).toString());
});
Expand Down
48 changes: 43 additions & 5 deletions packages/sdk/tests/utils/admin-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,57 @@ import {
} from '@credbull/contracts';
import * as ChildProcess from 'child_process';
import { config } from 'dotenv';
import { BigNumber, Signer, Wallet, providers } from 'ethers';
import { BigNumber, Signer, Wallet, providers, utils } from 'ethers';
import path from 'path';

config();

export async function createFixedYieldVault() {
export const TRASH_ADDRESS = "0xcabE80b332Aa9d900f5e32DF51cb0Bc5b276c556"

export const generateAddress = (name: string) => {
const hash = utils.id(name);
const hashBuffer = Buffer.from(hash.slice(2), 'hex');
const paddedHash = utils.hexlify(utils.zeroPad(hashBuffer, 32));
const privateKey = `${utils.hexlify(paddedHash)}`;
const wallet = new Wallet(privateKey);
return { pkey: privateKey, address: wallet.address };
};

function envCleanup(existing: any, newEnv: any) {
//Find keys of newEnv that are in existing and replace it with the new value
for (const key in newEnv) {
if (Object.prototype.hasOwnProperty.call(existing, key)) {
if (existing.hasOwnProperty(key)) {
existing[key] = newEnv[key];
}
} else {
existing[key] = newEnv[key];
}
}

return existing;
}

export async function createFixedYieldVault(envs?: any) {
let cleanedUpEnvs = JSON.parse(JSON.stringify(process.env));
if(envs !== undefined) {
cleanedUpEnvs = JSON.parse(JSON.stringify(envCleanup(cleanedUpEnvs, envs)));
}

ChildProcess.execSync('yarn op --create-vault matured', {
env: { ...process.env },
env: { ...cleanedUpEnvs },
cwd: path.resolve(__dirname, '../../../../scripts/operation'),
});
}

export async function createUpsideVaultVault() {
export async function createUpsideVaultVault(envs?: any) {
let cleanedUpEnvs = JSON.parse(JSON.stringify(process.env));
if(envs !== undefined) {
cleanedUpEnvs = JSON.parse(JSON.stringify(envCleanup(cleanedUpEnvs, envs)));
}

ChildProcess.execSync('yarn op --create-vault upside upsideVault:self', {
env: { ...process.env },
env: { ...cleanedUpEnvs },
cwd: path.resolve(__dirname, '../../../../scripts/operation'),
});
}
Expand Down Expand Up @@ -106,3 +142,5 @@ export async function toggleWindowCheck(
export async function getAdminSigner() {
return new Wallet(process.env.ADMIN_PRIVATE_KEY_SDK || '', new providers.JsonRpcProvider(`http://localhost:8545`));
}

export async function sleep(ms: number) { new Promise(resolve => setTimeout(resolve, ms)) };

0 comments on commit 78cc934

Please sign in to comment.