@meteora-ag/dynamic-bonding-curve-sdk 1.5.9 → 1.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -29014,999 +29014,997 @@ async function createLockEscrowIx(payer, pool, lpMint, escrowOwner, lockEscrowKe
29014
29014
 
29015
29015
 
29016
29016
 
29017
- var DynamicBondingCurveProgram = class {
29018
- constructor(connection, commitment, state) {
29017
+
29018
+ // src/services/state.ts
29019
+
29020
+
29021
+
29022
+
29023
+
29024
+ var StateService = class {
29025
+ constructor(connection, commitment) {
29019
29026
  const { program } = createDbcProgram(connection, commitment);
29020
29027
  this.program = program;
29021
- this.connection = connection;
29022
- this.poolAuthority = deriveDbcPoolAuthority();
29023
29028
  this.commitment = commitment;
29024
- this.state = state;
29025
29029
  }
29026
- async getPoolWithConfig(pool) {
29027
- const virtualPool = await this.state.getPool(pool);
29028
- if (!virtualPool) {
29029
- throw new Error(`Pool not found: ${pool.toString()}`);
29030
+ getProgram() {
29031
+ return this.program;
29032
+ }
29033
+ /**
29034
+ * Fetch virtual pools across both the standard and transfer-hook account variants.
29035
+ */
29036
+ async fetchVirtualPools(filters) {
29037
+ const [pools, transferHookPools] = await Promise.all([
29038
+ this.program.account.virtualPool.all(filters),
29039
+ this.program.account.transferHookPool.all(filters)
29040
+ ]);
29041
+ return [...pools, ...transferHookPools];
29042
+ }
29043
+ /**
29044
+ * Fetch pool configs across both the standard and transfer-hook account variants.
29045
+ */
29046
+ async fetchPoolConfigs(filters) {
29047
+ const [configs, transferHookConfigs] = await Promise.all([
29048
+ this.program.account.poolConfig.all(filters),
29049
+ this.program.account.configWithTransferHook.all(filters)
29050
+ ]);
29051
+ return [
29052
+ ...configs,
29053
+ ...transferHookConfigs.map((account) => ({
29054
+ publicKey: account.publicKey,
29055
+ account: account.account.config
29056
+ }))
29057
+ ];
29058
+ }
29059
+ /**
29060
+ * Fetch a pool config account.
29061
+ */
29062
+ async getPoolConfig(configAddress) {
29063
+ const address = configAddress instanceof _web3js.PublicKey ? configAddress : new (0, _web3js.PublicKey)(configAddress);
29064
+ try {
29065
+ const poolConfig = await this.program.account.poolConfig.fetchNullable(
29066
+ address,
29067
+ this.commitment
29068
+ );
29069
+ if (poolConfig) {
29070
+ return poolConfig;
29071
+ }
29072
+ } catch (e3) {
29030
29073
  }
29031
- const poolConfigState = await this.state.getPoolConfig(
29032
- virtualPool.poolState.config
29074
+ const configWithTransferHook = await this.program.account.configWithTransferHook.fetchNullable(
29075
+ address,
29076
+ this.commitment
29033
29077
  );
29034
- if (!poolConfigState) {
29035
- throw new Error(`Pool config not found for virtual pool`);
29036
- }
29037
- return { virtualPool, poolConfigState };
29078
+ return _nullishCoalesce(_optionalChain([configWithTransferHook, 'optionalAccess', _29 => _29.config]), () => ( null));
29038
29079
  }
29039
- prepareSwapParams(swapBaseForQuote, virtualPoolState, poolConfigState) {
29040
- if (swapBaseForQuote) {
29041
- return {
29042
- inputMint: new (0, _web3js.PublicKey)(virtualPoolState.baseMint),
29043
- outputMint: new (0, _web3js.PublicKey)(poolConfigState.quoteMint),
29044
- inputTokenProgram: getTokenProgram(virtualPoolState.poolType),
29045
- outputTokenProgram: getTokenProgram(
29046
- poolConfigState.quoteTokenFlag
29047
- )
29048
- };
29049
- }
29050
- return {
29051
- inputMint: new (0, _web3js.PublicKey)(poolConfigState.quoteMint),
29052
- outputMint: new (0, _web3js.PublicKey)(virtualPoolState.baseMint),
29053
- inputTokenProgram: getTokenProgram(poolConfigState.quoteTokenFlag),
29054
- outputTokenProgram: getTokenProgram(virtualPoolState.poolType)
29055
- };
29080
+ /**
29081
+ * Fetch all pool config accounts.
29082
+ */
29083
+ async getPoolConfigs() {
29084
+ return this.fetchPoolConfigs();
29056
29085
  }
29057
- async buildCreateConfigTx(configParam, config, feeClaimer, leftoverReceiver, quoteMint, payer) {
29058
- validateConfigParameters({ ...configParam, leftoverReceiver });
29059
- return this.program.methods.createConfig(configParam).accountsPartial({
29060
- config,
29061
- feeClaimer,
29062
- leftoverReceiver,
29063
- quoteMint,
29064
- payer
29065
- }).transaction();
29086
+ /**
29087
+ * Fetch all pool configs owned by a wallet.
29088
+ */
29089
+ async getPoolConfigsByOwner(owner) {
29090
+ const filters = createProgramAccountFilter(owner, 72);
29091
+ return this.fetchPoolConfigs(filters);
29066
29092
  }
29067
- async buildCreateConfigWithTransferHookTx(configParam, config, feeClaimer, leftoverReceiver, quoteMint, transferHookProgram, payer) {
29068
- validateConfigParameters(
29069
- { ...configParam, leftoverReceiver },
29070
- { isTransferHook: true, transferHookProgram }
29093
+ /**
29094
+ * Fetch a virtual pool account.
29095
+ */
29096
+ async getPool(poolAddress) {
29097
+ const address = poolAddress instanceof _web3js.PublicKey ? poolAddress : new (0, _web3js.PublicKey)(poolAddress);
29098
+ try {
29099
+ const virtualPool = await this.program.account.virtualPool.fetchNullable(
29100
+ address,
29101
+ this.commitment
29102
+ );
29103
+ if (virtualPool) {
29104
+ return virtualPool;
29105
+ }
29106
+ } catch (e4) {
29107
+ }
29108
+ return await this.program.account.transferHookPool.fetchNullable(
29109
+ address,
29110
+ this.commitment
29071
29111
  );
29072
- return this.program.methods.createConfigWithTransferHook(configParam).accountsPartial({
29073
- config,
29074
- feeClaimer,
29075
- leftoverReceiver,
29076
- quoteMint,
29077
- transferHookProgram,
29078
- payer
29079
- }).transaction();
29080
29112
  }
29081
- async initializeSplPool(params) {
29082
- const {
29083
- name,
29084
- symbol,
29085
- uri,
29086
- pool,
29087
- config,
29088
- payer,
29089
- poolCreator,
29090
- mintMetadata,
29091
- baseMint,
29092
- baseVault,
29093
- quoteVault,
29094
- quoteMint
29095
- } = params;
29096
- return this.program.methods.initializeVirtualPoolWithSplToken({
29097
- name,
29098
- symbol,
29099
- uri
29100
- }).accountsPartial({
29101
- pool,
29102
- config,
29103
- payer,
29104
- creator: poolCreator,
29105
- mintMetadata,
29106
- baseMint,
29107
- poolAuthority: this.poolAuthority,
29108
- baseVault,
29109
- quoteVault,
29110
- quoteMint,
29111
- tokenQuoteProgram: _spltoken.TOKEN_PROGRAM_ID,
29112
- metadataProgram: METAPLEX_PROGRAM_ID,
29113
- tokenProgram: _spltoken.TOKEN_PROGRAM_ID
29114
- }).transaction();
29113
+ /**
29114
+ * Fetch all virtual pool accounts.
29115
+ */
29116
+ async getPools() {
29117
+ return this.fetchVirtualPools();
29115
29118
  }
29116
- async initializeToken2022Pool(params) {
29117
- const {
29118
- name,
29119
- symbol,
29120
- uri,
29121
- pool,
29122
- config,
29123
- payer,
29124
- poolCreator,
29125
- baseMint,
29126
- baseVault,
29127
- quoteVault,
29128
- quoteMint
29129
- } = params;
29130
- return this.program.methods.initializeVirtualPoolWithToken2022({
29131
- name,
29132
- symbol,
29133
- uri
29134
- }).accountsPartial({
29135
- pool,
29136
- config,
29137
- payer,
29138
- creator: poolCreator,
29139
- baseMint,
29140
- poolAuthority: this.poolAuthority,
29141
- baseVault,
29142
- quoteVault,
29143
- quoteMint,
29144
- tokenQuoteProgram: _spltoken.TOKEN_PROGRAM_ID,
29145
- tokenProgram: _spltoken.TOKEN_2022_PROGRAM_ID
29146
- }).transaction();
29119
+ /**
29120
+ * Fetch all virtual pools that use a config.
29121
+ */
29122
+ async getPoolsByConfig(configAddress) {
29123
+ const filters = createProgramAccountFilter(configAddress, 72);
29124
+ return this.fetchVirtualPools(filters);
29147
29125
  }
29148
- async initializeToken2022PoolWithTransferHook(params) {
29149
- const {
29150
- name,
29151
- symbol,
29152
- uri,
29153
- pool,
29154
- config,
29155
- payer,
29156
- poolCreator,
29157
- baseMint,
29158
- baseVault,
29159
- quoteVault,
29160
- quoteMint,
29161
- transferHookProgram,
29162
- tokenQuoteProgram
29163
- } = params;
29164
- return this.program.methods.initializeVirtualPoolWithToken2022TransferHook({
29165
- name,
29166
- symbol,
29167
- uri
29168
- }).accountsPartial({
29169
- pool,
29170
- config,
29171
- payer,
29172
- creator: poolCreator,
29173
- baseMint,
29174
- poolAuthority: this.poolAuthority,
29175
- baseVault,
29176
- quoteVault,
29177
- quoteMint,
29178
- transferHookProgram,
29179
- tokenQuoteProgram,
29180
- tokenProgram: _spltoken.TOKEN_2022_PROGRAM_ID
29181
- }).transaction();
29126
+ /**
29127
+ * Fetch all virtual pools created by a wallet.
29128
+ */
29129
+ async getPoolsByCreator(creatorAddress) {
29130
+ const filters = createProgramAccountFilter(creatorAddress, 104);
29131
+ return this.fetchVirtualPools(filters);
29182
29132
  }
29183
- async buildCreatePoolTx(createPoolParam, tokenType, quoteMint) {
29184
- const { baseMint, name, symbol, uri, poolCreator, config, payer } = createPoolParam;
29185
- const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29186
- const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29187
- const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29188
- const baseParams = {
29189
- name,
29190
- symbol,
29191
- uri,
29192
- pool,
29193
- config,
29194
- payer,
29195
- poolCreator,
29196
- baseMint,
29197
- baseVault,
29198
- quoteVault,
29199
- quoteMint
29200
- };
29201
- if (tokenType === 0 /* SPLToken */) {
29202
- const mintMetadata = deriveMintMetadata(baseMint);
29203
- return this.initializeSplPool({ ...baseParams, mintMetadata });
29133
+ /**
29134
+ * Fetch the first virtual pool that uses a base mint.
29135
+ */
29136
+ async getPoolByBaseMint(baseMint) {
29137
+ const filters = createProgramAccountFilter(baseMint, 136);
29138
+ const pools = await this.fetchVirtualPools(filters);
29139
+ return pools.length > 0 ? pools[0] : null;
29140
+ }
29141
+ /**
29142
+ * Fetch the migration quote threshold for a pool.
29143
+ */
29144
+ async getPoolMigrationQuoteThreshold(poolAddress) {
29145
+ const pool = await this.getPool(poolAddress);
29146
+ if (!pool) {
29147
+ throw new Error(`Pool not found: ${poolAddress.toString()}`);
29204
29148
  }
29205
- return this.initializeToken2022Pool(baseParams);
29149
+ const configAddress = pool.poolState.config;
29150
+ const config = await this.getPoolConfig(configAddress);
29151
+ return config.migrationQuoteThreshold;
29206
29152
  }
29207
- async buildCreatePoolWithTransferHookTx(createPoolParam, quoteMint, tokenQuoteProgram) {
29208
- const {
29209
- baseMint,
29210
- name,
29211
- symbol,
29212
- uri,
29213
- poolCreator,
29214
- config,
29215
- payer,
29216
- transferHookProgram
29217
- } = createPoolParam;
29218
- if (!validateTransferHookProgram(transferHookProgram)) {
29219
- throw new Error(
29220
- "Invalid transfer hook program: cannot be the DBC program, SPL Token, SPL Token-2022, or the default pubkey"
29221
- );
29153
+ /**
29154
+ * Return quote-token curve progress as a ratio between 0 and 1.
29155
+ */
29156
+ async getPoolQuoteTokenCurveProgress(poolAddress) {
29157
+ const pool = await this.getPool(poolAddress);
29158
+ if (!pool) {
29159
+ throw new Error(`Pool not found: ${poolAddress.toString()}`);
29222
29160
  }
29223
- const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29224
- const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29225
- const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29226
- return this.initializeToken2022PoolWithTransferHook({
29227
- name,
29228
- symbol,
29229
- uri,
29230
- pool,
29231
- config,
29232
- payer,
29233
- poolCreator,
29234
- baseMint,
29235
- baseVault,
29236
- quoteVault,
29237
- quoteMint,
29238
- transferHookProgram,
29239
- tokenQuoteProgram
29240
- });
29161
+ const config = await this.getPoolConfig(pool.poolState.config);
29162
+ const quoteReserve = pool.poolState.quoteReserve;
29163
+ const migrationThreshold = config.migrationQuoteThreshold;
29164
+ const quoteReserveDecimal = new (0, _decimaljs2.default)(quoteReserve.toString());
29165
+ const thresholdDecimal = new (0, _decimaljs2.default)(migrationThreshold.toString());
29166
+ const progress = quoteReserveDecimal.div(thresholdDecimal).toNumber();
29167
+ return Math.min(Math.max(progress, 0), 1);
29241
29168
  }
29242
- async buildSwapBuyTx(firstBuyParam, baseMint, config, baseFee, swapBaseForQuote, activationType, tokenType, quoteMint, enableFirstSwapWithMinFee) {
29243
- const {
29244
- buyer,
29245
- receiver,
29246
- buyAmount,
29247
- minimumAmountOut,
29248
- referralTokenAccount
29249
- } = firstBuyParam;
29250
- validateSwapAmount(buyAmount);
29251
- let rateLimiterApplied = false;
29252
- if (baseFee.baseFeeMode === 2 /* RateLimiter */) {
29253
- const currentPoint = await getCurrentPoint(
29254
- this.connection,
29255
- activationType
29256
- );
29257
- rateLimiterApplied = isRateLimiterApplied(
29258
- currentPoint,
29259
- new (0, _bnjs2.default)(0),
29260
- swapBaseForQuote ? 0 /* BaseToQuote */ : 1 /* QuoteToBase */,
29261
- baseFee.secondFactor,
29262
- baseFee.thirdFactor,
29263
- new (0, _bnjs2.default)(baseFee.firstFactor)
29264
- );
29169
+ /**
29170
+ * Return base-token curve progress as a ratio between 0 and 1.
29171
+ */
29172
+ async getPoolBaseTokenCurveProgress(poolAddress) {
29173
+ const pool = await this.getPool(poolAddress);
29174
+ if (!pool) {
29175
+ throw new Error(`Pool not found: ${poolAddress.toString()}`);
29265
29176
  }
29266
- const quoteTokenFlag = await getTokenType(this.connection, quoteMint);
29267
- const { inputMint, outputMint, inputTokenProgram, outputTokenProgram } = this.prepareSwapParams(
29268
- false,
29269
- {
29270
- baseMint,
29271
- poolType: tokenType
29177
+ const config = await this.getPoolConfig(pool.poolState.config);
29178
+ const baseSold = new (0, _decimaljs2.default)(
29179
+ getBaseTokenForSwap(
29180
+ config.sqrtStartPrice,
29181
+ pool.poolState.sqrtPrice,
29182
+ config.curve
29183
+ ).toString()
29184
+ );
29185
+ const totalBaseCouldBeSold = new (0, _decimaljs2.default)(
29186
+ getBaseTokenForSwap(
29187
+ config.sqrtStartPrice,
29188
+ config.migrationSqrtPrice,
29189
+ config.curve
29190
+ ).toString()
29191
+ );
29192
+ const progress = baseSold.div(totalBaseCouldBeSold).toNumber();
29193
+ return Math.min(Math.max(progress, 0), 1);
29194
+ }
29195
+ /**
29196
+ * Fetch metadata accounts for a virtual pool.
29197
+ */
29198
+ async getPoolMetadata(poolAddress) {
29199
+ const filters = createProgramAccountFilter(poolAddress, 8);
29200
+ const accounts = await this.program.account.virtualPoolMetadata.all(filters);
29201
+ return accounts.map((account) => account.account);
29202
+ }
29203
+ /**
29204
+ * Fetch metadata accounts for a partner.
29205
+ */
29206
+ async getPartnerMetadata(partnerAddress) {
29207
+ const filters = createProgramAccountFilter(partnerAddress, 8);
29208
+ const accounts = await this.program.account.partnerMetadata.all(filters);
29209
+ return accounts.map((account) => account.account);
29210
+ }
29211
+ /**
29212
+ * Fetch current unclaimed fees and lifetime trading fee metrics for a pool.
29213
+ */
29214
+ async getPoolFeeMetrics(poolAddress) {
29215
+ const pool = await this.getPool(poolAddress);
29216
+ if (!pool) {
29217
+ throw new Error(`Pool not found: ${poolAddress.toString()}`);
29218
+ }
29219
+ return {
29220
+ current: {
29221
+ partnerBaseFee: pool.poolState.partnerBaseFee,
29222
+ partnerQuoteFee: pool.poolState.partnerQuoteFee,
29223
+ creatorBaseFee: pool.poolState.creatorBaseFee,
29224
+ creatorQuoteFee: pool.poolState.creatorQuoteFee
29272
29225
  },
29273
- {
29274
- quoteMint,
29275
- quoteTokenFlag
29226
+ total: {
29227
+ totalTradingBaseFee: pool.poolState.metrics.totalTradingBaseFee,
29228
+ totalTradingQuoteFee: pool.poolState.metrics.totalTradingQuoteFee
29276
29229
  }
29277
- );
29278
- const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29279
- const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29280
- const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29281
- const preInstructions = [];
29282
- const [
29283
- { ataPubkey: inputTokenAccount, ix: createAtaTokenAIx },
29284
- { ataPubkey: outputTokenAccount, ix: createAtaTokenBIx }
29285
- ] = await Promise.all([
29286
- getOrCreateATAInstruction(
29287
- this.connection,
29288
- inputMint,
29289
- buyer,
29290
- buyer,
29291
- true,
29292
- inputTokenProgram
29293
- ),
29294
- getOrCreateATAInstruction(
29295
- this.connection,
29296
- outputMint,
29297
- receiver ? receiver : buyer,
29298
- buyer,
29299
- true,
29300
- outputTokenProgram
29301
- )
29302
- ]);
29303
- createAtaTokenAIx && preInstructions.push(createAtaTokenAIx);
29304
- createAtaTokenBIx && preInstructions.push(createAtaTokenBIx);
29305
- if (inputMint.equals(_spltoken.NATIVE_MINT)) {
29306
- preInstructions.push(
29307
- ...wrapSOLInstruction(
29308
- buyer,
29309
- inputTokenAccount,
29310
- BigInt(buyAmount.toString())
29311
- )
29312
- );
29230
+ };
29231
+ }
29232
+ /**
29233
+ * Calculate claimed, unclaimed, and total trading fees split by creator and partner.
29234
+ */
29235
+ async getPoolFeeBreakdown(poolAddress) {
29236
+ const pool = await this.getPool(poolAddress);
29237
+ if (!pool) {
29238
+ throw new Error(`Pool not found: ${poolAddress.toString()}`);
29313
29239
  }
29314
- const postInstructions = [];
29315
- if ([inputMint.toBase58(), outputMint.toBase58()].includes(
29316
- _spltoken.NATIVE_MINT.toBase58()
29317
- )) {
29318
- const unwrapIx = unwrapSOLInstruction(buyer, buyer);
29319
- unwrapIx && postInstructions.push(unwrapIx);
29240
+ const config = await this.getPoolConfig(pool.poolState.config);
29241
+ if (!config) {
29242
+ throw new Error(
29243
+ `Config not found: ${pool.poolState.config.toString()}`
29244
+ );
29320
29245
  }
29321
- const remainingAccounts = [];
29322
- if (rateLimiterApplied || enableFirstSwapWithMinFee) {
29323
- remainingAccounts.push({
29324
- isSigner: false,
29325
- isWritable: false,
29326
- pubkey: _web3js.SYSVAR_INSTRUCTIONS_PUBKEY
29327
- });
29246
+ const creatorTradingFeePercentage = config.creatorTradingFeePercentage;
29247
+ const totalTradingBaseFee = pool.poolState.metrics.totalTradingBaseFee;
29248
+ const totalTradingQuoteFee = pool.poolState.metrics.totalTradingQuoteFee;
29249
+ let creatorTotalTradingBaseFee = new (0, _bnjs2.default)(0);
29250
+ let creatorTotalTradingQuoteFee = new (0, _bnjs2.default)(0);
29251
+ let partnerTotalTradingBaseFee = totalTradingBaseFee;
29252
+ let partnerTotalTradingQuoteFee = totalTradingQuoteFee;
29253
+ if (creatorTradingFeePercentage > 0) {
29254
+ creatorTotalTradingBaseFee = totalTradingBaseFee.mul(new (0, _bnjs2.default)(creatorTradingFeePercentage)).div(new (0, _bnjs2.default)(100));
29255
+ creatorTotalTradingQuoteFee = totalTradingQuoteFee.mul(new (0, _bnjs2.default)(creatorTradingFeePercentage)).div(new (0, _bnjs2.default)(100));
29256
+ partnerTotalTradingBaseFee = totalTradingBaseFee.sub(
29257
+ creatorTotalTradingBaseFee
29258
+ );
29259
+ partnerTotalTradingQuoteFee = totalTradingQuoteFee.sub(
29260
+ creatorTotalTradingQuoteFee
29261
+ );
29328
29262
  }
29329
- return this.program.methods.swap({
29330
- amountIn: buyAmount,
29331
- minimumAmountOut
29332
- }).accountsPartial({
29333
- baseMint,
29334
- quoteMint,
29335
- pool,
29336
- baseVault,
29337
- quoteVault,
29338
- config,
29339
- poolAuthority: this.poolAuthority,
29340
- referralTokenAccount,
29341
- inputTokenAccount,
29342
- outputTokenAccount,
29343
- payer: buyer,
29344
- tokenBaseProgram: outputTokenProgram,
29345
- tokenQuoteProgram: inputTokenProgram
29346
- }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
29347
- }
29348
- async buildSwap2WithTransferHookBuyTx(firstBuyParam, baseMint, config, baseFee, activationType, quoteMint, enableFirstSwapWithMinFee) {
29349
- const {
29350
- buyer,
29351
- receiver,
29352
- buyAmount,
29353
- minimumAmountOut,
29354
- referralTokenAccount
29355
- } = firstBuyParam;
29356
- validateSwapAmount(buyAmount);
29357
- let rateLimiterApplied = false;
29358
- if (baseFee.baseFeeMode === 2 /* RateLimiter */) {
29359
- const currentPoint = await getCurrentPoint(
29360
- this.connection,
29361
- activationType
29362
- );
29363
- rateLimiterApplied = isRateLimiterApplied(
29364
- currentPoint,
29365
- new (0, _bnjs2.default)(0),
29366
- 1 /* QuoteToBase */,
29367
- baseFee.secondFactor,
29368
- baseFee.thirdFactor,
29369
- new (0, _bnjs2.default)(baseFee.firstFactor)
29370
- );
29371
- }
29372
- const quoteTokenFlag = await getTokenType(this.connection, quoteMint);
29373
- const { inputMint, outputMint, inputTokenProgram, outputTokenProgram } = this.prepareSwapParams(
29374
- false,
29375
- {
29376
- baseMint,
29377
- poolType: 1 /* Token2022 */
29263
+ const creatorUnclaimedBaseFee = pool.poolState.creatorBaseFee;
29264
+ const creatorUnclaimedQuoteFee = pool.poolState.creatorQuoteFee;
29265
+ const partnerUnclaimedBaseFee = pool.poolState.partnerBaseFee;
29266
+ const partnerUnclaimedQuoteFee = pool.poolState.partnerQuoteFee;
29267
+ const creatorClaimedBaseFee = creatorTotalTradingBaseFee.sub(
29268
+ creatorUnclaimedBaseFee
29269
+ );
29270
+ const creatorClaimedQuoteFee = creatorTotalTradingQuoteFee.sub(
29271
+ creatorUnclaimedQuoteFee
29272
+ );
29273
+ const partnerClaimedBaseFee = partnerTotalTradingBaseFee.sub(
29274
+ partnerUnclaimedBaseFee
29275
+ );
29276
+ const partnerClaimedQuoteFee = partnerTotalTradingQuoteFee.sub(
29277
+ partnerUnclaimedQuoteFee
29278
+ );
29279
+ return {
29280
+ creator: {
29281
+ unclaimedBaseFee: creatorUnclaimedBaseFee,
29282
+ unclaimedQuoteFee: creatorUnclaimedQuoteFee,
29283
+ claimedBaseFee: creatorClaimedBaseFee,
29284
+ claimedQuoteFee: creatorClaimedQuoteFee,
29285
+ totalBaseFee: creatorTotalTradingBaseFee,
29286
+ totalQuoteFee: creatorTotalTradingQuoteFee
29378
29287
  },
29379
- {
29380
- quoteMint,
29381
- quoteTokenFlag
29288
+ partner: {
29289
+ unclaimedBaseFee: partnerUnclaimedBaseFee,
29290
+ unclaimedQuoteFee: partnerUnclaimedQuoteFee,
29291
+ claimedBaseFee: partnerClaimedBaseFee,
29292
+ claimedQuoteFee: partnerClaimedQuoteFee,
29293
+ totalBaseFee: partnerTotalTradingBaseFee,
29294
+ totalQuoteFee: partnerTotalTradingQuoteFee
29382
29295
  }
29296
+ };
29297
+ }
29298
+ /**
29299
+ * Fetch fee metrics for every pool linked to a config.
29300
+ */
29301
+ async getPoolsFeesByConfig(configAddress) {
29302
+ const filteredPools = await this.getPoolsByConfig(configAddress);
29303
+ return filteredPools.map((pool) => ({
29304
+ poolAddress: pool.publicKey,
29305
+ partnerBaseFee: pool.account.poolState.partnerBaseFee,
29306
+ partnerQuoteFee: pool.account.poolState.partnerQuoteFee,
29307
+ creatorBaseFee: pool.account.poolState.creatorBaseFee,
29308
+ creatorQuoteFee: pool.account.poolState.creatorQuoteFee,
29309
+ totalTradingBaseFee: pool.account.poolState.metrics.totalTradingBaseFee,
29310
+ totalTradingQuoteFee: pool.account.poolState.metrics.totalTradingQuoteFee
29311
+ }));
29312
+ }
29313
+ /**
29314
+ * Fetch fee metrics for every pool linked to a creator.
29315
+ */
29316
+ async getPoolsFeesByCreator(creatorAddress) {
29317
+ const filteredPools = await this.getPoolsByCreator(creatorAddress);
29318
+ return filteredPools.map((pool) => ({
29319
+ poolAddress: pool.publicKey,
29320
+ partnerBaseFee: pool.account.poolState.partnerBaseFee,
29321
+ partnerQuoteFee: pool.account.poolState.partnerQuoteFee,
29322
+ creatorBaseFee: pool.account.poolState.creatorBaseFee,
29323
+ creatorQuoteFee: pool.account.poolState.creatorQuoteFee,
29324
+ totalTradingBaseFee: pool.account.poolState.metrics.totalTradingBaseFee,
29325
+ totalTradingQuoteFee: pool.account.poolState.metrics.totalTradingQuoteFee
29326
+ }));
29327
+ }
29328
+ /**
29329
+ * Fetch DAMM V1 migration metadata for a pool.
29330
+ */
29331
+ async getDammV1MigrationMetadata(poolAddress) {
29332
+ const migrationMetadataAddress = deriveDammV1MigrationMetadataAddress(poolAddress);
29333
+ const metadata = await this.program.account.meteoraDammMigrationMetadata.fetch(
29334
+ migrationMetadataAddress
29383
29335
  );
29384
- const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29385
- const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29386
- const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29387
- const preInstructions = [];
29388
- const [
29389
- { ataPubkey: inputTokenAccount, ix: createAtaTokenAIx },
29390
- { ataPubkey: outputTokenAccount, ix: createAtaTokenBIx }
29391
- ] = await Promise.all([
29392
- getOrCreateATAInstruction(
29393
- this.connection,
29394
- inputMint,
29395
- buyer,
29396
- buyer,
29397
- true,
29398
- inputTokenProgram
29399
- ),
29400
- getOrCreateATAInstruction(
29401
- this.connection,
29402
- outputMint,
29403
- receiver ? receiver : buyer,
29404
- buyer,
29405
- true,
29406
- outputTokenProgram
29407
- )
29408
- ]);
29409
- createAtaTokenAIx && preInstructions.push(createAtaTokenAIx);
29410
- createAtaTokenBIx && preInstructions.push(createAtaTokenBIx);
29411
- if (inputMint.equals(_spltoken.NATIVE_MINT)) {
29412
- preInstructions.push(
29413
- ...wrapSOLInstruction(
29414
- buyer,
29415
- inputTokenAccount,
29416
- BigInt(buyAmount.toString())
29417
- )
29418
- );
29419
- }
29420
- const postInstructions = [];
29421
- if ([inputMint.toBase58(), outputMint.toBase58()].includes(
29422
- _spltoken.NATIVE_MINT.toBase58()
29423
- )) {
29424
- const unwrapIx = unwrapSOLInstruction(buyer, buyer);
29425
- unwrapIx && postInstructions.push(unwrapIx);
29336
+ return metadata;
29337
+ }
29338
+ };
29339
+
29340
+ // src/services/program.ts
29341
+ var DynamicBondingCurveProgram = class {
29342
+ constructor(connection, commitment) {
29343
+ const { program } = createDbcProgram(connection, commitment);
29344
+ this.program = program;
29345
+ this.connection = connection;
29346
+ this.poolAuthority = deriveDbcPoolAuthority();
29347
+ this.commitment = commitment;
29348
+ this.state = new StateService(connection, commitment);
29349
+ }
29350
+ async getPoolWithConfig(pool) {
29351
+ const virtualPool = await this.state.getPool(pool);
29352
+ if (!virtualPool) {
29353
+ throw new Error(`Pool not found: ${pool.toString()}`);
29426
29354
  }
29427
- const remainingAccounts = [];
29428
- if (rateLimiterApplied || enableFirstSwapWithMinFee) {
29429
- remainingAccounts.push({
29430
- isSigner: false,
29431
- isWritable: false,
29432
- pubkey: _web3js.SYSVAR_INSTRUCTIONS_PUBKEY
29433
- });
29355
+ const poolConfigState = await this.state.getPoolConfig(
29356
+ virtualPool.poolState.config
29357
+ );
29358
+ if (!poolConfigState) {
29359
+ throw new Error(`Pool config not found for virtual pool`);
29434
29360
  }
29435
- const transferHookAccountTypes = referralTokenAccount != null ? [
29436
- AccountsType.TransferHookBase,
29437
- AccountsType.TransferHookBaseReferral
29438
- ] : [AccountsType.TransferHookBase];
29439
- let transferHookAccountsResult;
29440
- if (firstBuyParam.transferHookAccountsInfo && firstBuyParam.transferHookAccounts) {
29441
- transferHookAccountsResult = {
29442
- info: firstBuyParam.transferHookAccountsInfo,
29443
- accounts: firstBuyParam.transferHookAccounts
29361
+ return { virtualPool, poolConfigState };
29362
+ }
29363
+ prepareSwapParams(swapBaseForQuote, virtualPoolState, poolConfigState) {
29364
+ if (swapBaseForQuote) {
29365
+ return {
29366
+ inputMint: new (0, _web3js.PublicKey)(virtualPoolState.baseMint),
29367
+ outputMint: new (0, _web3js.PublicKey)(poolConfigState.quoteMint),
29368
+ inputTokenProgram: getTokenProgram(virtualPoolState.poolType),
29369
+ outputTokenProgram: getTokenProgram(
29370
+ poolConfigState.quoteTokenFlag
29371
+ )
29444
29372
  };
29445
- } else {
29446
- try {
29447
- transferHookAccountsResult = await this.getRemainingAccountsForTransferHook(
29448
- baseMint,
29449
- transferHookAccountTypes
29450
- );
29451
- } catch (e3) {
29452
- throw new Error(
29453
- `Unable to resolve transfer-hook remaining accounts for ${baseMint.toString()}. When bundling pool initialization with the first buy, pass transferHookAccountsInfo and transferHookAccounts on the first-buy params.`
29454
- );
29455
- }
29456
29373
  }
29457
- remainingAccounts.push(...transferHookAccountsResult.accounts);
29458
- return this.program.methods.swap2WithTransferHook(
29459
- {
29460
- amount0: buyAmount,
29461
- amount1: minimumAmountOut,
29462
- swapMode: 0 /* ExactIn */
29463
- },
29464
- transferHookAccountsResult.info
29465
- ).accountsPartial({
29466
- baseMint,
29467
- quoteMint,
29468
- pool,
29469
- baseVault,
29470
- quoteVault,
29374
+ return {
29375
+ inputMint: new (0, _web3js.PublicKey)(poolConfigState.quoteMint),
29376
+ outputMint: new (0, _web3js.PublicKey)(virtualPoolState.baseMint),
29377
+ inputTokenProgram: getTokenProgram(poolConfigState.quoteTokenFlag),
29378
+ outputTokenProgram: getTokenProgram(virtualPoolState.poolType)
29379
+ };
29380
+ }
29381
+ async buildCreateConfigTx(configParam, config, feeClaimer, leftoverReceiver, quoteMint, payer) {
29382
+ validateConfigParameters({ ...configParam, leftoverReceiver });
29383
+ return this.program.methods.createConfig(configParam).accountsPartial({
29471
29384
  config,
29472
- poolAuthority: this.poolAuthority,
29473
- referralTokenAccount,
29474
- inputTokenAccount,
29475
- outputTokenAccount,
29476
- payer: buyer,
29477
- tokenBaseProgram: outputTokenProgram,
29478
- tokenQuoteProgram: inputTokenProgram
29479
- }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
29385
+ feeClaimer,
29386
+ leftoverReceiver,
29387
+ quoteMint,
29388
+ payer
29389
+ }).transaction();
29480
29390
  }
29481
- async buildClaimTradingFeeAccountsForSol(params) {
29391
+ async buildCreateConfigWithTransferHookTx(configParam, config, feeClaimer, leftoverReceiver, quoteMint, transferHookProgram, payer) {
29392
+ validateConfigParameters(
29393
+ { ...configParam, leftoverReceiver },
29394
+ { isTransferHook: true, transferHookProgram }
29395
+ );
29396
+ return this.program.methods.createConfigWithTransferHook(configParam).accountsPartial({
29397
+ config,
29398
+ feeClaimer,
29399
+ leftoverReceiver,
29400
+ quoteMint,
29401
+ transferHookProgram,
29402
+ payer
29403
+ }).transaction();
29404
+ }
29405
+ async initializeSplPool(params) {
29482
29406
  const {
29483
- payer,
29484
- feeReceiver,
29485
- tempWSolAcc,
29407
+ name,
29408
+ symbol,
29409
+ uri,
29486
29410
  pool,
29487
- virtualPool,
29488
- poolConfigState,
29489
- tokenBaseProgram,
29490
- tokenQuoteProgram
29411
+ config,
29412
+ payer,
29413
+ poolCreator,
29414
+ mintMetadata,
29415
+ baseMint,
29416
+ baseVault,
29417
+ quoteVault,
29418
+ quoteMint
29491
29419
  } = params;
29492
- const preInstructions = [];
29493
- const postInstructions = [];
29494
- const tokenBaseAccount = findAssociatedTokenAddress(
29495
- feeReceiver,
29496
- virtualPool.poolState.baseMint,
29497
- tokenBaseProgram
29498
- );
29499
- const tokenQuoteAccount = findAssociatedTokenAddress(
29500
- tempWSolAcc,
29501
- poolConfigState.quoteMint,
29502
- tokenQuoteProgram
29503
- );
29504
- preInstructions.push(
29505
- _spltoken.createAssociatedTokenAccountIdempotentInstruction.call(void 0,
29506
- payer,
29507
- tokenBaseAccount,
29508
- feeReceiver,
29509
- virtualPool.poolState.baseMint,
29510
- tokenBaseProgram
29511
- ),
29512
- _spltoken.createAssociatedTokenAccountIdempotentInstruction.call(void 0,
29513
- payer,
29514
- tokenQuoteAccount,
29515
- tempWSolAcc,
29516
- poolConfigState.quoteMint,
29517
- tokenQuoteProgram
29518
- )
29519
- );
29520
- const unwrapSolIx = unwrapSOLInstruction(tempWSolAcc, feeReceiver);
29521
- unwrapSolIx && postInstructions.push(unwrapSolIx);
29522
- const accounts = {
29523
- poolAuthority: this.poolAuthority,
29420
+ return this.program.methods.initializeVirtualPoolWithSplToken({
29421
+ name,
29422
+ symbol,
29423
+ uri
29424
+ }).accountsPartial({
29524
29425
  pool,
29525
- tokenAAccount: tokenBaseAccount,
29526
- tokenBAccount: tokenQuoteAccount,
29527
- baseVault: virtualPool.poolState.baseVault,
29528
- quoteVault: virtualPool.poolState.quoteVault,
29529
- baseMint: virtualPool.poolState.baseMint,
29530
- quoteMint: poolConfigState.quoteMint,
29531
- tokenBaseProgram,
29532
- tokenQuoteProgram
29533
- };
29534
- return { accounts, preInstructions, postInstructions };
29426
+ config,
29427
+ payer,
29428
+ creator: poolCreator,
29429
+ mintMetadata,
29430
+ baseMint,
29431
+ poolAuthority: this.poolAuthority,
29432
+ baseVault,
29433
+ quoteVault,
29434
+ quoteMint,
29435
+ tokenQuoteProgram: _spltoken.TOKEN_PROGRAM_ID,
29436
+ metadataProgram: METAPLEX_PROGRAM_ID,
29437
+ tokenProgram: _spltoken.TOKEN_PROGRAM_ID
29438
+ }).transaction();
29535
29439
  }
29536
- async buildClaimTradingFeeAccountsForNonSol(params) {
29440
+ async initializeToken2022Pool(params) {
29537
29441
  const {
29538
- payer,
29539
- feeReceiver,
29442
+ name,
29443
+ symbol,
29444
+ uri,
29540
29445
  pool,
29541
- virtualPool,
29542
- poolConfigState,
29543
- tokenBaseProgram,
29544
- tokenQuoteProgram
29446
+ config,
29447
+ payer,
29448
+ poolCreator,
29449
+ baseMint,
29450
+ baseVault,
29451
+ quoteVault,
29452
+ quoteMint
29545
29453
  } = params;
29454
+ return this.program.methods.initializeVirtualPoolWithToken2022({
29455
+ name,
29456
+ symbol,
29457
+ uri
29458
+ }).accountsPartial({
29459
+ pool,
29460
+ config,
29461
+ payer,
29462
+ creator: poolCreator,
29463
+ baseMint,
29464
+ poolAuthority: this.poolAuthority,
29465
+ baseVault,
29466
+ quoteVault,
29467
+ quoteMint,
29468
+ tokenQuoteProgram: _spltoken.TOKEN_PROGRAM_ID,
29469
+ tokenProgram: _spltoken.TOKEN_2022_PROGRAM_ID
29470
+ }).transaction();
29471
+ }
29472
+ async initializeToken2022PoolWithTransferHook(params) {
29546
29473
  const {
29547
- ataTokenA: tokenBaseAccount,
29548
- ataTokenB: tokenQuoteAccount,
29549
- instructions: preInstructions
29550
- } = await this.prepareTokenAccounts(
29551
- feeReceiver,
29474
+ name,
29475
+ symbol,
29476
+ uri,
29477
+ pool,
29478
+ config,
29552
29479
  payer,
29553
- virtualPool.poolState.baseMint,
29554
- poolConfigState.quoteMint,
29555
- tokenBaseProgram,
29480
+ poolCreator,
29481
+ baseMint,
29482
+ baseVault,
29483
+ quoteVault,
29484
+ quoteMint,
29485
+ transferHookProgram,
29556
29486
  tokenQuoteProgram
29557
- );
29558
- const accounts = {
29487
+ } = params;
29488
+ return this.program.methods.initializeVirtualPoolWithToken2022TransferHook({
29489
+ name,
29490
+ symbol,
29491
+ uri
29492
+ }).accountsPartial({
29493
+ pool,
29494
+ config,
29495
+ payer,
29496
+ creator: poolCreator,
29497
+ baseMint,
29559
29498
  poolAuthority: this.poolAuthority,
29499
+ baseVault,
29500
+ quoteVault,
29501
+ quoteMint,
29502
+ transferHookProgram,
29503
+ tokenQuoteProgram,
29504
+ tokenProgram: _spltoken.TOKEN_2022_PROGRAM_ID
29505
+ }).transaction();
29506
+ }
29507
+ async buildCreatePoolTx(createPoolParam, tokenType, quoteMint) {
29508
+ const { baseMint, name, symbol, uri, poolCreator, config, payer } = createPoolParam;
29509
+ const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29510
+ const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29511
+ const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29512
+ const baseParams = {
29513
+ name,
29514
+ symbol,
29515
+ uri,
29560
29516
  pool,
29561
- tokenAAccount: tokenBaseAccount,
29562
- tokenBAccount: tokenQuoteAccount,
29563
- baseVault: virtualPool.poolState.baseVault,
29564
- quoteVault: virtualPool.poolState.quoteVault,
29565
- baseMint: virtualPool.poolState.baseMint,
29566
- quoteMint: poolConfigState.quoteMint,
29567
- tokenBaseProgram,
29568
- tokenQuoteProgram
29517
+ config,
29518
+ payer,
29519
+ poolCreator,
29520
+ baseMint,
29521
+ baseVault,
29522
+ quoteVault,
29523
+ quoteMint
29569
29524
  };
29570
- return { accounts, preInstructions };
29571
- }
29572
- async getRemainingAccountsForTransferHook(mint, accountTypes = [AccountsType.TransferHookBase]) {
29573
- const emptyAccounts = { info: { slices: [] }, accounts: [] };
29574
- const mintInfo = await this.connection.getAccountInfo(
29575
- mint,
29576
- this.commitment
29577
- );
29578
- if (!mintInfo) {
29579
- throw new Error(`Invalid mint: ${mint.toString()}`);
29580
- }
29581
- if (mintInfo.owner.equals(_spltoken.TOKEN_PROGRAM_ID)) {
29582
- return emptyAccounts;
29583
- }
29584
- const mintState = _spltoken.unpackMint.call(void 0, mint, mintInfo, _spltoken.TOKEN_2022_PROGRAM_ID);
29585
- const transferHook = _spltoken.getTransferHook.call(void 0, mintState);
29586
- if (!transferHook || transferHook.programId.equals(_web3js.PublicKey.default)) {
29587
- return emptyAccounts;
29525
+ if (tokenType === 0 /* SPLToken */) {
29526
+ const mintMetadata = deriveMintMetadata(baseMint);
29527
+ return this.initializeSplPool({ ...baseParams, mintMetadata });
29588
29528
  }
29589
- const transferWithHookIx = await _spltoken.createTransferCheckedWithTransferHookInstruction.call(void 0,
29590
- this.connection,
29591
- _web3js.PublicKey.default,
29592
- mint,
29593
- _web3js.PublicKey.default,
29594
- _web3js.PublicKey.default,
29595
- BigInt(0),
29596
- mintState.decimals,
29597
- [],
29598
- this.commitment,
29599
- _spltoken.TOKEN_2022_PROGRAM_ID
29600
- );
29601
- const transferHookAccounts = transferWithHookIx.keys.slice(4);
29602
- const slices = accountTypes.map((accountsType) => ({
29603
- accountsType,
29604
- length: transferHookAccounts.length
29605
- }));
29606
- const accounts = accountTypes.flatMap(() => transferHookAccounts);
29607
- return { info: { slices }, accounts };
29529
+ return this.initializeToken2022Pool(baseParams);
29608
29530
  }
29609
- async buildWithdrawMigrationFeeTx(role, pool, sender) {
29610
- const { virtualPool, poolConfigState } = await this.getPoolWithConfig(pool);
29611
- const tokenQuoteProgram = getTokenProgram(
29612
- poolConfigState.quoteTokenFlag
29613
- );
29614
- const preInstructions = [];
29615
- const postInstructions = [];
29616
- const { ataPubkey: tokenQuoteAccount, ix: createTokenQuoteAccountIx } = await getOrCreateATAInstruction(
29617
- this.connection,
29618
- poolConfigState.quoteMint,
29619
- sender,
29620
- sender,
29621
- true,
29622
- tokenQuoteProgram
29623
- );
29624
- createTokenQuoteAccountIx && preInstructions.push(createTokenQuoteAccountIx);
29625
- if (poolConfigState.quoteMint.equals(_spltoken.NATIVE_MINT)) {
29626
- const unwrapSolIx = unwrapSOLInstruction(sender, sender);
29627
- unwrapSolIx && postInstructions.push(unwrapSolIx);
29628
- }
29629
- return this.program.methods.withdrawMigrationFee(role === "partner" ? 0 : 1).accountsPartial({
29630
- poolAuthority: this.poolAuthority,
29631
- config: virtualPool.poolState.config,
29632
- virtualPool: pool,
29633
- tokenQuoteAccount,
29634
- quoteVault: virtualPool.poolState.quoteVault,
29635
- quoteMint: poolConfigState.quoteMint,
29636
- sender,
29531
+ async buildCreatePoolWithTransferHookTx(createPoolParam, quoteMint, tokenQuoteProgram) {
29532
+ const {
29533
+ baseMint,
29534
+ name,
29535
+ symbol,
29536
+ uri,
29537
+ poolCreator,
29538
+ config,
29539
+ payer,
29540
+ transferHookProgram
29541
+ } = createPoolParam;
29542
+ if (!validateTransferHookProgram(transferHookProgram)) {
29543
+ throw new Error(
29544
+ "Invalid transfer hook program: cannot be the DBC program, SPL Token, SPL Token-2022, or the default pubkey"
29545
+ );
29546
+ }
29547
+ const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29548
+ const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29549
+ const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29550
+ return this.initializeToken2022PoolWithTransferHook({
29551
+ name,
29552
+ symbol,
29553
+ uri,
29554
+ pool,
29555
+ config,
29556
+ payer,
29557
+ poolCreator,
29558
+ baseMint,
29559
+ baseVault,
29560
+ quoteVault,
29561
+ quoteMint,
29562
+ transferHookProgram,
29637
29563
  tokenQuoteProgram
29638
- }).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
29564
+ });
29639
29565
  }
29640
- async prepareTokenAccounts(owner, payer, tokenAMint, tokenBMint, tokenAProgram, tokenBProgram) {
29641
- const instructions = [];
29566
+ async buildSwapBuyTx(firstBuyParam, baseMint, config, baseFee, swapBaseForQuote, activationType, tokenType, quoteMint, enableFirstSwapWithMinFee) {
29567
+ const {
29568
+ buyer,
29569
+ receiver,
29570
+ buyAmount,
29571
+ minimumAmountOut,
29572
+ referralTokenAccount
29573
+ } = firstBuyParam;
29574
+ validateSwapAmount(buyAmount);
29575
+ let rateLimiterApplied = false;
29576
+ if (baseFee.baseFeeMode === 2 /* RateLimiter */) {
29577
+ const currentPoint = await getCurrentPoint(
29578
+ this.connection,
29579
+ activationType
29580
+ );
29581
+ rateLimiterApplied = isRateLimiterApplied(
29582
+ currentPoint,
29583
+ new (0, _bnjs2.default)(0),
29584
+ swapBaseForQuote ? 0 /* BaseToQuote */ : 1 /* QuoteToBase */,
29585
+ baseFee.secondFactor,
29586
+ baseFee.thirdFactor,
29587
+ new (0, _bnjs2.default)(baseFee.firstFactor)
29588
+ );
29589
+ }
29590
+ const quoteTokenFlag = await getTokenType(this.connection, quoteMint);
29591
+ const { inputMint, outputMint, inputTokenProgram, outputTokenProgram } = this.prepareSwapParams(
29592
+ false,
29593
+ {
29594
+ baseMint,
29595
+ poolType: tokenType
29596
+ },
29597
+ {
29598
+ quoteMint,
29599
+ quoteTokenFlag
29600
+ }
29601
+ );
29602
+ const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29603
+ const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29604
+ const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29605
+ const preInstructions = [];
29642
29606
  const [
29643
- { ataPubkey: ataTokenA, ix: createAtaTokenAIx },
29644
- { ataPubkey: ataTokenB, ix: createAtaTokenBIx }
29607
+ { ataPubkey: inputTokenAccount, ix: createAtaTokenAIx },
29608
+ { ataPubkey: outputTokenAccount, ix: createAtaTokenBIx }
29645
29609
  ] = await Promise.all([
29646
29610
  getOrCreateATAInstruction(
29647
29611
  this.connection,
29648
- tokenAMint,
29649
- owner,
29650
- payer,
29612
+ inputMint,
29613
+ buyer,
29614
+ buyer,
29651
29615
  true,
29652
- tokenAProgram
29616
+ inputTokenProgram
29653
29617
  ),
29654
29618
  getOrCreateATAInstruction(
29655
29619
  this.connection,
29656
- tokenBMint,
29657
- owner,
29658
- payer,
29620
+ outputMint,
29621
+ receiver ? receiver : buyer,
29622
+ buyer,
29659
29623
  true,
29660
- tokenBProgram
29624
+ outputTokenProgram
29661
29625
  )
29662
29626
  ]);
29663
- createAtaTokenAIx && instructions.push(createAtaTokenAIx);
29664
- createAtaTokenBIx && instructions.push(createAtaTokenBIx);
29665
- return { ataTokenA, ataTokenB, instructions };
29666
- }
29667
- /**
29668
- * Return the underlying Anchor program client.
29669
- */
29670
- getProgram() {
29671
- return this.program;
29672
- }
29673
- };
29674
-
29675
- // src/services/migration.ts
29676
-
29677
-
29678
-
29679
-
29680
-
29681
-
29682
-
29683
-
29684
- // src/services/state.ts
29685
-
29686
-
29687
-
29688
-
29689
-
29690
- var StateService = class extends DynamicBondingCurveProgram {
29691
- constructor(connection, commitment) {
29692
- super(connection, commitment);
29693
- }
29694
- /**
29695
- * Fetch virtual pools across both the standard and transfer-hook account variants.
29696
- */
29697
- async fetchVirtualPools(filters) {
29698
- const [pools, transferHookPools] = await Promise.all([
29699
- this.program.account.virtualPool.all(filters),
29700
- this.program.account.transferHookPool.all(filters)
29701
- ]);
29702
- return [...pools, ...transferHookPools];
29703
- }
29704
- /**
29705
- * Fetch pool configs across both the standard and transfer-hook account variants.
29706
- */
29707
- async fetchPoolConfigs(filters) {
29708
- const [configs, transferHookConfigs] = await Promise.all([
29709
- this.program.account.poolConfig.all(filters),
29710
- this.program.account.configWithTransferHook.all(filters)
29711
- ]);
29712
- return [
29713
- ...configs,
29714
- ...transferHookConfigs.map((account) => ({
29715
- publicKey: account.publicKey,
29716
- account: account.account.config
29717
- }))
29718
- ];
29719
- }
29720
- /**
29721
- * Fetch a pool config account.
29722
- */
29723
- async getPoolConfig(configAddress) {
29724
- const address = configAddress instanceof _web3js.PublicKey ? configAddress : new (0, _web3js.PublicKey)(configAddress);
29725
- try {
29726
- const poolConfig = await this.program.account.poolConfig.fetchNullable(
29727
- address,
29728
- this.commitment
29627
+ createAtaTokenAIx && preInstructions.push(createAtaTokenAIx);
29628
+ createAtaTokenBIx && preInstructions.push(createAtaTokenBIx);
29629
+ if (inputMint.equals(_spltoken.NATIVE_MINT)) {
29630
+ preInstructions.push(
29631
+ ...wrapSOLInstruction(
29632
+ buyer,
29633
+ inputTokenAccount,
29634
+ BigInt(buyAmount.toString())
29635
+ )
29729
29636
  );
29730
- if (poolConfig) {
29731
- return poolConfig;
29732
- }
29733
- } catch (e4) {
29734
29637
  }
29735
- const configWithTransferHook = await this.program.account.configWithTransferHook.fetchNullable(
29736
- address,
29737
- this.commitment
29738
- );
29739
- return _nullishCoalesce(_optionalChain([configWithTransferHook, 'optionalAccess', _29 => _29.config]), () => ( null));
29740
- }
29741
- /**
29742
- * Fetch all pool config accounts.
29743
- */
29744
- async getPoolConfigs() {
29745
- return this.fetchPoolConfigs();
29746
- }
29747
- /**
29748
- * Fetch all pool configs owned by a wallet.
29749
- */
29750
- async getPoolConfigsByOwner(owner) {
29751
- const filters = createProgramAccountFilter(owner, 72);
29752
- return this.fetchPoolConfigs(filters);
29753
- }
29754
- /**
29755
- * Fetch a virtual pool account.
29756
- */
29757
- async getPool(poolAddress) {
29758
- const address = poolAddress instanceof _web3js.PublicKey ? poolAddress : new (0, _web3js.PublicKey)(poolAddress);
29759
- try {
29760
- const virtualPool = await this.program.account.virtualPool.fetchNullable(
29761
- address,
29762
- this.commitment
29763
- );
29764
- if (virtualPool) {
29765
- return virtualPool;
29766
- }
29767
- } catch (e5) {
29638
+ const postInstructions = [];
29639
+ if ([inputMint.toBase58(), outputMint.toBase58()].includes(
29640
+ _spltoken.NATIVE_MINT.toBase58()
29641
+ )) {
29642
+ const unwrapIx = unwrapSOLInstruction(buyer, buyer);
29643
+ unwrapIx && postInstructions.push(unwrapIx);
29768
29644
  }
29769
- return await this.program.account.transferHookPool.fetchNullable(
29770
- address,
29771
- this.commitment
29772
- );
29773
- }
29774
- /**
29775
- * Fetch all virtual pool accounts.
29776
- */
29777
- async getPools() {
29778
- return this.fetchVirtualPools();
29645
+ const remainingAccounts = [];
29646
+ if (rateLimiterApplied || enableFirstSwapWithMinFee) {
29647
+ remainingAccounts.push({
29648
+ isSigner: false,
29649
+ isWritable: false,
29650
+ pubkey: _web3js.SYSVAR_INSTRUCTIONS_PUBKEY
29651
+ });
29652
+ }
29653
+ return this.program.methods.swap({
29654
+ amountIn: buyAmount,
29655
+ minimumAmountOut
29656
+ }).accountsPartial({
29657
+ baseMint,
29658
+ quoteMint,
29659
+ pool,
29660
+ baseVault,
29661
+ quoteVault,
29662
+ config,
29663
+ poolAuthority: this.poolAuthority,
29664
+ referralTokenAccount,
29665
+ inputTokenAccount,
29666
+ outputTokenAccount,
29667
+ payer: buyer,
29668
+ tokenBaseProgram: outputTokenProgram,
29669
+ tokenQuoteProgram: inputTokenProgram
29670
+ }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
29779
29671
  }
29780
- /**
29781
- * Fetch all virtual pools that use a config.
29782
- */
29783
- async getPoolsByConfig(configAddress) {
29784
- const filters = createProgramAccountFilter(configAddress, 72);
29785
- return this.fetchVirtualPools(filters);
29786
- }
29787
- /**
29788
- * Fetch all virtual pools created by a wallet.
29789
- */
29790
- async getPoolsByCreator(creatorAddress) {
29791
- const filters = createProgramAccountFilter(creatorAddress, 104);
29792
- return this.fetchVirtualPools(filters);
29793
- }
29794
- /**
29795
- * Fetch the first virtual pool that uses a base mint.
29796
- */
29797
- async getPoolByBaseMint(baseMint) {
29798
- const filters = createProgramAccountFilter(baseMint, 136);
29799
- const pools = await this.fetchVirtualPools(filters);
29800
- return pools.length > 0 ? pools[0] : null;
29801
- }
29802
- /**
29803
- * Fetch the migration quote threshold for a pool.
29804
- */
29805
- async getPoolMigrationQuoteThreshold(poolAddress) {
29806
- const pool = await this.getPool(poolAddress);
29807
- if (!pool) {
29808
- throw new Error(`Pool not found: ${poolAddress.toString()}`);
29672
+ async buildSwap2WithTransferHookBuyTx(firstBuyParam, baseMint, config, baseFee, activationType, quoteMint, enableFirstSwapWithMinFee) {
29673
+ const {
29674
+ buyer,
29675
+ receiver,
29676
+ buyAmount,
29677
+ minimumAmountOut,
29678
+ referralTokenAccount
29679
+ } = firstBuyParam;
29680
+ validateSwapAmount(buyAmount);
29681
+ let rateLimiterApplied = false;
29682
+ if (baseFee.baseFeeMode === 2 /* RateLimiter */) {
29683
+ const currentPoint = await getCurrentPoint(
29684
+ this.connection,
29685
+ activationType
29686
+ );
29687
+ rateLimiterApplied = isRateLimiterApplied(
29688
+ currentPoint,
29689
+ new (0, _bnjs2.default)(0),
29690
+ 1 /* QuoteToBase */,
29691
+ baseFee.secondFactor,
29692
+ baseFee.thirdFactor,
29693
+ new (0, _bnjs2.default)(baseFee.firstFactor)
29694
+ );
29809
29695
  }
29810
- const configAddress = pool.poolState.config;
29811
- const config = await this.getPoolConfig(configAddress);
29812
- return config.migrationQuoteThreshold;
29813
- }
29814
- /**
29815
- * Return quote-token curve progress as a ratio between 0 and 1.
29816
- */
29817
- async getPoolQuoteTokenCurveProgress(poolAddress) {
29818
- const pool = await this.getPool(poolAddress);
29819
- if (!pool) {
29820
- throw new Error(`Pool not found: ${poolAddress.toString()}`);
29696
+ const quoteTokenFlag = await getTokenType(this.connection, quoteMint);
29697
+ const { inputMint, outputMint, inputTokenProgram, outputTokenProgram } = this.prepareSwapParams(
29698
+ false,
29699
+ {
29700
+ baseMint,
29701
+ poolType: 1 /* Token2022 */
29702
+ },
29703
+ {
29704
+ quoteMint,
29705
+ quoteTokenFlag
29706
+ }
29707
+ );
29708
+ const pool = deriveDbcPoolAddress(quoteMint, baseMint, config);
29709
+ const baseVault = deriveDbcTokenVaultAddress(pool, baseMint);
29710
+ const quoteVault = deriveDbcTokenVaultAddress(pool, quoteMint);
29711
+ const preInstructions = [];
29712
+ const [
29713
+ { ataPubkey: inputTokenAccount, ix: createAtaTokenAIx },
29714
+ { ataPubkey: outputTokenAccount, ix: createAtaTokenBIx }
29715
+ ] = await Promise.all([
29716
+ getOrCreateATAInstruction(
29717
+ this.connection,
29718
+ inputMint,
29719
+ buyer,
29720
+ buyer,
29721
+ true,
29722
+ inputTokenProgram
29723
+ ),
29724
+ getOrCreateATAInstruction(
29725
+ this.connection,
29726
+ outputMint,
29727
+ receiver ? receiver : buyer,
29728
+ buyer,
29729
+ true,
29730
+ outputTokenProgram
29731
+ )
29732
+ ]);
29733
+ createAtaTokenAIx && preInstructions.push(createAtaTokenAIx);
29734
+ createAtaTokenBIx && preInstructions.push(createAtaTokenBIx);
29735
+ if (inputMint.equals(_spltoken.NATIVE_MINT)) {
29736
+ preInstructions.push(
29737
+ ...wrapSOLInstruction(
29738
+ buyer,
29739
+ inputTokenAccount,
29740
+ BigInt(buyAmount.toString())
29741
+ )
29742
+ );
29821
29743
  }
29822
- const config = await this.getPoolConfig(pool.poolState.config);
29823
- const quoteReserve = pool.poolState.quoteReserve;
29824
- const migrationThreshold = config.migrationQuoteThreshold;
29825
- const quoteReserveDecimal = new (0, _decimaljs2.default)(quoteReserve.toString());
29826
- const thresholdDecimal = new (0, _decimaljs2.default)(migrationThreshold.toString());
29827
- const progress = quoteReserveDecimal.div(thresholdDecimal).toNumber();
29828
- return Math.min(Math.max(progress, 0), 1);
29829
- }
29830
- /**
29831
- * Return base-token curve progress as a ratio between 0 and 1.
29832
- */
29833
- async getPoolBaseTokenCurveProgress(poolAddress) {
29834
- const pool = await this.getPool(poolAddress);
29835
- if (!pool) {
29836
- throw new Error(`Pool not found: ${poolAddress.toString()}`);
29744
+ const postInstructions = [];
29745
+ if ([inputMint.toBase58(), outputMint.toBase58()].includes(
29746
+ _spltoken.NATIVE_MINT.toBase58()
29747
+ )) {
29748
+ const unwrapIx = unwrapSOLInstruction(buyer, buyer);
29749
+ unwrapIx && postInstructions.push(unwrapIx);
29837
29750
  }
29838
- const config = await this.getPoolConfig(pool.poolState.config);
29839
- const baseSold = new (0, _decimaljs2.default)(
29840
- getBaseTokenForSwap(
29841
- config.sqrtStartPrice,
29842
- pool.poolState.sqrtPrice,
29843
- config.curve
29844
- ).toString()
29751
+ const remainingAccounts = [];
29752
+ if (rateLimiterApplied || enableFirstSwapWithMinFee) {
29753
+ remainingAccounts.push({
29754
+ isSigner: false,
29755
+ isWritable: false,
29756
+ pubkey: _web3js.SYSVAR_INSTRUCTIONS_PUBKEY
29757
+ });
29758
+ }
29759
+ const transferHookAccountTypes = referralTokenAccount != null ? [
29760
+ AccountsType.TransferHookBase,
29761
+ AccountsType.TransferHookBaseReferral
29762
+ ] : [AccountsType.TransferHookBase];
29763
+ let transferHookAccountsResult;
29764
+ if (firstBuyParam.transferHookAccountsInfo && firstBuyParam.transferHookAccounts) {
29765
+ transferHookAccountsResult = {
29766
+ info: firstBuyParam.transferHookAccountsInfo,
29767
+ accounts: firstBuyParam.transferHookAccounts
29768
+ };
29769
+ } else {
29770
+ try {
29771
+ transferHookAccountsResult = await this.getRemainingAccountsForTransferHook(
29772
+ baseMint,
29773
+ transferHookAccountTypes
29774
+ );
29775
+ } catch (e5) {
29776
+ throw new Error(
29777
+ `Unable to resolve transfer-hook remaining accounts for ${baseMint.toString()}. When bundling pool initialization with the first buy, pass transferHookAccountsInfo and transferHookAccounts on the first-buy params.`
29778
+ );
29779
+ }
29780
+ }
29781
+ remainingAccounts.push(...transferHookAccountsResult.accounts);
29782
+ return this.program.methods.swap2WithTransferHook(
29783
+ {
29784
+ amount0: buyAmount,
29785
+ amount1: minimumAmountOut,
29786
+ swapMode: 0 /* ExactIn */
29787
+ },
29788
+ transferHookAccountsResult.info
29789
+ ).accountsPartial({
29790
+ baseMint,
29791
+ quoteMint,
29792
+ pool,
29793
+ baseVault,
29794
+ quoteVault,
29795
+ config,
29796
+ poolAuthority: this.poolAuthority,
29797
+ referralTokenAccount,
29798
+ inputTokenAccount,
29799
+ outputTokenAccount,
29800
+ payer: buyer,
29801
+ tokenBaseProgram: outputTokenProgram,
29802
+ tokenQuoteProgram: inputTokenProgram
29803
+ }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
29804
+ }
29805
+ async buildClaimTradingFeeAccountsForSol(params) {
29806
+ const {
29807
+ payer,
29808
+ feeReceiver,
29809
+ tempWSolAcc,
29810
+ pool,
29811
+ virtualPool,
29812
+ poolConfigState,
29813
+ tokenBaseProgram,
29814
+ tokenQuoteProgram
29815
+ } = params;
29816
+ const preInstructions = [];
29817
+ const postInstructions = [];
29818
+ const tokenBaseAccount = findAssociatedTokenAddress(
29819
+ feeReceiver,
29820
+ virtualPool.poolState.baseMint,
29821
+ tokenBaseProgram
29845
29822
  );
29846
- const totalBaseCouldBeSold = new (0, _decimaljs2.default)(
29847
- getBaseTokenForSwap(
29848
- config.sqrtStartPrice,
29849
- config.migrationSqrtPrice,
29850
- config.curve
29851
- ).toString()
29823
+ const tokenQuoteAccount = findAssociatedTokenAddress(
29824
+ tempWSolAcc,
29825
+ poolConfigState.quoteMint,
29826
+ tokenQuoteProgram
29852
29827
  );
29853
- const progress = baseSold.div(totalBaseCouldBeSold).toNumber();
29854
- return Math.min(Math.max(progress, 0), 1);
29855
- }
29856
- /**
29857
- * Fetch metadata accounts for a virtual pool.
29858
- */
29859
- async getPoolMetadata(poolAddress) {
29860
- const filters = createProgramAccountFilter(poolAddress, 8);
29861
- const accounts = await this.program.account.virtualPoolMetadata.all(filters);
29862
- return accounts.map((account) => account.account);
29863
- }
29864
- /**
29865
- * Fetch metadata accounts for a partner.
29866
- */
29867
- async getPartnerMetadata(partnerAddress) {
29868
- const filters = createProgramAccountFilter(partnerAddress, 8);
29869
- const accounts = await this.program.account.partnerMetadata.all(filters);
29870
- return accounts.map((account) => account.account);
29828
+ preInstructions.push(
29829
+ _spltoken.createAssociatedTokenAccountIdempotentInstruction.call(void 0,
29830
+ payer,
29831
+ tokenBaseAccount,
29832
+ feeReceiver,
29833
+ virtualPool.poolState.baseMint,
29834
+ tokenBaseProgram
29835
+ ),
29836
+ _spltoken.createAssociatedTokenAccountIdempotentInstruction.call(void 0,
29837
+ payer,
29838
+ tokenQuoteAccount,
29839
+ tempWSolAcc,
29840
+ poolConfigState.quoteMint,
29841
+ tokenQuoteProgram
29842
+ )
29843
+ );
29844
+ const unwrapSolIx = unwrapSOLInstruction(tempWSolAcc, feeReceiver);
29845
+ unwrapSolIx && postInstructions.push(unwrapSolIx);
29846
+ const accounts = {
29847
+ poolAuthority: this.poolAuthority,
29848
+ pool,
29849
+ tokenAAccount: tokenBaseAccount,
29850
+ tokenBAccount: tokenQuoteAccount,
29851
+ baseVault: virtualPool.poolState.baseVault,
29852
+ quoteVault: virtualPool.poolState.quoteVault,
29853
+ baseMint: virtualPool.poolState.baseMint,
29854
+ quoteMint: poolConfigState.quoteMint,
29855
+ tokenBaseProgram,
29856
+ tokenQuoteProgram
29857
+ };
29858
+ return { accounts, preInstructions, postInstructions };
29871
29859
  }
29872
- /**
29873
- * Fetch current unclaimed fees and lifetime trading fee metrics for a pool.
29874
- */
29875
- async getPoolFeeMetrics(poolAddress) {
29876
- const pool = await this.getPool(poolAddress);
29877
- if (!pool) {
29878
- throw new Error(`Pool not found: ${poolAddress.toString()}`);
29879
- }
29880
- return {
29881
- current: {
29882
- partnerBaseFee: pool.poolState.partnerBaseFee,
29883
- partnerQuoteFee: pool.poolState.partnerQuoteFee,
29884
- creatorBaseFee: pool.poolState.creatorBaseFee,
29885
- creatorQuoteFee: pool.poolState.creatorQuoteFee
29886
- },
29887
- total: {
29888
- totalTradingBaseFee: pool.poolState.metrics.totalTradingBaseFee,
29889
- totalTradingQuoteFee: pool.poolState.metrics.totalTradingQuoteFee
29890
- }
29860
+ async buildClaimTradingFeeAccountsForNonSol(params) {
29861
+ const {
29862
+ payer,
29863
+ feeReceiver,
29864
+ pool,
29865
+ virtualPool,
29866
+ poolConfigState,
29867
+ tokenBaseProgram,
29868
+ tokenQuoteProgram
29869
+ } = params;
29870
+ const {
29871
+ ataTokenA: tokenBaseAccount,
29872
+ ataTokenB: tokenQuoteAccount,
29873
+ instructions: preInstructions
29874
+ } = await this.prepareTokenAccounts(
29875
+ feeReceiver,
29876
+ payer,
29877
+ virtualPool.poolState.baseMint,
29878
+ poolConfigState.quoteMint,
29879
+ tokenBaseProgram,
29880
+ tokenQuoteProgram
29881
+ );
29882
+ const accounts = {
29883
+ poolAuthority: this.poolAuthority,
29884
+ pool,
29885
+ tokenAAccount: tokenBaseAccount,
29886
+ tokenBAccount: tokenQuoteAccount,
29887
+ baseVault: virtualPool.poolState.baseVault,
29888
+ quoteVault: virtualPool.poolState.quoteVault,
29889
+ baseMint: virtualPool.poolState.baseMint,
29890
+ quoteMint: poolConfigState.quoteMint,
29891
+ tokenBaseProgram,
29892
+ tokenQuoteProgram
29891
29893
  };
29894
+ return { accounts, preInstructions };
29892
29895
  }
29893
- /**
29894
- * Calculate claimed, unclaimed, and total trading fees split by creator and partner.
29895
- */
29896
- async getPoolFeeBreakdown(poolAddress) {
29897
- const pool = await this.getPool(poolAddress);
29898
- if (!pool) {
29899
- throw new Error(`Pool not found: ${poolAddress.toString()}`);
29896
+ async getRemainingAccountsForTransferHook(mint, accountTypes = [AccountsType.TransferHookBase]) {
29897
+ const emptyAccounts = { info: { slices: [] }, accounts: [] };
29898
+ const mintInfo = await this.connection.getAccountInfo(
29899
+ mint,
29900
+ this.commitment
29901
+ );
29902
+ if (!mintInfo) {
29903
+ throw new Error(`Invalid mint: ${mint.toString()}`);
29900
29904
  }
29901
- const config = await this.getPoolConfig(pool.poolState.config);
29902
- if (!config) {
29903
- throw new Error(
29904
- `Config not found: ${pool.poolState.config.toString()}`
29905
- );
29905
+ if (mintInfo.owner.equals(_spltoken.TOKEN_PROGRAM_ID)) {
29906
+ return emptyAccounts;
29906
29907
  }
29907
- const creatorTradingFeePercentage = config.creatorTradingFeePercentage;
29908
- const totalTradingBaseFee = pool.poolState.metrics.totalTradingBaseFee;
29909
- const totalTradingQuoteFee = pool.poolState.metrics.totalTradingQuoteFee;
29910
- let creatorTotalTradingBaseFee = new (0, _bnjs2.default)(0);
29911
- let creatorTotalTradingQuoteFee = new (0, _bnjs2.default)(0);
29912
- let partnerTotalTradingBaseFee = totalTradingBaseFee;
29913
- let partnerTotalTradingQuoteFee = totalTradingQuoteFee;
29914
- if (creatorTradingFeePercentage > 0) {
29915
- creatorTotalTradingBaseFee = totalTradingBaseFee.mul(new (0, _bnjs2.default)(creatorTradingFeePercentage)).div(new (0, _bnjs2.default)(100));
29916
- creatorTotalTradingQuoteFee = totalTradingQuoteFee.mul(new (0, _bnjs2.default)(creatorTradingFeePercentage)).div(new (0, _bnjs2.default)(100));
29917
- partnerTotalTradingBaseFee = totalTradingBaseFee.sub(
29918
- creatorTotalTradingBaseFee
29919
- );
29920
- partnerTotalTradingQuoteFee = totalTradingQuoteFee.sub(
29921
- creatorTotalTradingQuoteFee
29922
- );
29908
+ const mintState = _spltoken.unpackMint.call(void 0, mint, mintInfo, _spltoken.TOKEN_2022_PROGRAM_ID);
29909
+ const transferHook = _spltoken.getTransferHook.call(void 0, mintState);
29910
+ if (!transferHook || transferHook.programId.equals(_web3js.PublicKey.default)) {
29911
+ return emptyAccounts;
29923
29912
  }
29924
- const creatorUnclaimedBaseFee = pool.poolState.creatorBaseFee;
29925
- const creatorUnclaimedQuoteFee = pool.poolState.creatorQuoteFee;
29926
- const partnerUnclaimedBaseFee = pool.poolState.partnerBaseFee;
29927
- const partnerUnclaimedQuoteFee = pool.poolState.partnerQuoteFee;
29928
- const creatorClaimedBaseFee = creatorTotalTradingBaseFee.sub(
29929
- creatorUnclaimedBaseFee
29930
- );
29931
- const creatorClaimedQuoteFee = creatorTotalTradingQuoteFee.sub(
29932
- creatorUnclaimedQuoteFee
29913
+ const transferWithHookIx = await _spltoken.createTransferCheckedWithTransferHookInstruction.call(void 0,
29914
+ this.connection,
29915
+ _web3js.PublicKey.default,
29916
+ mint,
29917
+ _web3js.PublicKey.default,
29918
+ _web3js.PublicKey.default,
29919
+ BigInt(0),
29920
+ mintState.decimals,
29921
+ [],
29922
+ this.commitment,
29923
+ _spltoken.TOKEN_2022_PROGRAM_ID
29933
29924
  );
29934
- const partnerClaimedBaseFee = partnerTotalTradingBaseFee.sub(
29935
- partnerUnclaimedBaseFee
29925
+ const transferHookAccounts = transferWithHookIx.keys.slice(4);
29926
+ const slices = accountTypes.map((accountsType) => ({
29927
+ accountsType,
29928
+ length: transferHookAccounts.length
29929
+ }));
29930
+ const accounts = accountTypes.flatMap(() => transferHookAccounts);
29931
+ return { info: { slices }, accounts };
29932
+ }
29933
+ async buildWithdrawMigrationFeeTx(role, pool, sender) {
29934
+ const { virtualPool, poolConfigState } = await this.getPoolWithConfig(pool);
29935
+ const tokenQuoteProgram = getTokenProgram(
29936
+ poolConfigState.quoteTokenFlag
29936
29937
  );
29937
- const partnerClaimedQuoteFee = partnerTotalTradingQuoteFee.sub(
29938
- partnerUnclaimedQuoteFee
29938
+ const preInstructions = [];
29939
+ const postInstructions = [];
29940
+ const { ataPubkey: tokenQuoteAccount, ix: createTokenQuoteAccountIx } = await getOrCreateATAInstruction(
29941
+ this.connection,
29942
+ poolConfigState.quoteMint,
29943
+ sender,
29944
+ sender,
29945
+ true,
29946
+ tokenQuoteProgram
29939
29947
  );
29940
- return {
29941
- creator: {
29942
- unclaimedBaseFee: creatorUnclaimedBaseFee,
29943
- unclaimedQuoteFee: creatorUnclaimedQuoteFee,
29944
- claimedBaseFee: creatorClaimedBaseFee,
29945
- claimedQuoteFee: creatorClaimedQuoteFee,
29946
- totalBaseFee: creatorTotalTradingBaseFee,
29947
- totalQuoteFee: creatorTotalTradingQuoteFee
29948
- },
29949
- partner: {
29950
- unclaimedBaseFee: partnerUnclaimedBaseFee,
29951
- unclaimedQuoteFee: partnerUnclaimedQuoteFee,
29952
- claimedBaseFee: partnerClaimedBaseFee,
29953
- claimedQuoteFee: partnerClaimedQuoteFee,
29954
- totalBaseFee: partnerTotalTradingBaseFee,
29955
- totalQuoteFee: partnerTotalTradingQuoteFee
29956
- }
29957
- };
29958
- }
29959
- /**
29960
- * Fetch fee metrics for every pool linked to a config.
29961
- */
29962
- async getPoolsFeesByConfig(configAddress) {
29963
- const filteredPools = await this.getPoolsByConfig(configAddress);
29964
- return filteredPools.map((pool) => ({
29965
- poolAddress: pool.publicKey,
29966
- partnerBaseFee: pool.account.poolState.partnerBaseFee,
29967
- partnerQuoteFee: pool.account.poolState.partnerQuoteFee,
29968
- creatorBaseFee: pool.account.poolState.creatorBaseFee,
29969
- creatorQuoteFee: pool.account.poolState.creatorQuoteFee,
29970
- totalTradingBaseFee: pool.account.poolState.metrics.totalTradingBaseFee,
29971
- totalTradingQuoteFee: pool.account.poolState.metrics.totalTradingQuoteFee
29972
- }));
29948
+ createTokenQuoteAccountIx && preInstructions.push(createTokenQuoteAccountIx);
29949
+ if (poolConfigState.quoteMint.equals(_spltoken.NATIVE_MINT)) {
29950
+ const unwrapSolIx = unwrapSOLInstruction(sender, sender);
29951
+ unwrapSolIx && postInstructions.push(unwrapSolIx);
29952
+ }
29953
+ return this.program.methods.withdrawMigrationFee(role === "partner" ? 0 : 1).accountsPartial({
29954
+ poolAuthority: this.poolAuthority,
29955
+ config: virtualPool.poolState.config,
29956
+ virtualPool: pool,
29957
+ tokenQuoteAccount,
29958
+ quoteVault: virtualPool.poolState.quoteVault,
29959
+ quoteMint: poolConfigState.quoteMint,
29960
+ sender,
29961
+ tokenQuoteProgram
29962
+ }).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
29973
29963
  }
29974
- /**
29975
- * Fetch fee metrics for every pool linked to a creator.
29976
- */
29977
- async getPoolsFeesByCreator(creatorAddress) {
29978
- const filteredPools = await this.getPoolsByCreator(creatorAddress);
29979
- return filteredPools.map((pool) => ({
29980
- poolAddress: pool.publicKey,
29981
- partnerBaseFee: pool.account.poolState.partnerBaseFee,
29982
- partnerQuoteFee: pool.account.poolState.partnerQuoteFee,
29983
- creatorBaseFee: pool.account.poolState.creatorBaseFee,
29984
- creatorQuoteFee: pool.account.poolState.creatorQuoteFee,
29985
- totalTradingBaseFee: pool.account.poolState.metrics.totalTradingBaseFee,
29986
- totalTradingQuoteFee: pool.account.poolState.metrics.totalTradingQuoteFee
29987
- }));
29964
+ async prepareTokenAccounts(owner, payer, tokenAMint, tokenBMint, tokenAProgram, tokenBProgram) {
29965
+ const instructions = [];
29966
+ const [
29967
+ { ataPubkey: ataTokenA, ix: createAtaTokenAIx },
29968
+ { ataPubkey: ataTokenB, ix: createAtaTokenBIx }
29969
+ ] = await Promise.all([
29970
+ getOrCreateATAInstruction(
29971
+ this.connection,
29972
+ tokenAMint,
29973
+ owner,
29974
+ payer,
29975
+ true,
29976
+ tokenAProgram
29977
+ ),
29978
+ getOrCreateATAInstruction(
29979
+ this.connection,
29980
+ tokenBMint,
29981
+ owner,
29982
+ payer,
29983
+ true,
29984
+ tokenBProgram
29985
+ )
29986
+ ]);
29987
+ createAtaTokenAIx && instructions.push(createAtaTokenAIx);
29988
+ createAtaTokenBIx && instructions.push(createAtaTokenBIx);
29989
+ return { ataTokenA, ataTokenB, instructions };
29988
29990
  }
29989
29991
  /**
29990
- * Fetch DAMM V1 migration metadata for a pool.
29992
+ * Return the underlying Anchor program client.
29991
29993
  */
29992
- async getDammV1MigrationMetadata(poolAddress) {
29993
- const migrationMetadataAddress = deriveDammV1MigrationMetadataAddress(poolAddress);
29994
- const metadata = await this.program.account.meteoraDammMigrationMetadata.fetch(
29995
- migrationMetadataAddress
29996
- );
29997
- return metadata;
29994
+ getProgram() {
29995
+ return this.program;
29998
29996
  }
29999
29997
  };
30000
29998
 
30001
29999
  // src/services/migration.ts
30000
+
30001
+
30002
+
30003
+
30004
+
30005
+
30006
+
30002
30007
  var MigrationService = class extends DynamicBondingCurveProgram {
30003
- constructor(connection, commitment, state) {
30004
- super(
30005
- connection,
30006
- commitment,
30007
- _nullishCoalesce(state, () => ( new StateService(connection, commitment)))
30008
- );
30009
- }
30010
30008
  /**
30011
30009
  * Create a Dynamic Vault program client.
30012
30010
  */
@@ -30510,13 +30508,6 @@ var MigrationService = class extends DynamicBondingCurveProgram {
30510
30508
 
30511
30509
 
30512
30510
  var PartnerService = class extends DynamicBondingCurveProgram {
30513
- constructor(connection, commitment, state) {
30514
- super(
30515
- connection,
30516
- commitment,
30517
- _nullishCoalesce(state, () => ( new StateService(connection, commitment)))
30518
- );
30519
- }
30520
30511
  /**
30521
30512
  * Build a transaction that creates a partner-owned pool config.
30522
30513
  */
@@ -31003,13 +30994,6 @@ var PartnerService = class extends DynamicBondingCurveProgram {
31003
30994
 
31004
30995
 
31005
30996
  var PoolService = class extends DynamicBondingCurveProgram {
31006
- constructor(connection, commitment, state) {
31007
- super(
31008
- connection,
31009
- commitment,
31010
- _nullishCoalesce(state, () => ( new StateService(connection, commitment)))
31011
- );
31012
- }
31013
30997
  /**
31014
30998
  * Build an exact-in swap transaction for an existing pool.
31015
30999
  *
@@ -31409,6 +31393,128 @@ var PoolService = class extends DynamicBondingCurveProgram {
31409
31393
  throw new Error(`Unsupported swap mode: ${swapMode}`);
31410
31394
  }
31411
31395
  }
31396
+ /**
31397
+ * Reconcile the only two fields that differ between an on-chain `PoolConfig`
31398
+ * and a `buildCurve` output (`ConfigParameters`) so the quote math can
31399
+ * consume either directly:
31400
+ * - `migrationSqrtPrice`: used when present, otherwise derived from the
31401
+ * curve and migration quote threshold (it is the swap stop price).
31402
+ * - `dynamicFee`: a null/undefined object becomes a disabled one, and a
31403
+ * present object is treated as enabled unless `initialized` says otherwise.
31404
+ *
31405
+ * Everything else is already in the right shape and passed through.
31406
+ */
31407
+ normalizeQuoteConfig(config) {
31408
+ if (!config.curve || config.curve.length === 0) {
31409
+ throw new Error("config.curve is empty");
31410
+ }
31411
+ const migrationSqrtPrice = _nullishCoalesce(config.migrationSqrtPrice, () => ( getMigrationThresholdPrice(
31412
+ config.migrationQuoteThreshold,
31413
+ config.sqrtStartPrice,
31414
+ config.curve
31415
+ )));
31416
+ const dynamicFee = config.poolFees.dynamicFee;
31417
+ return {
31418
+ ...config,
31419
+ migrationSqrtPrice,
31420
+ poolFees: {
31421
+ ...config.poolFees,
31422
+ dynamicFee: dynamicFee ? {
31423
+ ...dynamicFee,
31424
+ initialized: _nullishCoalesce(dynamicFee.initialized, () => ( 1))
31425
+ } : { initialized: 0, binStep: 0, variableFeeControl: 0 }
31426
+ }
31427
+ };
31428
+ }
31429
+ /**
31430
+ * creates a virtual pool state at launch with zeroed reserves and volatility, start price set.
31431
+ */
31432
+ buildSimulatedVirtualPool(sqrtStartPrice) {
31433
+ return {
31434
+ poolState: {
31435
+ sqrtPrice: new (0, _bnjs2.default)(sqrtStartPrice),
31436
+ baseReserve: new (0, _bnjs2.default)(0),
31437
+ quoteReserve: new (0, _bnjs2.default)(0),
31438
+ activationPoint: new (0, _bnjs2.default)(0),
31439
+ volatilityTracker: {
31440
+ lastUpdateTimestamp: new (0, _bnjs2.default)(0),
31441
+ sqrtPriceReference: new (0, _bnjs2.default)(0),
31442
+ volatilityAccumulator: new (0, _bnjs2.default)(0),
31443
+ volatilityReference: new (0, _bnjs2.default)(0),
31444
+ padding: []
31445
+ }
31446
+ }
31447
+ };
31448
+ }
31449
+ /**
31450
+ * quotes a swap from an input amount before any pool exists.
31451
+ */
31452
+ getQuoteFromInputAmount(params) {
31453
+ const {
31454
+ config,
31455
+ swapBaseForQuote,
31456
+ amountIn,
31457
+ swapMode = 0 /* ExactIn */,
31458
+ slippageBps = 0,
31459
+ hasReferral = false,
31460
+ eligibleForFirstSwapWithMinFee = false,
31461
+ currentPoint = new (0, _bnjs2.default)(0)
31462
+ } = params;
31463
+ const poolConfig = this.normalizeQuoteConfig(config);
31464
+ const virtualPool = this.buildSimulatedVirtualPool(
31465
+ poolConfig.sqrtStartPrice
31466
+ );
31467
+ if (swapMode === 1 /* PartialFill */) {
31468
+ return swapQuotePartialFill(
31469
+ virtualPool,
31470
+ poolConfig,
31471
+ swapBaseForQuote,
31472
+ amountIn,
31473
+ slippageBps,
31474
+ hasReferral,
31475
+ currentPoint,
31476
+ eligibleForFirstSwapWithMinFee
31477
+ );
31478
+ }
31479
+ return swapQuoteExactIn(
31480
+ virtualPool,
31481
+ poolConfig,
31482
+ swapBaseForQuote,
31483
+ amountIn,
31484
+ slippageBps,
31485
+ hasReferral,
31486
+ currentPoint,
31487
+ eligibleForFirstSwapWithMinFee
31488
+ );
31489
+ }
31490
+ /**
31491
+ * quotes a swap from an exact output amount (`SwapMode.ExactOut`)
31492
+ */
31493
+ getQuoteFromOutputAmount(params) {
31494
+ const {
31495
+ config,
31496
+ swapBaseForQuote,
31497
+ amountOut,
31498
+ slippageBps = 0,
31499
+ hasReferral = false,
31500
+ eligibleForFirstSwapWithMinFee = false,
31501
+ currentPoint = new (0, _bnjs2.default)(0)
31502
+ } = params;
31503
+ const poolConfig = this.normalizeQuoteConfig(config);
31504
+ const virtualPool = this.buildSimulatedVirtualPool(
31505
+ poolConfig.sqrtStartPrice
31506
+ );
31507
+ return swapQuoteExactOut(
31508
+ virtualPool,
31509
+ poolConfig,
31510
+ swapBaseForQuote,
31511
+ amountOut,
31512
+ slippageBps,
31513
+ hasReferral,
31514
+ currentPoint,
31515
+ eligibleForFirstSwapWithMinFee
31516
+ );
31517
+ }
31412
31518
  };
31413
31519
 
31414
31520
  // src/services/creator.ts
@@ -31421,13 +31527,6 @@ var PoolService = class extends DynamicBondingCurveProgram {
31421
31527
 
31422
31528
 
31423
31529
  var CreatorService = class extends DynamicBondingCurveProgram {
31424
- constructor(connection, commitment, state) {
31425
- super(
31426
- connection,
31427
- commitment,
31428
- _nullishCoalesce(state, () => ( new StateService(connection, commitment)))
31429
- );
31430
- }
31431
31530
  /**
31432
31531
  * Build a transaction that creates metadata for a virtual pool.
31433
31532
  */
@@ -31877,19 +31976,15 @@ var CreatorService = class extends DynamicBondingCurveProgram {
31877
31976
  var DynamicBondingCurveClient = class _DynamicBondingCurveClient {
31878
31977
  constructor(connection, commitment) {
31879
31978
  this.state = new StateService(connection, commitment);
31880
- this.pool = new PoolService(connection, commitment, this.state);
31881
- this.partner = new PartnerService(connection, commitment, this.state);
31882
- this.creator = new CreatorService(connection, commitment, this.state);
31883
- this.migration = new MigrationService(
31884
- connection,
31885
- commitment,
31886
- this.state
31887
- );
31979
+ this.pool = new PoolService(connection, commitment);
31980
+ this.partner = new PartnerService(connection, commitment);
31981
+ this.creator = new CreatorService(connection, commitment);
31982
+ this.migration = new MigrationService(connection, commitment);
31888
31983
  this.commitment = commitment;
31889
31984
  this.connection = connection;
31890
31985
  }
31891
31986
  /**
31892
- * Create a client with shared service state.
31987
+ * Create a client with all DBC services.
31893
31988
  */
31894
31989
  static create(connection, commitment = "confirmed") {
31895
31990
  return new _DynamicBondingCurveClient(connection, commitment);