Skip to content

Commit 09397da

Browse files
authored
Check and test (#435)
* check script etc and launchpad * new contract * check indexer neg number and fix + clean * fix liq created event * new endpoints holdings * change ui endpoint render holding
1 parent b522013 commit 09397da

File tree

17 files changed

+315
-297
lines changed

17 files changed

+315
-297
lines changed

apps/data-backend/src/routes/indexer/holdings.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ interface HoldingsParams {
88
}
99

1010
async function holdingsRoute(fastify: FastifyInstance, options: RouteOptions) {
11+
1112
fastify.get<{
1213
Params: HoldingsParams;
1314
}>('/token-distribution/:tokenAddress', async (request, reply) => {
@@ -20,6 +21,57 @@ async function holdingsRoute(fastify: FastifyInstance, options: RouteOptions) {
2021
return;
2122
}
2223

24+
try {
25+
26+
const holdings = await prisma.shares_token_user.findMany({
27+
where: { token_address: tokenAddress, },
28+
select: {
29+
owner: true,
30+
token_address: true,
31+
amount_owned: true,
32+
// created_at: true,
33+
},
34+
});
35+
36+
// const distributions = await prisma.token_transactions.groupBy({
37+
// by: ['owner_address', 'transaction_type'],
38+
// // by: ["owner_address", "transaction_type"], // TODO add by tx type and sum sell and buy
39+
// where: { memecoin_address: tokenAddress },
40+
// _sum: {
41+
// amount: true,
42+
// },
43+
// _count: {
44+
// owner_address: true,
45+
// },
46+
// });
47+
48+
// if (distributions.length === 0) {
49+
// reply.status(HTTPStatus.NotFound).send({
50+
// message: 'No holders found for this token address.',
51+
// });
52+
// }
53+
54+
reply.status(HTTPStatus.OK).send({ data: holdings });
55+
} catch (error) {
56+
console.error('Failed to fetch holders distribution:', error);
57+
reply.status(HTTPStatus.InternalServerError).send({
58+
message: 'Internal Server Error while fetching token distribution.',
59+
});
60+
}
61+
});
62+
63+
fastify.get<{
64+
Params: HoldingsParams;
65+
}>('/token-distribution-holders/:tokenAddress', async (request, reply) => {
66+
const { tokenAddress } = request.params;
67+
if (!isValidStarknetAddress(tokenAddress)) {
68+
reply.status(HTTPStatus.BadRequest).send({
69+
code: HTTPStatus.BadRequest,
70+
message: 'Invalid token address',
71+
});
72+
return;
73+
}
74+
2375
try {
2476
const distributions = await prisma.token_transactions.groupBy({
2577
by: ['owner_address', 'transaction_type'],

apps/mobile/src/components/LaunchPad/TokenHolderDetail/index.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,16 @@ export const TokenHolderDetail: React.FC<HoldersProps> = ({holders, loading}) =>
2929
<View style={styles.holderRow}>
3030
<Text style={styles.label}>Owner Address</Text>
3131
<View style={styles.addressContainer}>
32-
<AddressComponent address={feltToAddress(BigInt(item.owner_address))} />
32+
{/* <AddressComponent address={feltToAddress(BigInt(item?.owner_address))} /> */}
33+
<AddressComponent address={feltToAddress(BigInt(item?.owner))} />
3334
</View>
3435
</View>
3536

3637
<View style={styles.holderRow}>
3738
<Text style={styles.label}>Amount</Text>
38-
<Text style={styles.value}>{item._sum.amount}</Text>
39+
<Text style={styles.value}>{item?.amount_owned}</Text>
40+
41+
{/* <Text style={styles.value}>{item._sum.amount}</Text> */}
3942
</View>
4043
</View>
4144
)}

apps/mobile/src/screens/LaunchDetail/index.tsx

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -127,33 +127,38 @@ export const LaunchDetail: React.FC<LaunchDetailScreenProps> = ({ navigation, ro
127127
}, [launchData]);
128128

129129
//Filter the data for holding to only show buys.
130+
// OLD Holdings by tx grooup by
131+
// const holdings = useMemo(() => {
132+
// if (!holdingsData?.data) return [];
133+
134+
// return holdingsData.data
135+
// .reduce((acc: any, tx: any) => {
136+
// const { owner_address, _count, _sum, transaction_type } = tx;
137+
// const existingHolder = acc.find((h: any) => h.owner_address === owner_address);
138+
139+
// const amount = transaction_type === 'buy' ? parseFloat(_sum.amount) : -parseFloat(_sum.amount);
140+
141+
// if (existingHolder) {
142+
// existingHolder._sum.amount = (parseFloat(existingHolder._sum.amount) + amount).toString();
143+
// } else {
144+
// acc.push({
145+
// owner_address,
146+
// _count: { owner_address: _count.owner_address },
147+
// _sum: { amount: amount.toString() },
148+
// });
149+
// }
150+
151+
// return acc;
152+
// }, [])
153+
// .filter((holder: any) => parseFloat(holder._sum.amount) > 0);
154+
// }, [holdingsData]);
155+
130156
const holdings = useMemo(() => {
131157
if (!holdingsData?.data) return [];
132158

133159
return holdingsData.data
134-
.reduce((acc: any, tx: any) => {
135-
const { owner_address, _count, _sum, transaction_type } = tx;
136-
const existingHolder = acc.find((h: any) => h.owner_address === owner_address);
137-
138-
const amount = transaction_type === 'buy' ? parseFloat(_sum.amount) : -parseFloat(_sum.amount);
139-
140-
if (existingHolder) {
141-
existingHolder._sum.amount = (parseFloat(existingHolder._sum.amount) + amount).toString();
142-
} else {
143-
acc.push({
144-
owner_address,
145-
_count: { owner_address: _count.owner_address },
146-
_sum: { amount: amount.toString() },
147-
});
148-
}
149-
150-
return acc;
151-
}, [])
152-
.filter((holder: any) => parseFloat(holder._sum.amount) > 0);
153160
}, [holdingsData]);
154161

155-
156-
157162
useEffect(() => {
158163
const data = transactionData || [];
159164
setTransaction(data?.data);

apps/nestjs-indexer/src/common/constants.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ export default {
1313
// LAUNCHPAD_ADDRESS:"0x525d47343caa4c56cd28eeeff7d503f1b80872c5a7f4a9f8ac8130de3513f70",
1414

1515
// LAUNCHPAD_ADDRESS:"0x6fbcf2a0df5716d83d9653985f9c9bde6fb73130f0804e18bb18ef6f6ae7ad2",
16-
LAUNCHPAD_ADDRESS:"0x6579503122e7564117f2192d6a66ec81b51dfd551b39a4fa26046044cd39a35",
16+
// LAUNCHPAD_ADDRESS:"0x6579503122e7564117f2192d6a66ec81b51dfd551b39a4fa26046044cd39a35",
17+
LAUNCHPAD_ADDRESS:"0x4cefb7ab4c3fda72df52f288e141ff1dc6956a497949bf7b0031f012f3d3afc",
1718
NAMESERVICE_ADDRESS:
1819
'0x15dcd3c28c07846fa98d3a40d29446de21b5e6cd8d49a43773da0f237d5ea7f',
1920
},

apps/nestjs-indexer/src/indexer/liquidity-added.indexer.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export class LiquidityAddedIndexer {
2020
private readonly indexerService: IndexerService,
2121
) {
2222
this.eventKeys = [
23-
validateAndParseAddress(hash.getSelectorFromName('LiquidityAdded')),
23+
validateAndParseAddress(hash.getSelectorFromName('LiquidityCreated')),
2424
];
2525
}
2626

@@ -40,8 +40,8 @@ export class LiquidityAddedIndexer {
4040
const eventKey = validateAndParseAddress(FieldElement.toHex(event.keys[0]));
4141

4242
switch (eventKey) {
43-
case validateAndParseAddress(hash.getSelectorFromName('LiquidityAdded')):
44-
this.logger.log('Event name: LiquidityAdded');
43+
case validateAndParseAddress(hash.getSelectorFromName('LiquidityCreated')):
44+
this.logger.log('Event name: LiquidityCreated');
4545
this.handleLiquidityAddedEvent(header, event, transaction);
4646
break;
4747
default:

apps/nestjs-indexer/src/services/sell-token/sell-token.service.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,24 @@ export class SellTokenService {
3232
} else {
3333
const newSupply =
3434
Number(tokenLaunchRecord.current_supply ?? 0) + Number(data.amount);
35-
const newLiquidityRaised =
35+
let newLiquidityRaised =
3636
Number(tokenLaunchRecord.liquidity_raised ?? 0) -
3737
Number(data.quoteAmount);
38-
// const newTotalTokenHolded =
39-
// Number(tokenLaunchRecord.total_token_holded ?? 0) -
40-
// Number(data.amount);
4138

42-
const newTotalTokenHolded =
39+
// TODO fix issue negative number
40+
// Check event fees etc
41+
if (newLiquidityRaised < 0) {
42+
newLiquidityRaised = 0;
43+
}
44+
// TODO fix issue negative number
45+
// Check event fees etc
46+
let newTotalTokenHolded =
4347
Number(tokenLaunchRecord.total_token_holded ?? 0) -
4448
Number(data.coinAmount ?? data?.amount);
4549

50+
if (newTotalTokenHolded < 0) {
51+
newTotalTokenHolded = 0;
52+
}
4653
await this.prismaService.token_launch.update({
4754
where: { transaction_hash: tokenLaunchRecord.transaction_hash },
4855
data: {

apps/nestjs-indexer/src/services/token-launch/token-launch.service.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { TokenLaunch } from './interfaces';
55
@Injectable()
66
export class TokenLaunchService {
77
private readonly logger = new Logger(TokenLaunchService.name);
8-
constructor(private readonly prismaService: PrismaService) {}
8+
constructor(private readonly prismaService: PrismaService) { }
99

1010
async create(data: TokenLaunch) {
1111
try {
@@ -21,6 +21,12 @@ export class TokenLaunchService {
2121
return;
2222
}
2323

24+
const bondingType = data.bondingType === '0'
25+
? 'Linear'
26+
: data.bondingType === '1'
27+
? 'Exponential'
28+
: null;
29+
2430
await this.prismaService.token_launch.create({
2531
data: {
2632
network: data.network,
@@ -35,8 +41,8 @@ export class TokenLaunchService {
3541
current_supply: data.totalSupply,
3642
is_liquidity_added: false,
3743
threshold_liquidity: data.thresholdLiquidity,
38-
bonding_type: data.bondingType,
3944
owner_address: data.ownerAddress,
45+
bonding_type: bondingType,
4046
},
4147
});
4248
} catch (error) {

onchain/cairo/launchpad/src/interfaces/launchpad.cairo

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,8 @@ pub trait ILaunchpadMarketplace<TContractState> {
7676
fn get_share_of_user_by_contract(
7777
self: @TContractState, owner: ContractAddress, key_user: ContractAddress,
7878
) -> SharesTokenUser;
79-
fn get_all_launch(self: @TContractState) -> Span<TokenLaunch>;
80-
81-
fn get_all_coins(self: @TContractState) -> Span<Token>;
79+
// fn get_all_launch(self: @TContractState) -> Span<TokenLaunch>;
80+
// fn get_all_coins(self: @TContractState) -> Span<Token>;
8281

8382
// Admins functions
8483
fn set_token(ref self: TContractState, token_quote: TokenQuoteBuyCoin);

onchain/cairo/launchpad/src/launchpad/launchpad.cairo

Lines changed: 31 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -518,35 +518,35 @@ pub mod LaunchpadMarketplace {
518518
self.shares_by_users.entry(owner).entry(key_user).read()
519519
}
520520

521-
fn get_all_coins(self: @ContractState) -> Span<Token> {
522-
let max_coin_id = self.total_token.read() + 1;
523-
let mut coins: Array<Token> = ArrayTrait::new();
524-
let mut i = 0; //Since the stream id starts from 0
525-
loop {
526-
if i >= max_coin_id {}
527-
let coin = self.array_coins.read(i);
528-
if coin.owner.is_zero() {
529-
break coins.span();
530-
}
531-
coins.append(coin);
532-
i += 1;
533-
}
534-
}
535-
536-
fn get_all_launch(self: @ContractState) -> Span<TokenLaunch> {
537-
let max_key_id = self.total_launch.read() + 1;
538-
let mut launches: Array<TokenLaunch> = ArrayTrait::new();
539-
let mut i = 0; //Since the stream id starts from 0
540-
loop {
541-
if i >= max_key_id {}
542-
let pool = self.array_launched_coins.read(i);
543-
if pool.owner.is_zero() {
544-
break launches.span();
545-
}
546-
launches.append(pool);
547-
i += 1;
548-
}
549-
}
521+
// fn get_all_coins(self: @ContractState) -> Span<Token> {
522+
// let max_coin_id = self.total_token.read() + 1;
523+
// let mut coins: Array<Token> = ArrayTrait::new();
524+
// let mut i = 0; //Since the stream id starts from 0
525+
// loop {
526+
// if i >= max_coin_id {}
527+
// let coin = self.array_coins.read(i);
528+
// if coin.owner.is_zero() {
529+
// break coins.span();
530+
// }
531+
// coins.append(coin);
532+
// i += 1;
533+
// }
534+
// }
535+
536+
// fn get_all_launch(self: @ContractState) -> Span<TokenLaunch> {
537+
// let max_key_id = self.total_launch.read() + 1;
538+
// let mut launches: Array<TokenLaunch> = ArrayTrait::new();
539+
// let mut i = 0; //Since the stream id starts from 0
540+
// loop {
541+
// if i >= max_key_id {}
542+
// let pool = self.array_launched_coins.read(i);
543+
// if pool.owner.is_zero() {
544+
// break launches.span();
545+
// }
546+
// launches.append(pool);
547+
// i += 1;
548+
// }
549+
// }
550550
// User call
551551

552552
// Create token for an user
@@ -780,7 +780,6 @@ pub mod LaunchpadMarketplace {
780780
get_caller_address(), get_contract_address(), remain_quote_to_liquidity
781781
);
782782

783-
// Assertion: Amount Received Validation
784783
// Update the Stats of pool:
785784
// Liquidity raised
786785
// Available supply
@@ -790,13 +789,10 @@ pub mod LaunchpadMarketplace {
790789
// Optionally, re-calculate the quote amount based on the amount to ensure consistency
791790
// println!("total_price {:?}", total_price);
792791
// println!("update pool");
793-
794-
795792
// println!("subtract amount and available supply");
796793
// println!("available supply {:?}", pool_coin.available_supply);
797794
// println!("amount {:?}", amount);
798795
pool_coin.liquidity_raised += remain_quote_to_liquidity;
799-
pool_coin.total_token_holded += coin_amount;
800796
pool_coin.price = total_price;
801797
// TODO TEST
802798
// EDGE CASE
@@ -812,9 +808,6 @@ pub mod LaunchpadMarketplace {
812808
}
813809

814810
// Update share and coin stats for an user
815-
// let mut old_share = self.shares_by_users.read((get_caller_address(), coin_address));
816-
// let mut old_share = self.shares_by_users.entry((get_caller_address(),
817-
// coin_address)).read();
818811
let mut old_share = self
819812
.shares_by_users
820813
.entry(get_caller_address())
@@ -823,7 +816,6 @@ pub mod LaunchpadMarketplace {
823816

824817
let mut share_user = old_share.clone();
825818
// println!("update share");
826-
827819
if share_user.owner.is_zero() {
828820
share_user =
829821
SharesTokenUser {
@@ -907,7 +899,8 @@ pub mod LaunchpadMarketplace {
907899
// creator_fee: 0,
908900
last_price: old_price,
909901
timestamp: get_block_timestamp(),
910-
quote_amount: quote_amount
902+
quote_amount:remain_quote_to_liquidity
903+
// quote_amount: quote_amount
911904
}
912905
);
913906
}

0 commit comments

Comments
 (0)