@streamflow/distributor 8.9.0 → 9.0.0-alpha.p308.8fcedb9

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.
@@ -54,8 +54,10 @@ __export(solana_exports, {
54
54
  clawback: () => clawback,
55
55
  closeClaim: () => closeClaim,
56
56
  constants: () => constants_exports,
57
+ fetchAirdropFee: () => fetchAirdropFee,
57
58
  fromCode: () => fromCode3,
58
59
  fromTxError: () => fromTxError,
60
+ getAirdropFeeQueryOptions: () => getAirdropFeeQueryOptions,
59
61
  getAlignedDistributorPda: () => getAlignedDistributorPda,
60
62
  getClaimantStatusPda: () => getClaimantStatusPda,
61
63
  getDistributorPda: () => getDistributorPda,
@@ -366,6 +368,150 @@ var DISTRIBUTOR_PROGRAM_ID = {
366
368
  [common.ICluster.Testnet]: "MErKy6nZVoVAkryxAejJz2juifQ4ArgLgHmaJCQkU7N",
367
369
  [common.ICluster.Local]: "MErKy6nZVoVAkryxAejJz2juifQ4ArgLgHmaJCQkU7N"
368
370
  };
371
+ var fetchAirdropFee = async (distributorId, cluster = common.ICluster.Mainnet, fetchFn = fetch) => {
372
+ const baseUrl = cluster === common.ICluster.Mainnet ? "https://api.streamflow.finance" : "https://staging-api.streamflow.finance";
373
+ const url = `${baseUrl}/v2/api/airdrops/${encodeURIComponent(distributorId)}/fees`;
374
+ const res = await fetchFn(url, {
375
+ method: "GET",
376
+ headers: {
377
+ "Content-Type": "application/json"
378
+ }
379
+ });
380
+ if (!res.ok) {
381
+ const text = await res.text().catch(() => "");
382
+ throw new Error(`Airdrop fee API error: ${res.status} ${res.statusText}${text ? ` - ${text}` : ""}`);
383
+ }
384
+ const json = await res.json();
385
+ return json;
386
+ };
387
+ function getAirdropFeeQueryOptions(params, options) {
388
+ const { staleTimeMs = 6e4, gcTimeMs = 3e5, retry = 2, refetchOnWindowFocus = false } = options ?? {};
389
+ const cluster = params.cluster ?? common.ICluster.Mainnet;
390
+ const key = ["sf", "airdrop", "fee", cluster, params.distributorId];
391
+ return {
392
+ queryKey: key,
393
+ queryFn: () => fetchAirdropFee(params.distributorId, cluster, params.fetchFn ?? fetch),
394
+ staleTime: staleTimeMs,
395
+ gcTime: gcTimeMs,
396
+ retry,
397
+ refetchOnWindowFocus
398
+ };
399
+ }
400
+
401
+ // solana/fees.ts
402
+ var MAXIMUM_FEE_FALLBACK = 9900000n;
403
+ var MINIMUM_FEE_FALLBACK = 5000000n;
404
+ var FEE_ALLOCATION_FACTOR_FALLBACK_NUMERATOR = 90n;
405
+ var FEE_ALLOCATION_FACTOR_FALLBACK_DENOMINATOR = 100n;
406
+ var LAMPORTS_PER_SOL = 1000000000n;
407
+ var lamportsToSolString = (lamports) => {
408
+ const int = lamports / LAMPORTS_PER_SOL;
409
+ const frac = lamports % LAMPORTS_PER_SOL;
410
+ if (frac === 0n) return int.toString();
411
+ const fracStr = frac.toString().padStart(9, "0").replace(/0+$/, "");
412
+ return `${int.toString()}.${fracStr}`;
413
+ };
414
+ var allocationToString = (num, den) => {
415
+ const SCALE = 1000000000n;
416
+ const scaled = num * SCALE / den;
417
+ const int = scaled / SCALE;
418
+ const frac = scaled % SCALE;
419
+ if (frac === 0n) return int.toString();
420
+ const fracStr = frac.toString().padStart(9, "0").replace(/0+$/, "");
421
+ return `${int.toString()}.${fracStr}`;
422
+ };
423
+ var defaultAPIFeesResponse = {
424
+ isCustom: false,
425
+ claimFee: void 0,
426
+ claimFeeDynamic: {
427
+ minPrice: lamportsToSolString(MINIMUM_FEE_FALLBACK),
428
+ maxPrice: lamportsToSolString(MAXIMUM_FEE_FALLBACK),
429
+ allocationFactor: allocationToString(
430
+ FEE_ALLOCATION_FACTOR_FALLBACK_NUMERATOR,
431
+ FEE_ALLOCATION_FACTOR_FALLBACK_DENOMINATOR
432
+ )
433
+ }
434
+ };
435
+ var toLamportsSOL = (value, solDecimals = 9) => {
436
+ const y = typeof value === "bigint" ? Number(value) : typeof value === "string" ? Number(value) : value;
437
+ if (!Number.isFinite(y) || y <= 0) return 0n;
438
+ const scale = 10n ** BigInt(solDecimals);
439
+ return common.multiplyBigIntByNumber(scale, y);
440
+ };
441
+ function calculateClaimableLamportsFromPrices(params) {
442
+ const {
443
+ claimableAmount,
444
+ tokenPriceUsd,
445
+ solPriceUsd,
446
+ tokenDecimals,
447
+ solDecimals = 9
448
+ } = params;
449
+ if (tokenPriceUsd <= 0 || solPriceUsd <= 0) return 0n;
450
+ const scaleDigits = Math.min(18, Math.max(0, tokenDecimals));
451
+ const SCALE = 10n ** BigInt(scaleDigits);
452
+ const pScaled = common.multiplyBigIntByNumber(SCALE, tokenPriceUsd, scaleDigits);
453
+ const sScaled = common.multiplyBigIntByNumber(SCALE, solPriceUsd, scaleDigits);
454
+ if (pScaled <= 0n || sScaled <= 0n) return 0n;
455
+ const pow10 = (n) => 10n ** BigInt(n);
456
+ const numerator = claimableAmount * pow10(solDecimals) * pScaled;
457
+ const denominator = pow10(tokenDecimals) * sScaled;
458
+ return numerator / denominator;
459
+ }
460
+ function calculateDynamicFeeFromSolParams(params) {
461
+ const { minPrice, maxPrice, allocationFactor, claimableLamports, solDecimals = 9 } = params;
462
+ const minLamports = toLamportsSOL(minPrice, solDecimals);
463
+ const maxLamports = toLamportsSOL(maxPrice, solDecimals);
464
+ const factor = Math.max(0, Math.min(1, parseFloat(allocationFactor)));
465
+ const raw = common.multiplyBigIntByNumber(claimableLamports, factor);
466
+ if (raw < minLamports) return minLamports;
467
+ if (raw > maxLamports) return maxLamports;
468
+ return raw;
469
+ }
470
+ async function fetchTokenPriceUsd(mintId, cluster, fetchFn = fetch) {
471
+ const url = `https://token-api.streamflow.finance/price?ids=${encodeURIComponent(mintId)}&cluster=${encodeURIComponent(cluster)}`;
472
+ const res = await fetchFn(url, { headers: { "Content-Type": "application/json" } });
473
+ if (!res.ok) return null;
474
+ const json = await res.json();
475
+ const val = json?.data?.[mintId]?.value;
476
+ return typeof val === "number" ? val : null;
477
+ }
478
+ async function resolveAirdropFeeLamportsUsingApi(params) {
479
+ const { distributorAddress, mintAccount, claimableAmount, cluster, fetchFn } = params;
480
+ let apiFeesResponse = void 0;
481
+ try {
482
+ apiFeesResponse = await fetchAirdropFee(distributorAddress, cluster);
483
+ } catch (_) {
484
+ }
485
+ let solPrice = null;
486
+ let tokenPrice = null;
487
+ try {
488
+ [solPrice, tokenPrice] = await Promise.all([
489
+ fetchTokenPriceUsd("So11111111111111111111111111111111111111112", cluster, fetchFn),
490
+ fetchTokenPriceUsd(mintAccount.address.toBase58(), cluster, fetchFn)
491
+ ]);
492
+ } catch (_) {
493
+ }
494
+ const response = apiFeesResponse ?? defaultAPIFeesResponse;
495
+ if (response?.isCustom && response.claimFee !== void 0) {
496
+ return toLamportsSOL(response.claimFee);
497
+ }
498
+ const claimFeeDynamic = response?.claimFeeDynamic ?? defaultAPIFeesResponse.claimFeeDynamic;
499
+ if (!tokenPrice || !solPrice) {
500
+ return MINIMUM_FEE_FALLBACK;
501
+ }
502
+ const baseLamports = calculateClaimableLamportsFromPrices({
503
+ claimableAmount,
504
+ tokenPriceUsd: tokenPrice,
505
+ solPriceUsd: solPrice,
506
+ tokenDecimals: mintAccount.decimals
507
+ });
508
+ return calculateDynamicFeeFromSolParams({
509
+ minPrice: claimFeeDynamic.minPrice,
510
+ maxPrice: claimFeeDynamic.maxPrice,
511
+ allocationFactor: claimFeeDynamic.allocationFactor,
512
+ claimableLamports: baseLamports
513
+ });
514
+ }
369
515
 
370
516
  // solana/descriptor/idl/merkle_distributor.json
371
517
  var merkle_distributor_default = {
@@ -3441,6 +3587,7 @@ var BaseDistributorClient = class {
3441
3587
  sendThrottler
3442
3588
  }) {
3443
3589
  this.commitment = commitment;
3590
+ this.cluster = cluster;
3444
3591
  this.connection = new web3_js.Connection(clusterUrl, this.commitment);
3445
3592
  this.programId = programId !== "" ? new web3_js.PublicKey(programId) : new web3_js.PublicKey(DISTRIBUTOR_PROGRAM_ID[cluster]);
3446
3593
  this.sendThrottler = sendThrottler ?? solana.buildSendThrottler(sendRate);
@@ -3624,12 +3771,21 @@ var BaseDistributorClient = class {
3624
3771
  if (claimStatus || new BN5__default.default(data.amountLocked).gtn(0) && nowTs.sub(distributor.startTs).gte(distributor.unlockPeriod)) {
3625
3772
  ixs.push(claimLocked(accounts, this.programId));
3626
3773
  }
3627
- ixs.push(
3628
- this.prepareClaimFeeInstruction(
3629
- extParams.feePayer ?? extParams.invoker.publicKey,
3630
- typeof _serviceTransfer === "bigint" ? _serviceTransfer : void 0
3631
- )
3632
- );
3774
+ let feeLamports = typeof _serviceTransfer === "bigint" ? _serviceTransfer : void 0;
3775
+ if (!feeLamports) {
3776
+ try {
3777
+ const { mint: mintAccount } = await solana.getMintAndProgram(this.connection, distributor.mint);
3778
+ feeLamports = await resolveAirdropFeeLamportsUsingApi({
3779
+ distributorAddress: distributorPublicKey.toBase58(),
3780
+ mintAccount,
3781
+ claimableAmount: BigInt(data.claimableAmount.toString()),
3782
+ cluster: this.cluster
3783
+ });
3784
+ } catch (_) {
3785
+ feeLamports = MINIMUM_FEE_FALLBACK;
3786
+ }
3787
+ }
3788
+ ixs.push(this.prepareClaimFeeInstruction(extParams.feePayer ?? extParams.invoker.publicKey, feeLamports));
3633
3789
  return ixs;
3634
3790
  }
3635
3791
  async closeClaim(data, extParams) {