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

Swap tx parsing examples #50

Merged
merged 3 commits into from
May 14, 2024
Merged
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
78 changes: 78 additions & 0 deletions examples/bonding-curve/trading/parsers/parsing-trade-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/* eslint-disable max-len */
import { getFullnodeUrl, SuiClient } from "@mysten/sui.js/client";
import { Trade, TradeEventParsedJson } from "./types";
import { BondingPoolSingleton } from "../../../../src";
import { SUI_TYPE_ARG } from "@mysten/sui.js/utils";

const provider = new SuiClient({ url: getFullnodeUrl("mainnet") });
const buyActionFunctionName = "buy_meme";
const sellActionFunctionName = "sell_meme";

const coinType = "0x9102bc69d1435288ba4bec1e5df506dafbcb2f6355f2cef9479c4a22bd2268da::test_token_4am::TEST_TOKEN_4AM";
// yarn tsx examples/bonding-curve/trading/parsers/parsing-trade-event.ts
export const parsingTradeEvent = async () => {
const { data } = await provider.queryEvents({
query: {
MoveEventType: `${BondingPoolSingleton.PACKAGE_OBJECT_ID}::events::Swap<0x2::sui::SUI, ${coinType}, ${BondingPoolSingleton.PACKAGE_OBJECT_ID}::seed_pool::SwapAmount>`,
},
});
const trades: Trade[] = [];
const { poolsByPoolId: seedPools } = await BondingPoolSingleton.getInstance(getFullnodeUrl("mainnet")).getAllPools();
for (const event of data) {
const parsedJson = event.parsedJson as TradeEventParsedJson;
const seedPool = seedPools[parsedJson.pool_address];
const coinType = seedPool.memeCoinType;
const coinMetadata = await provider.getCoinMetadata({ coinType });
if (!coinMetadata) continue;
const { transaction } = await provider.getTransactionBlock({
digest: event.id.txDigest,
options: {
showInput: true,
},
});
let action = undefined;
if (transaction?.data.transaction.kind === "ProgrammableTransaction") {
const buyAction = transaction?.data.transaction.transactions.find(
(t) => "MoveCall" in t && t.MoveCall.function === buyActionFunctionName,
);
const sellAction = transaction?.data.transaction.transactions.find(
(t) => "MoveCall" in t && t.MoveCall.function === sellActionFunctionName,
);
if (buyAction) {
action = "BUY";
}
if (sellAction) {
action = "SELL";
}
}

const memeCoin = {
decimals: coinMetadata.decimals,
symbol: coinMetadata.symbol,
coinType,
tradeAmount: parsedJson.swap_amount.amount_out,
};

const sui = {
tradeAmount: parsedJson.swap_amount.amount_in,
decimals: 9,
symbol: "SUI",
coinType: SUI_TYPE_ARG,
};
if (action === undefined) continue;
trades.push({
fromAmount: parsedJson.swap_amount.amount_in,
toAmount: parsedJson.swap_amount.amount_out,
signer: event.sender,
id: parsedJson.pool_address,
timestamp: event.timestampMs ? new Date(parseInt(event.timestampMs)) : new Date(),
pair: {
fromToken: action === "BUY" ? sui : memeCoin,
toToken: action === "BUY" ? memeCoin : sui,
},
});
}
console.log("TRADES", JSON.stringify(trades, null, 2));
};

parsingTradeEvent();
29 changes: 29 additions & 0 deletions examples/bonding-curve/trading/parsers/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interface TokenPairItem {
decimals: number;
symbol: string;
coinType: string;
tradeAmount: string;
}

export interface TradeEventParsedJson {
amount_in: string;
pool_address: string;
swap_amount: {
admin_fee_in: string;
admin_fee_out: string;
amount_in: string;
amount_out: string;
};
}

export interface Trade {
id: string;
fromAmount: string;
toAmount: string;
signer: string;
timestamp: Date;
pair: {
fromToken: TokenPairItem;
toToken: TokenPairItem;
};
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"engineStrict": true,
"scripts": {
"test": "vitest ./tests/unit",
"e2e": "vitest ./tests/e2e/SocialAPI.test.ts",
"e2e": "vitest ./tests/e2e",
"audit": "yarn audit --groups dependencies",
"format": "prettier --write src/**/*.ts",
"lint": "eslint './src/**/*.ts'",
Expand Down
31 changes: 15 additions & 16 deletions src/coin/schemas/pools-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,23 @@ export const livePool = z.object({
isStable: z.boolean(),
coinType: z.string(),
poolAdminAddress: z.string(),
a: z.bigint(),
futureA: z.bigint(),
gamma: z.bigint(),
initialTime: z.bigint(),
futureGamma: z.bigint(),
futureTime: z.bigint(),
adminBalance: z.bigint(),
balances: z.array(z.bigint()),
d: z.bigint(),
lastPriceTimestamp: z.bigint(),
lpCoinSupply: z.bigint(),
maxA: z.bigint(),
minA: z.bigint(),
a: z.number(),
futureA: z.number(),
gamma: z.number(),
initialTime: z.number(),
futureGamma: z.number(),
futureTime: z.number(),
adminBalance: z.number(),
balances: z.array(z.number()),
d: z.number(),
lastPriceTimestamp: z.number(),
lpCoinSupply: z.number(),
maxA: z.number(),
minA: z.number(),
nCoins: z.number(),
virtualPrice: z.bigint(),
xcpProfit: z.bigint(),
xcpProfitA: z.bigint(),
xcpProfit: z.number(),
xcpProfitA: z.number(),
notAdjusted: z.boolean(),
txDigest: z.string(),
creationDate: z.number(),
Expand All @@ -75,7 +75,6 @@ export const stakingPool = z.object({
totalSupply: z.string(),
ammPool: z.string(),
balanceLp: z.string(),
balanceMeme: z.string(),
poolAdmin: z.string(),
creationDate: z.number(),
txDigest: z.string(),
Expand Down
2 changes: 0 additions & 2 deletions src/staking-pool/StakingPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
totalSupply: string;
ammPool: string;
balanceLp: string;
balanceMeme: string;
feeState: FeeState;
poolAdmin: string;
vesting: VestingConfig;
Expand Down Expand Up @@ -320,7 +319,6 @@
lpCoinType,
memeCoinType,
balanceLp: stakingPoolResponse.balance_lp,
balanceMeme: stakingPoolResponse.balance_meme,
},
provider,
});
Expand All @@ -334,7 +332,7 @@
*/
static async fromObjectIds({
objectIds,
provider,

Check warning on line 335 in src/staking-pool/StakingPool.ts

View workflow job for this annotation

GitHub Actions / Build

'_' is assigned a value but never used

Check warning on line 335 in src/staking-pool/StakingPool.ts

View workflow job for this annotation

GitHub Actions / Build

'_' is assigned a value but never used
}: {
objectIds: string[];
provider: SuiClient;
Expand Down
3 changes: 1 addition & 2 deletions tests/e2e/AuthService.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";
import { Auth } from "../../src";

const BE_URL = "https://14r6b4r6kf.execute-api.us-east-1.amazonaws.com/prod";
import { BE_URL } from "./helpers";

describe("AuthService", () => {
test("check that the authentication flow is working properly", async () => {
Expand Down
4 changes: 1 addition & 3 deletions tests/e2e/CoinAPI.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";
import { Auth, CoinAPI } from "../../src";
import { Coin, coinSchema } from "../../src/coin/schemas/coin-schemas";
import { isSorted } from "./helpers";
import { BE_URL, isSorted } from "./helpers";
// eslint-disable-next-line max-len

const BE_URL = undefined; // "https://14r6b4r6kf.execute-api.us-east-1.amazonaws.com/prod";

describe("CoinService authenticated operations", () => {
let keypair: Ed25519Keypair;

Expand Down
1 change: 0 additions & 1 deletion tests/e2e/LivePool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ describe("Live pool", () => {
const livePools = await LivePool.fromRegistry({
provider: new SuiClient({ url: getFullnodeUrl("mainnet") }),
});
console.log("live pools", livePools);
livePools.forEach((pool) =>
expect(pool.data).toEqual({
address: expect.any(String),
Expand Down
7 changes: 4 additions & 3 deletions tests/e2e/PoolService.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { PoolAPI } from "../../src/coin/PoolApi";
import { livePool, SeedPool, seedPool, stakingPool } from "../../src/coin/schemas/pools-schema";

const BE_URL = undefined; // "https://14r6b4r6kf.execute-api.us-east-1.amazonaws.com/prod";
import { BE_URL } from "./helpers";

const api = new PoolAPI(BE_URL);

Expand Down Expand Up @@ -45,7 +44,9 @@ describe("PoolService", () => {
const { result: livePools } = await poolApi.getLivePools();
expect(Array.isArray(livePools)).toBe(true);
for (const parsedResult of livePools) {
livePool.parse(parsedResult);
if (livePool.safeParse(parsedResult).success) {
console.warn("Invalid live pool found with format", parsedResult);
}
}
});
});
7 changes: 3 additions & 4 deletions tests/e2e/SocialAPI.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";
import { Auth, CoinAPI } from "../../src";
import { SocialAPI } from "../../src/social/SocialAPI";
import { Coin } from "../../src/coin/schemas/coin-schemas";
import { isSorted } from "./helpers";

const BE_URL = "https://14r6b4r6kf.execute-api.us-east-1.amazonaws.com/prod";
import { BE_URL, isSorted } from "./helpers";

const socialAPI = new SocialAPI(BE_URL);

Expand All @@ -23,13 +21,14 @@ describe("Threads fetching", () => {
});
const coinApi = new CoinAPI();
const { coin: coinFetched } = await coinApi.createCoin({
txDigest: "Bdkcg4Z2HuUTRkvG5mrCZRya8fxqwPzbHnY3cfD1tTYQ",
txDigest: "At7GG8M3X73XkA6hqaVoYynge92hm7h1cYTsz3JAhP3G",
socialLinks: {
twitter: "mytwitter",
discord: "mydiscord",
},
});
coin = coinFetched;
console.log("COIN TYPE", coin?.type);
for (let i = 0; i < 10; i++) {
await socialAPI.createThread({
message: `Test message ${i}`,
Expand Down
4 changes: 0 additions & 4 deletions tests/e2e/StakingPool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { StakingPool } from "../../src";
import { FeeState } from "../../src/staking-pool/FeeState";
import { VestingConfig } from "../../src/staking-pool/VestingConfig";

const BE_URL = undefined; // "https://14r6b4r6kf.execute-api.us-east-1.amazonaws.com/prod";

describe("Staking Pool", () => {
/* test("Ensuring that the staking pool is instanciated properly starting from TX digest", async () => {
const stakingPool = await StakingPool.fromGoLiveDefaultTx({
Expand All @@ -21,7 +19,6 @@ describe("Staking Pool", () => {
lpCoinType: expect.any(String),
memeCoinType: expect.any(String),
balanceLp: expect.any(String),
balanceMeme: expect.any(String),
});
});*/

Expand All @@ -41,7 +38,6 @@ describe("Staking Pool", () => {
lpCoinType: expect.any(String),
memeCoinType: expect.any(String),
balanceLp: expect.any(String),
balanceMeme: expect.any(String),
}),
);
});
Expand Down
2 changes: 2 additions & 0 deletions tests/e2e/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ export const isSorted = <T>(array: T[], attribute: keyof T, order: "asc" | "desc

return true;
};

export const BE_URL = "https://14r6b4r6kf.execute-api.us-east-1.amazonaws.com/prod";
Loading