@meteora-ag/cp-amm-sdk 1.1.3 → 1.1.5-rc.0

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.mjs CHANGED
@@ -1,4 +1,23 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1
7
  var __pow = Math.pow;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
2
21
  var __async = (__this, __arguments, generator) => {
3
22
  return new Promise((resolve, reject) => {
4
23
  var fulfilled = (value) => {
@@ -21,7 +40,7 @@ var __async = (__this, __arguments, generator) => {
21
40
  };
22
41
 
23
42
  // src/CpAmm.ts
24
- import { Program, BN as BN10 } from "@coral-xyz/anchor";
43
+ import { Program } from "@coral-xyz/anchor";
25
44
  import { NATIVE_MINT as NATIVE_MINT2, TOKEN_2022_PROGRAM_ID as TOKEN_2022_PROGRAM_ID2 } from "@solana/spl-token";
26
45
  import invariant from "invariant";
27
46
 
@@ -30,7 +49,7 @@ var cp_amm_default = {
30
49
  address: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG",
31
50
  metadata: {
32
51
  name: "cp_amm",
33
- version: "0.1.3",
52
+ version: "0.1.5",
34
53
  spec: "0.1.0",
35
54
  description: "Created with Anchor"
36
55
  },
@@ -3376,6 +3395,107 @@ var cp_amm_default = {
3376
3395
  }
3377
3396
  ]
3378
3397
  },
3398
+ {
3399
+ name: "split_position2",
3400
+ discriminator: [
3401
+ 221,
3402
+ 147,
3403
+ 228,
3404
+ 207,
3405
+ 140,
3406
+ 212,
3407
+ 17,
3408
+ 119
3409
+ ],
3410
+ accounts: [
3411
+ {
3412
+ name: "pool",
3413
+ writable: true,
3414
+ relations: [
3415
+ "first_position",
3416
+ "second_position"
3417
+ ]
3418
+ },
3419
+ {
3420
+ name: "first_position",
3421
+ docs: [
3422
+ "The first position"
3423
+ ],
3424
+ writable: true
3425
+ },
3426
+ {
3427
+ name: "first_position_nft_account",
3428
+ docs: [
3429
+ "The token account for position nft"
3430
+ ]
3431
+ },
3432
+ {
3433
+ name: "second_position",
3434
+ docs: [
3435
+ "The second position"
3436
+ ],
3437
+ writable: true
3438
+ },
3439
+ {
3440
+ name: "second_position_nft_account",
3441
+ docs: [
3442
+ "The token account for position nft"
3443
+ ]
3444
+ },
3445
+ {
3446
+ name: "first_owner",
3447
+ docs: [
3448
+ "Owner of first position"
3449
+ ],
3450
+ signer: true
3451
+ },
3452
+ {
3453
+ name: "second_owner",
3454
+ docs: [
3455
+ "Owner of second position"
3456
+ ],
3457
+ signer: true
3458
+ },
3459
+ {
3460
+ name: "event_authority",
3461
+ pda: {
3462
+ seeds: [
3463
+ {
3464
+ kind: "const",
3465
+ value: [
3466
+ 95,
3467
+ 95,
3468
+ 101,
3469
+ 118,
3470
+ 101,
3471
+ 110,
3472
+ 116,
3473
+ 95,
3474
+ 97,
3475
+ 117,
3476
+ 116,
3477
+ 104,
3478
+ 111,
3479
+ 114,
3480
+ 105,
3481
+ 116,
3482
+ 121
3483
+ ]
3484
+ }
3485
+ ]
3486
+ }
3487
+ },
3488
+ {
3489
+ name: "program"
3490
+ }
3491
+ ],
3492
+ args: [
3493
+ {
3494
+ name: "numerator",
3495
+ type: "u32"
3496
+ }
3497
+ ]
3498
+ },
3379
3499
  {
3380
3500
  name: "swap",
3381
3501
  discriminator: [
@@ -3517,6 +3637,147 @@ var cp_amm_default = {
3517
3637
  }
3518
3638
  ]
3519
3639
  },
3640
+ {
3641
+ name: "swap2",
3642
+ discriminator: [
3643
+ 65,
3644
+ 75,
3645
+ 63,
3646
+ 76,
3647
+ 235,
3648
+ 91,
3649
+ 91,
3650
+ 136
3651
+ ],
3652
+ accounts: [
3653
+ {
3654
+ name: "pool_authority",
3655
+ address: "HLnpSz9h2S4hiLQ43rnSD9XkcUThA7B8hQMKmDaiTLcC"
3656
+ },
3657
+ {
3658
+ name: "pool",
3659
+ docs: [
3660
+ "Pool account"
3661
+ ],
3662
+ writable: true
3663
+ },
3664
+ {
3665
+ name: "input_token_account",
3666
+ docs: [
3667
+ "The user token account for input token"
3668
+ ],
3669
+ writable: true
3670
+ },
3671
+ {
3672
+ name: "output_token_account",
3673
+ docs: [
3674
+ "The user token account for output token"
3675
+ ],
3676
+ writable: true
3677
+ },
3678
+ {
3679
+ name: "token_a_vault",
3680
+ docs: [
3681
+ "The vault token account for input token"
3682
+ ],
3683
+ writable: true,
3684
+ relations: [
3685
+ "pool"
3686
+ ]
3687
+ },
3688
+ {
3689
+ name: "token_b_vault",
3690
+ docs: [
3691
+ "The vault token account for output token"
3692
+ ],
3693
+ writable: true,
3694
+ relations: [
3695
+ "pool"
3696
+ ]
3697
+ },
3698
+ {
3699
+ name: "token_a_mint",
3700
+ docs: [
3701
+ "The mint of token a"
3702
+ ]
3703
+ },
3704
+ {
3705
+ name: "token_b_mint",
3706
+ docs: [
3707
+ "The mint of token b"
3708
+ ]
3709
+ },
3710
+ {
3711
+ name: "payer",
3712
+ docs: [
3713
+ "The user performing the swap"
3714
+ ],
3715
+ signer: true
3716
+ },
3717
+ {
3718
+ name: "token_a_program",
3719
+ docs: [
3720
+ "Token a program"
3721
+ ]
3722
+ },
3723
+ {
3724
+ name: "token_b_program",
3725
+ docs: [
3726
+ "Token b program"
3727
+ ]
3728
+ },
3729
+ {
3730
+ name: "referral_token_account",
3731
+ docs: [
3732
+ "referral token account"
3733
+ ],
3734
+ writable: true,
3735
+ optional: true
3736
+ },
3737
+ {
3738
+ name: "event_authority",
3739
+ pda: {
3740
+ seeds: [
3741
+ {
3742
+ kind: "const",
3743
+ value: [
3744
+ 95,
3745
+ 95,
3746
+ 101,
3747
+ 118,
3748
+ 101,
3749
+ 110,
3750
+ 116,
3751
+ 95,
3752
+ 97,
3753
+ 117,
3754
+ 116,
3755
+ 104,
3756
+ 111,
3757
+ 114,
3758
+ 105,
3759
+ 116,
3760
+ 121
3761
+ ]
3762
+ }
3763
+ ]
3764
+ }
3765
+ },
3766
+ {
3767
+ name: "program"
3768
+ }
3769
+ ],
3770
+ args: [
3771
+ {
3772
+ name: "params",
3773
+ type: {
3774
+ defined: {
3775
+ name: "SwapParameters2"
3776
+ }
3777
+ }
3778
+ }
3779
+ ]
3780
+ },
3520
3781
  {
3521
3782
  name: "update_reward_duration",
3522
3783
  discriminator: [
@@ -4016,6 +4277,19 @@ var cp_amm_default = {
4016
4277
  249
4017
4278
  ]
4018
4279
  },
4280
+ {
4281
+ name: "EvtLiquidityChange",
4282
+ discriminator: [
4283
+ 197,
4284
+ 171,
4285
+ 78,
4286
+ 127,
4287
+ 224,
4288
+ 211,
4289
+ 87,
4290
+ 13
4291
+ ]
4292
+ },
4019
4293
  {
4020
4294
  name: "EvtLockPosition",
4021
4295
  discriminator: [
@@ -4069,20 +4343,20 @@ var cp_amm_default = {
4069
4343
  ]
4070
4344
  },
4071
4345
  {
4072
- name: "EvtSplitPosition",
4346
+ name: "EvtSplitPosition2",
4073
4347
  discriminator: [
4074
- 182,
4075
- 138,
4076
- 42,
4077
- 254,
4078
- 27,
4079
- 94,
4080
- 82,
4081
- 221
4082
- ]
4083
- },
4084
- {
4085
- name: "EvtSwap",
4348
+ 165,
4349
+ 32,
4350
+ 203,
4351
+ 174,
4352
+ 72,
4353
+ 100,
4354
+ 233,
4355
+ 103
4356
+ ]
4357
+ },
4358
+ {
4359
+ name: "EvtSwap",
4086
4360
  discriminator: [
4087
4361
  27,
4088
4362
  60,
@@ -4094,6 +4368,19 @@ var cp_amm_default = {
4094
4368
  147
4095
4369
  ]
4096
4370
  },
4371
+ {
4372
+ name: "EvtSwap2",
4373
+ discriminator: [
4374
+ 189,
4375
+ 66,
4376
+ 51,
4377
+ 168,
4378
+ 38,
4379
+ 80,
4380
+ 117,
4381
+ 153
4382
+ ]
4383
+ },
4097
4384
  {
4098
4385
  name: "EvtUpdateRewardDuration",
4099
4386
  discriminator: [
@@ -4369,6 +4656,36 @@ var cp_amm_default = {
4369
4656
  code: 6046,
4370
4657
  name: "SamePosition",
4371
4658
  msg: "Same position"
4659
+ },
4660
+ {
4661
+ code: 6047,
4662
+ name: "InvalidBaseFeeMode",
4663
+ msg: "Invalid base fee mode"
4664
+ },
4665
+ {
4666
+ code: 6048,
4667
+ name: "InvalidFeeRateLimiter",
4668
+ msg: "Invalid fee rate limiter"
4669
+ },
4670
+ {
4671
+ code: 6049,
4672
+ name: "FailToValidateSingleSwapInstruction",
4673
+ msg: "Fail to validate single swap instruction in rate limiter"
4674
+ },
4675
+ {
4676
+ code: 6050,
4677
+ name: "InvalidFeeScheduler",
4678
+ msg: "Invalid fee scheduler"
4679
+ },
4680
+ {
4681
+ code: 6051,
4682
+ name: "UndeterminedError",
4683
+ msg: "Undetermined error"
4684
+ },
4685
+ {
4686
+ code: 6052,
4687
+ name: "InvalidPoolVersion",
4688
+ msg: "Invalid pool version"
4372
4689
  }
4373
4690
  ],
4374
4691
  types: [
@@ -4415,7 +4732,7 @@ var cp_amm_default = {
4415
4732
  type: "u64"
4416
4733
  },
4417
4734
  {
4418
- name: "fee_scheduler_mode",
4735
+ name: "base_fee_mode",
4419
4736
  type: "u8"
4420
4737
  },
4421
4738
  {
@@ -4428,15 +4745,20 @@ var cp_amm_default = {
4428
4745
  }
4429
4746
  },
4430
4747
  {
4431
- name: "number_of_period",
4748
+ name: "first_factor",
4432
4749
  type: "u16"
4433
4750
  },
4434
4751
  {
4435
- name: "period_frequency",
4436
- type: "u64"
4752
+ name: "second_factor",
4753
+ type: {
4754
+ array: [
4755
+ "u8",
4756
+ 8
4757
+ ]
4758
+ }
4437
4759
  },
4438
4760
  {
4439
- name: "reduction_factor",
4761
+ name: "third_factor",
4440
4762
  type: "u64"
4441
4763
  }
4442
4764
  ]
@@ -4452,19 +4774,24 @@ var cp_amm_default = {
4452
4774
  type: "u64"
4453
4775
  },
4454
4776
  {
4455
- name: "number_of_period",
4777
+ name: "first_factor",
4456
4778
  type: "u16"
4457
4779
  },
4458
4780
  {
4459
- name: "period_frequency",
4460
- type: "u64"
4781
+ name: "second_factor",
4782
+ type: {
4783
+ array: [
4784
+ "u8",
4785
+ 8
4786
+ ]
4787
+ }
4461
4788
  },
4462
4789
  {
4463
- name: "reduction_factor",
4790
+ name: "third_factor",
4464
4791
  type: "u64"
4465
4792
  },
4466
4793
  {
4467
- name: "fee_scheduler_mode",
4794
+ name: "base_fee_mode",
4468
4795
  type: "u8"
4469
4796
  }
4470
4797
  ]
@@ -4484,7 +4811,7 @@ var cp_amm_default = {
4484
4811
  type: "u64"
4485
4812
  },
4486
4813
  {
4487
- name: "fee_scheduler_mode",
4814
+ name: "base_fee_mode",
4488
4815
  type: "u8"
4489
4816
  },
4490
4817
  {
@@ -4497,15 +4824,20 @@ var cp_amm_default = {
4497
4824
  }
4498
4825
  },
4499
4826
  {
4500
- name: "number_of_period",
4827
+ name: "first_factor",
4501
4828
  type: "u16"
4502
4829
  },
4503
4830
  {
4504
- name: "period_frequency",
4505
- type: "u64"
4831
+ name: "second_factor",
4832
+ type: {
4833
+ array: [
4834
+ "u8",
4835
+ 8
4836
+ ]
4837
+ }
4506
4838
  },
4507
4839
  {
4508
- name: "reduction_factor",
4840
+ name: "third_factor",
4509
4841
  type: "u64"
4510
4842
  },
4511
4843
  {
@@ -5344,6 +5676,66 @@ var cp_amm_default = {
5344
5676
  ]
5345
5677
  }
5346
5678
  },
5679
+ {
5680
+ name: "EvtLiquidityChange",
5681
+ type: {
5682
+ kind: "struct",
5683
+ fields: [
5684
+ {
5685
+ name: "pool",
5686
+ type: "pubkey"
5687
+ },
5688
+ {
5689
+ name: "position",
5690
+ type: "pubkey"
5691
+ },
5692
+ {
5693
+ name: "owner",
5694
+ type: "pubkey"
5695
+ },
5696
+ {
5697
+ name: "token_a_amount",
5698
+ type: "u64"
5699
+ },
5700
+ {
5701
+ name: "token_b_amount",
5702
+ type: "u64"
5703
+ },
5704
+ {
5705
+ name: "transfer_fee_included_token_a_amount",
5706
+ type: "u64"
5707
+ },
5708
+ {
5709
+ name: "transfer_fee_included_token_b_amount",
5710
+ type: "u64"
5711
+ },
5712
+ {
5713
+ name: "reserve_a_amount",
5714
+ type: "u64"
5715
+ },
5716
+ {
5717
+ name: "reserve_b_amount",
5718
+ type: "u64"
5719
+ },
5720
+ {
5721
+ name: "liquidity_delta",
5722
+ type: "u128"
5723
+ },
5724
+ {
5725
+ name: "token_a_amount_threshold",
5726
+ type: "u64"
5727
+ },
5728
+ {
5729
+ name: "token_b_amount_threshold",
5730
+ type: "u64"
5731
+ },
5732
+ {
5733
+ name: "change_type",
5734
+ type: "u8"
5735
+ }
5736
+ ]
5737
+ }
5738
+ },
5347
5739
  {
5348
5740
  name: "EvtLockPosition",
5349
5741
  type: {
@@ -5465,7 +5857,7 @@ var cp_amm_default = {
5465
5857
  }
5466
5858
  },
5467
5859
  {
5468
- name: "EvtSplitPosition",
5860
+ name: "EvtSplitPosition2",
5469
5861
  type: {
5470
5862
  kind: "struct",
5471
5863
  fields: [
@@ -5521,7 +5913,7 @@ var cp_amm_default = {
5521
5913
  name: "split_position_parameters",
5522
5914
  type: {
5523
5915
  defined: {
5524
- name: "SplitPositionParameters"
5916
+ name: "SplitPositionParameters2"
5525
5917
  }
5526
5918
  }
5527
5919
  }
@@ -5572,6 +5964,70 @@ var cp_amm_default = {
5572
5964
  ]
5573
5965
  }
5574
5966
  },
5967
+ {
5968
+ name: "EvtSwap2",
5969
+ type: {
5970
+ kind: "struct",
5971
+ fields: [
5972
+ {
5973
+ name: "pool",
5974
+ type: "pubkey"
5975
+ },
5976
+ {
5977
+ name: "trade_direction",
5978
+ type: "u8"
5979
+ },
5980
+ {
5981
+ name: "collect_fee_mode",
5982
+ type: "u8"
5983
+ },
5984
+ {
5985
+ name: "has_referral",
5986
+ type: "bool"
5987
+ },
5988
+ {
5989
+ name: "params",
5990
+ type: {
5991
+ defined: {
5992
+ name: "SwapParameters2"
5993
+ }
5994
+ }
5995
+ },
5996
+ {
5997
+ name: "swap_result",
5998
+ type: {
5999
+ defined: {
6000
+ name: "SwapResult2"
6001
+ }
6002
+ }
6003
+ },
6004
+ {
6005
+ name: "included_transfer_fee_amount_in",
6006
+ type: "u64"
6007
+ },
6008
+ {
6009
+ name: "included_transfer_fee_amount_out",
6010
+ type: "u64"
6011
+ },
6012
+ {
6013
+ name: "excluded_transfer_fee_amount_out",
6014
+ type: "u64"
6015
+ },
6016
+ {
6017
+ name: "current_timestamp",
6018
+ type: "u64"
6019
+ },
6020
+ {
6021
+ name: "reserve_a_amount",
6022
+ type: "u64"
6023
+ },
6024
+ {
6025
+ name: "reserve_b_amount",
6026
+ type: "u64"
6027
+ }
6028
+ ]
6029
+ }
6030
+ },
5575
6031
  {
5576
6032
  name: "EvtUpdateRewardDuration",
5577
6033
  type: {
@@ -5922,17 +6378,19 @@ var cp_amm_default = {
5922
6378
  ],
5923
6379
  type: "u8"
5924
6380
  },
6381
+ {
6382
+ name: "version",
6383
+ docs: [
6384
+ "pool version, 0: max_fee is still capped at 50%, 1: max_fee is capped at 99%"
6385
+ ],
6386
+ type: "u8"
6387
+ },
5925
6388
  {
5926
6389
  name: "_padding_0",
5927
6390
  docs: [
5928
6391
  "padding"
5929
6392
  ],
5930
- type: {
5931
- array: [
5932
- "u8",
5933
- 2
5934
- ]
5935
- }
6393
+ type: "u8"
5936
6394
  },
5937
6395
  {
5938
6396
  name: "fee_a_per_liquidity",
@@ -6665,6 +7123,38 @@ var cp_amm_default = {
6665
7123
  ]
6666
7124
  }
6667
7125
  },
7126
+ {
7127
+ name: "SplitPositionParameters2",
7128
+ type: {
7129
+ kind: "struct",
7130
+ fields: [
7131
+ {
7132
+ name: "unlocked_liquidity_numerator",
7133
+ type: "u32"
7134
+ },
7135
+ {
7136
+ name: "permanent_locked_liquidity_numerator",
7137
+ type: "u32"
7138
+ },
7139
+ {
7140
+ name: "fee_a_numerator",
7141
+ type: "u32"
7142
+ },
7143
+ {
7144
+ name: "fee_b_numerator",
7145
+ type: "u32"
7146
+ },
7147
+ {
7148
+ name: "reward_0_numerator",
7149
+ type: "u32"
7150
+ },
7151
+ {
7152
+ name: "reward_1_numerator",
7153
+ type: "u32"
7154
+ }
7155
+ ]
7156
+ }
7157
+ },
6668
7158
  {
6669
7159
  name: "StaticConfigParameters",
6670
7160
  type: {
@@ -6721,6 +7211,35 @@ var cp_amm_default = {
6721
7211
  ]
6722
7212
  }
6723
7213
  },
7214
+ {
7215
+ name: "SwapParameters2",
7216
+ type: {
7217
+ kind: "struct",
7218
+ fields: [
7219
+ {
7220
+ name: "amount_0",
7221
+ docs: [
7222
+ "When it's exact in, partial fill, this will be amount_in. When it's exact out, this will be amount_out"
7223
+ ],
7224
+ type: "u64"
7225
+ },
7226
+ {
7227
+ name: "amount_1",
7228
+ docs: [
7229
+ "When it's exact in, partial fill, this will be minimum_amount_out. When it's exact out, this will be maximum_amount_in"
7230
+ ],
7231
+ type: "u64"
7232
+ },
7233
+ {
7234
+ name: "swap_mode",
7235
+ docs: [
7236
+ "Swap mode, refer [SwapMode]"
7237
+ ],
7238
+ type: "u8"
7239
+ }
7240
+ ]
7241
+ }
7242
+ },
6724
7243
  {
6725
7244
  name: "SwapResult",
6726
7245
  docs: [
@@ -6757,34 +7276,78 @@ var cp_amm_default = {
6757
7276
  }
6758
7277
  },
6759
7278
  {
6760
- name: "TokenBadge",
6761
- docs: [
6762
- "Parameter that set by the protocol"
6763
- ],
6764
- serialization: "bytemuck",
6765
- repr: {
6766
- kind: "c"
6767
- },
7279
+ name: "SwapResult2",
6768
7280
  type: {
6769
7281
  kind: "struct",
6770
7282
  fields: [
6771
7283
  {
6772
- name: "token_mint",
6773
- docs: [
6774
- "token mint"
6775
- ],
6776
- type: "pubkey"
7284
+ name: "included_fee_input_amount",
7285
+ type: "u64"
6777
7286
  },
6778
7287
  {
6779
- name: "_padding",
6780
- docs: [
6781
- "Reserve"
6782
- ],
6783
- type: {
6784
- array: [
6785
- "u8",
6786
- 128
6787
- ]
7288
+ name: "excluded_fee_input_amount",
7289
+ type: "u64"
7290
+ },
7291
+ {
7292
+ name: "amount_left",
7293
+ type: "u64"
7294
+ },
7295
+ {
7296
+ name: "output_amount",
7297
+ type: "u64"
7298
+ },
7299
+ {
7300
+ name: "next_sqrt_price",
7301
+ type: "u128"
7302
+ },
7303
+ {
7304
+ name: "trading_fee",
7305
+ type: "u64"
7306
+ },
7307
+ {
7308
+ name: "protocol_fee",
7309
+ type: "u64"
7310
+ },
7311
+ {
7312
+ name: "partner_fee",
7313
+ type: "u64"
7314
+ },
7315
+ {
7316
+ name: "referral_fee",
7317
+ type: "u64"
7318
+ }
7319
+ ]
7320
+ }
7321
+ },
7322
+ {
7323
+ name: "TokenBadge",
7324
+ docs: [
7325
+ "Parameter that set by the protocol"
7326
+ ],
7327
+ serialization: "bytemuck",
7328
+ repr: {
7329
+ kind: "c"
7330
+ },
7331
+ type: {
7332
+ kind: "struct",
7333
+ fields: [
7334
+ {
7335
+ name: "token_mint",
7336
+ docs: [
7337
+ "token mint"
7338
+ ],
7339
+ type: "pubkey"
7340
+ },
7341
+ {
7342
+ name: "_padding",
7343
+ docs: [
7344
+ "Reserve"
7345
+ ],
7346
+ type: {
7347
+ array: [
7348
+ "u8",
7349
+ 128
7350
+ ]
6788
7351
  }
6789
7352
  }
6790
7353
  ]
@@ -6922,7 +7485,8 @@ var cp_amm_default = {
6922
7485
  // src/CpAmm.ts
6923
7486
  import {
6924
7487
  Transaction,
6925
- SystemProgram as SystemProgram2
7488
+ SystemProgram as SystemProgram2,
7489
+ SYSVAR_INSTRUCTIONS_PUBKEY
6926
7490
  } from "@solana/web3.js";
6927
7491
 
6928
7492
  // src/types.ts
@@ -6936,51 +7500,85 @@ var ActivationPoint = /* @__PURE__ */ ((ActivationPoint2) => {
6936
7500
  ActivationPoint2[ActivationPoint2["Slot"] = 1] = "Slot";
6937
7501
  return ActivationPoint2;
6938
7502
  })(ActivationPoint || {});
6939
- var FeeSchedulerMode = /* @__PURE__ */ ((FeeSchedulerMode2) => {
6940
- FeeSchedulerMode2[FeeSchedulerMode2["Linear"] = 0] = "Linear";
6941
- FeeSchedulerMode2[FeeSchedulerMode2["Exponential"] = 1] = "Exponential";
6942
- return FeeSchedulerMode2;
6943
- })(FeeSchedulerMode || {});
6944
- var CollectFeeMode = /* @__PURE__ */ ((CollectFeeMode2) => {
6945
- CollectFeeMode2[CollectFeeMode2["BothToken"] = 0] = "BothToken";
6946
- CollectFeeMode2[CollectFeeMode2["OnlyB"] = 1] = "OnlyB";
6947
- return CollectFeeMode2;
7503
+ var BaseFeeMode = /* @__PURE__ */ ((BaseFeeMode3) => {
7504
+ BaseFeeMode3[BaseFeeMode3["FeeSchedulerLinear"] = 0] = "FeeSchedulerLinear";
7505
+ BaseFeeMode3[BaseFeeMode3["FeeSchedulerExponential"] = 1] = "FeeSchedulerExponential";
7506
+ BaseFeeMode3[BaseFeeMode3["RateLimiter"] = 2] = "RateLimiter";
7507
+ return BaseFeeMode3;
7508
+ })(BaseFeeMode || {});
7509
+ var CollectFeeMode = /* @__PURE__ */ ((CollectFeeMode3) => {
7510
+ CollectFeeMode3[CollectFeeMode3["BothToken"] = 0] = "BothToken";
7511
+ CollectFeeMode3[CollectFeeMode3["OnlyB"] = 1] = "OnlyB";
7512
+ return CollectFeeMode3;
6948
7513
  })(CollectFeeMode || {});
6949
- var TradeDirection = /* @__PURE__ */ ((TradeDirection2) => {
6950
- TradeDirection2[TradeDirection2["AtoB"] = 0] = "AtoB";
6951
- TradeDirection2[TradeDirection2["BtoA"] = 1] = "BtoA";
6952
- return TradeDirection2;
7514
+ var TradeDirection = /* @__PURE__ */ ((TradeDirection3) => {
7515
+ TradeDirection3[TradeDirection3["AtoB"] = 0] = "AtoB";
7516
+ TradeDirection3[TradeDirection3["BtoA"] = 1] = "BtoA";
7517
+ return TradeDirection3;
6953
7518
  })(TradeDirection || {});
6954
- var ActivationType = /* @__PURE__ */ ((ActivationType2) => {
6955
- ActivationType2[ActivationType2["Slot"] = 0] = "Slot";
6956
- ActivationType2[ActivationType2["Timestamp"] = 1] = "Timestamp";
6957
- return ActivationType2;
7519
+ var ActivationType = /* @__PURE__ */ ((ActivationType3) => {
7520
+ ActivationType3[ActivationType3["Slot"] = 0] = "Slot";
7521
+ ActivationType3[ActivationType3["Timestamp"] = 1] = "Timestamp";
7522
+ return ActivationType3;
6958
7523
  })(ActivationType || {});
7524
+ var PoolVersion = /* @__PURE__ */ ((PoolVersion5) => {
7525
+ PoolVersion5[PoolVersion5["V0"] = 0] = "V0";
7526
+ PoolVersion5[PoolVersion5["V1"] = 1] = "V1";
7527
+ return PoolVersion5;
7528
+ })(PoolVersion || {});
7529
+ var PoolStatus = /* @__PURE__ */ ((PoolStatus2) => {
7530
+ PoolStatus2[PoolStatus2["Enable"] = 0] = "Enable";
7531
+ PoolStatus2[PoolStatus2["Disable"] = 1] = "Disable";
7532
+ return PoolStatus2;
7533
+ })(PoolStatus || {});
7534
+ var SwapMode = /* @__PURE__ */ ((SwapMode2) => {
7535
+ SwapMode2[SwapMode2["ExactIn"] = 0] = "ExactIn";
7536
+ SwapMode2[SwapMode2["PartialFill"] = 1] = "PartialFill";
7537
+ SwapMode2[SwapMode2["ExactOut"] = 2] = "ExactOut";
7538
+ return SwapMode2;
7539
+ })(SwapMode || {});
6959
7540
 
6960
7541
  // src/pda.ts
6961
7542
  import { PublicKey as PublicKey2 } from "@solana/web3.js";
6962
7543
 
6963
7544
  // src/constants.ts
6964
- import { BN } from "@coral-xyz/anchor";
6965
7545
  import { PublicKey } from "@solana/web3.js";
7546
+ import BN from "bn.js";
6966
7547
  var CP_AMM_PROGRAM_ID = new PublicKey(
6967
7548
  "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG"
6968
7549
  );
6969
7550
  var LIQUIDITY_SCALE = 128;
6970
7551
  var SCALE_OFFSET = 64;
6971
7552
  var BASIS_POINT_MAX = 1e4;
6972
- var MAX_FEE_NUMERATOR = 5e8;
6973
7553
  var FEE_DENOMINATOR = 1e9;
7554
+ var ONE_Q64 = new BN(1).shln(SCALE_OFFSET);
7555
+ var MAX_EXPONENTIAL = new BN(524288);
7556
+ var MAX = new BN(2).pow(new BN(128)).sub(new BN(1));
7557
+ var MIN_FEE_BPS = 1;
7558
+ var MIN_FEE_NUMERATOR = 1e5;
7559
+ var MAX_FEE_BPS_V0 = 5e3;
7560
+ var MAX_FEE_NUMERATOR_V0 = 5e8;
7561
+ var MAX_FEE_BPS_V1 = 9900;
7562
+ var MAX_FEE_NUMERATOR_V1 = 99e7;
6974
7563
  var MIN_SQRT_PRICE = new BN("4295048016");
6975
7564
  var MAX_SQRT_PRICE = new BN("79226673521066979257578248091");
6976
7565
  var MIN_CU_BUFFER = 5e4;
6977
7566
  var MAX_CU_BUFFER = 2e5;
7567
+ var DYNAMIC_FEE_SCALING_FACTOR = new BN(1e11);
7568
+ var DYNAMIC_FEE_ROUNDING_OFFSET = new BN(99999999999);
6978
7569
  var DYNAMIC_FEE_FILTER_PERIOD_DEFAULT = 10;
6979
7570
  var DYNAMIC_FEE_DECAY_PERIOD_DEFAULT = 120;
6980
7571
  var DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT = 5e3;
6981
7572
  var BIN_STEP_BPS_DEFAULT = 1;
6982
7573
  var BIN_STEP_BPS_U128_DEFAULT = new BN("1844674407370955");
6983
7574
  var MAX_PRICE_CHANGE_BPS_DEFAULT = 1500;
7575
+ var U128_MAX = new BN("340282366920938463463374607431768211455");
7576
+ var U64_MAX = new BN("18446744073709551615");
7577
+ var U16_MAX = 65535;
7578
+ var MAX_RATE_LIMITER_DURATION_IN_SECONDS = 43200;
7579
+ var MAX_RATE_LIMITER_DURATION_IN_SLOTS = 108e3;
7580
+ var SPLIT_POSITION_DENOMINATOR = 1e9;
7581
+ var CURRENT_POOL_VERSION = 0 /* V0 */;
6984
7582
 
6985
7583
  // src/pda.ts
6986
7584
  function getFirstKey(key1, key2) {
@@ -7211,877 +7809,2153 @@ function getAllPositionNftAccountByOwner(connection, user) {
7211
7809
  });
7212
7810
  }
7213
7811
 
7214
- // src/helpers/fee.ts
7215
- import { BN as BN5 } from "@coral-xyz/anchor";
7216
-
7217
- // src/math/feeMath.ts
7218
- import { BN as BN2 } from "@coral-xyz/anchor";
7219
- var MAX_EXPONENTIAL = new BN2(524288);
7220
- var ONE = new BN2(1).shln(SCALE_OFFSET);
7221
- var MAX = new BN2(2).pow(new BN2(128)).sub(new BN2(1));
7222
- function pow(base, exp) {
7223
- let invert = exp.isNeg();
7224
- if (exp.isZero()) {
7225
- return ONE;
7226
- }
7227
- exp = invert ? exp.abs() : exp;
7228
- if (exp.gt(MAX_EXPONENTIAL)) {
7229
- return new BN2(0);
7230
- }
7231
- let squaredBase = base;
7232
- let result = ONE;
7233
- if (squaredBase.gte(result)) {
7234
- squaredBase = MAX.div(squaredBase);
7235
- invert = !invert;
7236
- }
7237
- if (!exp.and(new BN2(1)).isZero()) {
7238
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7239
- }
7240
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7241
- if (!exp.and(new BN2(2)).isZero()) {
7242
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7243
- }
7244
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7245
- if (!exp.and(new BN2(4)).isZero()) {
7246
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7247
- }
7248
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7249
- if (!exp.and(new BN2(8)).isZero()) {
7250
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7251
- }
7252
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7253
- if (!exp.and(new BN2(16)).isZero()) {
7254
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7255
- }
7256
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7257
- if (!exp.and(new BN2(32)).isZero()) {
7258
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7259
- }
7260
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7261
- if (!exp.and(new BN2(64)).isZero()) {
7262
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7263
- }
7264
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7265
- if (!exp.and(new BN2(128)).isZero()) {
7266
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7267
- }
7268
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7269
- if (!exp.and(new BN2(256)).isZero()) {
7270
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7271
- }
7272
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7273
- if (!exp.and(new BN2(512)).isZero()) {
7274
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7275
- }
7276
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7277
- if (!exp.and(new BN2(1024)).isZero()) {
7278
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7279
- }
7280
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7281
- if (!exp.and(new BN2(2048)).isZero()) {
7282
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7283
- }
7284
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7285
- if (!exp.and(new BN2(4096)).isZero()) {
7286
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7287
- }
7288
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7289
- if (!exp.and(new BN2(8192)).isZero()) {
7290
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7291
- }
7292
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7293
- if (!exp.and(new BN2(16384)).isZero()) {
7294
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7295
- }
7296
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7297
- if (!exp.and(new BN2(32768)).isZero()) {
7298
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7299
- }
7300
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7301
- if (!exp.and(new BN2(65536)).isZero()) {
7302
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7303
- }
7304
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7305
- if (!exp.and(new BN2(131072)).isZero()) {
7306
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7812
+ // src/helpers/computeUnits.ts
7813
+ import {
7814
+ ComputeBudgetProgram,
7815
+ PublicKey as PublicKey4,
7816
+ TransactionMessage,
7817
+ VersionedTransaction
7818
+ } from "@solana/web3.js";
7819
+ var getSimulationComputeUnits = (connection, instructions, payer, lookupTables, commitment = "confirmed") => __async(void 0, null, function* () {
7820
+ var _a, _b, _c;
7821
+ const testInstructions = [
7822
+ // Set an arbitrarily high number in simulation
7823
+ // so we can be sure the transaction will succeed
7824
+ // and get the real compute units used
7825
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 14e5 }),
7826
+ ...instructions
7827
+ ];
7828
+ const testTransaction = new VersionedTransaction(
7829
+ new TransactionMessage({
7830
+ instructions: testInstructions,
7831
+ payerKey: payer,
7832
+ // RecentBlockhash can by any public key during simulation
7833
+ // since 'replaceRecentBlockhash' is set to 'true' below
7834
+ recentBlockhash: PublicKey4.default.toString()
7835
+ }).compileToV0Message(lookupTables)
7836
+ );
7837
+ const rpcResponse = yield connection.simulateTransaction(testTransaction, {
7838
+ replaceRecentBlockhash: true,
7839
+ sigVerify: false,
7840
+ commitment
7841
+ });
7842
+ if ((_a = rpcResponse == null ? void 0 : rpcResponse.value) == null ? void 0 : _a.err) {
7843
+ const logs = ((_b = rpcResponse.value.logs) == null ? void 0 : _b.join("\n \u2022 ")) || "No logs available";
7844
+ throw new Error(
7845
+ `Transaction simulation failed:
7846
+ \u2022${logs}` + JSON.stringify((_c = rpcResponse == null ? void 0 : rpcResponse.value) == null ? void 0 : _c.err)
7847
+ );
7307
7848
  }
7308
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7309
- if (!exp.and(new BN2(262144)).isZero()) {
7310
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7849
+ return rpcResponse.value.unitsConsumed || null;
7850
+ });
7851
+ var getEstimatedComputeUnitUsageWithBuffer = (connection, instructions, feePayer, buffer) => __async(void 0, null, function* () {
7852
+ if (!buffer) {
7853
+ buffer = 0.1;
7311
7854
  }
7312
- if (result.isZero()) {
7313
- return new BN2(0);
7855
+ buffer = Math.max(0, buffer);
7856
+ buffer = Math.min(1, buffer);
7857
+ const estimatedComputeUnitUsage = yield getSimulationComputeUnits(
7858
+ connection,
7859
+ instructions,
7860
+ feePayer,
7861
+ []
7862
+ );
7863
+ if (!estimatedComputeUnitUsage) {
7864
+ return 0;
7314
7865
  }
7315
- if (invert) {
7316
- result = MAX.div(result);
7866
+ let extraComputeUnitBuffer = estimatedComputeUnitUsage * buffer;
7867
+ if (extraComputeUnitBuffer > MAX_CU_BUFFER) {
7868
+ extraComputeUnitBuffer = MAX_CU_BUFFER;
7869
+ } else if (extraComputeUnitBuffer < MIN_CU_BUFFER) {
7870
+ extraComputeUnitBuffer = MIN_CU_BUFFER;
7317
7871
  }
7318
- return result;
7319
- }
7872
+ return estimatedComputeUnitUsage + extraComputeUnitBuffer;
7873
+ });
7874
+ var getEstimatedComputeUnitIxWithBuffer = (connection, instructions, feePayer, buffer) => __async(void 0, null, function* () {
7875
+ const units = yield getEstimatedComputeUnitUsageWithBuffer(
7876
+ connection,
7877
+ instructions,
7878
+ feePayer,
7879
+ buffer
7880
+ ).catch((error) => {
7881
+ console.error("Error::getEstimatedComputeUnitUsageWithBuffer", error);
7882
+ return 14e5;
7883
+ });
7884
+ return ComputeBudgetProgram.setComputeUnitLimit({ units });
7885
+ });
7320
7886
 
7321
- // src/math/mathUtils.ts
7322
- import { BN as BN3 } from "@coral-xyz/anchor";
7887
+ // src/helpers/utils.ts
7888
+ import { BN as BN2 } from "@coral-xyz/anchor";
7323
7889
  import Decimal from "decimal.js";
7324
- function mulDiv(x, y, denominator, rounding) {
7325
- const { div, mod } = x.mul(y).divmod(denominator);
7326
- if (rounding == 0 /* Up */ && !mod.isZero()) {
7327
- return div.add(new BN3(1));
7328
- }
7329
- return div;
7330
- }
7331
- function q64ToDecimal(num, decimalPlaces) {
7332
- return new Decimal(num.toString()).div(Decimal.pow(2, 64)).toDecimalPlaces(decimalPlaces);
7333
- }
7334
- function decimalToQ64(num) {
7335
- return new BN3(num.mul(Decimal.pow(2, 64)).floor().toFixed());
7336
- }
7337
-
7338
- // src/helpers/curve.ts
7339
- import { BN as BN4 } from "@coral-xyz/anchor";
7340
- function getNextSqrtPrice(amount, sqrtPrice, liquidity, aToB) {
7890
+ var getMaxAmountWithSlippage = (amount, rate) => {
7891
+ const slippage = (100 + rate) / 100 * BASIS_POINT_MAX;
7892
+ return amount.mul(new BN2(slippage)).div(new BN2(BASIS_POINT_MAX));
7893
+ };
7894
+ var getAmountWithSlippage = (amount, slippageBps, swapMode) => {
7341
7895
  let result;
7342
- if (aToB) {
7343
- const product = amount.mul(sqrtPrice);
7344
- const denominator = liquidity.add(product);
7345
- const numerator = liquidity.mul(sqrtPrice);
7346
- result = numerator.add(denominator.sub(new BN4(1))).div(denominator);
7896
+ if (slippageBps > 0) {
7897
+ if (swapMode === 2 /* ExactOut */) {
7898
+ const slippageFactor = new BN2(BASIS_POINT_MAX + slippageBps);
7899
+ result = amount.mul(slippageFactor).div(new BN2(BASIS_POINT_MAX));
7900
+ } else {
7901
+ const slippageFactor = new BN2(BASIS_POINT_MAX - slippageBps);
7902
+ result = amount.mul(slippageFactor).div(new BN2(BASIS_POINT_MAX));
7903
+ }
7347
7904
  } else {
7348
- const quotient = amount.shln(SCALE_OFFSET * 2).div(liquidity);
7349
- result = sqrtPrice.add(quotient);
7350
- }
7351
- return result;
7352
- }
7353
- function getLiquidityDeltaFromAmountA(amountA, lowerSqrtPrice, upperSqrtPrice) {
7354
- const product = amountA.mul(lowerSqrtPrice).mul(upperSqrtPrice);
7355
- const denominator = upperSqrtPrice.sub(lowerSqrtPrice);
7356
- return product.div(denominator);
7357
- }
7358
- function getLiquidityDeltaFromAmountB(amountB, lowerSqrtPrice, upperSqrtPrice) {
7359
- const denominator = upperSqrtPrice.sub(lowerSqrtPrice);
7360
- const product = amountB.shln(128);
7361
- return product.div(denominator);
7362
- }
7363
- function getAmountAFromLiquidityDelta(liquidity, currentSqrtPrice, maxSqrtPrice, rounding) {
7364
- const product = liquidity.mul(maxSqrtPrice.sub(currentSqrtPrice));
7365
- const denominator = currentSqrtPrice.mul(maxSqrtPrice);
7366
- if (rounding == 0 /* Up */) {
7367
- return product.add(denominator.sub(new BN4(1))).div(denominator);
7368
- }
7369
- return product.div(denominator);
7370
- }
7371
- function getAmountBFromLiquidityDelta(liquidity, currentSqrtPrice, minSqrtPrice, rounding) {
7372
- const one = new BN4(1).shln(128);
7373
- const deltaPrice = currentSqrtPrice.sub(minSqrtPrice);
7374
- const result = liquidity.mul(deltaPrice);
7375
- if (rounding == 0 /* Up */) {
7376
- return result.add(one.sub(new BN4(1))).div(one);
7377
- }
7378
- return result.shrn(128);
7379
- }
7380
- function getNextSqrtPriceFromAmountBRoundingUp(sqrtPrice, liquidity, amount) {
7381
- const quotient = amount.shln(128).add(liquidity).sub(new BN4(1)).div(liquidity);
7382
- const result = sqrtPrice.sub(quotient);
7383
- if (result.isNeg()) {
7384
- throw new Error("sqrt price cannot be negative");
7905
+ result = amount;
7385
7906
  }
7386
7907
  return result;
7387
- }
7388
- function getNextSqrtPriceFromAmountARoundingDown(sqrtPrice, liquidity, amount) {
7389
- if (amount.isZero()) {
7390
- return sqrtPrice;
7391
- }
7392
- const product = amount.mul(sqrtPrice);
7393
- const denominator = liquidity.sub(product);
7394
- if (denominator.isNeg() || denominator.isZero()) {
7395
- throw new Error("Invalid denominator in sqrt price calculation");
7908
+ };
7909
+ var getPriceImpact = (amountIn, amountOut, currentSqrtPrice, aToB, tokenADecimal, tokenBDecimal) => {
7910
+ if (amountIn.eq(new BN2(0))) {
7911
+ return new Decimal(0);
7396
7912
  }
7397
- const numerator = liquidity.mul(sqrtPrice);
7398
- const result = numerator.div(denominator);
7399
- return result;
7400
- }
7401
- function getNextSqrtPriceFromOutput(sqrtPrice, liquidity, outAmount, isB) {
7402
- if (sqrtPrice.isZero()) {
7403
- throw new Error("sqrt price must be greater than 0");
7913
+ if (amountOut.eq(new BN2(0))) {
7914
+ throw new Error("Amount out must be greater than 0");
7404
7915
  }
7405
- if (isB) {
7406
- return getNextSqrtPriceFromAmountBRoundingUp(
7916
+ const spotPrice = getPriceFromSqrtPrice(
7917
+ currentSqrtPrice,
7918
+ tokenADecimal,
7919
+ tokenBDecimal
7920
+ );
7921
+ const executionPrice = new Decimal(amountIn.toString()).div(new Decimal(amountOut.toString())).mul(
7922
+ Decimal.pow(
7923
+ 10,
7924
+ aToB ? tokenBDecimal - tokenADecimal : tokenADecimal - tokenBDecimal
7925
+ )
7926
+ );
7927
+ let priceImpact;
7928
+ let actualExecutionPrice;
7929
+ if (aToB) {
7930
+ actualExecutionPrice = new Decimal(1).div(executionPrice);
7931
+ } else {
7932
+ actualExecutionPrice = executionPrice;
7933
+ }
7934
+ priceImpact = actualExecutionPrice.sub(spotPrice).abs().div(spotPrice).mul(100);
7935
+ return priceImpact;
7936
+ };
7937
+ var getPriceChange = (nextSqrtPrice, currentSqrtPrice) => {
7938
+ const diff = nextSqrtPrice.pow(new BN2(2)).sub(currentSqrtPrice.pow(new BN2(2))).abs();
7939
+ return new Decimal(diff.toString()).div(new Decimal(currentSqrtPrice.pow(new BN2(2)).toString())).mul(100).toNumber();
7940
+ };
7941
+ var getPriceFromSqrtPrice = (sqrtPrice, tokenADecimal, tokenBDecimal) => {
7942
+ const decimalSqrtPrice = new Decimal(sqrtPrice.toString());
7943
+ const price = decimalSqrtPrice.mul(decimalSqrtPrice).mul(new Decimal(__pow(10, tokenADecimal - tokenBDecimal))).div(Decimal.pow(2, 128));
7944
+ return price;
7945
+ };
7946
+ var getSqrtPriceFromPrice = (price, tokenADecimal, tokenBDecimal) => {
7947
+ const decimalPrice = new Decimal(price);
7948
+ const adjustedByDecimals = decimalPrice.div(
7949
+ new Decimal(__pow(10, tokenADecimal - tokenBDecimal))
7950
+ );
7951
+ const sqrtValue = Decimal.sqrt(adjustedByDecimals);
7952
+ const sqrtValueQ64 = sqrtValue.mul(Decimal.pow(2, 64));
7953
+ return new BN2(sqrtValueQ64.floor().toFixed());
7954
+ };
7955
+ var getUnClaimReward = (poolState, positionState) => {
7956
+ const totalPositionLiquidity = positionState.unlockedLiquidity.add(positionState.vestedLiquidity).add(positionState.permanentLockedLiquidity);
7957
+ const feeAPerTokenStored = new BN2(
7958
+ Buffer.from(poolState.feeAPerLiquidity).reverse()
7959
+ ).sub(new BN2(Buffer.from(positionState.feeAPerTokenCheckpoint).reverse()));
7960
+ const feeBPerTokenStored = new BN2(
7961
+ Buffer.from(poolState.feeBPerLiquidity).reverse()
7962
+ ).sub(new BN2(Buffer.from(positionState.feeBPerTokenCheckpoint).reverse()));
7963
+ const feeA = totalPositionLiquidity.mul(feeAPerTokenStored).shrn(LIQUIDITY_SCALE);
7964
+ const feeB = totalPositionLiquidity.mul(feeBPerTokenStored).shrn(LIQUIDITY_SCALE);
7965
+ return {
7966
+ feeTokenA: positionState.feeAPending.add(feeA),
7967
+ feeTokenB: positionState.feeBPending.add(feeB),
7968
+ rewards: positionState.rewardInfos.length > 0 ? positionState.rewardInfos.map((item) => item.rewardPendings) : []
7969
+ };
7970
+ };
7971
+
7972
+ // src/helpers/accountFilters.ts
7973
+ var positionByPoolFilter = (pool) => {
7974
+ return {
7975
+ memcmp: {
7976
+ bytes: pool.toBase58(),
7977
+ offset: 8
7978
+ }
7979
+ };
7980
+ };
7981
+ var vestingByPositionFilter = (position) => {
7982
+ return {
7983
+ memcmp: {
7984
+ bytes: position.toBase58(),
7985
+ offset: 8
7986
+ }
7987
+ };
7988
+ };
7989
+
7990
+ // src/helpers/token2022.ts
7991
+ import { BN as BN3 } from "@coral-xyz/anchor";
7992
+ import {
7993
+ calculateFee,
7994
+ getEpochFee,
7995
+ getTransferFeeConfig,
7996
+ MAX_FEE_BASIS_POINTS
7997
+ } from "@solana/spl-token";
7998
+ function calculatePreFeeAmount(transferFee, postFeeAmount) {
7999
+ if (postFeeAmount.isZero()) {
8000
+ return new BN3(0);
8001
+ }
8002
+ if (transferFee.transferFeeBasisPoints === 0) {
8003
+ return postFeeAmount;
8004
+ }
8005
+ const maximumFee = new BN3(transferFee.maximumFee.toString());
8006
+ if (transferFee.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS) {
8007
+ return postFeeAmount.add(maximumFee);
8008
+ }
8009
+ const ONE_IN_BASIS_POINTS = new BN3(MAX_FEE_BASIS_POINTS);
8010
+ const numerator = postFeeAmount.mul(ONE_IN_BASIS_POINTS);
8011
+ const denominator = ONE_IN_BASIS_POINTS.sub(
8012
+ new BN3(transferFee.transferFeeBasisPoints)
8013
+ );
8014
+ const rawPreFeeAmount = numerator.add(denominator).sub(new BN3(1)).div(denominator);
8015
+ if (rawPreFeeAmount.sub(postFeeAmount).gte(maximumFee)) {
8016
+ return postFeeAmount.add(maximumFee);
8017
+ }
8018
+ return rawPreFeeAmount;
8019
+ }
8020
+ function calculateInverseFee(transferFee, postFeeAmount) {
8021
+ const preFeeAmount = calculatePreFeeAmount(transferFee, postFeeAmount);
8022
+ return new BN3(
8023
+ calculateFee(transferFee, BigInt(preFeeAmount.toString())).toString()
8024
+ );
8025
+ }
8026
+ function calculateTransferFeeIncludedAmount(transferFeeExcludedAmount, mint, currentEpoch) {
8027
+ if (transferFeeExcludedAmount.isZero()) {
8028
+ return {
8029
+ amount: new BN3(0),
8030
+ transferFee: new BN3(0)
8031
+ };
8032
+ }
8033
+ const transferFeeConfig = getTransferFeeConfig(mint);
8034
+ if (transferFeeConfig === null) {
8035
+ return {
8036
+ amount: transferFeeExcludedAmount,
8037
+ transferFee: new BN3(0)
8038
+ };
8039
+ }
8040
+ const epochFee = getEpochFee(transferFeeConfig, BigInt(currentEpoch));
8041
+ const transferFee = epochFee.transferFeeBasisPoints == MAX_FEE_BASIS_POINTS ? new BN3(epochFee.maximumFee.toString()) : calculateInverseFee(epochFee, transferFeeExcludedAmount);
8042
+ const transferFeeIncludedAmount = transferFeeExcludedAmount.add(transferFee);
8043
+ return {
8044
+ amount: transferFeeIncludedAmount,
8045
+ transferFee
8046
+ };
8047
+ }
8048
+ function calculateTransferFeeExcludedAmount(transferFeeIncludedAmount, mint, currentEpoch) {
8049
+ const transferFeeConfig = getTransferFeeConfig(mint);
8050
+ if (transferFeeConfig === null) {
8051
+ return {
8052
+ amount: transferFeeIncludedAmount,
8053
+ transferFee: new BN3(0)
8054
+ };
8055
+ }
8056
+ const transferFeeIncludedAmountN = BigInt(
8057
+ transferFeeIncludedAmount.toString()
8058
+ );
8059
+ const transferFee = calculateFee(
8060
+ getEpochFee(transferFeeConfig, BigInt(currentEpoch)),
8061
+ transferFeeIncludedAmountN
8062
+ );
8063
+ const transferFeeExcludedAmount = new BN3(
8064
+ (transferFeeIncludedAmountN - transferFee).toString()
8065
+ );
8066
+ return {
8067
+ amount: transferFeeExcludedAmount,
8068
+ transferFee: new BN3(transferFee.toString())
8069
+ };
8070
+ }
8071
+
8072
+ // src/helpers/vestings.ts
8073
+ import { BN as BN4 } from "@coral-xyz/anchor";
8074
+ import { min } from "bn.js";
8075
+ function isVestingComplete(vestingData, currentPoint) {
8076
+ const cliffPoint = vestingData.cliffPoint;
8077
+ const periodFrequency = vestingData.periodFrequency;
8078
+ const numberOfPeriods = vestingData.numberOfPeriod;
8079
+ const endPoint = cliffPoint.add(periodFrequency.muln(numberOfPeriods));
8080
+ return currentPoint.gte(endPoint);
8081
+ }
8082
+ function getTotalLockedLiquidity(vestingData) {
8083
+ return vestingData.cliffUnlockLiquidity.add(
8084
+ vestingData.liquidityPerPeriod.mul(new BN4(vestingData.numberOfPeriod))
8085
+ );
8086
+ }
8087
+ function getAvailableVestingLiquidity(vestingData, currentPoint) {
8088
+ const {
8089
+ cliffPoint,
8090
+ periodFrequency,
8091
+ cliffUnlockLiquidity,
8092
+ liquidityPerPeriod,
8093
+ numberOfPeriod,
8094
+ totalReleasedLiquidity
8095
+ } = vestingData;
8096
+ if (currentPoint.lt(cliffPoint)) {
8097
+ return new BN4(0);
8098
+ }
8099
+ if (periodFrequency.isZero()) {
8100
+ return cliffUnlockLiquidity;
8101
+ }
8102
+ let passedPeriod = new BN4(currentPoint).sub(cliffPoint).div(periodFrequency);
8103
+ passedPeriod = min(passedPeriod, new BN4(numberOfPeriod));
8104
+ const unlockedLiquidity = cliffUnlockLiquidity.add(
8105
+ passedPeriod.mul(liquidityPerPeriod)
8106
+ );
8107
+ const availableReleasingLiquidity = unlockedLiquidity.sub(
8108
+ totalReleasedLiquidity
8109
+ );
8110
+ return availableReleasingLiquidity;
8111
+ }
8112
+
8113
+ // src/helpers/validation.ts
8114
+ import BN14 from "bn.js";
8115
+
8116
+ // src/math/poolFees/baseFee.ts
8117
+ import BN9 from "bn.js";
8118
+
8119
+ // src/math/poolFees/rateLimiter.ts
8120
+ import BN7 from "bn.js";
8121
+
8122
+ // src/math/feeMath.ts
8123
+ import { BN as BN6 } from "@coral-xyz/anchor";
8124
+
8125
+ // src/math/utilsMath.ts
8126
+ import Decimal2 from "decimal.js";
8127
+ import BN5 from "bn.js";
8128
+ function mulDiv(x, y, denominator, rounding) {
8129
+ const { div, mod } = x.mul(y).divmod(denominator);
8130
+ if (rounding == 0 /* Up */ && !mod.isZero()) {
8131
+ return div.add(new BN5(1));
8132
+ }
8133
+ return div;
8134
+ }
8135
+ function q64ToDecimal(num, decimalPlaces) {
8136
+ return new Decimal2(num.toString()).div(Decimal2.pow(2, 64)).toDecimalPlaces(decimalPlaces);
8137
+ }
8138
+ function decimalToQ64(num) {
8139
+ return new BN5(num.mul(Decimal2.pow(2, 64)).floor().toFixed());
8140
+ }
8141
+ function sqrt(value) {
8142
+ if (value.isZero()) {
8143
+ return new BN5(0);
8144
+ }
8145
+ if (value.eq(new BN5(1))) {
8146
+ return new BN5(1);
8147
+ }
8148
+ let x = value;
8149
+ let y = value.add(new BN5(1)).div(new BN5(2));
8150
+ while (y.lt(x)) {
8151
+ x = y;
8152
+ y = x.add(value.div(x)).div(new BN5(2));
8153
+ }
8154
+ return x;
8155
+ }
8156
+ function pow(base, exp) {
8157
+ let invert = exp.isNeg();
8158
+ if (exp.isZero()) {
8159
+ return ONE_Q64;
8160
+ }
8161
+ exp = invert ? exp.abs() : exp;
8162
+ if (exp.gt(MAX_EXPONENTIAL)) {
8163
+ return new BN5(0);
8164
+ }
8165
+ let squaredBase = base;
8166
+ let result = ONE_Q64;
8167
+ if (squaredBase.gte(result)) {
8168
+ squaredBase = MAX.div(squaredBase);
8169
+ invert = !invert;
8170
+ }
8171
+ if (!exp.and(new BN5(1)).isZero()) {
8172
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8173
+ }
8174
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8175
+ if (!exp.and(new BN5(2)).isZero()) {
8176
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8177
+ }
8178
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8179
+ if (!exp.and(new BN5(4)).isZero()) {
8180
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8181
+ }
8182
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8183
+ if (!exp.and(new BN5(8)).isZero()) {
8184
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8185
+ }
8186
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8187
+ if (!exp.and(new BN5(16)).isZero()) {
8188
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8189
+ }
8190
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8191
+ if (!exp.and(new BN5(32)).isZero()) {
8192
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8193
+ }
8194
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8195
+ if (!exp.and(new BN5(64)).isZero()) {
8196
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8197
+ }
8198
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8199
+ if (!exp.and(new BN5(128)).isZero()) {
8200
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8201
+ }
8202
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8203
+ if (!exp.and(new BN5(256)).isZero()) {
8204
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8205
+ }
8206
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8207
+ if (!exp.and(new BN5(512)).isZero()) {
8208
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8209
+ }
8210
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8211
+ if (!exp.and(new BN5(1024)).isZero()) {
8212
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8213
+ }
8214
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8215
+ if (!exp.and(new BN5(2048)).isZero()) {
8216
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8217
+ }
8218
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8219
+ if (!exp.and(new BN5(4096)).isZero()) {
8220
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8221
+ }
8222
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8223
+ if (!exp.and(new BN5(8192)).isZero()) {
8224
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8225
+ }
8226
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8227
+ if (!exp.and(new BN5(16384)).isZero()) {
8228
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8229
+ }
8230
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8231
+ if (!exp.and(new BN5(32768)).isZero()) {
8232
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8233
+ }
8234
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8235
+ if (!exp.and(new BN5(65536)).isZero()) {
8236
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8237
+ }
8238
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8239
+ if (!exp.and(new BN5(131072)).isZero()) {
8240
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8241
+ }
8242
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8243
+ if (!exp.and(new BN5(262144)).isZero()) {
8244
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8245
+ }
8246
+ if (result.isZero()) {
8247
+ return new BN5(0);
8248
+ }
8249
+ if (invert) {
8250
+ result = MAX.div(result);
8251
+ }
8252
+ return result;
8253
+ }
8254
+
8255
+ // src/math/feeMath.ts
8256
+ function toNumerator(bps, feeDenominator) {
8257
+ try {
8258
+ const numerator = mulDiv(
8259
+ bps,
8260
+ feeDenominator,
8261
+ new BN6(BASIS_POINT_MAX),
8262
+ 1 /* Down */
8263
+ );
8264
+ return numerator;
8265
+ } catch (error) {
8266
+ throw new Error("Type cast failed or calculation overflow in toNumerator");
8267
+ }
8268
+ }
8269
+ function getFeeInPeriod(cliffFeeNumerator, reductionFactor, passedPeriod) {
8270
+ if (reductionFactor.isZero()) {
8271
+ return cliffFeeNumerator;
8272
+ }
8273
+ const bps = reductionFactor.shln(SCALE_OFFSET).div(new BN6(BASIS_POINT_MAX));
8274
+ const base = ONE_Q64.sub(bps);
8275
+ const result = pow(base, new BN6(passedPeriod));
8276
+ if (result.gt(U128_MAX)) {
8277
+ throw new Error("Math overflow");
8278
+ }
8279
+ const fee = result.mul(cliffFeeNumerator).shrn(SCALE_OFFSET);
8280
+ if (fee.gt(U64_MAX)) {
8281
+ throw new Error("Type cast failed: fee does not fit in u64");
8282
+ }
8283
+ return fee;
8284
+ }
8285
+ function getFeeMode(collectFeeMode, tradeDirection, hasReferral) {
8286
+ let feesOnInput;
8287
+ let feesOnTokenA;
8288
+ if (collectFeeMode === 0 /* BothToken */) {
8289
+ if (tradeDirection === 0 /* AtoB */) {
8290
+ feesOnInput = false;
8291
+ feesOnTokenA = false;
8292
+ } else {
8293
+ feesOnInput = false;
8294
+ feesOnTokenA = true;
8295
+ }
8296
+ } else {
8297
+ if (tradeDirection === 0 /* AtoB */) {
8298
+ feesOnInput = false;
8299
+ feesOnTokenA = false;
8300
+ } else {
8301
+ feesOnInput = true;
8302
+ feesOnTokenA = false;
8303
+ }
8304
+ }
8305
+ return {
8306
+ feesOnInput,
8307
+ feesOnTokenA,
8308
+ hasReferral
8309
+ };
8310
+ }
8311
+ function getTotalFeeNumerator(poolFees, baseFeeNumerator, maxFeeNumerator) {
8312
+ const dynamicFeeNumerator = getDynamicFeeNumerator(
8313
+ poolFees.dynamicFee.volatilityAccumulator,
8314
+ new BN6(poolFees.dynamicFee.binStep),
8315
+ new BN6(poolFees.dynamicFee.variableFeeControl)
8316
+ );
8317
+ const totalFeeNumerator = dynamicFeeNumerator.add(baseFeeNumerator);
8318
+ if (totalFeeNumerator.gt(U64_MAX)) {
8319
+ throw new Error("Type cast failed: fee does not fit in u64");
8320
+ }
8321
+ if (totalFeeNumerator.gt(maxFeeNumerator)) {
8322
+ return maxFeeNumerator;
8323
+ } else {
8324
+ return totalFeeNumerator;
8325
+ }
8326
+ }
8327
+ function getTotalTradingFeeFromIncludedFeeAmount(poolFees, currentPoint, activationPoint, includedFeeAmount, tradeDirection, maxFeeNumerator) {
8328
+ const baseFeeHandler = getBaseFeeHandler(
8329
+ poolFees.baseFee.cliffFeeNumerator,
8330
+ poolFees.baseFee.firstFactor,
8331
+ poolFees.baseFee.secondFactor,
8332
+ poolFees.baseFee.thirdFactor,
8333
+ poolFees.baseFee.baseFeeMode
8334
+ );
8335
+ const baseFeeNumerator = baseFeeHandler.getBaseFeeNumeratorFromIncludedFeeAmount(
8336
+ currentPoint,
8337
+ activationPoint,
8338
+ tradeDirection,
8339
+ includedFeeAmount
8340
+ );
8341
+ return getTotalFeeNumerator(poolFees, baseFeeNumerator, maxFeeNumerator);
8342
+ }
8343
+ function getTotalTradingFeeFromExcludedFeeAmount(poolFees, currentPoint, activationPoint, excludedFeeAmount, tradeDirection, maxFeeNumerator) {
8344
+ const baseFeeHandler = getBaseFeeHandler(
8345
+ poolFees.baseFee.cliffFeeNumerator,
8346
+ poolFees.baseFee.firstFactor,
8347
+ poolFees.baseFee.secondFactor,
8348
+ poolFees.baseFee.thirdFactor,
8349
+ poolFees.baseFee.baseFeeMode
8350
+ );
8351
+ const baseFeeNumerator = baseFeeHandler.getBaseFeeNumeratorFromExcludedFeeAmount(
8352
+ currentPoint,
8353
+ activationPoint,
8354
+ tradeDirection,
8355
+ excludedFeeAmount
8356
+ );
8357
+ return getTotalFeeNumerator(poolFees, baseFeeNumerator, maxFeeNumerator);
8358
+ }
8359
+ function splitFees(poolFees, feeAmount, hasReferral, hasPartner2) {
8360
+ const protocolFee = feeAmount.muln(poolFees.protocolFeePercent).divn(100);
8361
+ const tradingFee = feeAmount.sub(protocolFee);
8362
+ let referralFee = new BN6(0);
8363
+ if (hasReferral) {
8364
+ referralFee = protocolFee.muln(poolFees.referralFeePercent).divn(100);
8365
+ }
8366
+ const protocolFeeAfterReferral = protocolFee.sub(referralFee);
8367
+ let partnerFee = new BN6(0);
8368
+ if (hasPartner2 && poolFees.partnerFeePercent > 0) {
8369
+ partnerFee = protocolFeeAfterReferral.muln(poolFees.partnerFeePercent).divn(100);
8370
+ }
8371
+ const finalProtocolFee = protocolFeeAfterReferral.sub(partnerFee);
8372
+ return {
8373
+ tradingFee,
8374
+ protocolFee: finalProtocolFee,
8375
+ referralFee,
8376
+ partnerFee
8377
+ };
8378
+ }
8379
+ function getFeeOnAmount(poolFees, amount, tradeFeeNumerator, hasReferral, hasPartner2) {
8380
+ const { excludedFeeAmount, tradingFee } = getExcludedFeeAmount(
8381
+ tradeFeeNumerator,
8382
+ amount
8383
+ );
8384
+ const splitFeesResult = splitFees(
8385
+ poolFees,
8386
+ tradingFee,
8387
+ hasReferral,
8388
+ hasPartner2
8389
+ );
8390
+ return {
8391
+ amount: excludedFeeAmount,
8392
+ tradingFee: splitFeesResult.tradingFee,
8393
+ protocolFee: splitFeesResult.protocolFee,
8394
+ partnerFee: splitFeesResult.partnerFee,
8395
+ referralFee: splitFeesResult.referralFee
8396
+ };
8397
+ }
8398
+ function getExcludedFeeAmount(tradeFeeNumerator, includedFeeAmount) {
8399
+ const tradingFee = mulDiv(
8400
+ includedFeeAmount,
8401
+ tradeFeeNumerator,
8402
+ new BN6(FEE_DENOMINATOR),
8403
+ 0 /* Up */
8404
+ );
8405
+ const excludedFeeAmount = includedFeeAmount.sub(tradingFee);
8406
+ return { excludedFeeAmount, tradingFee };
8407
+ }
8408
+ function getIncludedFeeAmount(tradeFeeNumerator, excludedFeeAmount) {
8409
+ const denominator = new BN6(FEE_DENOMINATOR).sub(tradeFeeNumerator);
8410
+ if (denominator.isZero() || denominator.isNeg()) {
8411
+ throw new Error("Invalid fee numerator");
8412
+ }
8413
+ const includedFeeAmount = mulDiv(
8414
+ excludedFeeAmount,
8415
+ new BN6(FEE_DENOMINATOR),
8416
+ denominator,
8417
+ 0 /* Up */
8418
+ );
8419
+ const feeAmount = includedFeeAmount.sub(excludedFeeAmount);
8420
+ return { includedFeeAmount, feeAmount };
8421
+ }
8422
+ function getMaxFeeNumerator(poolVersion) {
8423
+ switch (poolVersion) {
8424
+ case 0 /* V0 */:
8425
+ return new BN6(MAX_FEE_NUMERATOR_V0);
8426
+ case 1 /* V1 */:
8427
+ return new BN6(MAX_FEE_NUMERATOR_V1);
8428
+ default:
8429
+ throw new Error("Invalid pool version");
8430
+ }
8431
+ }
8432
+ function getMaxFeeBps(poolVersion) {
8433
+ switch (poolVersion) {
8434
+ case 0 /* V0 */:
8435
+ return MAX_FEE_BPS_V0;
8436
+ case 1 /* V1 */:
8437
+ return MAX_FEE_BPS_V1;
8438
+ default:
8439
+ throw new Error("Invalid pool version");
8440
+ }
8441
+ }
8442
+
8443
+ // src/math/poolFees/rateLimiter.ts
8444
+ function isZeroRateLimiter(referenceAmount, maxLimiterDuration, maxFeeBps, feeIncrementBps) {
8445
+ return referenceAmount.isZero() && maxLimiterDuration === 0 && maxFeeBps === 0 && feeIncrementBps === 0;
8446
+ }
8447
+ function isNonZeroRateLimiter(referenceAmount, maxLimiterDuration, maxFeeBps, feeIncrementBps) {
8448
+ return referenceAmount.isZero() && maxLimiterDuration !== 0 && maxFeeBps !== 0 && feeIncrementBps !== 0;
8449
+ }
8450
+ function isRateLimiterApplied(referenceAmount, maxLimiterDuration, maxFeeBps, feeIncrementBps, currentPoint, activationPoint, tradeDirection) {
8451
+ if (isZeroRateLimiter(
8452
+ referenceAmount,
8453
+ maxLimiterDuration,
8454
+ maxFeeBps,
8455
+ feeIncrementBps
8456
+ )) {
8457
+ return false;
8458
+ }
8459
+ if (tradeDirection === 0 /* AtoB */) {
8460
+ return false;
8461
+ }
8462
+ if (currentPoint.lt(activationPoint)) {
8463
+ return false;
8464
+ }
8465
+ const lastEffectiveRateLimiterPoint = activationPoint.add(
8466
+ new BN7(maxLimiterDuration)
8467
+ );
8468
+ if (currentPoint.gt(lastEffectiveRateLimiterPoint)) {
8469
+ return false;
8470
+ }
8471
+ return true;
8472
+ }
8473
+ function getMaxIndex(maxFeeBps, cliffFeeNumerator, feeIncrementBps) {
8474
+ const maxFeeNumerator = toNumerator(
8475
+ new BN7(maxFeeBps),
8476
+ new BN7(FEE_DENOMINATOR)
8477
+ );
8478
+ if (cliffFeeNumerator.gt(maxFeeNumerator)) {
8479
+ throw new Error("cliffFeeNumerator cannot be greater than maxFeeNumerator");
8480
+ }
8481
+ const deltaNumerator = maxFeeNumerator.sub(cliffFeeNumerator);
8482
+ const feeIncrementNumerator = toNumerator(
8483
+ new BN7(feeIncrementBps),
8484
+ new BN7(FEE_DENOMINATOR)
8485
+ );
8486
+ if (feeIncrementNumerator.isZero()) {
8487
+ throw new Error("feeIncrementNumerator cannot be zero");
8488
+ }
8489
+ const maxIndex = deltaNumerator.div(feeIncrementNumerator);
8490
+ return maxIndex;
8491
+ }
8492
+ function getFeeNumeratorFromIncludedFeeAmount(inputAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps) {
8493
+ if (inputAmount.lte(referenceAmount)) {
8494
+ return cliffFeeNumerator;
8495
+ } else {
8496
+ const maxFeeNumerator = toNumerator(
8497
+ new BN7(maxFeeBps),
8498
+ new BN7(FEE_DENOMINATOR)
8499
+ );
8500
+ const c = cliffFeeNumerator;
8501
+ const inputMinusRef = inputAmount.sub(referenceAmount);
8502
+ const a = inputMinusRef.div(referenceAmount);
8503
+ const b = inputMinusRef.mod(referenceAmount);
8504
+ const maxIndex = getMaxIndex(maxFeeBps, cliffFeeNumerator, feeIncrementBps);
8505
+ const i = toNumerator(new BN7(feeIncrementBps), new BN7(FEE_DENOMINATOR));
8506
+ const x0 = referenceAmount;
8507
+ const one = new BN7(1);
8508
+ const two = new BN7(2);
8509
+ let tradingFeeNumerator;
8510
+ if (a.lt(maxIndex)) {
8511
+ const numerator1 = c.add(c.mul(a)).add(i.mul(a).mul(a.add(one)).div(two));
8512
+ const numerator2 = c.add(i.mul(a.add(one)));
8513
+ const firstFee = x0.mul(numerator1);
8514
+ const secondFee = b.mul(numerator2);
8515
+ tradingFeeNumerator = firstFee.add(secondFee);
8516
+ } else {
8517
+ const numerator1 = c.add(c.mul(maxIndex)).add(i.mul(maxIndex).mul(maxIndex.add(one)).div(two));
8518
+ const numerator2 = maxFeeNumerator;
8519
+ const firstFee = x0.mul(numerator1);
8520
+ const d = a.sub(maxIndex);
8521
+ const leftAmount = d.mul(x0).add(b);
8522
+ const secondFee = leftAmount.mul(numerator2);
8523
+ tradingFeeNumerator = firstFee.add(secondFee);
8524
+ }
8525
+ const denominator = new BN7(FEE_DENOMINATOR);
8526
+ const tradingFee = tradingFeeNumerator.add(denominator).sub(one).div(denominator);
8527
+ const numerator = mulDiv(tradingFee, denominator, inputAmount, 0 /* Up */);
8528
+ if (numerator.gt(new BN7(U64_MAX))) {
8529
+ throw new Error("Numerator does not fit in u64");
8530
+ }
8531
+ return numerator;
8532
+ }
8533
+ }
8534
+ function getExcludedFeeAmountFromIncludedFeeAmount(includedFeeAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps) {
8535
+ const feeNumerator = getFeeNumeratorFromIncludedFeeAmount(
8536
+ includedFeeAmount,
8537
+ referenceAmount,
8538
+ cliffFeeNumerator,
8539
+ maxFeeBps,
8540
+ feeIncrementBps
8541
+ );
8542
+ const { excludedFeeAmount } = getExcludedFeeAmount(
8543
+ feeNumerator,
8544
+ includedFeeAmount
8545
+ );
8546
+ return excludedFeeAmount;
8547
+ }
8548
+ function getCheckedAmounts(referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps) {
8549
+ const maxIndex = getMaxIndex(maxFeeBps, cliffFeeNumerator, feeIncrementBps);
8550
+ const x0 = referenceAmount;
8551
+ const one = new BN7(1);
8552
+ const maxIndexInputAmount = maxIndex.add(one).mul(x0);
8553
+ if (maxIndexInputAmount.lte(U64_MAX)) {
8554
+ const checkedIncludedFeeAmount = maxIndexInputAmount;
8555
+ const checkedOutputAmount = getExcludedFeeAmountFromIncludedFeeAmount(
8556
+ checkedIncludedFeeAmount,
8557
+ referenceAmount,
8558
+ cliffFeeNumerator,
8559
+ maxFeeBps,
8560
+ feeIncrementBps
8561
+ );
8562
+ return [checkedOutputAmount, checkedIncludedFeeAmount, false];
8563
+ } else {
8564
+ const checkedIncludedFeeAmount = U64_MAX;
8565
+ const checkedOutputAmount = getExcludedFeeAmountFromIncludedFeeAmount(
8566
+ checkedIncludedFeeAmount,
8567
+ referenceAmount,
8568
+ cliffFeeNumerator,
8569
+ maxFeeBps,
8570
+ feeIncrementBps
8571
+ );
8572
+ return [checkedOutputAmount, checkedIncludedFeeAmount, true];
8573
+ }
8574
+ }
8575
+ function getFeeNumeratorFromExcludedFeeAmount(excludedFeeAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps) {
8576
+ const excludedFeeReferenceAmount = getExcludedFeeAmountFromIncludedFeeAmount(
8577
+ referenceAmount,
8578
+ referenceAmount,
8579
+ cliffFeeNumerator,
8580
+ maxFeeBps,
8581
+ feeIncrementBps
8582
+ );
8583
+ if (excludedFeeAmount.lte(excludedFeeReferenceAmount)) {
8584
+ return cliffFeeNumerator;
8585
+ }
8586
+ const [checkedExcludedFeeAmount, checkedIncludedFeeAmount, isOverflow] = getCheckedAmounts(
8587
+ referenceAmount,
8588
+ cliffFeeNumerator,
8589
+ maxFeeBps,
8590
+ feeIncrementBps
8591
+ );
8592
+ if (excludedFeeAmount.eq(checkedExcludedFeeAmount)) {
8593
+ return getFeeNumeratorFromIncludedFeeAmount(
8594
+ checkedIncludedFeeAmount,
8595
+ referenceAmount,
8596
+ cliffFeeNumerator,
8597
+ maxFeeBps,
8598
+ feeIncrementBps
8599
+ );
8600
+ }
8601
+ let includedFeeAmount;
8602
+ if (excludedFeeAmount.lt(checkedExcludedFeeAmount)) {
8603
+ const TWO = new BN7(2);
8604
+ const FOUR = new BN7(4);
8605
+ const i = toNumerator(new BN7(feeIncrementBps), new BN7(FEE_DENOMINATOR));
8606
+ const x0 = referenceAmount;
8607
+ const d = new BN7(FEE_DENOMINATOR);
8608
+ const c = cliffFeeNumerator;
8609
+ const ex = excludedFeeAmount;
8610
+ const x = i;
8611
+ const y = TWO.mul(d).mul(x0).add(i.mul(x0)).sub(TWO.mul(c).mul(x0));
8612
+ const z = TWO.mul(ex).mul(d).mul(x0);
8613
+ const discriminant = y.mul(y).sub(FOUR.mul(x).mul(z));
8614
+ const sqrtDiscriminant = sqrt(discriminant);
8615
+ includedFeeAmount = y.sub(sqrtDiscriminant).div(TWO.mul(x));
8616
+ const numerator = y.sub(sqrtDiscriminant);
8617
+ const denominator = TWO.mul(x);
8618
+ includedFeeAmount = numerator.div(denominator);
8619
+ const aPlusOne = includedFeeAmount.div(x0);
8620
+ const firstExcludedFeeAmount = getExcludedFeeAmountFromIncludedFeeAmount(
8621
+ includedFeeAmount,
8622
+ referenceAmount,
8623
+ cliffFeeNumerator,
8624
+ maxFeeBps,
8625
+ feeIncrementBps
8626
+ );
8627
+ const excludedFeeRemainingAmount = excludedFeeAmount.sub(
8628
+ firstExcludedFeeAmount
8629
+ );
8630
+ const remainingAmountFeeNumerator = c.add(i.mul(aPlusOne));
8631
+ const { includedFeeAmount: includedFeeRemainingAmount } = getIncludedFeeAmount(
8632
+ remainingAmountFeeNumerator,
8633
+ excludedFeeRemainingAmount
8634
+ );
8635
+ includedFeeAmount = includedFeeAmount.add(includedFeeRemainingAmount);
8636
+ } else {
8637
+ if (isOverflow) {
8638
+ throw new Error("Math overflow in getFeeNumeratorFromExcludedFeeAmount");
8639
+ }
8640
+ const excludedFeeRemainingAmount = excludedFeeAmount.sub(
8641
+ checkedExcludedFeeAmount
8642
+ );
8643
+ const maxFeeNumerator = toNumerator(
8644
+ new BN7(maxFeeBps),
8645
+ new BN7(FEE_DENOMINATOR)
8646
+ );
8647
+ const { includedFeeAmount: includedFeeRemainingAmount } = getIncludedFeeAmount(maxFeeNumerator, excludedFeeRemainingAmount);
8648
+ includedFeeAmount = includedFeeRemainingAmount.add(
8649
+ checkedIncludedFeeAmount
8650
+ );
8651
+ }
8652
+ const tradingFee = includedFeeAmount.sub(excludedFeeAmount);
8653
+ const feeNumerator = mulDiv(
8654
+ tradingFee,
8655
+ new BN7(FEE_DENOMINATOR),
8656
+ includedFeeAmount,
8657
+ 0 /* Up */
8658
+ );
8659
+ if (feeNumerator.lt(cliffFeeNumerator)) {
8660
+ throw new Error("feeNumerator is less than cliffFeeNumerator");
8661
+ }
8662
+ return feeNumerator;
8663
+ }
8664
+
8665
+ // src/math/poolFees/feeScheduler.ts
8666
+ import BN8 from "bn.js";
8667
+ function getMaxBaseFeeNumerator(cliffFeeNumerator) {
8668
+ return cliffFeeNumerator;
8669
+ }
8670
+ function getMinBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, periodFrequency, reductionFactor, feeSchedulerMode) {
8671
+ return getBaseFeeNumeratorByPeriod(
8672
+ cliffFeeNumerator,
8673
+ numberOfPeriod,
8674
+ periodFrequency,
8675
+ reductionFactor,
8676
+ feeSchedulerMode
8677
+ );
8678
+ }
8679
+ function getBaseFeeNumeratorByPeriod(cliffFeeNumerator, numberOfPeriod, period, reductionFactor, feeSchedulerMode) {
8680
+ const periodValue = BN8.min(period, new BN8(numberOfPeriod));
8681
+ const periodNumber = periodValue.toNumber();
8682
+ if (periodNumber > U16_MAX) {
8683
+ throw new Error("Math overflow");
8684
+ }
8685
+ switch (feeSchedulerMode) {
8686
+ case 0 /* FeeSchedulerLinear */: {
8687
+ const feeNumerator = getFeeNumeratorOnLinearFeeScheduler(
8688
+ cliffFeeNumerator,
8689
+ reductionFactor,
8690
+ periodNumber
8691
+ );
8692
+ return feeNumerator;
8693
+ }
8694
+ case 1 /* FeeSchedulerExponential */: {
8695
+ const feeNumerator = getFeeNumeratorOnExponentialFeeScheduler(
8696
+ cliffFeeNumerator,
8697
+ reductionFactor,
8698
+ periodNumber
8699
+ );
8700
+ return feeNumerator;
8701
+ }
8702
+ default:
8703
+ throw new Error("Invalid fee scheduler mode");
8704
+ }
8705
+ }
8706
+ function getFeeNumeratorOnLinearFeeScheduler(cliffFeeNumerator, reductionFactor, period) {
8707
+ const reduction = new BN8(period).mul(reductionFactor);
8708
+ return cliffFeeNumerator.sub(reduction);
8709
+ }
8710
+ function getFeeNumeratorOnExponentialFeeScheduler(cliffFeeNumerator, reductionFactor, period) {
8711
+ if (period === 0) {
8712
+ return cliffFeeNumerator;
8713
+ }
8714
+ const basisPointMax = new BN8(BASIS_POINT_MAX);
8715
+ const bps = new BN8(reductionFactor).shln(64).div(basisPointMax);
8716
+ const base = ONE_Q64.sub(bps);
8717
+ const result = pow(base, new BN8(period));
8718
+ return cliffFeeNumerator.mul(result).div(ONE_Q64);
8719
+ }
8720
+ function getBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, periodFrequency, reductionFactor, feeSchedulerMode, currentPoint, activationPoint) {
8721
+ if (periodFrequency.isZero()) {
8722
+ return cliffFeeNumerator;
8723
+ }
8724
+ const period = currentPoint.sub(activationPoint).div(periodFrequency);
8725
+ return getBaseFeeNumeratorByPeriod(
8726
+ cliffFeeNumerator,
8727
+ numberOfPeriod,
8728
+ period,
8729
+ reductionFactor,
8730
+ feeSchedulerMode
8731
+ );
8732
+ }
8733
+
8734
+ // src/math/poolFees/baseFee.ts
8735
+ var FeeRateLimiter = class {
8736
+ constructor(cliffFeeNumerator, feeIncrementBps, maxFeeBps, maxLimiterDuration, referenceAmount) {
8737
+ this.cliffFeeNumerator = cliffFeeNumerator;
8738
+ this.feeIncrementBps = feeIncrementBps;
8739
+ this.maxFeeBps = maxFeeBps;
8740
+ this.maxLimiterDuration = maxLimiterDuration;
8741
+ this.referenceAmount = referenceAmount;
8742
+ }
8743
+ validate(collectFeeMode, activationType, poolVersion) {
8744
+ return validateFeeRateLimiter(
8745
+ this.cliffFeeNumerator,
8746
+ this.feeIncrementBps,
8747
+ this.maxFeeBps,
8748
+ this.maxLimiterDuration,
8749
+ this.referenceAmount,
8750
+ collectFeeMode,
8751
+ activationType,
8752
+ poolVersion
8753
+ );
8754
+ }
8755
+ getBaseFeeNumeratorFromIncludedFeeAmount(currentPoint, activationPoint, tradeDirection, includedFeeAmount) {
8756
+ if (isRateLimiterApplied(
8757
+ this.referenceAmount,
8758
+ this.maxLimiterDuration,
8759
+ this.maxFeeBps,
8760
+ this.feeIncrementBps,
8761
+ currentPoint,
8762
+ activationPoint,
8763
+ tradeDirection
8764
+ )) {
8765
+ return getFeeNumeratorFromIncludedFeeAmount(
8766
+ includedFeeAmount,
8767
+ this.referenceAmount,
8768
+ this.cliffFeeNumerator,
8769
+ this.maxFeeBps,
8770
+ this.feeIncrementBps
8771
+ );
8772
+ } else {
8773
+ return this.cliffFeeNumerator;
8774
+ }
8775
+ }
8776
+ getBaseFeeNumeratorFromExcludedFeeAmount(currentPoint, activationPoint, tradeDirection, excludedFeeAmount) {
8777
+ if (isRateLimiterApplied(
8778
+ this.referenceAmount,
8779
+ this.maxLimiterDuration,
8780
+ this.maxFeeBps,
8781
+ this.feeIncrementBps,
8782
+ currentPoint,
8783
+ activationPoint,
8784
+ tradeDirection
8785
+ )) {
8786
+ return getFeeNumeratorFromExcludedFeeAmount(
8787
+ excludedFeeAmount,
8788
+ this.referenceAmount,
8789
+ this.cliffFeeNumerator,
8790
+ this.maxFeeBps,
8791
+ this.feeIncrementBps
8792
+ );
8793
+ } else {
8794
+ return this.cliffFeeNumerator;
8795
+ }
8796
+ }
8797
+ };
8798
+ var FeeScheduler = class {
8799
+ constructor(cliffFeeNumerator, numberOfPeriod, periodFrequency, reductionFactor, feeSchedulerMode) {
8800
+ this.cliffFeeNumerator = cliffFeeNumerator;
8801
+ this.numberOfPeriod = numberOfPeriod;
8802
+ this.periodFrequency = periodFrequency;
8803
+ this.reductionFactor = reductionFactor;
8804
+ this.feeSchedulerMode = feeSchedulerMode;
8805
+ }
8806
+ validate(collectFeeMode, activationType, poolVersion) {
8807
+ return validateFeeScheduler(
8808
+ this.numberOfPeriod,
8809
+ this.periodFrequency,
8810
+ this.reductionFactor,
8811
+ this.cliffFeeNumerator,
8812
+ this.feeSchedulerMode,
8813
+ poolVersion
8814
+ );
8815
+ }
8816
+ getBaseFeeNumeratorFromIncludedFeeAmount(currentPoint, activationPoint) {
8817
+ return getBaseFeeNumerator(
8818
+ this.cliffFeeNumerator,
8819
+ this.numberOfPeriod,
8820
+ this.periodFrequency,
8821
+ this.reductionFactor,
8822
+ this.feeSchedulerMode,
8823
+ currentPoint,
8824
+ activationPoint
8825
+ );
8826
+ }
8827
+ getBaseFeeNumeratorFromExcludedFeeAmount(currentPoint, activationPoint) {
8828
+ return getBaseFeeNumerator(
8829
+ this.cliffFeeNumerator,
8830
+ this.numberOfPeriod,
8831
+ this.periodFrequency,
8832
+ this.reductionFactor,
8833
+ this.feeSchedulerMode,
8834
+ currentPoint,
8835
+ activationPoint
8836
+ );
8837
+ }
8838
+ };
8839
+ function getBaseFeeHandler(cliffFeeNumerator, firstFactor, secondFactor, thirdFactor, baseFeeMode) {
8840
+ switch (baseFeeMode) {
8841
+ case 0 /* FeeSchedulerLinear */:
8842
+ case 1 /* FeeSchedulerExponential */: {
8843
+ if (secondFactor.length < 8) {
8844
+ throw new Error(
8845
+ "TypeCastFailed: secondFactor must be at least 8 bytes"
8846
+ );
8847
+ }
8848
+ const periodFrequency = new BN9(
8849
+ Buffer.from(secondFactor.slice(0, 8)),
8850
+ "le"
8851
+ );
8852
+ const feeScheduler = new FeeScheduler(
8853
+ cliffFeeNumerator,
8854
+ firstFactor,
8855
+ periodFrequency,
8856
+ thirdFactor,
8857
+ baseFeeMode
8858
+ );
8859
+ return feeScheduler;
8860
+ }
8861
+ case 2 /* RateLimiter */: {
8862
+ if (secondFactor.length < 8) {
8863
+ throw new Error(
8864
+ "TypeCastFailed: secondFactor must be at least 8 bytes"
8865
+ );
8866
+ }
8867
+ const maxLimiterDuration = Buffer.from(
8868
+ secondFactor.slice(0, 4)
8869
+ ).readUInt32LE(0);
8870
+ const maxFeeBps = Buffer.from(secondFactor.slice(4, 8)).readUInt32LE(0);
8871
+ const feeRateLimiter = new FeeRateLimiter(
8872
+ cliffFeeNumerator,
8873
+ firstFactor,
8874
+ maxLimiterDuration,
8875
+ maxFeeBps,
8876
+ thirdFactor
8877
+ );
8878
+ return feeRateLimiter;
8879
+ }
8880
+ default:
8881
+ throw new Error("Invalid base fee mode");
8882
+ }
8883
+ }
8884
+
8885
+ // src/math/poolFees/dynamicFee.ts
8886
+ import BN10 from "bn.js";
8887
+ function isDynamicFeeEnabled(dynamicFee) {
8888
+ return dynamicFee.initialized !== 0;
8889
+ }
8890
+ function getDynamicFeeNumerator(volatilityAccumulator, binStep, variableFeeControl) {
8891
+ if (variableFeeControl.isZero()) {
8892
+ return new BN10(0);
8893
+ }
8894
+ const squareVfaBin = volatilityAccumulator.mul(new BN10(binStep)).pow(new BN10(2));
8895
+ const vFee = variableFeeControl.mul(squareVfaBin);
8896
+ return vFee.add(new BN10(DYNAMIC_FEE_ROUNDING_OFFSET)).div(new BN10(DYNAMIC_FEE_SCALING_FACTOR));
8897
+ }
8898
+
8899
+ // src/math/quote.ts
8900
+ import BN12 from "bn.js";
8901
+
8902
+ // src/math/curve.ts
8903
+ import BN11 from "bn.js";
8904
+ function getNextSqrtPriceFromAmountInBRoundingDown(sqrtPrice, liquidity, amount) {
8905
+ const quotient = amount.shln(SCALE_OFFSET * 2).div(liquidity);
8906
+ const result = sqrtPrice.add(quotient);
8907
+ return result;
8908
+ }
8909
+ function getNextSqrtPriceFromAmountOutBRoundingDown(sqrtPrice, liquidity, amount) {
8910
+ const numerator = amount.shln(SCALE_OFFSET * 2);
8911
+ const quotient = numerator.add(liquidity).subn(1).div(liquidity);
8912
+ const result = sqrtPrice.sub(quotient);
8913
+ if (result.isNeg()) {
8914
+ throw new Error("sqrt price cannot be negative");
8915
+ }
8916
+ return result;
8917
+ }
8918
+ function getNextSqrtPriceFromAmountInARoundingUp(sqrtPrice, liquidity, amount) {
8919
+ if (amount.isZero()) {
8920
+ return sqrtPrice;
8921
+ }
8922
+ const product = amount.mul(sqrtPrice);
8923
+ const denominator = liquidity.add(product);
8924
+ const result = mulDiv(liquidity, sqrtPrice, denominator, 0 /* Up */);
8925
+ return result;
8926
+ }
8927
+ function getNextSqrtPriceFromAmountOutARoundingUp(sqrtPrice, liquidity, amount) {
8928
+ if (amount.isZero()) {
8929
+ return sqrtPrice;
8930
+ }
8931
+ const product = amount.mul(sqrtPrice);
8932
+ const denominator = liquidity.sub(product);
8933
+ if (denominator.lte(new BN11(0))) {
8934
+ throw new Error("MathOverflow: denominator is zero or negative");
8935
+ }
8936
+ return mulDiv(liquidity, sqrtPrice, denominator, 0 /* Up */);
8937
+ }
8938
+ function getNextSqrtPriceFromOutput(sqrtPrice, liquidity, amountOut, aForB) {
8939
+ if (sqrtPrice.lte(new BN11(0))) {
8940
+ throw new Error("sqrtPrice must be greater than 0");
8941
+ }
8942
+ if (liquidity.lte(new BN11(0))) {
8943
+ throw new Error("liquidity must be greater than 0");
8944
+ }
8945
+ if (aForB) {
8946
+ return getNextSqrtPriceFromAmountOutBRoundingDown(
7407
8947
  sqrtPrice,
7408
8948
  liquidity,
7409
- outAmount
8949
+ amountOut
7410
8950
  );
7411
8951
  } else {
7412
- return getNextSqrtPriceFromAmountARoundingDown(
8952
+ return getNextSqrtPriceFromAmountOutARoundingUp(
7413
8953
  sqrtPrice,
7414
8954
  liquidity,
7415
- outAmount
8955
+ amountOut
7416
8956
  );
7417
8957
  }
7418
8958
  }
7419
-
7420
- // src/helpers/fee.ts
7421
- import Decimal2 from "decimal.js";
7422
- function getBaseFeeNumerator(feeSchedulerMode, cliffFeeNumerator, period, reductionFactor) {
7423
- let feeNumerator;
7424
- if (feeSchedulerMode == 0 /* Linear */) {
7425
- feeNumerator = cliffFeeNumerator.sub(period.mul(reductionFactor));
8959
+ function getNextSqrtPriceFromInput(sqrtPrice, liquidity, amountIn, aForB) {
8960
+ if (sqrtPrice.lte(new BN11(0))) {
8961
+ throw new Error("sqrtPrice must be greater than 0");
8962
+ }
8963
+ if (liquidity.lte(new BN11(0))) {
8964
+ throw new Error("liquidity must be greater than 0");
8965
+ }
8966
+ if (aForB) {
8967
+ return getNextSqrtPriceFromAmountInARoundingUp(
8968
+ sqrtPrice,
8969
+ liquidity,
8970
+ amountIn
8971
+ );
7426
8972
  } else {
7427
- const bps = reductionFactor.shln(SCALE_OFFSET).div(new BN5(BASIS_POINT_MAX));
7428
- const base = ONE.sub(bps);
7429
- const result = pow(base, period);
7430
- feeNumerator = cliffFeeNumerator.mul(result).shrn(SCALE_OFFSET);
8973
+ return getNextSqrtPriceFromAmountInBRoundingDown(
8974
+ sqrtPrice,
8975
+ liquidity,
8976
+ amountIn
8977
+ );
7431
8978
  }
7432
- return feeNumerator;
7433
8979
  }
7434
- function getDynamicFeeNumerator(volatilityAccumulator, binStep, variableFeeControl) {
7435
- if (variableFeeControl.isZero()) {
7436
- return new BN5(0);
8980
+ function getAmountBFromLiquidityDelta(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding) {
8981
+ const result = getDeltaAmountBUnsignedUnchecked(
8982
+ lowerSqrtPrice,
8983
+ upperSqrtPrice,
8984
+ liquidity,
8985
+ rounding
8986
+ );
8987
+ if (result.gt(U64_MAX)) {
8988
+ throw new Error("MathOverflow: result exceeds u64 max");
7437
8989
  }
7438
- const squareVfaBin = volatilityAccumulator.mul(new BN5(binStep)).pow(new BN5(2));
7439
- const vFee = variableFeeControl.mul(squareVfaBin);
7440
- return vFee.add(new BN5(99999999999)).div(new BN5(1e11));
8990
+ return result;
7441
8991
  }
7442
- function getFeeNumerator(currentPoint, activationPoint, numberOfPeriod, periodFrequency, feeSchedulerMode, cliffFeeNumerator, reductionFactor, dynamicFeeParams) {
7443
- if (Number(periodFrequency) == 0 || new BN5(currentPoint).lt(activationPoint)) {
7444
- return cliffFeeNumerator;
8992
+ function getDeltaAmountBUnsignedUnchecked(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding) {
8993
+ const deltaSqrtPrice = upperSqrtPrice.sub(lowerSqrtPrice);
8994
+ const prod = liquidity.mul(deltaSqrtPrice);
8995
+ const shift = SCALE_OFFSET * 2;
8996
+ if (rounding === 0 /* Up */) {
8997
+ const denominator = new BN11(1).ushln(shift);
8998
+ const result = prod.add(denominator.subn(1)).div(denominator);
8999
+ return result;
9000
+ } else {
9001
+ const result = prod.ushrn(shift);
9002
+ return result;
7445
9003
  }
7446
- const period = BN5.min(
7447
- new BN5(numberOfPeriod),
7448
- new BN5(currentPoint).sub(activationPoint).div(periodFrequency)
9004
+ }
9005
+ function getAmountAFromLiquidityDelta(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding) {
9006
+ const result = getDeltaAmountAUnsignedUnchecked(
9007
+ lowerSqrtPrice,
9008
+ upperSqrtPrice,
9009
+ liquidity,
9010
+ rounding
7449
9011
  );
7450
- let feeNumerator = getBaseFeeNumerator(
7451
- feeSchedulerMode,
7452
- cliffFeeNumerator,
7453
- period,
7454
- reductionFactor
9012
+ if (result.gt(U64_MAX)) {
9013
+ throw new Error("MathOverflow: result exceeds u64 max");
9014
+ }
9015
+ return result;
9016
+ }
9017
+ function getDeltaAmountAUnsignedUnchecked(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding) {
9018
+ const numerator1 = liquidity;
9019
+ const numerator2 = upperSqrtPrice.sub(lowerSqrtPrice);
9020
+ const denominator = lowerSqrtPrice.mul(upperSqrtPrice);
9021
+ if (denominator.lte(new BN11(0))) {
9022
+ throw new Error("Denominator must be greater than zero");
9023
+ }
9024
+ const result = mulDiv(numerator1, numerator2, denominator, rounding);
9025
+ return result;
9026
+ }
9027
+ function getLiquidityDeltaFromAmountA(amountA, lowerSqrtPrice, upperSqrtPrice) {
9028
+ const product = amountA.mul(lowerSqrtPrice).mul(upperSqrtPrice);
9029
+ const denominator = upperSqrtPrice.sub(lowerSqrtPrice);
9030
+ return product.div(denominator);
9031
+ }
9032
+ function getLiquidityDeltaFromAmountB(amountB, lowerSqrtPrice, upperSqrtPrice) {
9033
+ const denominator = upperSqrtPrice.sub(lowerSqrtPrice);
9034
+ const product = amountB.shln(128);
9035
+ return product.div(denominator);
9036
+ }
9037
+
9038
+ // src/math/quote.ts
9039
+ function getSwapResultFromExactInput(poolState, amountIn, feeMode, tradeDirection, currentPoint) {
9040
+ let actualProtocolFee = new BN12(0);
9041
+ let actualTradingFee = new BN12(0);
9042
+ let actualReferralFee = new BN12(0);
9043
+ let actualPartnerFee = new BN12(0);
9044
+ const maxFeeNumerator = getMaxFeeNumerator(poolState.version);
9045
+ const tradeFeeNumerator = getTotalTradingFeeFromIncludedFeeAmount(
9046
+ poolState.poolFees,
9047
+ currentPoint,
9048
+ poolState.activationPoint,
9049
+ amountIn,
9050
+ tradeDirection,
9051
+ maxFeeNumerator
7455
9052
  );
7456
- if (dynamicFeeParams) {
7457
- const { volatilityAccumulator, binStep, variableFeeControl } = dynamicFeeParams;
7458
- const dynamicFeeNumberator = getDynamicFeeNumerator(
7459
- volatilityAccumulator,
7460
- new BN5(binStep),
7461
- new BN5(variableFeeControl)
9053
+ let actualAmountIn;
9054
+ if (feeMode.feesOnInput) {
9055
+ const { amount, tradingFee, protocolFee, partnerFee, referralFee } = getFeeOnAmount(
9056
+ poolState.poolFees,
9057
+ amountIn,
9058
+ tradeFeeNumerator,
9059
+ feeMode.hasReferral,
9060
+ hasPartner(poolState.partner)
7462
9061
  );
7463
- feeNumerator = feeNumerator.add(dynamicFeeNumberator);
9062
+ actualProtocolFee = protocolFee;
9063
+ actualTradingFee = tradingFee;
9064
+ actualReferralFee = referralFee;
9065
+ actualPartnerFee = partnerFee;
9066
+ actualAmountIn = amount;
9067
+ } else {
9068
+ actualAmountIn = amountIn;
9069
+ }
9070
+ let swapAmountFromInput;
9071
+ if (tradeDirection === 0 /* AtoB */) {
9072
+ swapAmountFromInput = calculateAtoBFromAmountIn(poolState, actualAmountIn);
9073
+ } else {
9074
+ swapAmountFromInput = calculateBtoAFromAmountIn(poolState, actualAmountIn);
9075
+ }
9076
+ const { outputAmount, nextSqrtPrice, amountLeft } = swapAmountFromInput;
9077
+ let actualAmountOut;
9078
+ if (feeMode.feesOnInput) {
9079
+ actualAmountOut = outputAmount;
9080
+ } else {
9081
+ const { amount, tradingFee, protocolFee, partnerFee, referralFee } = getFeeOnAmount(
9082
+ poolState.poolFees,
9083
+ outputAmount,
9084
+ tradeFeeNumerator,
9085
+ feeMode.hasReferral,
9086
+ hasPartner(poolState.partner)
9087
+ );
9088
+ actualProtocolFee = protocolFee;
9089
+ actualTradingFee = tradingFee;
9090
+ actualReferralFee = referralFee;
9091
+ actualPartnerFee = partnerFee;
9092
+ actualAmountOut = amount;
7464
9093
  }
7465
- return feeNumerator.gt(new BN5(MAX_FEE_NUMERATOR)) ? new BN5(MAX_FEE_NUMERATOR) : feeNumerator;
7466
- }
7467
- function getFeeMode(collectFeeMode, btoA) {
7468
- const feeOnInput = btoA && collectFeeMode === 1 /* OnlyB */;
7469
- const feesOnTokenA = btoA && collectFeeMode === 0 /* BothToken */;
7470
9094
  return {
7471
- feeOnInput,
7472
- feesOnTokenA
9095
+ amountLeft,
9096
+ includedFeeInputAmount: amountIn,
9097
+ excludedFeeInputAmount: actualAmountIn,
9098
+ outputAmount: actualAmountOut,
9099
+ nextSqrtPrice,
9100
+ tradingFee: actualTradingFee,
9101
+ protocolFee: actualProtocolFee,
9102
+ partnerFee: actualPartnerFee,
9103
+ referralFee: actualReferralFee
7473
9104
  };
7474
9105
  }
7475
- function getTotalFeeOnAmount(amount, tradeFeeNumerator) {
7476
- return mulDiv(
7477
- amount,
7478
- tradeFeeNumerator,
7479
- new BN5(FEE_DENOMINATOR),
7480
- 0 /* Up */
7481
- );
7482
- }
7483
- function getSwapAmount(inAmount, sqrtPrice, liquidity, tradeFeeNumerator, aToB, collectFeeMode) {
7484
- let feeMode = getFeeMode(collectFeeMode, !aToB);
7485
- let actualInAmount = inAmount;
7486
- let totalFee = new BN5(0);
7487
- if (feeMode.feeOnInput) {
7488
- totalFee = getTotalFeeOnAmount(inAmount, tradeFeeNumerator);
7489
- actualInAmount = inAmount.sub(totalFee);
7490
- }
7491
- const nextSqrtPrice = getNextSqrtPrice(
7492
- actualInAmount,
7493
- sqrtPrice,
7494
- liquidity,
7495
- aToB
9106
+ function calculateAtoBFromAmountIn(poolState, amountIn) {
9107
+ const nextSqrtPrice = getNextSqrtPriceFromInput(
9108
+ poolState.sqrtPrice,
9109
+ poolState.liquidity,
9110
+ amountIn,
9111
+ true
7496
9112
  );
7497
- const outAmount = aToB ? getAmountBFromLiquidityDelta(
7498
- liquidity,
7499
- sqrtPrice,
9113
+ if (nextSqrtPrice.lt(poolState.sqrtMinPrice)) {
9114
+ throw new Error("Price range is violated");
9115
+ }
9116
+ const outputAmount = getAmountBFromLiquidityDelta(
9117
+ poolState.sqrtPrice,
7500
9118
  nextSqrtPrice,
9119
+ poolState.liquidity,
7501
9120
  1 /* Down */
7502
- ) : getAmountAFromLiquidityDelta(
7503
- liquidity,
7504
- sqrtPrice,
9121
+ );
9122
+ return {
9123
+ outputAmount,
9124
+ nextSqrtPrice,
9125
+ amountLeft: new BN12(0)
9126
+ };
9127
+ }
9128
+ function calculateBtoAFromAmountIn(poolState, amountIn) {
9129
+ const nextSqrtPrice = getNextSqrtPriceFromInput(
9130
+ poolState.sqrtPrice,
9131
+ poolState.liquidity,
9132
+ amountIn,
9133
+ false
9134
+ );
9135
+ if (nextSqrtPrice.gt(poolState.sqrtMaxPrice)) {
9136
+ throw new Error("Price range is violated");
9137
+ }
9138
+ const outputAmount = getAmountAFromLiquidityDelta(
9139
+ poolState.sqrtPrice,
7505
9140
  nextSqrtPrice,
9141
+ poolState.liquidity,
7506
9142
  1 /* Down */
7507
9143
  );
7508
- const amountOut = feeMode.feeOnInput ? outAmount : (totalFee = getTotalFeeOnAmount(outAmount, tradeFeeNumerator), outAmount.sub(totalFee));
7509
- return { amountOut, totalFee, nextSqrtPrice };
7510
- }
7511
- function bpsToFeeNumerator(bps) {
7512
- return new BN5(bps * FEE_DENOMINATOR).divn(BASIS_POINT_MAX);
7513
- }
7514
- function feeNumeratorToBps(feeNumerator) {
7515
- return feeNumerator.muln(BASIS_POINT_MAX).div(new BN5(FEE_DENOMINATOR)).toNumber();
9144
+ return {
9145
+ outputAmount,
9146
+ nextSqrtPrice,
9147
+ amountLeft: new BN12(0)
9148
+ };
7516
9149
  }
7517
- function getBaseFeeParams(maxBaseFeeBps, minBaseFeeBps, feeSchedulerMode, numberOfPeriod, totalDuration) {
7518
- if (maxBaseFeeBps == minBaseFeeBps) {
7519
- if (numberOfPeriod != 0 || totalDuration != 0) {
7520
- throw new Error("numberOfPeriod and totalDuration must both be zero");
7521
- }
7522
- return {
7523
- cliffFeeNumerator: bpsToFeeNumerator(maxBaseFeeBps),
7524
- numberOfPeriod: 0,
7525
- periodFrequency: new BN5(0),
7526
- reductionFactor: new BN5(0),
7527
- feeSchedulerMode: 0
7528
- };
7529
- }
7530
- if (numberOfPeriod <= 0) {
7531
- throw new Error("Total periods must be greater than zero");
7532
- }
7533
- if (maxBaseFeeBps > feeNumeratorToBps(new BN5(MAX_FEE_NUMERATOR))) {
7534
- throw new Error(
7535
- `maxBaseFeeBps (${maxBaseFeeBps} bps) exceeds maximum allowed value of ${feeNumeratorToBps(
7536
- new BN5(MAX_FEE_NUMERATOR)
7537
- )} bps`
9150
+ function getSwapResultFromPartialInput(poolState, amountIn, feeMode, tradeDirection, currentPoint) {
9151
+ let actualProtocolFee = new BN12(0);
9152
+ let actualTradingFee = new BN12(0);
9153
+ let actualReferralFee = new BN12(0);
9154
+ let actualPartnerFee = new BN12(0);
9155
+ const maxFeeNumerator = getMaxFeeNumerator(poolState.version);
9156
+ const tradeFeeNumerator = getTotalTradingFeeFromIncludedFeeAmount(
9157
+ poolState.poolFees,
9158
+ currentPoint,
9159
+ poolState.activationPoint,
9160
+ amountIn,
9161
+ tradeDirection,
9162
+ maxFeeNumerator
9163
+ );
9164
+ let actualAmountIn;
9165
+ if (feeMode.feesOnInput) {
9166
+ const { amount, tradingFee, protocolFee, partnerFee, referralFee } = getFeeOnAmount(
9167
+ poolState.poolFees,
9168
+ amountIn,
9169
+ tradeFeeNumerator,
9170
+ feeMode.hasReferral,
9171
+ hasPartner(poolState.partner)
7538
9172
  );
9173
+ actualProtocolFee = protocolFee;
9174
+ actualTradingFee = tradingFee;
9175
+ actualReferralFee = referralFee;
9176
+ actualPartnerFee = partnerFee;
9177
+ actualAmountIn = amount;
9178
+ } else {
9179
+ actualAmountIn = amountIn;
7539
9180
  }
7540
- if (minBaseFeeBps > maxBaseFeeBps) {
7541
- throw new Error(
7542
- "minBaseFee bps must be less than or equal to maxBaseFee bps"
9181
+ let swapAmountFromInput;
9182
+ if (tradeDirection === 0 /* AtoB */) {
9183
+ swapAmountFromInput = calculateAtoBFromPartialAmountIn(
9184
+ poolState,
9185
+ actualAmountIn
7543
9186
  );
7544
- }
7545
- if (numberOfPeriod == 0 || totalDuration == 0) {
7546
- throw new Error(
7547
- "numberOfPeriod and totalDuration must both greater than zero"
9187
+ } else {
9188
+ swapAmountFromInput = calculateBtoAFromPartialAmountIn(
9189
+ poolState,
9190
+ actualAmountIn
7548
9191
  );
7549
9192
  }
7550
- const maxBaseFeeNumerator = bpsToFeeNumerator(maxBaseFeeBps);
7551
- const minBaseFeeNumerator = bpsToFeeNumerator(minBaseFeeBps);
7552
- const periodFrequency = new BN5(totalDuration / numberOfPeriod);
7553
- let reductionFactor;
7554
- if (feeSchedulerMode == 0 /* Linear */) {
7555
- const totalReduction = maxBaseFeeNumerator.sub(minBaseFeeNumerator);
7556
- reductionFactor = totalReduction.divn(numberOfPeriod);
9193
+ let { amountLeft, outputAmount, nextSqrtPrice } = swapAmountFromInput;
9194
+ let includedFeeInputAmount;
9195
+ if (amountLeft.gt(new BN12(0))) {
9196
+ actualAmountIn = actualAmountIn.sub(amountLeft);
9197
+ if (feeMode.feesOnInput) {
9198
+ const tradeFeeNumerator2 = getTotalTradingFeeFromExcludedFeeAmount(
9199
+ poolState.poolFees,
9200
+ currentPoint,
9201
+ poolState.activationPoint,
9202
+ actualAmountIn,
9203
+ tradeDirection,
9204
+ maxFeeNumerator
9205
+ );
9206
+ const { includedFeeAmount, feeAmount } = getIncludedFeeAmount(
9207
+ tradeFeeNumerator2,
9208
+ actualAmountIn
9209
+ );
9210
+ const { tradingFee, protocolFee, referralFee, partnerFee } = splitFees(
9211
+ poolState.poolFees,
9212
+ feeAmount,
9213
+ feeMode.hasReferral,
9214
+ hasPartner(poolState.partner)
9215
+ );
9216
+ actualProtocolFee = protocolFee;
9217
+ actualTradingFee = tradingFee;
9218
+ actualReferralFee = referralFee;
9219
+ actualPartnerFee = partnerFee;
9220
+ includedFeeInputAmount = includedFeeAmount;
9221
+ } else {
9222
+ includedFeeInputAmount = actualAmountIn;
9223
+ }
7557
9224
  } else {
7558
- const ratio = minBaseFeeNumerator.toNumber() / maxBaseFeeNumerator.toNumber();
7559
- const decayBase = Math.pow(ratio, 1 / numberOfPeriod);
7560
- reductionFactor = new BN5(BASIS_POINT_MAX * (1 - decayBase));
9225
+ includedFeeInputAmount = amountIn;
7561
9226
  }
7562
- return {
7563
- cliffFeeNumerator: maxBaseFeeNumerator,
7564
- numberOfPeriod,
7565
- periodFrequency,
7566
- reductionFactor,
7567
- feeSchedulerMode
7568
- };
7569
- }
7570
- function getDynamicFeeParams(baseFeeBps, maxPriceChangeBps = MAX_PRICE_CHANGE_BPS_DEFAULT) {
7571
- if (maxPriceChangeBps > MAX_PRICE_CHANGE_BPS_DEFAULT) {
7572
- throw new Error(
7573
- `maxPriceChangeBps (${maxPriceChangeBps} bps) must be less than or equal to ${MAX_PRICE_CHANGE_BPS_DEFAULT}`
9227
+ let actualAmountOut;
9228
+ if (feeMode.feesOnInput) {
9229
+ actualAmountOut = outputAmount;
9230
+ } else {
9231
+ const { amount, tradingFee, protocolFee, partnerFee, referralFee } = getFeeOnAmount(
9232
+ poolState.poolFees,
9233
+ outputAmount,
9234
+ tradeFeeNumerator,
9235
+ feeMode.hasReferral,
9236
+ hasPartner(poolState.partner)
7574
9237
  );
9238
+ actualProtocolFee = protocolFee;
9239
+ actualTradingFee = tradingFee;
9240
+ actualReferralFee = referralFee;
9241
+ actualPartnerFee = partnerFee;
9242
+ actualAmountOut = amount;
7575
9243
  }
7576
- const priceRatio = maxPriceChangeBps / BASIS_POINT_MAX + 1;
7577
- const sqrtPriceRatioQ64 = new BN5(
7578
- Decimal2.sqrt(priceRatio.toString()).mul(Decimal2.pow(2, 64)).floor().toFixed()
7579
- );
7580
- const deltaBinId = sqrtPriceRatioQ64.sub(ONE).div(BIN_STEP_BPS_U128_DEFAULT).muln(2);
7581
- const maxVolatilityAccumulator = new BN5(deltaBinId.muln(BASIS_POINT_MAX));
7582
- const squareVfaBin = maxVolatilityAccumulator.mul(new BN5(BIN_STEP_BPS_DEFAULT)).pow(new BN5(2));
7583
- const baseFeeNumerator = new BN5(bpsToFeeNumerator(baseFeeBps));
7584
- const maxDynamicFeeNumerator = baseFeeNumerator.muln(20).divn(100);
7585
- const vFee = maxDynamicFeeNumerator.mul(new BN5(1e11)).sub(new BN5(99999999999));
7586
- const variableFeeControl = vFee.div(squareVfaBin);
7587
9244
  return {
7588
- binStep: BIN_STEP_BPS_DEFAULT,
7589
- binStepU128: BIN_STEP_BPS_U128_DEFAULT,
7590
- filterPeriod: DYNAMIC_FEE_FILTER_PERIOD_DEFAULT,
7591
- decayPeriod: DYNAMIC_FEE_DECAY_PERIOD_DEFAULT,
7592
- reductionFactor: DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT,
7593
- maxVolatilityAccumulator: maxVolatilityAccumulator.toNumber(),
7594
- variableFeeControl: variableFeeControl.toNumber()
9245
+ includedFeeInputAmount,
9246
+ excludedFeeInputAmount: actualAmountIn,
9247
+ amountLeft,
9248
+ outputAmount: actualAmountOut,
9249
+ nextSqrtPrice,
9250
+ tradingFee: actualTradingFee,
9251
+ protocolFee: actualProtocolFee,
9252
+ partnerFee: actualPartnerFee,
9253
+ referralFee: actualReferralFee
7595
9254
  };
7596
9255
  }
7597
- function getExcludedFeeAmount(tradeFeeNumerator, includedFeeAmount) {
7598
- const tradingFee = mulDiv(
7599
- includedFeeAmount,
7600
- tradeFeeNumerator,
7601
- new BN5(FEE_DENOMINATOR),
7602
- 0 /* Up */
7603
- );
7604
- const excludedFeeAmount = includedFeeAmount.sub(tradingFee);
7605
- return { excludedFeeAmount, tradingFee };
7606
- }
7607
- function getIncludedFeeAmount(tradeFeeNumerator, excludedFeeAmount) {
7608
- const denominator = new BN5(FEE_DENOMINATOR).sub(tradeFeeNumerator);
7609
- if (denominator.isZero() || denominator.isNeg()) {
7610
- throw new Error("Invalid fee numerator");
7611
- }
7612
- const includedFeeAmount = mulDiv(
7613
- excludedFeeAmount,
7614
- new BN5(FEE_DENOMINATOR),
7615
- denominator,
9256
+ function calculateAtoBFromPartialAmountIn(poolState, amountIn) {
9257
+ const maxAmountIn = getAmountAFromLiquidityDelta(
9258
+ poolState.sqrtMinPrice,
9259
+ poolState.sqrtPrice,
9260
+ poolState.liquidity,
7616
9261
  0 /* Up */
7617
9262
  );
7618
- const { excludedFeeAmount: inverseAmount } = getExcludedFeeAmount(
7619
- tradeFeeNumerator,
7620
- includedFeeAmount
7621
- );
7622
- if (inverseAmount.lt(excludedFeeAmount)) {
7623
- throw new Error("Inverse amount is less than excluded_fee_amount");
7624
- }
7625
- return includedFeeAmount;
7626
- }
7627
- function getInAmountFromAToB(pool, outAmount) {
7628
- const nextSqrtPrice = getNextSqrtPriceFromOutput(
7629
- pool.sqrtPrice,
7630
- pool.liquidity,
7631
- outAmount,
7632
- true
7633
- );
7634
- if (nextSqrtPrice.lt(pool.sqrtMinPrice)) {
7635
- throw new Error("Price range is violated");
9263
+ let consumedInAmount;
9264
+ let nextSqrtPrice;
9265
+ if (amountIn.gte(maxAmountIn)) {
9266
+ consumedInAmount = maxAmountIn;
9267
+ nextSqrtPrice = poolState.sqrtMinPrice;
9268
+ } else {
9269
+ nextSqrtPrice = getNextSqrtPriceFromInput(
9270
+ poolState.sqrtPrice,
9271
+ poolState.liquidity,
9272
+ amountIn,
9273
+ true
9274
+ );
9275
+ consumedInAmount = amountIn;
7636
9276
  }
7637
- const outputAmount = getAmountAFromLiquidityDelta(
7638
- pool.liquidity,
9277
+ const outputAmount = getAmountBFromLiquidityDelta(
7639
9278
  nextSqrtPrice,
7640
- pool.sqrtPrice,
7641
- 0 /* Up */
9279
+ poolState.sqrtPrice,
9280
+ poolState.liquidity,
9281
+ 1 /* Down */
7642
9282
  );
9283
+ const amountLeft = amountIn.sub(consumedInAmount);
7643
9284
  return {
7644
9285
  outputAmount,
7645
- nextSqrtPrice
9286
+ nextSqrtPrice,
9287
+ amountLeft
7646
9288
  };
7647
9289
  }
7648
- function getInAmountFromBToA(pool, outAmount) {
7649
- const nextSqrtPrice = getNextSqrtPriceFromOutput(
7650
- pool.sqrtPrice,
7651
- pool.liquidity,
7652
- outAmount,
7653
- false
9290
+ function calculateBtoAFromPartialAmountIn(poolState, amountIn) {
9291
+ const maxAmountIn = getAmountBFromLiquidityDelta(
9292
+ poolState.sqrtPrice,
9293
+ poolState.sqrtMaxPrice,
9294
+ poolState.liquidity,
9295
+ 0 /* Up */
7654
9296
  );
7655
- if (nextSqrtPrice.gt(pool.sqrtMaxPrice)) {
7656
- throw new Error("Price range is violated");
9297
+ let consumedInAmount;
9298
+ let nextSqrtPrice;
9299
+ if (amountIn.gte(maxAmountIn)) {
9300
+ consumedInAmount = maxAmountIn;
9301
+ nextSqrtPrice = poolState.sqrtMaxPrice;
9302
+ } else {
9303
+ nextSqrtPrice = getNextSqrtPriceFromInput(
9304
+ poolState.sqrtPrice,
9305
+ poolState.liquidity,
9306
+ amountIn,
9307
+ false
9308
+ );
9309
+ consumedInAmount = amountIn;
7657
9310
  }
7658
- const outputAmount = getAmountBFromLiquidityDelta(
7659
- pool.liquidity,
7660
- pool.sqrtPrice,
9311
+ const outputAmount = getAmountAFromLiquidityDelta(
9312
+ poolState.sqrtPrice,
7661
9313
  nextSqrtPrice,
7662
- 0 /* Up */
9314
+ poolState.liquidity,
9315
+ 1 /* Down */
7663
9316
  );
9317
+ const amountLeft = amountIn.sub(consumedInAmount);
7664
9318
  return {
7665
9319
  outputAmount,
7666
- nextSqrtPrice
9320
+ nextSqrtPrice,
9321
+ amountLeft
7667
9322
  };
7668
9323
  }
7669
- function getSwapResultFromOutAmount(pool, outAmount, feeMode, tradeDirection, currentPoint) {
7670
- let actualProtocolFee = new BN5(0);
7671
- let actualLpFee = new BN5(0);
7672
- let actualPartnerFee = new BN5(0);
7673
- let actualReferralFee = new BN5(0);
7674
- const tradeFeeNumerator = getFeeNumerator(
7675
- currentPoint,
7676
- pool.activationPoint,
7677
- pool.poolFees.baseFee.numberOfPeriod,
7678
- pool.poolFees.baseFee.periodFrequency,
7679
- pool.poolFees.baseFee.feeSchedulerMode,
7680
- pool.poolFees.baseFee.cliffFeeNumerator,
7681
- pool.poolFees.baseFee.reductionFactor,
7682
- pool.poolFees.dynamicFee.initialized === 1 ? {
7683
- volatilityAccumulator: pool.poolFees.dynamicFee.volatilityAccumulator,
7684
- binStep: pool.poolFees.dynamicFee.binStep,
7685
- variableFeeControl: pool.poolFees.dynamicFee.variableFeeControl
7686
- } : void 0
7687
- );
7688
- let includedFeeOutAmount;
7689
- if (feeMode.feeOnInput) {
7690
- includedFeeOutAmount = outAmount;
9324
+ function getSwapResultFromExactOutput(poolState, amountOut, feeMode, tradeDirection, currentPoint) {
9325
+ let actualProtocolFee = new BN12(0);
9326
+ let actualTradingFee = new BN12(0);
9327
+ let actualReferralFee = new BN12(0);
9328
+ let actualPartnerFee = new BN12(0);
9329
+ const maxFeeNumerator = getMaxFeeNumerator(poolState.version);
9330
+ let includedFeeAmountOut;
9331
+ if (feeMode.feesOnInput) {
9332
+ includedFeeAmountOut = amountOut;
7691
9333
  } else {
7692
- includedFeeOutAmount = getIncludedFeeAmount(tradeFeeNumerator, outAmount);
7693
- const totalFee = getTotalFeeOnAmount(outAmount, tradeFeeNumerator);
7694
- actualProtocolFee = mulDiv(
7695
- totalFee,
7696
- new BN5(pool.poolFees.protocolFeePercent),
7697
- new BN5(100),
7698
- 1 /* Down */
7699
- );
7700
- if (feeMode.hasReferral) {
7701
- actualReferralFee = mulDiv(
7702
- actualProtocolFee,
7703
- new BN5(pool.poolFees.referralFeePercent),
7704
- new BN5(100),
7705
- 1 /* Down */
7706
- );
7707
- }
7708
- const protocolFeeAfterReferral = actualProtocolFee.sub(actualReferralFee);
7709
- actualPartnerFee = mulDiv(
7710
- protocolFeeAfterReferral,
7711
- new BN5(pool.poolFees.partnerFeePercent),
7712
- new BN5(100),
7713
- 1 /* Down */
9334
+ const tradeFeeNumerator = getTotalTradingFeeFromExcludedFeeAmount(
9335
+ poolState.poolFees,
9336
+ currentPoint,
9337
+ poolState.activationPoint,
9338
+ amountOut,
9339
+ tradeDirection,
9340
+ maxFeeNumerator
7714
9341
  );
7715
- actualLpFee = totalFee.sub(actualProtocolFee).sub(actualPartnerFee);
7716
- }
7717
- const { outputAmount: excludedFeeInAmount, nextSqrtPrice } = tradeDirection === 0 /* AtoB */ ? getInAmountFromAToB(pool, includedFeeOutAmount) : getInAmountFromBToA(pool, includedFeeOutAmount);
7718
- let includedFeeInAmount;
7719
- if (feeMode.feeOnInput) {
7720
- includedFeeInAmount = getIncludedFeeAmount(
9342
+ const { includedFeeAmount, feeAmount } = getIncludedFeeAmount(
7721
9343
  tradeFeeNumerator,
7722
- excludedFeeInAmount
9344
+ amountOut
7723
9345
  );
7724
- const totalFee = getTotalFeeOnAmount(
7725
- includedFeeInAmount,
7726
- tradeFeeNumerator
9346
+ const split = splitFees(
9347
+ poolState.poolFees,
9348
+ feeAmount,
9349
+ feeMode.hasReferral,
9350
+ hasPartner(poolState.partner)
7727
9351
  );
7728
- actualProtocolFee = mulDiv(
7729
- totalFee,
7730
- new BN5(pool.poolFees.protocolFeePercent),
7731
- new BN5(100),
7732
- 1 /* Down */
9352
+ actualTradingFee = split.tradingFee;
9353
+ actualProtocolFee = split.protocolFee;
9354
+ actualReferralFee = split.referralFee;
9355
+ actualPartnerFee = split.partnerFee;
9356
+ includedFeeAmountOut = includedFeeAmount;
9357
+ }
9358
+ let swapAmountFromOutput;
9359
+ if (tradeDirection === 0 /* AtoB */) {
9360
+ swapAmountFromOutput = calculateAtoBFromAmountOut(
9361
+ poolState,
9362
+ includedFeeAmountOut
7733
9363
  );
7734
- if (feeMode.hasReferral) {
7735
- actualReferralFee = mulDiv(
7736
- actualProtocolFee,
7737
- new BN5(pool.poolFees.referralFeePercent),
7738
- new BN5(100),
7739
- 1 /* Down */
7740
- );
7741
- }
7742
- const protocolFeeAfterReferral = actualProtocolFee.sub(actualReferralFee);
7743
- actualPartnerFee = mulDiv(
7744
- protocolFeeAfterReferral,
7745
- new BN5(pool.poolFees.partnerFeePercent),
7746
- new BN5(100),
7747
- 1 /* Down */
9364
+ } else {
9365
+ swapAmountFromOutput = calculateBtoAFromAmountOut(
9366
+ poolState,
9367
+ includedFeeAmountOut
9368
+ );
9369
+ }
9370
+ const { inputAmount, nextSqrtPrice } = swapAmountFromOutput;
9371
+ let includedFeeInputAmount;
9372
+ if (feeMode.feesOnInput) {
9373
+ const tradeFeeNumerator = getTotalTradingFeeFromExcludedFeeAmount(
9374
+ poolState.poolFees,
9375
+ currentPoint,
9376
+ poolState.activationPoint,
9377
+ inputAmount,
9378
+ tradeDirection,
9379
+ maxFeeNumerator
7748
9380
  );
7749
- actualLpFee = totalFee.sub(actualProtocolFee).sub(actualPartnerFee);
9381
+ const { includedFeeAmount, feeAmount } = getIncludedFeeAmount(
9382
+ tradeFeeNumerator,
9383
+ inputAmount
9384
+ );
9385
+ const split = splitFees(
9386
+ poolState.poolFees,
9387
+ feeAmount,
9388
+ feeMode.hasReferral,
9389
+ hasPartner(poolState.partner)
9390
+ );
9391
+ actualTradingFee = split.tradingFee;
9392
+ actualProtocolFee = split.protocolFee;
9393
+ actualReferralFee = split.referralFee;
9394
+ actualPartnerFee = split.partnerFee;
9395
+ includedFeeInputAmount = includedFeeAmount;
7750
9396
  } else {
7751
- includedFeeInAmount = excludedFeeInAmount;
9397
+ includedFeeInputAmount = inputAmount;
9398
+ }
9399
+ return {
9400
+ amountLeft: new BN12(0),
9401
+ includedFeeInputAmount,
9402
+ excludedFeeInputAmount: inputAmount,
9403
+ outputAmount: amountOut,
9404
+ nextSqrtPrice,
9405
+ tradingFee: actualTradingFee,
9406
+ protocolFee: actualProtocolFee,
9407
+ partnerFee: actualPartnerFee,
9408
+ referralFee: actualReferralFee
9409
+ };
9410
+ }
9411
+ function calculateAtoBFromAmountOut(poolState, amountOut) {
9412
+ const nextSqrtPrice = getNextSqrtPriceFromOutput(
9413
+ poolState.sqrtPrice,
9414
+ poolState.liquidity,
9415
+ amountOut,
9416
+ true
9417
+ );
9418
+ if (nextSqrtPrice.lt(poolState.sqrtMinPrice)) {
9419
+ throw new Error("Price Range Violation");
7752
9420
  }
9421
+ const inputAmount = getAmountAFromLiquidityDelta(
9422
+ nextSqrtPrice,
9423
+ poolState.sqrtPrice,
9424
+ poolState.liquidity,
9425
+ 0 /* Up */
9426
+ );
7753
9427
  return {
7754
- swapResult: {
7755
- outputAmount: outAmount,
7756
- nextSqrtPrice,
7757
- lpFee: actualLpFee,
7758
- protocolFee: actualProtocolFee,
7759
- referralFee: actualReferralFee,
7760
- partnerFee: actualPartnerFee
7761
- },
7762
- inputAmount: includedFeeInAmount
9428
+ inputAmount,
9429
+ nextSqrtPrice
7763
9430
  };
7764
9431
  }
7765
-
7766
- // src/helpers/computeUnits.ts
7767
- import {
7768
- ComputeBudgetProgram,
7769
- PublicKey as PublicKey4,
7770
- TransactionMessage,
7771
- VersionedTransaction
7772
- } from "@solana/web3.js";
7773
- var getSimulationComputeUnits = (connection, instructions, payer, lookupTables, commitment = "confirmed") => __async(void 0, null, function* () {
7774
- var _a, _b, _c;
7775
- const testInstructions = [
7776
- // Set an arbitrarily high number in simulation
7777
- // so we can be sure the transaction will succeed
7778
- // and get the real compute units used
7779
- ComputeBudgetProgram.setComputeUnitLimit({ units: 14e5 }),
7780
- ...instructions
7781
- ];
7782
- const testTransaction = new VersionedTransaction(
7783
- new TransactionMessage({
7784
- instructions: testInstructions,
7785
- payerKey: payer,
7786
- // RecentBlockhash can by any public key during simulation
7787
- // since 'replaceRecentBlockhash' is set to 'true' below
7788
- recentBlockhash: PublicKey4.default.toString()
7789
- }).compileToV0Message(lookupTables)
9432
+ function calculateBtoAFromAmountOut(poolState, amountOut) {
9433
+ const nextSqrtPrice = getNextSqrtPriceFromOutput(
9434
+ poolState.sqrtPrice,
9435
+ poolState.liquidity,
9436
+ amountOut,
9437
+ false
7790
9438
  );
7791
- const rpcResponse = yield connection.simulateTransaction(testTransaction, {
7792
- replaceRecentBlockhash: true,
7793
- sigVerify: false,
7794
- commitment
7795
- });
7796
- if ((_a = rpcResponse == null ? void 0 : rpcResponse.value) == null ? void 0 : _a.err) {
7797
- const logs = ((_b = rpcResponse.value.logs) == null ? void 0 : _b.join("\n \u2022 ")) || "No logs available";
7798
- throw new Error(
7799
- `Transaction simulation failed:
7800
- \u2022${logs}` + JSON.stringify((_c = rpcResponse == null ? void 0 : rpcResponse.value) == null ? void 0 : _c.err)
7801
- );
7802
- }
7803
- return rpcResponse.value.unitsConsumed || null;
7804
- });
7805
- var getEstimatedComputeUnitUsageWithBuffer = (connection, instructions, feePayer, buffer) => __async(void 0, null, function* () {
7806
- if (!buffer) {
7807
- buffer = 0.1;
9439
+ if (nextSqrtPrice.gt(poolState.sqrtMaxPrice)) {
9440
+ throw new Error("Price Range Violation");
7808
9441
  }
7809
- buffer = Math.max(0, buffer);
7810
- buffer = Math.min(1, buffer);
7811
- const estimatedComputeUnitUsage = yield getSimulationComputeUnits(
7812
- connection,
7813
- instructions,
7814
- feePayer,
7815
- []
9442
+ const inputAmount = getAmountBFromLiquidityDelta(
9443
+ poolState.sqrtPrice,
9444
+ nextSqrtPrice,
9445
+ poolState.liquidity,
9446
+ 0 /* Up */
7816
9447
  );
7817
- if (!estimatedComputeUnitUsage) {
7818
- return 0;
7819
- }
7820
- let extraComputeUnitBuffer = estimatedComputeUnitUsage * buffer;
7821
- if (extraComputeUnitBuffer > MAX_CU_BUFFER) {
7822
- extraComputeUnitBuffer = MAX_CU_BUFFER;
7823
- } else if (extraComputeUnitBuffer < MIN_CU_BUFFER) {
7824
- extraComputeUnitBuffer = MIN_CU_BUFFER;
9448
+ return {
9449
+ inputAmount,
9450
+ nextSqrtPrice
9451
+ };
9452
+ }
9453
+ function swapQuoteExactInput(pool, currentPoint, amountIn, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo, outputTokenInfo) {
9454
+ if (amountIn.lte(new BN12(0))) {
9455
+ throw new Error("Amount in must be greater than 0");
9456
+ }
9457
+ if (!isSwapEnabled(pool, currentPoint)) {
9458
+ throw new Error("Swap is disabled");
9459
+ }
9460
+ const tradeDirection = aToB ? 0 /* AtoB */ : 1 /* BtoA */;
9461
+ const feeMode = getFeeMode(pool.collectFeeMode, tradeDirection, hasReferral);
9462
+ let actualAmountIn = amountIn;
9463
+ if (inputTokenInfo) {
9464
+ actualAmountIn = calculateTransferFeeExcludedAmount(
9465
+ amountIn,
9466
+ inputTokenInfo.mint,
9467
+ inputTokenInfo.currentEpoch
9468
+ ).amount;
9469
+ }
9470
+ const swapResult = getSwapResultFromExactInput(
9471
+ pool,
9472
+ actualAmountIn,
9473
+ feeMode,
9474
+ tradeDirection,
9475
+ currentPoint
9476
+ );
9477
+ let actualAmountOut = swapResult.outputAmount;
9478
+ if (outputTokenInfo) {
9479
+ actualAmountOut = calculateTransferFeeExcludedAmount(
9480
+ swapResult.outputAmount,
9481
+ outputTokenInfo.mint,
9482
+ outputTokenInfo.currentEpoch
9483
+ ).amount;
7825
9484
  }
7826
- return estimatedComputeUnitUsage + extraComputeUnitBuffer;
7827
- });
7828
- var getEstimatedComputeUnitIxWithBuffer = (connection, instructions, feePayer, buffer) => __async(void 0, null, function* () {
7829
- const units = yield getEstimatedComputeUnitUsageWithBuffer(
7830
- connection,
7831
- instructions,
7832
- feePayer,
7833
- buffer
7834
- ).catch((error) => {
7835
- console.error("Error::getEstimatedComputeUnitUsageWithBuffer", error);
7836
- return 14e5;
9485
+ const minimumAmountOut = getAmountWithSlippage(
9486
+ actualAmountOut,
9487
+ slippage,
9488
+ 0 /* ExactIn */
9489
+ );
9490
+ const priceImpact = getPriceImpact(
9491
+ actualAmountIn,
9492
+ actualAmountOut,
9493
+ pool.sqrtPrice,
9494
+ aToB,
9495
+ tokenADecimal,
9496
+ tokenBDecimal
9497
+ );
9498
+ return __spreadProps(__spreadValues({}, swapResult), {
9499
+ minimumAmountOut,
9500
+ priceImpact
7837
9501
  });
7838
- return ComputeBudgetProgram.setComputeUnitLimit({ units });
7839
- });
7840
-
7841
- // src/helpers/utils.ts
7842
- import { BN as BN6 } from "@coral-xyz/anchor";
7843
- import Decimal3 from "decimal.js";
7844
- var getMaxAmountWithSlippage = (amount, rate) => {
7845
- const slippage = (100 + rate) / 100 * BASIS_POINT_MAX;
7846
- return amount.mul(new BN6(slippage)).div(new BN6(BASIS_POINT_MAX));
7847
- };
7848
- var getMinAmountWithSlippage = (amount, rate) => {
7849
- const slippage = (100 - rate) / 100 * BASIS_POINT_MAX;
7850
- return amount.mul(new BN6(slippage)).div(new BN6(BASIS_POINT_MAX));
7851
- };
7852
- var getPriceImpact = (amountIn, amountOut, currentSqrtPrice, aToB, tokenADecimal, tokenBDecimal) => {
7853
- if (amountIn.eq(new BN6(0))) {
7854
- return new Decimal3(0);
7855
- }
7856
- if (amountOut.eq(new BN6(0))) {
9502
+ }
9503
+ function swapQuoteExactOutput(pool, currentPoint, amountOut, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo, outputTokenInfo) {
9504
+ if (amountOut.lte(new BN12(0))) {
7857
9505
  throw new Error("Amount out must be greater than 0");
7858
9506
  }
7859
- const spotPrice = getPriceFromSqrtPrice(
7860
- currentSqrtPrice,
9507
+ if (!isSwapEnabled(pool, currentPoint)) {
9508
+ throw new Error("Swap is disabled");
9509
+ }
9510
+ const tradeDirection = aToB ? 0 /* AtoB */ : 1 /* BtoA */;
9511
+ const feeMode = getFeeMode(pool.collectFeeMode, tradeDirection, hasReferral);
9512
+ let actualAmountOut = amountOut;
9513
+ if (outputTokenInfo) {
9514
+ actualAmountOut = calculateTransferFeeIncludedAmount(
9515
+ amountOut,
9516
+ outputTokenInfo.mint,
9517
+ outputTokenInfo.currentEpoch
9518
+ ).amount;
9519
+ }
9520
+ const swapResult = getSwapResultFromExactOutput(
9521
+ pool,
9522
+ actualAmountOut,
9523
+ feeMode,
9524
+ tradeDirection,
9525
+ currentPoint
9526
+ );
9527
+ let actualAmountIn = swapResult.includedFeeInputAmount;
9528
+ if (inputTokenInfo) {
9529
+ actualAmountIn = calculateTransferFeeIncludedAmount(
9530
+ swapResult.includedFeeInputAmount,
9531
+ inputTokenInfo.mint,
9532
+ inputTokenInfo.currentEpoch
9533
+ ).amount;
9534
+ }
9535
+ const maximumAmountIn = getAmountWithSlippage(
9536
+ actualAmountIn,
9537
+ slippage,
9538
+ 2 /* ExactOut */
9539
+ );
9540
+ const priceImpact = getPriceImpact(
9541
+ actualAmountIn,
9542
+ actualAmountOut,
9543
+ pool.sqrtPrice,
9544
+ aToB,
7861
9545
  tokenADecimal,
7862
9546
  tokenBDecimal
7863
9547
  );
7864
- const executionPrice = new Decimal3(amountIn.toString()).div(new Decimal3(amountOut.toString())).mul(
7865
- Decimal3.pow(
7866
- 10,
7867
- aToB ? tokenBDecimal - tokenADecimal : tokenADecimal - tokenBDecimal
7868
- )
9548
+ return __spreadProps(__spreadValues({}, swapResult), {
9549
+ maximumAmountIn,
9550
+ priceImpact
9551
+ });
9552
+ }
9553
+ function swapQuotePartialInput(pool, currentPoint, amountIn, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo, outputTokenInfo) {
9554
+ if (amountIn.lte(new BN12(0))) {
9555
+ throw new Error("Amount in must be greater than 0");
9556
+ }
9557
+ if (!isSwapEnabled(pool, currentPoint)) {
9558
+ throw new Error("Swap is disabled");
9559
+ }
9560
+ const tradeDirection = aToB ? 0 /* AtoB */ : 1 /* BtoA */;
9561
+ const feeMode = getFeeMode(pool.collectFeeMode, tradeDirection, hasReferral);
9562
+ let actualAmountIn = amountIn;
9563
+ if (inputTokenInfo) {
9564
+ actualAmountIn = calculateTransferFeeExcludedAmount(
9565
+ amountIn,
9566
+ inputTokenInfo.mint,
9567
+ inputTokenInfo.currentEpoch
9568
+ ).amount;
9569
+ }
9570
+ const swapResult = getSwapResultFromPartialInput(
9571
+ pool,
9572
+ actualAmountIn,
9573
+ feeMode,
9574
+ tradeDirection,
9575
+ currentPoint
7869
9576
  );
7870
- let priceImpact;
7871
- let actualExecutionPrice;
7872
- if (aToB) {
7873
- actualExecutionPrice = new Decimal3(1).div(executionPrice);
7874
- } else {
7875
- actualExecutionPrice = executionPrice;
9577
+ let actualAmountOut = swapResult.outputAmount;
9578
+ if (outputTokenInfo) {
9579
+ actualAmountOut = calculateTransferFeeExcludedAmount(
9580
+ swapResult.outputAmount,
9581
+ outputTokenInfo.mint,
9582
+ outputTokenInfo.currentEpoch
9583
+ ).amount;
7876
9584
  }
7877
- priceImpact = actualExecutionPrice.sub(spotPrice).abs().div(spotPrice).mul(100);
7878
- return priceImpact;
7879
- };
7880
- var getPriceChange = (nextSqrtPrice, currentSqrtPrice) => {
7881
- const diff = nextSqrtPrice.pow(new BN6(2)).sub(currentSqrtPrice.pow(new BN6(2))).abs();
7882
- return new Decimal3(diff.toString()).div(new Decimal3(currentSqrtPrice.pow(new BN6(2)).toString())).mul(100).toNumber();
7883
- };
7884
- var getPriceFromSqrtPrice = (sqrtPrice, tokenADecimal, tokenBDecimal) => {
7885
- const decimalSqrtPrice = new Decimal3(sqrtPrice.toString());
7886
- const price = decimalSqrtPrice.mul(decimalSqrtPrice).mul(new Decimal3(__pow(10, tokenADecimal - tokenBDecimal))).div(Decimal3.pow(2, 128));
7887
- return price;
7888
- };
7889
- var getSqrtPriceFromPrice = (price, tokenADecimal, tokenBDecimal) => {
7890
- const decimalPrice = new Decimal3(price);
7891
- const adjustedByDecimals = decimalPrice.div(
7892
- new Decimal3(__pow(10, tokenADecimal - tokenBDecimal))
9585
+ const minimumAmountOut = getAmountWithSlippage(
9586
+ actualAmountOut,
9587
+ slippage,
9588
+ 1 /* PartialFill */
7893
9589
  );
7894
- const sqrtValue = Decimal3.sqrt(adjustedByDecimals);
7895
- const sqrtValueQ64 = sqrtValue.mul(Decimal3.pow(2, 64));
7896
- return new BN6(sqrtValueQ64.floor().toFixed());
7897
- };
7898
- var getUnClaimReward = (poolState, positionState) => {
7899
- const totalPositionLiquidity = positionState.unlockedLiquidity.add(positionState.vestedLiquidity).add(positionState.permanentLockedLiquidity);
7900
- const feeAPerTokenStored = new BN6(
7901
- Buffer.from(poolState.feeAPerLiquidity).reverse()
7902
- ).sub(new BN6(Buffer.from(positionState.feeAPerTokenCheckpoint).reverse()));
7903
- const feeBPerTokenStored = new BN6(
7904
- Buffer.from(poolState.feeBPerLiquidity).reverse()
7905
- ).sub(new BN6(Buffer.from(positionState.feeBPerTokenCheckpoint).reverse()));
7906
- const feeA = totalPositionLiquidity.mul(feeAPerTokenStored).shrn(LIQUIDITY_SCALE);
7907
- const feeB = totalPositionLiquidity.mul(feeBPerTokenStored).shrn(LIQUIDITY_SCALE);
7908
- return {
7909
- feeTokenA: positionState.feeAPending.add(feeA),
7910
- feeTokenB: positionState.feeBPending.add(feeB),
7911
- rewards: positionState.rewardInfos.length > 0 ? positionState.rewardInfos.map((item) => item.rewardPendings) : []
7912
- };
7913
- };
7914
-
7915
- // src/helpers/accountFilters.ts
7916
- var positionByPoolFilter = (pool) => {
7917
- return {
7918
- memcmp: {
7919
- bytes: pool.toBase58(),
7920
- offset: 8
7921
- }
7922
- };
7923
- };
7924
- var vestingByPositionFilter = (position) => {
7925
- return {
7926
- memcmp: {
7927
- bytes: position.toBase58(),
7928
- offset: 8
7929
- }
7930
- };
7931
- };
9590
+ const priceImpact = getPriceImpact(
9591
+ actualAmountIn,
9592
+ actualAmountOut,
9593
+ pool.sqrtPrice,
9594
+ aToB,
9595
+ tokenADecimal,
9596
+ tokenBDecimal
9597
+ );
9598
+ return __spreadProps(__spreadValues({}, swapResult), {
9599
+ minimumAmountOut,
9600
+ priceImpact
9601
+ });
9602
+ }
7932
9603
 
7933
- // src/helpers/priceMath.ts
7934
- import { BN as BN7 } from "@coral-xyz/anchor";
7935
- import Decimal4 from "decimal.js";
9604
+ // src/math/priceMath.ts
9605
+ import { BN as BN13 } from "@coral-xyz/anchor";
9606
+ import Decimal3 from "decimal.js";
7936
9607
  function calculateInitSqrtPrice(tokenAAmount, tokenBAmount, minSqrtPrice, maxSqrtPrice) {
7937
9608
  if (tokenAAmount.isZero() || tokenBAmount.isZero()) {
7938
9609
  throw new Error("Amount cannot be zero");
7939
9610
  }
7940
- const amountADecimal = new Decimal4(tokenAAmount.toString());
7941
- const amountBDecimal = new Decimal4(tokenBAmount.toString());
7942
- const minSqrtPriceDecimal = new Decimal4(minSqrtPrice.toString()).div(
7943
- Decimal4.pow(2, 64)
9611
+ const amountADecimal = new Decimal3(tokenAAmount.toString());
9612
+ const amountBDecimal = new Decimal3(tokenBAmount.toString());
9613
+ const minSqrtPriceDecimal = new Decimal3(minSqrtPrice.toString()).div(
9614
+ Decimal3.pow(2, 64)
7944
9615
  );
7945
- const maxSqrtPriceDecimal = new Decimal4(maxSqrtPrice.toString()).div(
7946
- Decimal4.pow(2, 64)
9616
+ const maxSqrtPriceDecimal = new Decimal3(maxSqrtPrice.toString()).div(
9617
+ Decimal3.pow(2, 64)
7947
9618
  );
7948
- const x = new Decimal4(1).div(maxSqrtPriceDecimal);
9619
+ const x = new Decimal3(1).div(maxSqrtPriceDecimal);
7949
9620
  const y = amountBDecimal.div(amountADecimal);
7950
9621
  const xy = x.mul(y);
7951
9622
  const paMinusXY = minSqrtPriceDecimal.sub(xy);
7952
9623
  const xyMinusPa = xy.sub(minSqrtPriceDecimal);
7953
- const fourY = new Decimal4(4).mul(y);
9624
+ const fourY = new Decimal3(4).mul(y);
7954
9625
  const discriminant = xyMinusPa.mul(xyMinusPa).add(fourY);
7955
9626
  const sqrtDiscriminant = discriminant.sqrt();
7956
- const result = paMinusXY.add(sqrtDiscriminant).div(new Decimal4(2)).mul(Decimal4.pow(2, 64));
7957
- return new BN7(result.floor().toFixed());
9627
+ const result = paMinusXY.add(sqrtDiscriminant).div(new Decimal3(2)).mul(Decimal3.pow(2, 64));
9628
+ return new BN13(result.floor().toFixed());
7958
9629
  }
7959
9630
 
7960
- // src/helpers/token2022.ts
7961
- import { BN as BN8 } from "@coral-xyz/anchor";
7962
- import {
7963
- calculateFee,
7964
- getEpochFee,
7965
- getTransferFeeConfig,
7966
- MAX_FEE_BASIS_POINTS
7967
- } from "@solana/spl-token";
7968
- function calculatePreFeeAmount(transferFee, postFeeAmount) {
7969
- if (postFeeAmount.isZero()) {
7970
- return new BN8(0);
9631
+ // src/helpers/validation.ts
9632
+ function validateFeeScheduler(numberOfPeriod, periodFrequency, reductionFactor, cliffFeeNumerator, baseFeeMode, poolVersion) {
9633
+ if (!periodFrequency.eq(new BN14(0)) || numberOfPeriod !== 0 || !reductionFactor.eq(new BN14(0))) {
9634
+ if (numberOfPeriod === 0 || periodFrequency.eq(new BN14(0)) || reductionFactor.eq(new BN14(0))) {
9635
+ return false;
9636
+ }
7971
9637
  }
7972
- if (transferFee.transferFeeBasisPoints === 0) {
7973
- return postFeeAmount;
9638
+ const minFeeNumerator = getMinBaseFeeNumerator(
9639
+ cliffFeeNumerator,
9640
+ numberOfPeriod,
9641
+ periodFrequency,
9642
+ reductionFactor,
9643
+ baseFeeMode
9644
+ );
9645
+ const maxFeeNumerator = getMaxBaseFeeNumerator(cliffFeeNumerator);
9646
+ validateFeeFraction(minFeeNumerator, new BN14(FEE_DENOMINATOR));
9647
+ validateFeeFraction(maxFeeNumerator, new BN14(FEE_DENOMINATOR));
9648
+ if (minFeeNumerator.lt(new BN14(MIN_FEE_NUMERATOR)) || maxFeeNumerator.gt(getMaxFeeNumerator(poolVersion))) {
9649
+ throw new Error("PoolError::ExceedMaxFeeBps");
7974
9650
  }
7975
- const maximumFee = new BN8(transferFee.maximumFee.toString());
7976
- if (transferFee.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS) {
7977
- return postFeeAmount.add(maximumFee);
9651
+ return true;
9652
+ }
9653
+ function validateFeeRateLimiter(cliffFeeNumerator, feeIncrementBps, maxFeeBps, maxLimiterDuration, referenceAmount, collectFeeMode, activationType, poolVersion) {
9654
+ if (collectFeeMode !== 1 /* OnlyB */) {
9655
+ return false;
7978
9656
  }
7979
- const ONE_IN_BASIS_POINTS = new BN8(MAX_FEE_BASIS_POINTS);
7980
- const numerator = postFeeAmount.mul(ONE_IN_BASIS_POINTS);
7981
- const denominator = ONE_IN_BASIS_POINTS.sub(
7982
- new BN8(transferFee.transferFeeBasisPoints)
9657
+ const maxFeeNumeratorFromBps = toNumerator(
9658
+ new BN14(maxFeeBps),
9659
+ new BN14(FEE_DENOMINATOR)
7983
9660
  );
7984
- const rawPreFeeAmount = numerator.add(denominator).sub(new BN8(1)).div(denominator);
7985
- if (rawPreFeeAmount.sub(postFeeAmount).gte(maximumFee)) {
7986
- return postFeeAmount.add(maximumFee);
9661
+ if (cliffFeeNumerator.lt(new BN14(MIN_FEE_NUMERATOR)) || cliffFeeNumerator.gt(maxFeeNumeratorFromBps)) {
9662
+ return false;
9663
+ }
9664
+ if (isZeroRateLimiter(
9665
+ referenceAmount,
9666
+ maxLimiterDuration,
9667
+ maxFeeBps,
9668
+ feeIncrementBps
9669
+ )) {
9670
+ return true;
9671
+ }
9672
+ if (isNonZeroRateLimiter(
9673
+ referenceAmount,
9674
+ maxLimiterDuration,
9675
+ maxFeeBps,
9676
+ feeIncrementBps
9677
+ )) {
9678
+ return false;
9679
+ }
9680
+ const maxLimiterDurationLimit = activationType === 0 /* Slot */ ? new BN14(MAX_RATE_LIMITER_DURATION_IN_SLOTS) : new BN14(MAX_RATE_LIMITER_DURATION_IN_SECONDS);
9681
+ if (new BN14(maxLimiterDuration).gt(maxLimiterDurationLimit)) {
9682
+ return false;
9683
+ }
9684
+ const feeIncrementNumerator = toNumerator(
9685
+ new BN14(feeIncrementBps),
9686
+ new BN14(FEE_DENOMINATOR)
9687
+ );
9688
+ if (feeIncrementNumerator.gte(new BN14(FEE_DENOMINATOR))) {
9689
+ return false;
7987
9690
  }
7988
- return rawPreFeeAmount;
9691
+ if (maxFeeBps > getMaxFeeBps(poolVersion)) {
9692
+ return false;
9693
+ }
9694
+ const minFeeNumerator = getFeeNumeratorFromIncludedFeeAmount(
9695
+ new BN14(0),
9696
+ cliffFeeNumerator,
9697
+ referenceAmount,
9698
+ maxFeeBps,
9699
+ feeIncrementBps
9700
+ );
9701
+ const maxFeeNumeratorFromAmount = getFeeNumeratorFromIncludedFeeAmount(
9702
+ new BN14(Number.MAX_SAFE_INTEGER),
9703
+ cliffFeeNumerator,
9704
+ referenceAmount,
9705
+ maxFeeBps,
9706
+ feeIncrementBps
9707
+ );
9708
+ if (minFeeNumerator.lt(new BN14(MIN_FEE_NUMERATOR)) || maxFeeNumeratorFromAmount.gt(getMaxFeeNumerator(poolVersion))) {
9709
+ return false;
9710
+ }
9711
+ return true;
7989
9712
  }
7990
- function calculateInverseFee(transferFee, postFeeAmount) {
7991
- const preFeeAmount = calculatePreFeeAmount(transferFee, postFeeAmount);
7992
- return new BN8(
7993
- calculateFee(transferFee, BigInt(preFeeAmount.toString())).toString()
9713
+ function validateFeeFraction(numerator, denominator) {
9714
+ if (denominator.isZero() || numerator.gte(denominator)) {
9715
+ throw new Error(
9716
+ "InvalidFee: Fee numerator must be less than denominator and denominator must be non-zero"
9717
+ );
9718
+ }
9719
+ }
9720
+
9721
+ // src/helpers/common.ts
9722
+ import { PublicKey as PublicKey5 } from "@solana/web3.js";
9723
+ import BN15 from "bn.js";
9724
+ import Decimal4 from "decimal.js";
9725
+ function hasPartner(partner) {
9726
+ return !partner.equals(PublicKey5.default);
9727
+ }
9728
+ function getCurrentPoint(connection, activationType) {
9729
+ return __async(this, null, function* () {
9730
+ const currentSlot = yield connection.getSlot();
9731
+ if (activationType === 0 /* Slot */) {
9732
+ return new BN15(currentSlot);
9733
+ } else {
9734
+ const currentTime = yield connection.getBlockTime(currentSlot);
9735
+ return new BN15(currentTime);
9736
+ }
9737
+ });
9738
+ }
9739
+ function isSwapEnabled(pool, currentPoint) {
9740
+ if (typeof pool.poolStatus !== "number") {
9741
+ throw new Error("invalid pool status");
9742
+ }
9743
+ return pool.poolStatus === 0 /* Enable */ && currentPoint.gte(pool.activationPoint);
9744
+ }
9745
+ function convertToFeeSchedulerSecondFactor(value) {
9746
+ return Array.from(value.toArrayLike(Buffer, "le", 8));
9747
+ }
9748
+ function parseFeeSchedulerSecondFactor(secondFactor) {
9749
+ return new BN15(Buffer.from(secondFactor), "le");
9750
+ }
9751
+ function convertToRateLimiterSecondFactor(maxLimiterDuration, maxFeeBps) {
9752
+ const buffer1 = maxLimiterDuration.toArrayLike(Buffer, "le", 4);
9753
+ const buffer2 = maxFeeBps.toArrayLike(Buffer, "le", 4);
9754
+ const buffer = Buffer.concat([buffer1, buffer2]);
9755
+ return Array.from(buffer);
9756
+ }
9757
+ function parseRateLimiterSecondFactor(secondFactor) {
9758
+ const buffer = Buffer.from(secondFactor);
9759
+ return {
9760
+ maxLimiterDuration: buffer.readUInt32LE(0),
9761
+ maxFeeBps: buffer.readUInt32LE(4)
9762
+ };
9763
+ }
9764
+ function bpsToFeeNumerator(bps) {
9765
+ return new BN15(bps * FEE_DENOMINATOR).divn(BASIS_POINT_MAX);
9766
+ }
9767
+ function feeNumeratorToBps(feeNumerator) {
9768
+ return feeNumerator.muln(BASIS_POINT_MAX).div(new BN15(FEE_DENOMINATOR)).toNumber();
9769
+ }
9770
+ function convertToLamports(amount, tokenDecimal) {
9771
+ const valueInLamports = new Decimal4(amount).mul(
9772
+ Decimal4.pow(10, tokenDecimal)
7994
9773
  );
9774
+ return fromDecimalToBN(valueInLamports);
7995
9775
  }
7996
- function calculateTransferFeeIncludedAmount(transferFeeExcludedAmount, mint, currentEpoch) {
7997
- if (transferFeeExcludedAmount.isZero()) {
9776
+ function fromDecimalToBN(value) {
9777
+ return new BN15(value.floor().toFixed());
9778
+ }
9779
+ function getFeeSchedulerParams(startingBaseFeeBps, endingBaseFeeBps, baseFeeMode, numberOfPeriod, totalDuration) {
9780
+ if (startingBaseFeeBps == endingBaseFeeBps) {
9781
+ if (numberOfPeriod != 0 || totalDuration != 0) {
9782
+ throw new Error("numberOfPeriod and totalDuration must both be zero");
9783
+ }
7998
9784
  return {
7999
- amount: new BN8(0),
8000
- transferFee: new BN8(0)
9785
+ cliffFeeNumerator: bpsToFeeNumerator(startingBaseFeeBps),
9786
+ firstFactor: 0,
9787
+ secondFactor: Array.from(new BN15(0).toArrayLike(Buffer, "le", 8)),
9788
+ thirdFactor: new BN15(0),
9789
+ baseFeeMode: 0 /* FeeSchedulerLinear */
8001
9790
  };
8002
9791
  }
8003
- const transferFeeConfig = getTransferFeeConfig(mint);
8004
- if (transferFeeConfig === null) {
8005
- return {
8006
- amount: transferFeeExcludedAmount,
8007
- transferFee: new BN8(0)
8008
- };
9792
+ if (numberOfPeriod <= 0) {
9793
+ throw new Error("Total periods must be greater than zero");
9794
+ }
9795
+ const poolMaxFeeBps = getMaxFeeBps(CURRENT_POOL_VERSION);
9796
+ if (startingBaseFeeBps > poolMaxFeeBps) {
9797
+ throw new Error(
9798
+ `startingBaseFeeBps (${startingBaseFeeBps} bps) exceeds maximum allowed value of ${poolMaxFeeBps} bps`
9799
+ );
9800
+ }
9801
+ if (endingBaseFeeBps > startingBaseFeeBps) {
9802
+ throw new Error(
9803
+ "endingBaseFeeBps bps must be less than or equal to startingBaseFeeBps bps"
9804
+ );
9805
+ }
9806
+ if (numberOfPeriod == 0 || totalDuration == 0) {
9807
+ throw new Error(
9808
+ "numberOfPeriod and totalDuration must both greater than zero"
9809
+ );
9810
+ }
9811
+ const maxBaseFeeNumerator = bpsToFeeNumerator(startingBaseFeeBps);
9812
+ const minBaseFeeNumerator = bpsToFeeNumerator(endingBaseFeeBps);
9813
+ const periodFrequency = new BN15(totalDuration / numberOfPeriod);
9814
+ const secondFactor = convertToFeeSchedulerSecondFactor(periodFrequency);
9815
+ let reductionFactor;
9816
+ if (baseFeeMode == 0 /* FeeSchedulerLinear */) {
9817
+ const totalReduction = maxBaseFeeNumerator.sub(minBaseFeeNumerator);
9818
+ reductionFactor = totalReduction.divn(numberOfPeriod);
9819
+ } else {
9820
+ const ratio = minBaseFeeNumerator.toNumber() / maxBaseFeeNumerator.toNumber();
9821
+ const decayBase = Math.pow(ratio, 1 / numberOfPeriod);
9822
+ reductionFactor = new BN15(BASIS_POINT_MAX * (1 - decayBase));
8009
9823
  }
8010
- const epochFee = getEpochFee(transferFeeConfig, BigInt(currentEpoch));
8011
- const transferFee = epochFee.transferFeeBasisPoints == MAX_FEE_BASIS_POINTS ? new BN8(epochFee.maximumFee.toString()) : calculateInverseFee(epochFee, transferFeeExcludedAmount);
8012
- const transferFeeIncludedAmount = transferFeeExcludedAmount.add(transferFee);
8013
9824
  return {
8014
- amount: transferFeeIncludedAmount,
8015
- transferFee
9825
+ cliffFeeNumerator: maxBaseFeeNumerator,
9826
+ firstFactor: numberOfPeriod,
9827
+ secondFactor,
9828
+ thirdFactor: reductionFactor,
9829
+ baseFeeMode
8016
9830
  };
8017
9831
  }
8018
- function calculateTransferFeeExcludedAmount(transferFeeIncludedAmount, mint, currentEpoch) {
8019
- const transferFeeConfig = getTransferFeeConfig(mint);
8020
- if (transferFeeConfig === null) {
8021
- return {
8022
- amount: transferFeeIncludedAmount,
8023
- transferFee: new BN8(0)
8024
- };
9832
+ function getRateLimiterParams(baseFeeBps, feeIncrementBps, referenceAmount, maxLimiterDuration, maxFeeBps, tokenBDecimal, activationType) {
9833
+ const cliffFeeNumerator = bpsToFeeNumerator(baseFeeBps);
9834
+ const feeIncrementNumerator = bpsToFeeNumerator(feeIncrementBps);
9835
+ if (baseFeeBps <= 0 || feeIncrementBps <= 0 || referenceAmount <= 0 || maxLimiterDuration <= 0) {
9836
+ throw new Error("All rate limiter parameters must be greater than zero");
9837
+ }
9838
+ const poolMaxFeeBps = getMaxFeeBps(CURRENT_POOL_VERSION);
9839
+ const poolMaxFeeNumerator = getMaxFeeNumerator(CURRENT_POOL_VERSION);
9840
+ if (baseFeeBps > poolMaxFeeBps) {
9841
+ throw new Error(
9842
+ `Base fee (${baseFeeBps} bps) exceeds maximum allowed value of ${poolMaxFeeBps} bps`
9843
+ );
8025
9844
  }
8026
- const transferFeeIncludedAmountN = BigInt(
8027
- transferFeeIncludedAmount.toString()
8028
- );
8029
- const transferFee = calculateFee(
8030
- getEpochFee(transferFeeConfig, BigInt(currentEpoch)),
8031
- transferFeeIncludedAmountN
9845
+ if (feeIncrementBps > poolMaxFeeBps) {
9846
+ throw new Error(
9847
+ `Fee increment (${feeIncrementBps} bps) exceeds maximum allowed value of ${poolMaxFeeBps} bps`
9848
+ );
9849
+ }
9850
+ if (feeIncrementNumerator.gte(new BN15(FEE_DENOMINATOR))) {
9851
+ throw new Error(
9852
+ "Fee increment numerator must be less than FEE_DENOMINATOR"
9853
+ );
9854
+ }
9855
+ if (maxFeeBps > poolMaxFeeBps) {
9856
+ throw new Error(
9857
+ `Max fee (${maxFeeBps} bps) exceeds maximum allowed value of ${poolMaxFeeBps} bps for PoolVersion V${CURRENT_POOL_VERSION}`
9858
+ );
9859
+ }
9860
+ const deltaNumerator = new BN15(poolMaxFeeNumerator).sub(cliffFeeNumerator);
9861
+ const maxIndex = deltaNumerator.div(feeIncrementNumerator);
9862
+ if (maxIndex.lt(new BN15(1))) {
9863
+ throw new Error("Fee increment is too large for the given base fee");
9864
+ }
9865
+ if (cliffFeeNumerator.lt(new BN15(MIN_FEE_NUMERATOR)) || cliffFeeNumerator.gt(new BN15(poolMaxFeeNumerator))) {
9866
+ throw new Error("Base fee must be between 0.01% and 99%");
9867
+ }
9868
+ const maxDuration = activationType === 0 /* Slot */ ? MAX_RATE_LIMITER_DURATION_IN_SLOTS : MAX_RATE_LIMITER_DURATION_IN_SECONDS;
9869
+ if (maxLimiterDuration > maxDuration) {
9870
+ throw new Error(
9871
+ `Max duration exceeds maximum allowed value of ${maxDuration}`
9872
+ );
9873
+ }
9874
+ const referenceAmountInLamports = convertToLamports(
9875
+ referenceAmount,
9876
+ tokenBDecimal
8032
9877
  );
8033
- const transferFeeExcludedAmount = new BN8(
8034
- (transferFeeIncludedAmountN - transferFee).toString()
9878
+ const secondFactor = convertToRateLimiterSecondFactor(
9879
+ new BN15(maxLimiterDuration),
9880
+ new BN15(maxFeeBps)
8035
9881
  );
8036
9882
  return {
8037
- amount: transferFeeExcludedAmount,
8038
- transferFee: new BN8(transferFee.toString())
9883
+ cliffFeeNumerator,
9884
+ firstFactor: feeIncrementBps,
9885
+ secondFactor,
9886
+ thirdFactor: new BN15(referenceAmountInLamports),
9887
+ baseFeeMode: 2 /* RateLimiter */
8039
9888
  };
8040
9889
  }
8041
-
8042
- // src/helpers/vestings.ts
8043
- import { BN as BN9 } from "@coral-xyz/anchor";
8044
- import { min } from "bn.js";
8045
- function isVestingComplete(vestingData, currentPoint) {
8046
- const cliffPoint = vestingData.cliffPoint;
8047
- const periodFrequency = vestingData.periodFrequency;
8048
- const numberOfPeriods = vestingData.numberOfPeriod;
8049
- const endPoint = cliffPoint.add(periodFrequency.muln(numberOfPeriods));
8050
- return currentPoint.gte(endPoint);
8051
- }
8052
- function getTotalLockedLiquidity(vestingData) {
8053
- return vestingData.cliffUnlockLiquidity.add(
8054
- vestingData.liquidityPerPeriod.mul(new BN9(vestingData.numberOfPeriod))
8055
- );
8056
- }
8057
- function getAvailableVestingLiquidity(vestingData, currentPoint) {
8058
- const {
8059
- cliffPoint,
8060
- periodFrequency,
8061
- cliffUnlockLiquidity,
8062
- liquidityPerPeriod,
8063
- numberOfPeriod,
8064
- totalReleasedLiquidity
8065
- } = vestingData;
8066
- if (currentPoint.lt(cliffPoint)) {
8067
- return new BN9(0);
9890
+ function getBaseFeeParams(baseFeeParams, tokenBDecimal, activationType) {
9891
+ if (baseFeeParams.baseFeeMode === 2 /* RateLimiter */) {
9892
+ if (!baseFeeParams.rateLimiterParam) {
9893
+ throw new Error(
9894
+ "Rate limiter parameters are required for RateLimiter mode"
9895
+ );
9896
+ }
9897
+ const {
9898
+ baseFeeBps,
9899
+ feeIncrementBps,
9900
+ referenceAmount,
9901
+ maxLimiterDuration,
9902
+ maxFeeBps
9903
+ } = baseFeeParams.rateLimiterParam;
9904
+ return getRateLimiterParams(
9905
+ baseFeeBps,
9906
+ feeIncrementBps,
9907
+ referenceAmount,
9908
+ maxLimiterDuration,
9909
+ maxFeeBps,
9910
+ tokenBDecimal,
9911
+ activationType
9912
+ );
9913
+ } else {
9914
+ if (!baseFeeParams.feeSchedulerParam) {
9915
+ throw new Error(
9916
+ "Fee scheduler parameters are required for FeeScheduler mode"
9917
+ );
9918
+ }
9919
+ const { startingFeeBps, endingFeeBps, numberOfPeriod, totalDuration } = baseFeeParams.feeSchedulerParam;
9920
+ return getFeeSchedulerParams(
9921
+ startingFeeBps,
9922
+ endingFeeBps,
9923
+ baseFeeParams.baseFeeMode,
9924
+ numberOfPeriod,
9925
+ totalDuration
9926
+ );
8068
9927
  }
8069
- if (periodFrequency.isZero()) {
8070
- return cliffUnlockLiquidity;
9928
+ }
9929
+ function getDynamicFeeParams(baseFeeBps, maxPriceChangeBps = MAX_PRICE_CHANGE_BPS_DEFAULT) {
9930
+ if (maxPriceChangeBps > MAX_PRICE_CHANGE_BPS_DEFAULT) {
9931
+ throw new Error(
9932
+ `maxPriceChangeBps (${maxPriceChangeBps} bps) must be less than or equal to ${MAX_PRICE_CHANGE_BPS_DEFAULT}`
9933
+ );
8071
9934
  }
8072
- let passedPeriod = new BN9(currentPoint).sub(cliffPoint).div(periodFrequency);
8073
- passedPeriod = min(passedPeriod, new BN9(numberOfPeriod));
8074
- const unlockedLiquidity = cliffUnlockLiquidity.add(
8075
- passedPeriod.mul(liquidityPerPeriod)
8076
- );
8077
- const availableReleasingLiquidity = unlockedLiquidity.sub(
8078
- totalReleasedLiquidity
9935
+ const priceRatio = maxPriceChangeBps / BASIS_POINT_MAX + 1;
9936
+ const sqrtPriceRatioQ64 = new BN15(
9937
+ Decimal4.sqrt(priceRatio.toString()).mul(Decimal4.pow(2, 64)).floor().toFixed()
8079
9938
  );
8080
- return availableReleasingLiquidity;
9939
+ const deltaBinId = sqrtPriceRatioQ64.sub(ONE_Q64).div(BIN_STEP_BPS_U128_DEFAULT).muln(2);
9940
+ const maxVolatilityAccumulator = new BN15(deltaBinId.muln(BASIS_POINT_MAX));
9941
+ const squareVfaBin = maxVolatilityAccumulator.mul(new BN15(BIN_STEP_BPS_DEFAULT)).pow(new BN15(2));
9942
+ const baseFeeNumerator = new BN15(bpsToFeeNumerator(baseFeeBps));
9943
+ const maxDynamicFeeNumerator = baseFeeNumerator.muln(20).divn(100);
9944
+ const vFee = maxDynamicFeeNumerator.mul(new BN15(1e11)).sub(new BN15(99999999999));
9945
+ const variableFeeControl = vFee.div(squareVfaBin);
9946
+ return {
9947
+ binStep: BIN_STEP_BPS_DEFAULT,
9948
+ binStepU128: BIN_STEP_BPS_U128_DEFAULT,
9949
+ filterPeriod: DYNAMIC_FEE_FILTER_PERIOD_DEFAULT,
9950
+ decayPeriod: DYNAMIC_FEE_DECAY_PERIOD_DEFAULT,
9951
+ reductionFactor: DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT,
9952
+ maxVolatilityAccumulator: maxVolatilityAccumulator.toNumber(),
9953
+ variableFeeControl: variableFeeControl.toNumber()
9954
+ };
8081
9955
  }
8082
9956
 
8083
9957
  // src/CpAmm.ts
8084
- import { min as min2, max } from "bn.js";
9958
+ import BN16, { min as min2, max } from "bn.js";
8085
9959
  var CpAmm = class {
8086
9960
  constructor(connection) {
8087
9961
  this._program = new Program(cp_amm_default, {
@@ -8796,158 +10670,101 @@ var CpAmm = class {
8796
10670
  currentTime,
8797
10671
  currentSlot,
8798
10672
  inputTokenInfo,
8799
- outputTokenInfo
10673
+ outputTokenInfo,
10674
+ tokenADecimal,
10675
+ tokenBDecimal,
10676
+ hasReferral
8800
10677
  } = params;
8801
- const {
8802
- sqrtPrice: sqrtPriceQ64,
8803
- liquidity: liquidityQ64,
8804
- activationType,
8805
- activationPoint,
8806
- collectFeeMode,
8807
- poolFees
8808
- } = poolState;
8809
- const {
8810
- feeSchedulerMode,
8811
- cliffFeeNumerator,
8812
- numberOfPeriod,
8813
- reductionFactor,
8814
- periodFrequency
8815
- } = poolFees.baseFee;
8816
- const dynamicFee = poolFees.dynamicFee;
8817
- let actualAmountIn = inAmount;
8818
- if (inputTokenInfo) {
8819
- actualAmountIn = calculateTransferFeeExcludedAmount(
8820
- inAmount,
8821
- inputTokenInfo.mint,
8822
- inputTokenInfo.currentEpoch
8823
- ).amount;
8824
- }
10678
+ const { sqrtPrice: sqrtPriceQ64, activationType } = poolState;
8825
10679
  const aToB = poolState.tokenAMint.equals(inputTokenMint);
8826
- const currentPoint = activationType ? currentTime : currentSlot;
8827
- let dynamicFeeParams;
8828
- if (dynamicFee.initialized) {
8829
- const { volatilityAccumulator, binStep, variableFeeControl } = dynamicFee;
8830
- dynamicFeeParams = { volatilityAccumulator, binStep, variableFeeControl };
8831
- }
8832
- const tradeFeeNumerator = getFeeNumerator(
10680
+ const currentPoint = activationType ? new BN16(currentTime) : new BN16(currentSlot);
10681
+ const swapResult = swapQuoteExactInput(
10682
+ poolState,
8833
10683
  currentPoint,
8834
- activationPoint,
8835
- numberOfPeriod,
8836
- periodFrequency,
8837
- feeSchedulerMode,
8838
- cliffFeeNumerator,
8839
- reductionFactor,
8840
- dynamicFeeParams
8841
- );
8842
- const { amountOut, totalFee, nextSqrtPrice } = getSwapAmount(
8843
- actualAmountIn,
8844
- sqrtPriceQ64,
8845
- liquidityQ64,
8846
- tradeFeeNumerator,
10684
+ inAmount,
10685
+ slippage,
8847
10686
  aToB,
8848
- collectFeeMode
8849
- );
8850
- let actualAmountOut = amountOut;
8851
- if (outputTokenInfo) {
8852
- actualAmountOut = calculateTransferFeeExcludedAmount(
8853
- amountOut,
8854
- outputTokenInfo.mint,
8855
- outputTokenInfo.currentEpoch
8856
- ).amount;
8857
- }
8858
- const minSwapOutAmount = getMinAmountWithSlippage(
8859
- actualAmountOut,
8860
- slippage
10687
+ hasReferral,
10688
+ tokenADecimal,
10689
+ tokenBDecimal,
10690
+ inputTokenInfo,
10691
+ outputTokenInfo
8861
10692
  );
8862
10693
  return {
8863
10694
  swapInAmount: inAmount,
8864
- consumedInAmount: actualAmountIn,
8865
- swapOutAmount: actualAmountOut,
8866
- minSwapOutAmount,
8867
- totalFee,
8868
- priceImpact: getPriceImpact(
8869
- actualAmountIn,
8870
- actualAmountOut,
8871
- sqrtPriceQ64,
8872
- aToB,
8873
- params.tokenADecimal,
8874
- params.tokenBDecimal
8875
- )
10695
+ consumedInAmount: swapResult.includedFeeInputAmount,
10696
+ swapOutAmount: swapResult.outputAmount,
10697
+ minSwapOutAmount: swapResult.minimumAmountOut,
10698
+ totalFee: swapResult.tradingFee.add(swapResult.protocolFee).add(swapResult.partnerFee).add(swapResult.referralFee),
10699
+ priceImpact: swapResult.priceImpact
8876
10700
  };
8877
10701
  }
8878
- /**
8879
- * Calculates swap quote based on desired output amount and pool state.
8880
- * @param params - Swap parameters including output amount, pool state, slippage, etc.
8881
- * @returns Swap quote including required input amount, fees, and price impact.
8882
- */
8883
- getQuoteExactOut(params) {
10702
+ getQuote2(params) {
8884
10703
  const {
8885
- outAmount,
8886
- outputTokenMint,
10704
+ inputTokenMint,
8887
10705
  slippage,
8888
10706
  poolState,
8889
- currentTime,
8890
- currentSlot,
10707
+ currentPoint,
8891
10708
  inputTokenInfo,
8892
- outputTokenInfo
10709
+ outputTokenInfo,
10710
+ hasReferral,
10711
+ tokenADecimal,
10712
+ tokenBDecimal,
10713
+ swapMode
8893
10714
  } = params;
8894
- const {
8895
- sqrtPrice: sqrtPriceQ64,
8896
- activationType,
8897
- collectFeeMode,
8898
- poolFees
8899
- } = poolState;
8900
- const dynamicFee = poolFees.dynamicFee;
8901
- const bToA = poolState.tokenAMint.equals(outputTokenMint);
8902
- const tradeDirection = bToA ? 1 /* BtoA */ : 0 /* AtoB */;
8903
- const currentPoint = activationType ? currentTime : currentSlot;
8904
- let dynamicFeeParams;
8905
- if (dynamicFee.initialized) {
8906
- const { volatilityAccumulator, binStep, variableFeeControl } = dynamicFee;
8907
- dynamicFeeParams = { volatilityAccumulator, binStep, variableFeeControl };
8908
- }
8909
- let actualAmountOut = outAmount;
8910
- if (outputTokenInfo) {
8911
- actualAmountOut = calculateTransferFeeIncludedAmount(
8912
- outAmount,
8913
- outputTokenInfo.mint,
8914
- outputTokenInfo.currentEpoch
8915
- ).amount;
8916
- }
8917
- const feeMode = getFeeMode(collectFeeMode, bToA);
8918
- const { swapResult, inputAmount } = getSwapResultFromOutAmount(
8919
- poolState,
8920
- actualAmountOut,
8921
- feeMode,
8922
- tradeDirection,
8923
- currentPoint
8924
- );
8925
- let actualInputAmount = inputAmount;
8926
- if (inputTokenInfo) {
8927
- actualInputAmount = calculateTransferFeeIncludedAmount(
8928
- inputAmount,
8929
- inputTokenInfo.mint,
8930
- inputTokenInfo.currentEpoch
8931
- ).amount;
10715
+ const aToB = poolState.tokenAMint.equals(inputTokenMint);
10716
+ switch (swapMode) {
10717
+ case 0 /* ExactIn */:
10718
+ if ("amountIn" in params) {
10719
+ return swapQuoteExactInput(
10720
+ poolState,
10721
+ currentPoint,
10722
+ params.amountIn,
10723
+ slippage,
10724
+ aToB,
10725
+ hasReferral,
10726
+ tokenADecimal,
10727
+ tokenBDecimal,
10728
+ inputTokenInfo,
10729
+ outputTokenInfo
10730
+ );
10731
+ }
10732
+ throw new Error("amountIn is required for ExactIn swap mode");
10733
+ case 2 /* ExactOut */:
10734
+ if ("amountOut" in params) {
10735
+ return swapQuoteExactOutput(
10736
+ poolState,
10737
+ currentPoint,
10738
+ params.amountOut,
10739
+ slippage,
10740
+ aToB,
10741
+ hasReferral,
10742
+ tokenADecimal,
10743
+ tokenBDecimal,
10744
+ inputTokenInfo,
10745
+ outputTokenInfo
10746
+ );
10747
+ }
10748
+ throw new Error("outAmount is required for ExactOut swap mode");
10749
+ case 1 /* PartialFill */:
10750
+ if ("amountIn" in params) {
10751
+ return swapQuotePartialInput(
10752
+ poolState,
10753
+ currentPoint,
10754
+ params.amountIn,
10755
+ slippage,
10756
+ aToB,
10757
+ hasReferral,
10758
+ tokenADecimal,
10759
+ tokenBDecimal,
10760
+ inputTokenInfo,
10761
+ outputTokenInfo
10762
+ );
10763
+ }
10764
+ throw new Error("amountIn is required for PartialFill swap mode");
10765
+ default:
10766
+ throw new Error(`Unsupported swap mode: ${swapMode}`);
8932
10767
  }
8933
- const maxInputAmount = new BN10(
8934
- Math.ceil(actualInputAmount.toNumber() * (1 + slippage / 100))
8935
- );
8936
- const priceImpact = getPriceImpact(
8937
- actualInputAmount,
8938
- actualAmountOut,
8939
- sqrtPriceQ64,
8940
- !bToA,
8941
- // aToB is the opposite of bToA
8942
- params.tokenADecimal,
8943
- params.tokenBDecimal
8944
- ).toNumber();
8945
- return {
8946
- swapResult,
8947
- inputAmount: actualInputAmount,
8948
- maxInputAmount,
8949
- priceImpact
8950
- };
8951
10768
  }
8952
10769
  /**
8953
10770
  * Calculates the deposit quote for liquidity pool.
@@ -8999,7 +10816,7 @@ var CpAmm = class {
8999
10816
  0 /* Up */
9000
10817
  )
9001
10818
  };
9002
- const rawOutputAmount = new BN10(rawAmount(liquidityDelta));
10819
+ const rawOutputAmount = new BN16(rawAmount(liquidityDelta));
9003
10820
  const outputAmount = outputTokenInfo ? calculateTransferFeeIncludedAmount(
9004
10821
  rawOutputAmount,
9005
10822
  outputTokenInfo.mint,
@@ -9106,7 +10923,7 @@ var CpAmm = class {
9106
10923
  tokenAInfo,
9107
10924
  tokenBInfo
9108
10925
  } = params;
9109
- if (tokenAAmount.eq(new BN10(0)) && tokenBAmount.eq(new BN10(0))) {
10926
+ if (tokenAAmount.eq(new BN16(0)) && tokenBAmount.eq(new BN16(0))) {
9110
10927
  throw new Error("Invalid input amount");
9111
10928
  }
9112
10929
  const actualAmountAIn = tokenAInfo ? tokenAAmount.sub(
@@ -9273,7 +11090,7 @@ var CpAmm = class {
9273
11090
  tokenAMint,
9274
11091
  tokenBMint,
9275
11092
  tokenAAmount,
9276
- tokenBAmount: tokenBMint.equals(NATIVE_MINT2) ? max(tokenBAmount, new BN10(1)) : tokenBAmount,
11093
+ tokenBAmount: tokenBMint.equals(NATIVE_MINT2) ? max(tokenBAmount, new BN16(1)) : tokenBAmount,
9277
11094
  payer,
9278
11095
  positionNft,
9279
11096
  tokenAProgram,
@@ -9785,6 +11602,7 @@ var CpAmm = class {
9785
11602
  const [inputTokenProgram, outputTokenProgram] = inputTokenMint.equals(
9786
11603
  tokenAMint
9787
11604
  ) ? [tokenAProgram, tokenBProgram] : [tokenBProgram, tokenAProgram];
11605
+ const tradeDirection = inputTokenMint.equals(tokenAMint) ? 0 /* AtoB */ : 1 /* BtoA */;
9788
11606
  const {
9789
11607
  tokenAAta: inputTokenAccount,
9790
11608
  tokenBAta: outputTokenAccount,
@@ -9813,6 +11631,30 @@ var CpAmm = class {
9813
11631
  const closeWrappedSOLIx = yield unwrapSOLInstruction(payer);
9814
11632
  closeWrappedSOLIx && postInstructions.push(closeWrappedSOLIx);
9815
11633
  }
11634
+ const poolState = yield this.fetchPoolState(pool);
11635
+ const currentPoint = yield getCurrentPoint(
11636
+ this._program.provider.connection,
11637
+ poolState.activationType
11638
+ );
11639
+ const { maxLimiterDuration, maxFeeBps } = parseRateLimiterSecondFactor(
11640
+ poolState.poolFees.baseFee.secondFactor
11641
+ );
11642
+ const rateLimiterApplied = isRateLimiterApplied(
11643
+ poolState.poolFees.baseFee.thirdFactor,
11644
+ maxLimiterDuration,
11645
+ maxFeeBps,
11646
+ poolState.poolFees.baseFee.firstFactor,
11647
+ currentPoint,
11648
+ poolState.activationPoint,
11649
+ tradeDirection
11650
+ );
11651
+ const remainingAccounts = rateLimiterApplied ? [
11652
+ {
11653
+ isSigner: false,
11654
+ isWritable: false,
11655
+ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY
11656
+ }
11657
+ ] : [];
9816
11658
  return yield this._program.methods.swap({
9817
11659
  amountIn,
9818
11660
  minimumAmountOut
@@ -9829,7 +11671,109 @@ var CpAmm = class {
9829
11671
  tokenAProgram,
9830
11672
  tokenBProgram,
9831
11673
  referralTokenAccount
9832
- }).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
11674
+ }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
11675
+ });
11676
+ }
11677
+ swap2(params) {
11678
+ return __async(this, null, function* () {
11679
+ const {
11680
+ payer,
11681
+ pool,
11682
+ inputTokenMint,
11683
+ outputTokenMint,
11684
+ tokenAVault,
11685
+ tokenBVault,
11686
+ tokenAMint,
11687
+ tokenBMint,
11688
+ tokenAProgram,
11689
+ tokenBProgram,
11690
+ referralTokenAccount,
11691
+ swapMode
11692
+ } = params;
11693
+ const [inputTokenProgram, outputTokenProgram] = inputTokenMint.equals(
11694
+ tokenAMint
11695
+ ) ? [tokenAProgram, tokenBProgram] : [tokenBProgram, tokenAProgram];
11696
+ const tradeDirection = inputTokenMint.equals(tokenAMint) ? 0 /* AtoB */ : 1 /* BtoA */;
11697
+ const {
11698
+ tokenAAta: inputTokenAccount,
11699
+ tokenBAta: outputTokenAccount,
11700
+ instructions: preInstructions
11701
+ } = yield this.prepareTokenAccounts({
11702
+ payer,
11703
+ tokenAOwner: payer,
11704
+ tokenBOwner: payer,
11705
+ tokenAMint: inputTokenMint,
11706
+ tokenBMint: outputTokenMint,
11707
+ tokenAProgram: inputTokenProgram,
11708
+ tokenBProgram: outputTokenProgram
11709
+ });
11710
+ let amount0;
11711
+ let amount1;
11712
+ if (swapMode === 2 /* ExactOut */) {
11713
+ amount0 = params.amountOut;
11714
+ amount1 = params.maximumAmountIn;
11715
+ } else {
11716
+ amount0 = params.amountIn;
11717
+ amount1 = params.minimumAmountOut;
11718
+ }
11719
+ if (inputTokenMint.equals(NATIVE_MINT2)) {
11720
+ const amount = swapMode === 0 /* ExactIn */ || swapMode === 1 /* PartialFill */ ? amount0 : amount1;
11721
+ const wrapSOLIx = wrapSOLInstruction(
11722
+ payer,
11723
+ inputTokenAccount,
11724
+ BigInt(amount.toString())
11725
+ );
11726
+ preInstructions.push(...wrapSOLIx);
11727
+ }
11728
+ const postInstructions = [];
11729
+ if ([tokenAMint.toBase58(), tokenBMint.toBase58()].includes(
11730
+ NATIVE_MINT2.toBase58()
11731
+ )) {
11732
+ const closeWrappedSOLIx = yield unwrapSOLInstruction(payer);
11733
+ closeWrappedSOLIx && postInstructions.push(closeWrappedSOLIx);
11734
+ }
11735
+ const poolState = yield this.fetchPoolState(pool);
11736
+ const currentPoint = yield getCurrentPoint(
11737
+ this._program.provider.connection,
11738
+ poolState.activationType
11739
+ );
11740
+ const { maxLimiterDuration, maxFeeBps } = parseRateLimiterSecondFactor(
11741
+ poolState.poolFees.baseFee.secondFactor
11742
+ );
11743
+ const rateLimiterApplied = isRateLimiterApplied(
11744
+ poolState.poolFees.baseFee.thirdFactor,
11745
+ maxLimiterDuration,
11746
+ maxFeeBps,
11747
+ poolState.poolFees.baseFee.firstFactor,
11748
+ currentPoint,
11749
+ poolState.activationPoint,
11750
+ tradeDirection
11751
+ );
11752
+ const remainingAccounts = rateLimiterApplied ? [
11753
+ {
11754
+ isSigner: false,
11755
+ isWritable: false,
11756
+ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY
11757
+ }
11758
+ ] : [];
11759
+ return yield this._program.methods.swap2({
11760
+ amount0,
11761
+ amount1,
11762
+ swapMode
11763
+ }).accountsPartial({
11764
+ poolAuthority: this.poolAuthority,
11765
+ pool,
11766
+ payer,
11767
+ inputTokenAccount,
11768
+ outputTokenAccount,
11769
+ tokenAVault,
11770
+ tokenBVault,
11771
+ tokenAMint,
11772
+ tokenBMint,
11773
+ tokenAProgram,
11774
+ tokenBProgram,
11775
+ referralTokenAccount
11776
+ }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
9833
11777
  });
9834
11778
  }
9835
11779
  /**
@@ -10063,7 +12007,7 @@ var CpAmm = class {
10063
12007
  );
10064
12008
  return total.add(available);
10065
12009
  },
10066
- new BN10(0)
12010
+ new BN16(0)
10067
12011
  );
10068
12012
  positionBLiquidityDelta = positionBLiquidityDelta.add(
10069
12013
  totalAvailableVestingLiquidity
@@ -10510,6 +12454,29 @@ var CpAmm = class {
10510
12454
  }).transaction();
10511
12455
  });
10512
12456
  }
12457
+ splitPosition2(params) {
12458
+ return __async(this, null, function* () {
12459
+ const {
12460
+ firstPositionOwner,
12461
+ secondPositionOwner,
12462
+ pool,
12463
+ firstPosition,
12464
+ firstPositionNftAccount,
12465
+ secondPosition,
12466
+ secondPositionNftAccount,
12467
+ numerator
12468
+ } = params;
12469
+ return yield this._program.methods.splitPosition2(numerator).accountsPartial({
12470
+ pool,
12471
+ firstPosition,
12472
+ firstPositionNftAccount,
12473
+ secondPosition,
12474
+ secondPositionNftAccount,
12475
+ firstOwner: firstPositionOwner,
12476
+ secondOwner: secondPositionOwner
12477
+ }).transaction();
12478
+ });
12479
+ }
10513
12480
  };
10514
12481
 
10515
12482
  // src/index.ts
@@ -10520,29 +12487,59 @@ export {
10520
12487
  BASIS_POINT_MAX,
10521
12488
  BIN_STEP_BPS_DEFAULT,
10522
12489
  BIN_STEP_BPS_U128_DEFAULT,
12490
+ BaseFeeMode,
10523
12491
  CP_AMM_PROGRAM_ID,
12492
+ CURRENT_POOL_VERSION,
10524
12493
  CollectFeeMode,
10525
12494
  CpAmm,
10526
12495
  DYNAMIC_FEE_DECAY_PERIOD_DEFAULT,
10527
12496
  DYNAMIC_FEE_FILTER_PERIOD_DEFAULT,
10528
12497
  DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT,
12498
+ DYNAMIC_FEE_ROUNDING_OFFSET,
12499
+ DYNAMIC_FEE_SCALING_FACTOR,
10529
12500
  FEE_DENOMINATOR,
10530
- FeeSchedulerMode,
12501
+ FeeRateLimiter,
12502
+ FeeScheduler,
10531
12503
  LIQUIDITY_SCALE,
12504
+ MAX,
10532
12505
  MAX_CU_BUFFER,
10533
- MAX_FEE_NUMERATOR,
12506
+ MAX_EXPONENTIAL,
12507
+ MAX_FEE_BPS_V0,
12508
+ MAX_FEE_BPS_V1,
12509
+ MAX_FEE_NUMERATOR_V0,
12510
+ MAX_FEE_NUMERATOR_V1,
10534
12511
  MAX_PRICE_CHANGE_BPS_DEFAULT,
12512
+ MAX_RATE_LIMITER_DURATION_IN_SECONDS,
12513
+ MAX_RATE_LIMITER_DURATION_IN_SLOTS,
10535
12514
  MAX_SQRT_PRICE,
10536
12515
  MIN_CU_BUFFER,
12516
+ MIN_FEE_BPS,
12517
+ MIN_FEE_NUMERATOR,
10537
12518
  MIN_SQRT_PRICE,
10538
- ONE,
12519
+ ONE_Q64,
12520
+ PoolStatus,
12521
+ PoolVersion,
10539
12522
  Rounding,
10540
12523
  SCALE_OFFSET,
12524
+ SPLIT_POSITION_DENOMINATOR,
12525
+ SwapMode,
10541
12526
  TradeDirection,
12527
+ U128_MAX,
12528
+ U16_MAX,
12529
+ U64_MAX,
10542
12530
  bpsToFeeNumerator,
12531
+ calculateAtoBFromAmountIn,
12532
+ calculateAtoBFromAmountOut,
12533
+ calculateAtoBFromPartialAmountIn,
12534
+ calculateBtoAFromAmountIn,
12535
+ calculateBtoAFromAmountOut,
12536
+ calculateBtoAFromPartialAmountIn,
10543
12537
  calculateInitSqrtPrice,
10544
12538
  calculateTransferFeeExcludedAmount,
10545
12539
  calculateTransferFeeIncludedAmount,
12540
+ convertToFeeSchedulerSecondFactor,
12541
+ convertToLamports,
12542
+ convertToRateLimiterSecondFactor,
10546
12543
  decimalToQ64,
10547
12544
  index_default as default,
10548
12545
  deriveClaimFeeOperatorAddress,
@@ -10556,49 +12553,90 @@ export {
10556
12553
  deriveTokenBadgeAddress,
10557
12554
  deriveTokenVaultAddress,
10558
12555
  feeNumeratorToBps,
12556
+ fromDecimalToBN,
10559
12557
  getAllPositionNftAccountByOwner,
10560
12558
  getAllUserPositionNftAccount,
10561
12559
  getAmountAFromLiquidityDelta,
10562
12560
  getAmountBFromLiquidityDelta,
12561
+ getAmountWithSlippage,
10563
12562
  getAvailableVestingLiquidity,
12563
+ getBaseFeeHandler,
10564
12564
  getBaseFeeNumerator,
12565
+ getBaseFeeNumeratorByPeriod,
10565
12566
  getBaseFeeParams,
12567
+ getCheckedAmounts,
12568
+ getCurrentPoint,
10566
12569
  getDynamicFeeNumerator,
10567
12570
  getDynamicFeeParams,
10568
12571
  getEstimatedComputeUnitIxWithBuffer,
10569
12572
  getEstimatedComputeUnitUsageWithBuffer,
10570
12573
  getExcludedFeeAmount,
12574
+ getExcludedFeeAmountFromIncludedFeeAmount,
12575
+ getFeeInPeriod,
10571
12576
  getFeeMode,
10572
- getFeeNumerator,
12577
+ getFeeNumeratorFromExcludedFeeAmount,
12578
+ getFeeNumeratorFromIncludedFeeAmount,
12579
+ getFeeNumeratorOnExponentialFeeScheduler,
12580
+ getFeeNumeratorOnLinearFeeScheduler,
12581
+ getFeeOnAmount,
12582
+ getFeeSchedulerParams,
10573
12583
  getFirstKey,
10574
12584
  getIncludedFeeAmount,
10575
12585
  getLiquidityDeltaFromAmountA,
10576
12586
  getLiquidityDeltaFromAmountB,
10577
12587
  getMaxAmountWithSlippage,
10578
- getMinAmountWithSlippage,
10579
- getNextSqrtPrice,
10580
- getNextSqrtPriceFromAmountARoundingDown,
10581
- getNextSqrtPriceFromAmountBRoundingUp,
12588
+ getMaxBaseFeeNumerator,
12589
+ getMaxFeeBps,
12590
+ getMaxFeeNumerator,
12591
+ getMaxIndex,
12592
+ getMinBaseFeeNumerator,
12593
+ getNextSqrtPriceFromAmountInARoundingUp,
12594
+ getNextSqrtPriceFromAmountInBRoundingDown,
12595
+ getNextSqrtPriceFromAmountOutARoundingUp,
12596
+ getNextSqrtPriceFromAmountOutBRoundingDown,
12597
+ getNextSqrtPriceFromInput,
10582
12598
  getNextSqrtPriceFromOutput,
10583
12599
  getOrCreateATAInstruction,
10584
12600
  getPriceChange,
10585
12601
  getPriceFromSqrtPrice,
10586
12602
  getPriceImpact,
12603
+ getRateLimiterParams,
10587
12604
  getSecondKey,
10588
12605
  getSimulationComputeUnits,
10589
12606
  getSqrtPriceFromPrice,
10590
- getSwapAmount,
10591
- getSwapResultFromOutAmount,
12607
+ getSwapResultFromExactInput,
12608
+ getSwapResultFromExactOutput,
12609
+ getSwapResultFromPartialInput,
10592
12610
  getTokenDecimals,
10593
12611
  getTokenProgram,
12612
+ getTotalFeeNumerator,
10594
12613
  getTotalLockedLiquidity,
12614
+ getTotalTradingFeeFromExcludedFeeAmount,
12615
+ getTotalTradingFeeFromIncludedFeeAmount,
10595
12616
  getUnClaimReward,
12617
+ hasPartner,
12618
+ isDynamicFeeEnabled,
12619
+ isNonZeroRateLimiter,
12620
+ isRateLimiterApplied,
12621
+ isSwapEnabled,
10596
12622
  isVestingComplete,
12623
+ isZeroRateLimiter,
10597
12624
  mulDiv,
12625
+ parseFeeSchedulerSecondFactor,
12626
+ parseRateLimiterSecondFactor,
10598
12627
  positionByPoolFilter,
10599
12628
  pow,
10600
12629
  q64ToDecimal,
12630
+ splitFees,
12631
+ sqrt,
12632
+ swapQuoteExactInput,
12633
+ swapQuoteExactOutput,
12634
+ swapQuotePartialInput,
12635
+ toNumerator,
10601
12636
  unwrapSOLInstruction,
12637
+ validateFeeFraction,
12638
+ validateFeeRateLimiter,
12639
+ validateFeeScheduler,
10602
12640
  vestingByPositionFilter,
10603
12641
  wrapSOLInstruction
10604
12642
  };