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

Create lending pool add and remove liquidity transactions #83

Open
wants to merge 4 commits into
base: fix/swap-examples
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions dist/folks-lending-pools/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,21 @@ import { FolksLendingPool } from "./types";
/**
* Calculates the amount fAsset received when adding liquidity with original asset.
*/
declare function calculateDepositReturn(depositAmount: number, depositInterestIndex: bigint, depositInterestRate: bigint, lastUpdate?: number): bigint;
declare function calculateDepositReturn({ depositAmount, depositInterestIndex, depositInterestRate, lastUpdate }: {
depositAmount: number;
depositInterestIndex: bigint;
depositInterestRate: bigint;
lastUpdate?: number;
}): bigint;
/**
* Calculates the amount original asset received when removing liquidity from fAsset pool.
*/
declare function calculateWithdrawReturn(withdrawAmount: number, depositInterestIndex: bigint, depositInterestRate: bigint, lastUpdate?: number): bigint;
declare function calculateWithdrawReturn({ withdrawAmount, depositInterestIndex, depositInterestRate, lastUpdate }: {
withdrawAmount: number;
depositInterestIndex: bigint;
depositInterestRate: bigint;
lastUpdate?: number;
}): bigint;
/**
* Fetches Folks lending pool application info from the algod, parses the global state and builds FolksLendingPool object.
*/
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions dist/util/pool/common/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ export declare function getPoolShare(totalLiquidity: bigint, ownedLiquidity: big
/**
* Calculates the pair ratio for the pool reserves
*/
export declare function getPoolPairRatio(decimals: {
asset1: undefined | number;
asset2: undefined | number;
}, reserves: null | PoolReserves): null | number;
export declare function getPoolPairRatio(reserves: null | PoolReserves): null | number;
/**
* Checks if the pool is empty
*
Expand Down
15 changes: 3 additions & 12 deletions dist/util/pool/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
export declare const poolUtils: {
getPoolShare(totalLiquidity: bigint, ownedLiquidity: bigint): number;
getPoolPairRatio(decimals: {
asset1: number | undefined;
asset2: number | undefined;
}, reserves: import("./poolTypes").PoolReserves | null): number | null;
getPoolPairRatio(reserves: import("./poolTypes").PoolReserves | null): number | null;
isPoolEmpty(poolReserves: import("./poolTypes").PoolReserves | null | undefined): boolean;
isPoolNotCreated(pool: import("./poolTypes").V1PoolInfo | import("./poolTypes").V2PoolInfo | null | undefined): boolean;
isPoolReady(pool: import("./poolTypes").V1PoolInfo | import("./poolTypes").V2PoolInfo | null | undefined): boolean;
Expand All @@ -15,10 +12,7 @@ export declare const poolUtils: {
}): Promise<[import("./poolTypes").V1PoolInfo, import("./poolTypes").V2PoolInfo]>;
v1_1: {
getPoolShare(totalLiquidity: bigint, ownedLiquidity: bigint): number;
getPoolPairRatio(decimals: {
asset1: number | undefined;
asset2: number | undefined;
}, reserves: import("./poolTypes").PoolReserves | null): number | null;
getPoolPairRatio(reserves: import("./poolTypes").PoolReserves | null): number | null;
isPoolEmpty(poolReserves: import("./poolTypes").PoolReserves | null | undefined): boolean;
isPoolNotCreated(pool: import("./poolTypes").V1PoolInfo | import("./poolTypes").V2PoolInfo | null | undefined): boolean;
isPoolReady(pool: import("./poolTypes").V1PoolInfo | import("./poolTypes").V2PoolInfo | null | undefined): boolean;
Expand All @@ -43,10 +37,7 @@ export declare const poolUtils: {
};
v2: {
getPoolShare(totalLiquidity: bigint, ownedLiquidity: bigint): number;
getPoolPairRatio(decimals: {
asset1: number | undefined;
asset2: number | undefined;
}, reserves: import("./poolTypes").PoolReserves | null): number | null;
getPoolPairRatio(reserves: import("./poolTypes").PoolReserves | null): number | null;
isPoolEmpty(poolReserves: import("./poolTypes").PoolReserves | null | undefined): boolean;
isPoolNotCreated(pool: import("./poolTypes").V1PoolInfo | import("./poolTypes").V2PoolInfo | null | undefined): boolean;
isPoolReady(pool: import("./poolTypes").V1PoolInfo | import("./poolTypes").V2PoolInfo | null | undefined): boolean;
Expand Down
16 changes: 8 additions & 8 deletions examples/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"author": "Tinyman Core Team",
"license": "ISC",
"dependencies": {
"algosdk": "^2.1.0",
"@tinymanorg/tinyman-js-sdk": "^3.1.0"
"algosdk": "^2.7.0",
"@tinymanorg/tinyman-js-sdk": "^3.1.1"
},
"devDependencies": {
"@types/node": "^18.8.5",
Expand Down
53 changes: 50 additions & 3 deletions examples/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import {removeLiquidityWithSingleAssetOut} from "./operation/remove-liquidity/re
import {fixedInputSwap} from "./operation/swap/fixedInputSwap";
import {fixedOutputSwap} from "./operation/swap/fixedOutputSwap";
import {getAccount} from "./util/account";
import {getAssetParams} from "./util/asset";
import {getAssetBalance, getAssetParams, getIsAccountOptedIntoAsset} from "./util/asset";
import {assertAccountHasBalance, executeAssetOptIn} from "./util/other";
import {lendingPoolAddLiquidity} from "./operation/lending-pool/add-liquidity/lendingPoolAddLiquidity";
import {lendingPoolRemoveLiquidity} from "./operation/lending-pool/remove-liquidity/lendingPoolRemoveLiquidity";

/**
* Will run all the operations in the order they are defined
Expand All @@ -20,10 +23,10 @@ async function main() {
const {asset_1, asset_2} = await getAssetParams();

// Create the pool with the owned assets
// await bootstrapPool({ account, asset_1, asset_2 });
await bootstrapPool({account, asset_1, asset_2});

// Add some initial liquidity to the pool
// await addInitialLiquidity({account, asset_1, asset_2});
await addInitialLiquidity({account, asset_1, asset_2});

// Add subsequent liquidity to the pool using the flexible mode
await addFlexibleLiquidity({account, asset_1, asset_2});
Expand All @@ -43,6 +46,50 @@ async function main() {
// Swap assets with fixed output
await fixedOutputSwap({account, asset_1, asset_2});

const shouldIncludeLendingPoolExamples = true;

if (shouldIncludeLendingPoolExamples) {
const algoAsset = {
id: "0",
unit_name: "ALGO",
fAsset_id: "147171698",
folks_lending_pool_application_id: "147169673"
};
const usdcAsset = {
id: "67395862",
unit_name: "USDC",
fAsset_id: "147171826",
folks_lending_pool_application_id: "147170678"
};

// Check if the user has enough ALGO balance
const minAlgoAmount = 3_000_000;

await assertAccountHasBalance(account.addr, minAlgoAmount);

// Check if the user is opted into the USDC asset, if not, opt-in
if (!(await getIsAccountOptedIntoAsset(account.addr, Number(usdcAsset.id)))) {
await executeAssetOptIn(account, Number(usdcAsset.id));
}

if ((await getAssetBalance(account.addr, Number(usdcAsset.id))) < 100_000) {
await fixedInputSwap({
account,
asset_1: algoAsset,
asset_2: usdcAsset,
isSwapRouterEnabled: false
});
}

// Make sure to sort the assets according to the fAssetIds
const [asset1, asset2] = [algoAsset, usdcAsset].sort(
(a, b) => Number(b.fAsset_id) - Number(a.fAsset_id)
);

await lendingPoolAddLiquidity({account, asset_1: asset1, asset_2: asset2});
await lendingPoolRemoveLiquidity({account, asset_1: asset1, asset_2: asset2});
}

console.log("✅ All operations completed successfully");
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {Account} from "algosdk";
import {
AddLiquidity,
LendingPool,
SupportedNetwork,
combineAndRegroupSignerTxns,
fetchFolksLendingPool,
generateOptIntoAssetTxns,
poolUtils
} from "@tinymanorg/tinyman-js-sdk";

import {algodClient} from "../../../util/client";
import {getIsAccountOptedIntoAsset} from "../../../util/asset";
import signerWithSecretKey from "../../../util/initiatorSigner";

/**
* Adds liquidity to an existent lending pool using the proportional mode
*/
export async function lendingPoolAddLiquidity({
account,
asset_1,
asset_2
}: {
account: Account;
asset_1: {
id: string;
unit_name: string;
fAsset_id: string;
folks_lending_pool_application_id: string;
};
asset_2: {
id: string;
unit_name: string;
fAsset_id: string;
folks_lending_pool_application_id: string;
};
}) {
const initiatorAddr = account.addr;
const poolInfo = await poolUtils.v2.getPoolInfo({
network: "testnet" as SupportedNetwork,
client: algodClient,
asset1ID: Number(asset_1.fAsset_id),
asset2ID: Number(asset_2.fAsset_id)
});
const asset1FolksLendingPool = await fetchFolksLendingPool(
algodClient,
Number(asset_1.folks_lending_pool_application_id)
);
const asset2FolksLendingPool = await fetchFolksLendingPool(
algodClient,
Number(asset_2.folks_lending_pool_application_id)
);
/*
* For testing purposes, we will add 100_000 of asset1 into the pool,
* and calculate the amount of asset2 to be added.
*/
const asset1Amount = 100_000;
const lendingPoolRatio =
Number(poolInfo.asset1Reserves) / Number(poolInfo.asset2Reserves);

// Calculate the amount of fAsset1 to be added from the original asset1 amount
const fAsset1Amount = LendingPool.calculateDepositReturn({
depositAmount: asset1Amount,
...asset1FolksLendingPool
});
// Get the amount of fAsset2 to be added from the pool ratio
const fAsset2Amount = Math.floor(Number(fAsset1Amount) / lendingPoolRatio);
// Retrieve the amount of asset2 to be added from the fAsset2Amount
const asset2Amount = LendingPool.calculateWithdrawReturn({
withdrawAmount: fAsset2Amount,
...asset2FolksLendingPool
});

let txGroup = await LendingPool.AddLiquidity.generateTxns({
client: algodClient,
network: "testnet" as SupportedNetwork,
poolAddress: poolInfo.account.address(),
poolTokenId: poolInfo.poolTokenID!,
lendingManagerId: asset1FolksLendingPool.managerAppId,
asset1In: {
amount: asset1Amount,
id: Number(asset_1.id),
fAssetId: Number(asset_1.fAsset_id),
lendingAppId: Number(asset_1.folks_lending_pool_application_id)
},
asset2In: {
amount: asset2Amount,
id: Number(asset_2.id),
fAssetId: Number(asset_2.fAsset_id),
lendingAppId: Number(asset_2.folks_lending_pool_application_id)
},
initiatorAddr
});

if (!(await getIsAccountOptedIntoAsset(initiatorAddr, Number(poolInfo.poolTokenID!)))) {
/**
* Insert opt-in transaction to the txn group
* if the account is not opted-in to the pool token
*/
txGroup = combineAndRegroupSignerTxns(
await generateOptIntoAssetTxns({
client: algodClient,
assetID: Number(poolInfo.poolTokenID),
initiatorAddr
}),
txGroup
);
}

const signedTxns = await AddLiquidity.v2.flexible.signTxns({
txGroup,
initiatorSigner: signerWithSecretKey(account)
});

const executionResponse = await AddLiquidity.v2.flexible.execute({
client: algodClient,
pool: poolInfo,
txGroup,
signedTxns
});

console.log("✅ Lending Pool Add Liquidity executed successfully!");
console.log({txnID: executionResponse.txnID});
}
Loading