@zebec-network/zebec-stream-sdk 3.0.0-dev.3 → 3.1.0-dev.1

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.
@@ -4,11 +4,12 @@ import { TransactionPayload } from "@zebec-network/solana-common";
4
4
  import { type ZebecStreamIdl } from "../artifacts";
5
5
  import type { CancelStreamParams, ChangeStreamReceiverParams, CreateStreamParams, InitializeStreamConfigParams, RpcNetwork, StreamConfigInfo, StreamMetadataInfo, TokenMetadata, UpdateStreamConfigParams, WhiteListTokensParams, WithdrawStreamParams } from "../types";
6
6
  export declare class ZebecStreamService {
7
+ readonly streamConfigName: string;
7
8
  readonly provider: Provider;
8
9
  readonly network: RpcNetwork;
9
10
  readonly program: Program<ZebecStreamIdl>;
10
- constructor(provider: Provider, network: RpcNetwork, program: Program<ZebecStreamIdl>);
11
- static create(provider: Provider, network: RpcNetwork): ZebecStreamService;
11
+ constructor(streamConfigName: string, provider: Provider, network: RpcNetwork, program: Program<ZebecStreamIdl>);
12
+ static create(streamConfigName: string, provider: Provider, network: RpcNetwork): ZebecStreamService;
12
13
  private _createPayload;
13
14
  get connection(): Connection;
14
15
  get programId(): PublicKey;
@@ -38,7 +39,7 @@ export declare class ZebecStreamService {
38
39
  }[];
39
40
  feeVault: PublicKey;
40
41
  }): Promise<TransactionInstruction>;
41
- getCreateStreamInstruction(feePayer: PublicKey, receiver: PublicKey, senderAta: PublicKey, streamToken: PublicKey, withdrawAccount: PublicKey, sender: PublicKey, streamMetadata: PublicKey, streamData: {
42
+ getCreateStreamInstruction(streamConfig: PublicKey, feePayer: PublicKey, receiver: PublicKey, senderAta: PublicKey, streamToken: PublicKey, withdrawAccount: PublicKey, sender: PublicKey, streamMetadata: PublicKey, streamData: {
42
43
  amount: BN;
43
44
  automaticWithdrawal: boolean;
44
45
  cancelableByRecipient: boolean;
@@ -58,7 +59,7 @@ export declare class ZebecStreamService {
58
59
  getPauseResumeStreamInstruction(streamMetadata: PublicKey, user: PublicKey): Promise<TransactionInstruction>;
59
60
  getCancelStreamInstruction(feePayer: PublicKey, otherParty: PublicKey, otherPartyAta: PublicKey, signer: PublicKey, signerAta: PublicKey, streamMetadata: PublicKey, streamToken: PublicKey, streamVault: PublicKey, streamVaultAta: PublicKey): Promise<TransactionInstruction>;
60
61
  getWithdrawStreamInstruction(receiver: PublicKey, receiverAta: PublicKey, streamMetadata: PublicKey, streamToken: PublicKey, streamVault: PublicKey, streamVaultAta: PublicKey, withdrawer: PublicKey, feePayer: PublicKey): Promise<TransactionInstruction>;
61
- getWhitelistTokensInstruction(admin: PublicKey, tokens: PublicKey[]): Promise<TransactionInstruction>;
62
+ getWhitelistTokensInstruction(admin: PublicKey, streamConfig: PublicKey, tokens: PublicKey[]): Promise<TransactionInstruction>;
62
63
  getChangeStreamReceiverInstruction(streamMetadata: PublicKey, newRecipient: PublicKey, signer: PublicKey): Promise<TransactionInstruction>;
63
64
  initializeStreamConfig(params: InitializeStreamConfigParams): Promise<TransactionPayload>;
64
65
  updateStreamConfig(params: UpdateStreamConfigParams): Promise<TransactionPayload>;
@@ -19,15 +19,17 @@ const constants_1 = require("../constants");
19
19
  const pda_1 = require("../pda");
20
20
  const utils_1 = require("../utils");
21
21
  class ZebecStreamService {
22
+ streamConfigName;
22
23
  provider;
23
24
  network;
24
25
  program;
25
- constructor(provider, network, program) {
26
+ constructor(streamConfigName, provider, network, program) {
27
+ this.streamConfigName = streamConfigName;
26
28
  this.provider = provider;
27
29
  this.network = network;
28
30
  this.program = program;
29
31
  }
30
- static create(provider, network) {
32
+ static create(streamConfigName, provider, network) {
31
33
  const connection = provider.connection;
32
34
  const rpcEndpoint = connection.rpcEndpoint;
33
35
  const connNetwork = rpcEndpoint.includes("devnet")
@@ -42,7 +44,7 @@ class ZebecStreamService {
42
44
  throw new Error(`InvalidOperation: Network mismatch. network and connection network should be same. network: ${network}, connection: ${connNetwork}`);
43
45
  }
44
46
  const program = new anchor_1.Program(artifacts_1.ZEBEC_STREAM_IDL, provider);
45
- return new ZebecStreamService(provider, network, program);
47
+ return new ZebecStreamService(streamConfigName, provider, network, program);
46
48
  }
47
49
  async _createPayload(payerKey, instructions, signers, addressLookupTableAccounts) {
48
50
  const errorMap = new Map();
@@ -101,7 +103,7 @@ class ZebecStreamService {
101
103
  })
102
104
  .instruction();
103
105
  }
104
- async getCreateStreamInstruction(feePayer, receiver, senderAta, streamToken, withdrawAccount, sender, streamMetadata, streamData) {
106
+ async getCreateStreamInstruction(streamConfig, feePayer, receiver, senderAta, streamToken, withdrawAccount, sender, streamMetadata, streamData) {
105
107
  (0, assert_1.default)(streamData.streamName.length === constants_1.STREAM_NAME_BUFFER_SIZE, `Stream name buffer must be of size ${constants_1.STREAM_NAME_BUFFER_SIZE}`);
106
108
  return this.program.methods
107
109
  .createStream({
@@ -129,6 +131,7 @@ class ZebecStreamService {
129
131
  withdrawAccount,
130
132
  sender,
131
133
  streamMetadata,
134
+ streamConfig,
132
135
  })
133
136
  .instruction();
134
137
  }
@@ -172,13 +175,14 @@ class ZebecStreamService {
172
175
  })
173
176
  .instruction();
174
177
  }
175
- async getWhitelistTokensInstruction(admin, tokens) {
178
+ async getWhitelistTokensInstruction(admin, streamConfig, tokens) {
176
179
  return this.program.methods
177
180
  .whitelistTokens({
178
181
  tokens,
179
182
  })
180
- .accounts({
183
+ .accountsPartial({
181
184
  admin,
185
+ streamConfig,
182
186
  })
183
187
  .instruction();
184
188
  }
@@ -193,11 +197,13 @@ class ZebecStreamService {
193
197
  .instruction();
194
198
  }
195
199
  async initializeStreamConfig(params) {
196
- const admin = params.admin ? (0, anchor_1.translateAddress)(params.admin) : this.provider.publicKey;
200
+ const admin = params.admin
201
+ ? (0, anchor_1.translateAddress)(params.admin)
202
+ : this.provider.publicKey;
197
203
  if (!admin) {
198
204
  throw new Error("Either provide admin or create provider with public key");
199
205
  }
200
- const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(params.config.configName, this.programId);
206
+ const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(this.streamConfigName, this.programId);
201
207
  const baseFee = new anchor_1.BN((0, core_utils_1.percentToBps)(params.config.baseFeePercent));
202
208
  const frequencies = params.config.frequencies.map((frequency) => new anchor_1.BN(frequency));
203
209
  const platformFee = new anchor_1.BN((0, core_utils_1.percentToBps)(params.config.platformFeePercent));
@@ -205,8 +211,12 @@ class ZebecStreamService {
205
211
  const feeVault = (0, anchor_1.translateAddress)(params.config.feeVault);
206
212
  const feeTiers = params.config.feeTiers.map((tier) => {
207
213
  return {
208
- minAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.minThreshold).times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS)).toFixed(0)),
209
- maxAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.maxThreshold).times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS)).toFixed(0)),
214
+ minAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.minThreshold)
215
+ .times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS))
216
+ .toFixed(0)),
217
+ maxAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.maxThreshold)
218
+ .times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS))
219
+ .toFixed(0)),
210
220
  fee: new anchor_1.BN((0, core_utils_1.percentToBps)(tier.feeRateInPercent)),
211
221
  };
212
222
  });
@@ -216,17 +226,19 @@ class ZebecStreamService {
216
226
  platformFee,
217
227
  withdrawAccount,
218
228
  feeTiers,
219
- configName: params.config.configName,
229
+ configName: this.streamConfigName,
220
230
  feeVault,
221
231
  });
222
232
  return this._createPayload(admin, [ix]);
223
233
  }
224
234
  async updateStreamConfig(params) {
225
- const admin = params.admin ? (0, anchor_1.translateAddress)(params.admin) : this.provider.publicKey;
235
+ const admin = params.admin
236
+ ? (0, anchor_1.translateAddress)(params.admin)
237
+ : this.provider.publicKey;
226
238
  if (!admin) {
227
239
  throw new Error("Either provide admin or create provider with public key");
228
240
  }
229
- const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(params.config.configName, this.programId);
241
+ const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(this.streamConfigName, this.programId);
230
242
  const baseFee = new anchor_1.BN((0, core_utils_1.percentToBps)(params.config.baseFeePercent));
231
243
  const frequencies = params.config.frequencies.map((frequency) => new anchor_1.BN(frequency));
232
244
  const platformFee = new anchor_1.BN((0, core_utils_1.percentToBps)(params.config.platformFeePercent));
@@ -234,8 +246,12 @@ class ZebecStreamService {
234
246
  const feeVault = (0, anchor_1.translateAddress)(params.config.feeVault);
235
247
  const feeTiers = params.config.feeTiers.map((tier) => {
236
248
  return {
237
- minAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.minThreshold).times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS)).toFixed(0)),
238
- maxAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.maxThreshold).times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS)).toFixed(0)),
249
+ minAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.minThreshold)
250
+ .times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS))
251
+ .toFixed(0)),
252
+ maxAmount: new anchor_1.BN((0, bignumber_js_1.BigNumber)(tier.maxThreshold)
253
+ .times(solana_common_1.TEN_BIGNUM.pow(solana_common_1.USDC_DECIMALS))
254
+ .toFixed(0)),
239
255
  fee: new anchor_1.BN((0, core_utils_1.percentToBps)(tier.feeRateInPercent)),
240
256
  };
241
257
  });
@@ -245,7 +261,7 @@ class ZebecStreamService {
245
261
  platformFee,
246
262
  withdrawAccount,
247
263
  feeTiers,
248
- configName: params.config.configName,
264
+ configName: this.streamConfigName,
249
265
  feeVault,
250
266
  });
251
267
  return this._createPayload(admin, [ix]);
@@ -253,32 +269,31 @@ class ZebecStreamService {
253
269
  async createStream(params) {
254
270
  const receiver = (0, anchor_1.translateAddress)(params.receiver);
255
271
  const sender = (0, anchor_1.translateAddress)(params.sender);
256
- const feePayer = params.feePayer ? (0, anchor_1.translateAddress)(params.feePayer) : sender;
272
+ const feePayer = params.feePayer
273
+ ? (0, anchor_1.translateAddress)(params.feePayer)
274
+ : sender;
257
275
  const streamToken = (0, anchor_1.translateAddress)(params.streamToken);
258
- const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(params.configName, this.programId);
276
+ const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(this.streamConfigName, this.programId);
259
277
  const streamConfigAccount = await this.program.account.streamConfig.fetch(streamConfig);
260
278
  const withdrawer = streamConfigAccount.withdrawAccount;
261
279
  const autoWithdrawFrequencies = new Set(Array.from(streamConfigAccount.frequencies.map((f) => f.toNumber())));
262
- if (params.automaticWithdrawal && !autoWithdrawFrequencies.has(params.autoWithdrawFrequency)) {
280
+ if (params.automaticWithdrawal &&
281
+ !autoWithdrawFrequencies.has(params.autoWithdrawFrequency)) {
263
282
  throw new Error("Invalid stream frequency");
264
283
  }
265
284
  const senderAta = (0, solana_common_1.getAssociatedTokenAddressSync)(streamToken, sender, true);
266
285
  const streamMetadataKeypair = params.streamMetadataKeypair ?? web3_js_1.Keypair.generate();
267
286
  const streamTokenDecimals = await (0, solana_common_1.getMintDecimals)(this.connection, streamToken);
268
- const amount = (0, bignumber_js_1.BigNumber)(params.amount).times(solana_common_1.TEN_BIGNUM.pow(streamTokenDecimals)).toFixed(0);
287
+ const amount = (0, bignumber_js_1.BigNumber)(params.amount)
288
+ .times(solana_common_1.TEN_BIGNUM.pow(streamTokenDecimals))
289
+ .toFixed(0);
269
290
  const cliffPercentage = new anchor_1.BN((0, core_utils_1.percentToBps)(params.cliffPercentage));
270
291
  const streamName = new Uint8Array(constants_1.STREAM_NAME_BUFFER_SIZE);
271
292
  streamName.set(anchor_1.utils.bytes.utf8.encode(params.streamName));
272
293
  const configAccount = await this.program.account.streamConfig.fetch(streamConfig);
273
- const feeTiers = configAccount.feeTiers.tiers.map((tier) => ({
274
- feeRateInPercent: (0, core_utils_1.bpsToPercent)(tier.fee.toNumber()),
275
- minThreshold: (0, bignumber_js_1.BigNumber)(tier.minAmount.toString()).div(solana_common_1.UNITS_PER_USDC).toFixed(),
276
- maxThreshold: (0, bignumber_js_1.BigNumber)(tier.maxAmount.toString()).div(solana_common_1.UNITS_PER_USDC).toFixed(),
277
- }));
278
- const feeAmount = await (0, utils_1.calculateFeeTokenAmountForStream)(params.streamTokenSymbol, params.amount, params.feeTokenSymbol, feeTiers, this.network);
279
- const feeToken = (0, anchor_1.translateAddress)(params.feeToken);
280
- const feeTokenDecimals = await (0, solana_common_1.getMintDecimals)(this.connection, feeToken);
281
- const parsedFeeAmount = (0, bignumber_js_1.BigNumber)(feeAmount).times(solana_common_1.TEN_BIGNUM.pow(feeTokenDecimals)).toFixed(0);
294
+ const feeInfo = await (0, utils_1.getFeeInfoForStream)(streamToken, amount, streamTokenDecimals, this.network);
295
+ const feeToken = (0, anchor_1.translateAddress)(feeInfo.feeToken.mintAddress);
296
+ const parsedFeeAmount = feeInfo.feeAmountRaw;
282
297
  const feeVault = configAccount.feeVault;
283
298
  const feeVaultAta = (0, solana_common_1.getAssociatedTokenAddressSync)(feeToken, feeVault, true);
284
299
  const senderFeeTokenAta = (0, solana_common_1.getAssociatedTokenAddressSync)(feeToken, sender, true);
@@ -292,7 +307,7 @@ class ZebecStreamService {
292
307
  // add instruction to transfer fee to fee vault
293
308
  const transferFeeToVaultIx = (0, spl_token_1.createTransferInstruction)(senderFeeTokenAta, feeVaultAta, sender, BigInt(parsedFeeAmount));
294
309
  ixs.push(transferFeeToVaultIx);
295
- const createStreamIx = await this.getCreateStreamInstruction(feePayer, receiver, senderAta, streamToken, withdrawer, sender, streamMetadataKeypair.publicKey, {
310
+ const createStreamIx = await this.getCreateStreamInstruction(streamConfig, feePayer, receiver, senderAta, streamToken, withdrawer, sender, streamMetadataKeypair.publicKey, {
296
311
  amount: new anchor_1.BN(amount),
297
312
  automaticWithdrawal: params.automaticWithdrawal,
298
313
  cancelableByRecipient: params.cancelableByRecipient,
@@ -346,8 +361,14 @@ class ZebecStreamService {
346
361
  }
347
362
  async withdrawStream(params) {
348
363
  const receiver = (0, anchor_1.translateAddress)(params.receiver);
349
- const withdrawer = params.withdrawer ? (0, anchor_1.translateAddress)(params.withdrawer) : receiver;
350
- const feePayer = params.feePayer ? (0, anchor_1.translateAddress)(params.feePayer) : params.withdrawer ? withdrawer : receiver;
364
+ const withdrawer = params.withdrawer
365
+ ? (0, anchor_1.translateAddress)(params.withdrawer)
366
+ : receiver;
367
+ const feePayer = params.feePayer
368
+ ? (0, anchor_1.translateAddress)(params.feePayer)
369
+ : params.withdrawer
370
+ ? withdrawer
371
+ : receiver;
351
372
  const streamMetadata = (0, anchor_1.translateAddress)(params.streamMetadata);
352
373
  const streamMetadataAccount = await this.program.account.paymentStream.fetch(streamMetadata);
353
374
  const streamToken = streamMetadataAccount.financials.streamToken;
@@ -359,8 +380,9 @@ class ZebecStreamService {
359
380
  }
360
381
  async whiteListTokens(params) {
361
382
  const admin = (0, anchor_1.translateAddress)(params.admin);
383
+ const [streamConfig] = (0, pda_1.deriveStreamConfigPda)(this.streamConfigName, this.programId);
362
384
  const tokens = params.tokens.map((token) => (0, anchor_1.translateAddress)(token));
363
- const ix = await this.getWhitelistTokensInstruction(admin, tokens);
385
+ const ix = await this.getWhitelistTokensInstruction(admin, streamConfig, tokens);
364
386
  return this._createPayload(admin, [ix]);
365
387
  }
366
388
  async changeStreamReceiver(params) {
@@ -383,8 +405,12 @@ class ZebecStreamService {
383
405
  frequencies: configInfo.frequencies.map((frequency) => frequency.toNumber()),
384
406
  feeTiers: configInfo.feeTiers.tiers.map((tier) => ({
385
407
  feeRateInPercent: (0, core_utils_1.bpsToPercent)(tier.fee.toNumber()),
386
- minThreshold: (0, bignumber_js_1.BigNumber)(tier.minAmount.toString()).div(solana_common_1.UNITS_PER_USDC).toFixed(),
387
- maxThreshold: (0, bignumber_js_1.BigNumber)(tier.maxAmount.toString()).div(solana_common_1.UNITS_PER_USDC).toFixed(),
408
+ minThreshold: (0, bignumber_js_1.BigNumber)(tier.minAmount.toString())
409
+ .div(solana_common_1.UNITS_PER_USDC)
410
+ .toFixed(),
411
+ maxThreshold: (0, bignumber_js_1.BigNumber)(tier.maxAmount.toString())
412
+ .div(solana_common_1.UNITS_PER_USDC)
413
+ .toFixed(),
388
414
  })),
389
415
  feeVault: configInfo.feeVault,
390
416
  };
@@ -414,7 +440,9 @@ class ZebecStreamService {
414
440
  freezeAuthority: mintData.parsed.info.freezeAuthority
415
441
  ? new web3_js_1.PublicKey(mintData.parsed.info.freezeAuthority)
416
442
  : null,
417
- supply: (0, bignumber_js_1.BigNumber)(mintData.parsed.info.supply).div(solana_common_1.TEN_BIGNUM.pow(mintData.parsed.info.decimals)).toFixed(),
443
+ supply: (0, bignumber_js_1.BigNumber)(mintData.parsed.info.supply)
444
+ .div(solana_common_1.TEN_BIGNUM.pow(mintData.parsed.info.decimals))
445
+ .toFixed(),
418
446
  isInitialized: Boolean(mintData.parsed.info.isInitialized),
419
447
  mintAuthority: mintData.parsed.info.mintAuthority
420
448
  ? new web3_js_1.PublicKey(mintData.parsed.info.mintAuthority)
package/dist/types.d.ts CHANGED
@@ -63,14 +63,10 @@ export type TokenMetadata = {
63
63
  } | null;
64
64
  };
65
65
  export type CreateStreamParams = {
66
- configName: string;
67
66
  feePayer?: Address;
68
67
  receiver: Address;
69
68
  sender: Address;
70
69
  streamToken: Address;
71
- streamTokenSymbol: string;
72
- feeToken: Address;
73
- feeTokenSymbol: string;
74
70
  amount: Numeric;
75
71
  automaticWithdrawal: boolean;
76
72
  cancelableByRecipient: boolean;
@@ -95,7 +91,6 @@ export type InitializeStreamConfigParams = {
95
91
  frequencies: number[];
96
92
  platformFeePercent: Numeric;
97
93
  withdrawAccount: Address;
98
- configName: string;
99
94
  feeTiers: FeeTier[];
100
95
  feeVault: Address;
101
96
  };
@@ -112,7 +107,6 @@ export type UpdateStreamConfigParams = {
112
107
  frequencies: number[];
113
108
  platformFeePercent: Numeric;
114
109
  withdrawAccount: Address;
115
- configName: string;
116
110
  feeTiers: FeeTier[];
117
111
  feeVault: Address;
118
112
  };
@@ -140,3 +134,27 @@ export type ChangeStreamReceiverParams = {
140
134
  newRecipient: Address;
141
135
  signer: Address;
142
136
  };
137
+ export type StreamFeeInfo = {
138
+ tokenSymbol: string;
139
+ mintAddress: string;
140
+ chain: string;
141
+ streamAmount: string;
142
+ streamAmountUi: string;
143
+ tokenPriceUsd: number;
144
+ streamAmountUsd: number;
145
+ feeTier: {
146
+ tier: number;
147
+ range: string;
148
+ feeRatePercent: number;
149
+ };
150
+ feeRatePercent: number;
151
+ feeAmountUsd: number;
152
+ feeToken: {
153
+ symbol: string;
154
+ decimals: number;
155
+ priceUsd: number;
156
+ mintAddress: string;
157
+ };
158
+ feeAmount: number;
159
+ feeAmountRaw: string;
160
+ };
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { FeeTier, Numeric, RpcNetwork } from "./types";
2
- export declare function getTokenUsdPrice(tokenSymbol: string, network: RpcNetwork): Promise<number>;
3
- export declare function calculateFeeTokenAmountForStream(streamTokenSymbol: string, streamTokenAmount: Numeric, feeTokenSymbol: string, feeTiers: FeeTier[], network: RpcNetwork): Promise<BigNumber>;
4
- export declare function getFeeRateForUsdAmount(amount: BigNumber, feeTiers: FeeTier[]): string;
1
+ import type { PublicKey } from "@solana/web3.js";
2
+ import type { FeeTier, RpcNetwork, StreamFeeInfo } from "./types";
3
+ export declare function getFeeInfoForStream(streamToken: PublicKey, parsedStreamTokenAmount: BigNumber.Value, streamTokenDecimals: number, network: RpcNetwork): Promise<StreamFeeInfo>;
4
+ export declare function getFeeRateForUsdAmount(amount: BigNumber.Value, feeTiers: FeeTier[]): string;
package/dist/utils.js CHANGED
@@ -1,40 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTokenUsdPrice = getTokenUsdPrice;
4
- exports.calculateFeeTokenAmountForStream = calculateFeeTokenAmountForStream;
3
+ exports.getFeeInfoForStream = getFeeInfoForStream;
5
4
  exports.getFeeRateForUsdAmount = getFeeRateForUsdAmount;
6
- const bignumber_js_1 = require("bignumber.js");
7
5
  const core_utils_1 = require("@zebec-network/core-utils");
6
+ const bignumber_js_1 = require("bignumber.js");
8
7
  const constants_1 = require("./constants");
9
- async function getTokenUsdPrice(tokenSymbol, network) {
10
- const url = `${constants_1.SUPERAPP_BACKEND_URL[network]}/tokens/quotes/${encodeURIComponent(`${tokenSymbol}_USD`)}/1?type=EXACT_IN&chainName=SOLANA`;
8
+ async function getFeeInfoForStream(streamToken, parsedStreamTokenAmount, streamTokenDecimals, network) {
9
+ const urlsParams = new URLSearchParams({
10
+ streamToken: streamToken.toBase58(),
11
+ chain: "SOLANA",
12
+ amount: (0, bignumber_js_1.BigNumber)(parsedStreamTokenAmount).toFixed(0),
13
+ decimals: streamTokenDecimals.toString(),
14
+ });
15
+ const url = `${constants_1.SUPERAPP_BACKEND_URL[network]}/l1-stream/fees/stream-quote?${urlsParams}`;
16
+ console.debug("fetching fee token amount from url:", url);
11
17
  const response = await fetch(url);
12
18
  if (!response.ok) {
13
19
  const body = await response.text().catch(() => "");
14
- throw new Error(`Failed to fetch token price for symbol: ${tokenSymbol}, network: ${network}, status: ${response.status} ${body}`);
20
+ throw new Error(`Failed to fetch fee token amount: ${response.status} ${response.statusText} ${body}`.trim());
15
21
  }
16
22
  const data = await response.json();
17
- if (!data || !("exchangeRate" in data)) {
18
- console.debug("Unexpected response format when fetching token price:", data);
19
- throw new Error(`Invalid response format when fetching token price for symbol: ${tokenSymbol}, network: ${network}`);
20
- }
21
- return Number(data.exchangeRate);
22
- }
23
- async function calculateFeeTokenAmountForStream(streamTokenSymbol, streamTokenAmount, feeTokenSymbol, feeTiers, network) {
24
- const oneStreamTokenPriceInUsd = await getTokenUsdPrice(streamTokenSymbol, network);
25
- const oneFeeTokenPriceInUsd = await getTokenUsdPrice(feeTokenSymbol, network);
26
- if (oneFeeTokenPriceInUsd === 0) {
27
- throw new Error(`Fee token price is zero for symbol: ${feeTokenSymbol}, network: ${network}`);
28
- }
29
- const streamTokenAmountUsdPrice = new bignumber_js_1.BigNumber(streamTokenAmount).times(oneStreamTokenPriceInUsd);
30
- const feeRateInBps = getFeeRateForUsdAmount(streamTokenAmountUsdPrice, feeTiers);
31
- const feeAmountUsdPrice = streamTokenAmountUsdPrice.times(feeRateInBps).div(10000);
32
- const feeTokenAmount = feeAmountUsdPrice.div(oneFeeTokenPriceInUsd);
33
- return feeTokenAmount;
23
+ return data;
34
24
  }
35
25
  function getFeeRateForUsdAmount(amount, feeTiers) {
36
26
  feeTiers.sort((a, b) => (0, bignumber_js_1.BigNumber)(a.minThreshold).comparedTo((0, bignumber_js_1.BigNumber)(b.minThreshold)) ?? 0);
37
- const tier = feeTiers.find((tier) => amount.gte(tier.minThreshold) && amount.lt(tier.maxThreshold));
27
+ const tier = feeTiers.find((tier) => (0, bignumber_js_1.BigNumber)(amount).gte(tier.minThreshold) &&
28
+ (0, bignumber_js_1.BigNumber)(amount).lt(tier.maxThreshold));
38
29
  if (!tier) {
39
30
  throw new Error(`No fee tier found for amount: ${amount}`);
40
31
  }
package/package.json CHANGED
@@ -40,5 +40,5 @@
40
40
  "test:single": "ts-mocha -p ./tsconfig.json -t 1000000000"
41
41
  },
42
42
  "types": "dist/index.d.ts",
43
- "version": "3.0.0-dev.3"
43
+ "version": "3.1.0-dev.1"
44
44
  }