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

Feature/interest protocol trading #64

Merged
merged 25 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2eca313
Create static mergeAllCoinObjects() in WalletManager
bathord May 3, 2024
0fbb6cd
Create separate util getUserCoinObjects() method
bathord May 3, 2024
1b4daf7
Add interest protocol clamm sdk to deps
bathord May 3, 2024
774107b
Create interest protocol singleton init version
bathord May 3, 2024
93e6e85
Add InterestProtocolSingleton to Provider type
bathord May 3, 2024
17c4980
Create example for interest & add it to common example method
bathord May 3, 2024
2727b29
Add JSDoc for Interest Protocol Singleton
bathord May 3, 2024
954f045
Upd interest SDK version
bathord May 6, 2024
ac94784
Create interest protocol config
bathord May 6, 2024
ab58c78
Create getBestInterestRoute() util
bathord May 6, 2024
5eeebe6
Upd interest protocol types
bathord May 6, 2024
ac78440
Upd interest protocol type guards
bathord May 6, 2024
6c06105
Upd interest proto pools getting & getRouteData() & getSwapTransaction()
bathord May 6, 2024
8b2e262
Upd interest example
bathord May 6, 2024
dfa71ae
Add formattedInputAmount to InterestRouteData type
bathord May 7, 2024
9b02b7d
Upd interest getSwapTransaction() & handle short sui coin type
bathord May 7, 2024
b6db0e8
Bump interest sdk version
bathord May 9, 2024
fedbb41
Add return type for getBestInterestRoute()
bathord May 9, 2024
5c3d11a
Add try/catch for updatePoolsCache()
bathord May 9, 2024
e3d7383
Export InterestProtocol from index
bathord May 9, 2024
9358251
Create getAmountWithSlippage()
bathord May 10, 2024
45ade32
Fix interest methods to work with slippage & split input coin
bathord May 10, 2024
65829b9
Prettify & add comments
bathord May 10, 2024
9fbcd8c
Remove wallet manager getAllCoinObjects() & replace it with getUserCo…
bathord May 11, 2024
5cf03c1
upgrade jest.config.js
avernikoz May 11, 2024
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
8 changes: 7 additions & 1 deletion examples/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CetusSingleton } from "../src/providers/cetus/cetus";
import { clmmMainnet } from "../src/providers/cetus/config";
import { SWAP_GAS_BUDGET } from "../src/providers/common";
import { FlowxSingleton } from "../src/providers/flowx/flowx";
import { InterestProtocolSingleton } from "../src/providers/interest/interest";
import { TurbosSingleton } from "../src/providers/turbos/turbos";
import { CacheOptions } from "../src/providers/types";
import { RedisStorageSingleton } from "../src/storages/RedisStorage";
Expand Down Expand Up @@ -91,8 +92,13 @@ export const initAndGetProviders = async (storage?: Storage): Promise<Providers>
cacheOptions: { storage, ...cacheOptions },
lazyLoading: false,
});
const interest: InterestProtocolSingleton = await InterestProtocolSingleton.getInstance({
suiProviderUrl,
cacheOptions: { storage, ...cacheOptions },
lazyLoading: false,
});

const providers: Providers = [turbos, cetus, aftermath, flowx];
const providers: Providers = [turbos, cetus, aftermath, flowx, interest];

return providers;
};
12 changes: 4 additions & 8 deletions examples/dca/create-dca.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { SuiClient } from "@mysten/sui.js/client";
import { TransactionBlock } from "@mysten/sui.js/transactions";
import { CoinManagerSingleton, WalletManagerSingleton } from "../../src";
import { DCAManagerSingleton } from "../../src/managers/dca/DCAManager";
import { DCATimescale } from "../../src/managers/dca/types";
import { getUserCoinObjects } from "../../src/providers/utils/getUserCoinObjects";
import { RINCEL_COIN_TYPE, USDC_COIN_TYPE } from "../coin-types";
import { initAndGetProviders, initAndGetRedisStorage, keypair, user } from "../common";
import { keypair, user } from "../common";

// yarn ts-node examples/dca/create-dca.ts
export const createDCA = async () => {
Expand All @@ -23,14 +23,10 @@ export const createDCA = async () => {
// TODO: Need to update inner function where this value is used
const baseCoinAmountToDepositIntoDCA = "150000";

const storage = await initAndGetRedisStorage();
const providers = await initAndGetProviders(storage);
const coinManager: CoinManagerSingleton = CoinManagerSingleton.getInstance(providers, suiProviderUrl);
const walletManager: WalletManagerSingleton = WalletManagerSingleton.getInstance(provider, coinManager);

const allCoinObjectsList = await walletManager.getAllCoinObjects({
const allCoinObjectsList = await getUserCoinObjects({
publicKey: keypair.toSuiAddress(),
coinType: baseCoinType,
provider,
});

const totalOrders = 10;
Expand Down
31 changes: 4 additions & 27 deletions examples/dca/deposit-base.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import { SuiClient } from "@mysten/sui.js/client";
import { TransactionBlock } from "@mysten/sui.js/transactions";
import {
AftermathSingleton,
CetusSingleton,
CoinManagerSingleton,
Providers,
TurbosSingleton,
WalletManagerSingleton,
clmmMainnet,
} from "../../src";
import { DCAManagerSingleton } from "../../src/managers/dca/DCAManager";
import { cacheOptions, keypair, user } from "../common";
import { getUserCoinObjects } from "../../src/providers/utils/getUserCoinObjects";
import { keypair, user } from "../common";

// yarn ts-node examples/dca/deposit-base.ts
export const depositBase = async () => {
Expand All @@ -37,25 +29,10 @@ export const depositBase = async () => {
const baseCoinAmountToDepositIntoDCA = "250000";
const addOrdersCount = 1;

const turbos: TurbosSingleton = await TurbosSingleton.getInstance({
suiProviderUrl,
cacheOptions,
lazyLoading: false,
});
const cetus: CetusSingleton = await CetusSingleton.getInstance({
sdkOptions: clmmMainnet,
cacheOptions,
suiProviderUrl,
lazyLoading: false,
});
const aftermath: AftermathSingleton = await AftermathSingleton.getInstance({ cacheOptions, lazyLoading: false });
const providers: Providers = [turbos, cetus, aftermath];
const coinManager: CoinManagerSingleton = CoinManagerSingleton.getInstance(providers, suiProviderUrl);
const walletManager: WalletManagerSingleton = WalletManagerSingleton.getInstance(provider, coinManager);

const allCoinObjectsList = await walletManager.getAllCoinObjects({
const allCoinObjectsList = await getUserCoinObjects({
publicKey: keypair.toSuiAddress(),
coinType: baseCoinType,
provider,
});

const { tx, txRes } = await DCAManagerSingleton.createDCADepositBaseTransaction({
Expand Down
54 changes: 54 additions & 0 deletions examples/interest/interest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { InterestProtocolSingleton } from "../../src/providers/interest/interest";
import { cacheOptions, initAndGetRedisStorage, provider, suiProviderUrl, user } from "../common";

// yarn ts-node examples/interest/interest.ts
export const interest = async ({
tokenFrom,
tokenTo,
amount,
slippagePercentage,
signerAddress,
}: {
tokenFrom: string;
tokenTo: string;
amount: string;
slippagePercentage: number;
signerAddress: string;
}) => {
const storage = await initAndGetRedisStorage();

const interest = await InterestProtocolSingleton.getInstance({
suiProviderUrl,
cacheOptions: { storage, ...cacheOptions },
lazyLoading: false,
});

const routeData = await interest.getRouteData({
coinTypeFrom: tokenFrom,
coinTypeTo: tokenTo,
inputAmount: amount,
publicKey: signerAddress,
slippagePercentage,
});
console.debug("routeData:", routeData);

const transaction = await interest.getSwapTransaction({
publicKey: user,
route: routeData.route,
slippagePercentage: 10,
});

const res = await provider.devInspectTransactionBlock({
transactionBlock: transaction,
sender: user,
});
console.debug("res: ", res);
};

interest({
tokenFrom: "0xae870af23dda8285a5f11e8136190568796bb76a6e7f3b4061f7ded0c1ebe889::usdt::USDT",
tokenTo: "0x62a807f396a729dfb9dd931bc6a49d840ede3ce058fe11e38d1f097d8466ee60::bonden::BONDEN",
amount: "10",
signerAddress: user,
slippagePercentage: 10,
});
3 changes: 3 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
transform: {
"^.+\\.[tj]s$": "ts-jest",
},
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"dependencies": {
"@cetusprotocol/cetus-sui-clmm-sdk": "^3.17.8",
"@flowx-pkg/ts-sdk": "^0.0.11",
"@interest-protocol/clamm-sdk": "^6.1.1-alpha",
"@mysten/sui.js": "yarn:@mysten/sui.js@^0.42.0",
"@mysten/sui.js-0.51.2": "yarn:@mysten/sui.js@^0.51.2",
"@types/redis": "^4.0.11",
Expand Down
7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export * from "./providers/turbos/turbos";
export * from "./providers/turbos/types";
export * from "./providers/turbos/utils";

// Interest Protocol
export * from "./providers/interest/interest";
export * from "./providers/interest/types";
export * from "./providers/interest/utils";
export * from "./providers/interest/type-guards";
export * from "./providers/interest/config";

// Storages
export * from "./storages/RedisStorage";
export * from "./storages/InMemoryStorage";
Expand Down
69 changes: 32 additions & 37 deletions src/managers/WalletManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "@mysten/sui.js/client";
import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";
import { TransactionBlock } from "@mysten/sui.js/transactions";
import { TransactionBlock as UpdatedTransactionBlock } from "@mysten/sui.js-0.51.2/transactions";
import { SUI_DECIMALS } from "@mysten/sui.js/utils";
import BigNumber from "bignumber.js";
import { SUI_DENOMINATOR, SWAP_GAS_BUDGET } from "../providers/common";
Expand All @@ -16,6 +17,7 @@ import { CoinAssetData, IWalletManager } from "./types";
import { getCoinsAssetsFromCoinObjects, normalizeMnemonic } from "./utils";
import { bech32 } from "bech32";
import { determineFormat } from "./WalletManager.utils";
import { TransactionResult } from "../transactions/types";

/**
* @class WalletManagerSingleton
Expand Down Expand Up @@ -317,49 +319,42 @@ export class WalletManagerSingleton implements IWalletManager {
}

/**
* @public
* @method getAllCoinObjects
* @param {Object} params - Parameters object.
* @param {string} params.publicKey - The public key of the wallet.
* @param {string} params.coinType - The coin type of specified coin.
* @description Retrieves all coin objects associated with a wallet and specified coinType.
* @return {Promise<CoinStruct[]>} A promise that resolves to an array of coin objects data.
* Note: this method is using an `UpdatedTransactionBlock`, that is a `TransactionBlock` from
* the @mysten/sui.js v0.51.2 package.
*
* @description Merges all the passed `coinObjects` into one object.
* @return {object} A transaction block, that contains the coins merge; a destination coin object id, into which all
* the other coin objects are merged; a transaction result, that is the result of the coins merge.
*/
public async getAllCoinObjects({
publicKey,
coinType,
public static mergeAllCoinObjects({
coinObjects,
txb,
}: {
publicKey: string;
coinType: string;
}): Promise<CoinStruct[]> {
const pageCapacity = 50;
const allObjects: CoinStruct[] = [];
let nextCursor: string | null | undefined = null;
let assets: PaginatedCoins = await this.provider.getCoins({
owner: publicKey,
coinType,
limit: pageCapacity,
cursor: nextCursor,
});
coinObjects: CoinStruct[];
txb?: UpdatedTransactionBlock;
}): {
tx: UpdatedTransactionBlock;
destinationObjectId: string;
txRes?: TransactionResult;
} {
if (coinObjects.length === 0) {
throw new Error("[mergeAllCoinObjects] Passed `coinObjects` are empty.");
}

// fetching and combining part
while (assets.hasNextPage) {
const coinObjects: CoinStruct[] = assets.data;
allObjects.push(...coinObjects);
const tx = txb ?? new UpdatedTransactionBlock();

nextCursor = assets.nextCursor;
assets = await this.provider.getCoins({
owner: publicKey,
coinType,
limit: pageCapacity,
cursor: nextCursor,
});
const objectIds = coinObjects.map((obj) => obj.coinObjectId);
const [destinationObjectId, ...sourceObjectIds] = objectIds;

if (sourceObjectIds.length === 0) {
return { tx, destinationObjectId };
}

// In case user has less tokens than `pageCapacity` (1 page only), we should put them into `allObjects`
const coinObjects: CoinStruct[] = assets.data;
allObjects.push(...coinObjects);
const txRes = tx.mergeCoins(
tx.object(destinationObjectId),
sourceObjectIds.map((objId) => tx.object(objId)),
);

return allObjects;
return { tx, txRes, destinationObjectId };
}
}
8 changes: 7 additions & 1 deletion src/managers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { TransactionBlock } from "@mysten/sui.js/transactions";
import { AftermathSingleton } from "../providers/aftermath/aftermath";
import { CetusSingleton } from "../providers/cetus/cetus";
import { FlowxSingleton } from "../providers/flowx/flowx";
import { InterestProtocolSingleton } from "../providers/interest/interest";
import { TurbosSingleton } from "../providers/turbos/turbos";
import { TryCatchWrapperResult } from "../providers/types";

Expand All @@ -19,7 +20,12 @@ export type CoinAssetData = Omit<CommonCoinData, "decimals"> & {

export type UpdatedCoinsCache = { provider: string; data: CommonCoinData[] };

export type Provider = TurbosSingleton | CetusSingleton | AftermathSingleton | FlowxSingleton;
export type Provider =
| TurbosSingleton
| CetusSingleton
| AftermathSingleton
| FlowxSingleton
| InterestProtocolSingleton;

export type Providers = Provider[];

Expand Down
1 change: 1 addition & 0 deletions src/providers/interest/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const ROUTES_QUOTES_AMOUNT_OBJECT_INDEX = 2;
Loading
Loading